1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import java.io.*;
  29 import java.util.*;
  30 import java.lang.reflect.Modifier;
  31 
  32 import jdk.internal.org.objectweb.asm.*;
  33 
  34 import static java.lang.invoke.LambdaForm.*;
  35 import static java.lang.invoke.LambdaForm.BasicType.*;
  36 import static java.lang.invoke.MethodHandleStatics.*;
  37 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  38 
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 import sun.reflect.misc.ReflectUtil;
  43 
  44 /**
  45  * Code generation backend for LambdaForm.
  46  * <p>
  47  * @author John Rose, JSR 292 EG
  48  */
  49 class InvokerBytecodeGenerator {
  50     /** Define class names for convenience. */
  51     private static final String MH      = "java/lang/invoke/MethodHandle";
  52     private static final String MHI     = "java/lang/invoke/MethodHandleImpl";
  53     private static final String LF      = "java/lang/invoke/LambdaForm";
  54     private static final String LFN     = "java/lang/invoke/LambdaForm$Name";
  55     private static final String CLS     = "java/lang/Class";
  56     private static final String OBJ     = "java/lang/Object";
  57     private static final String OBJARY  = "[Ljava/lang/Object;";
  58 
  59     private static final String MH_SIG  = "L" + MH + ";";
  60     private static final String LF_SIG  = "L" + LF + ";";
  61     private static final String LFN_SIG = "L" + LFN + ";";
  62     private static final String LL_SIG  = "(L" + OBJ + ";)L" + OBJ + ";";
  63     private static final String LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V";
  64     private static final String CLL_SIG = "(L" + CLS + ";L" + OBJ + ";)L" + OBJ + ";";
  65 
  66     /** Name of its super class*/
  67     private static final String superName = OBJ;
  68 
  69     /** Name of new class */
  70     private final String className;
  71 
  72     /** Name of the source file (for stack trace printing). */
  73     private final String sourceFile;
  74 
  75     private final LambdaForm lambdaForm;
  76     private final String     invokerName;
  77     private final MethodType invokerType;
  78 
  79     /** Info about local variables in compiled lambda form */
  80     private final int[]       localsMap;    // index
  81     private final BasicType[] localTypes;   // basic type
  82     private final Class<?>[]  localClasses; // type
  83 
  84     /** ASM bytecode generation. */
  85     private ClassWriter cw;
  86     private MethodVisitor mv;
  87 
  88     private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory();
  89     private static final Class<?> HOST_CLASS = LambdaForm.class;
  90 
  91     /** Main constructor; other constructors delegate to this one. */
  92     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
  93                                      String className, String invokerName, MethodType invokerType) {
  94         if (invokerName.contains(".")) {
  95             int p = invokerName.indexOf('.');
  96             className = invokerName.substring(0, p);
  97             invokerName = invokerName.substring(p+1);
  98         }
  99         if (DUMP_CLASS_FILES) {
 100             className = makeDumpableClassName(className);
 101         }
 102         this.className  = LF + "$" + className;
 103         this.sourceFile = "LambdaForm$" + className;
 104         this.lambdaForm = lambdaForm;
 105         this.invokerName = invokerName;
 106         this.invokerType = invokerType;
 107         this.localsMap = new int[localsMapSize+1];
 108         // last entry of localsMap is count of allocated local slots
 109         this.localTypes = new BasicType[localsMapSize+1];
 110         this.localClasses = new Class<?>[localsMapSize+1];
 111     }
 112 
 113     /** For generating LambdaForm interpreter entry points. */
 114     private InvokerBytecodeGenerator(String className, String invokerName, MethodType invokerType) {
 115         this(null, invokerType.parameterCount(),
 116              className, invokerName, invokerType);
 117         // Create an array to map name indexes to locals indexes.
 118         localTypes[localTypes.length - 1] = V_TYPE;
 119         for (int i = 0; i < localsMap.length; i++) {
 120             localsMap[i] = invokerType.parameterSlotCount() - invokerType.parameterSlotDepth(i);
 121             if (i < invokerType.parameterCount())
 122                 localTypes[i] = basicType(invokerType.parameterType(i));
 123         }
 124     }
 125 
 126     /** For generating customized code for a single LambdaForm. */
 127     private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
 128         this(form, form.names.length,
 129              className, form.debugName, invokerType);
 130         // Create an array to map name indexes to locals indexes.
 131         Name[] names = form.names;
 132         for (int i = 0, index = 0; i < localsMap.length; i++) {
 133             localsMap[i] = index;
 134             if (i < names.length) {
 135                 BasicType type = names[i].type();
 136                 index += type.basicTypeSlots();
 137                 localTypes[i] = type;
 138             }
 139         }
 140     }
 141 
 142 
 143     /** instance counters for dumped classes */
 144     private final static HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS;
 145     /** debugging flag for saving generated class files */
 146     private final static File DUMP_CLASS_FILES_DIR;
 147 
 148     static {
 149         if (DUMP_CLASS_FILES) {
 150             DUMP_CLASS_FILES_COUNTERS = new HashMap<>();
 151             try {
 152                 File dumpDir = new File("DUMP_CLASS_FILES");
 153                 if (!dumpDir.exists()) {
 154                     dumpDir.mkdirs();
 155                 }
 156                 DUMP_CLASS_FILES_DIR = dumpDir;
 157                 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/...");
 158             } catch (Exception e) {
 159                 throw newInternalError(e);
 160             }
 161         } else {
 162             DUMP_CLASS_FILES_COUNTERS = null;
 163             DUMP_CLASS_FILES_DIR = null;
 164         }
 165     }
 166 
 167     static void maybeDump(final String className, final byte[] classFile) {
 168         if (DUMP_CLASS_FILES) {
 169             java.security.AccessController.doPrivileged(
 170             new java.security.PrivilegedAction<Void>() {
 171                 public Void run() {
 172                     try {
 173                         String dumpName = className;
 174                         //dumpName = dumpName.replace('/', '-');
 175                         File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class");
 176                         System.out.println("dump: " + dumpFile);
 177                         dumpFile.getParentFile().mkdirs();
 178                         FileOutputStream file = new FileOutputStream(dumpFile);
 179                         file.write(classFile);
 180                         file.close();
 181                         return null;
 182                     } catch (IOException ex) {
 183                         throw newInternalError(ex);
 184                     }
 185                 }
 186             });
 187         }
 188 
 189     }
 190 
 191     private static String makeDumpableClassName(String className) {
 192         Integer ctr;
 193         synchronized (DUMP_CLASS_FILES_COUNTERS) {
 194             ctr = DUMP_CLASS_FILES_COUNTERS.get(className);
 195             if (ctr == null)  ctr = 0;
 196             DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1);
 197         }
 198         String sfx = ctr.toString();
 199         while (sfx.length() < 3)
 200             sfx = "0"+sfx;
 201         className += sfx;
 202         return className;
 203     }
 204 
 205     class CpPatch {
 206         final int index;
 207         final String placeholder;
 208         final Object value;
 209         CpPatch(int index, String placeholder, Object value) {
 210             this.index = index;
 211             this.placeholder = placeholder;
 212             this.value = value;
 213         }
 214         public String toString() {
 215             return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value;
 216         }
 217     }
 218 
 219     Map<Object, CpPatch> cpPatches = new HashMap<>();
 220 
 221     int cph = 0;  // for counting constant placeholders
 222 
 223     String constantPlaceholder(Object arg) {
 224         String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++;
 225         if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>";  // debugging aid
 226         if (cpPatches.containsKey(cpPlaceholder)) {
 227             throw new InternalError("observed CP placeholder twice: " + cpPlaceholder);
 228         }
 229         // insert placeholder in CP and remember the patch
 230         int index = cw.newConst((Object) cpPlaceholder);  // TODO check if already in the constant pool
 231         cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg));
 232         return cpPlaceholder;
 233     }
 234 
 235     Object[] cpPatches(byte[] classFile) {
 236         int size = getConstantPoolSize(classFile);
 237         Object[] res = new Object[size];
 238         for (CpPatch p : cpPatches.values()) {
 239             if (p.index >= size)
 240                 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20)));
 241             res[p.index] = p.value;
 242         }
 243         return res;
 244     }
 245 
 246     private static String debugString(Object arg) {
 247         if (arg instanceof MethodHandle) {
 248             MethodHandle mh = (MethodHandle) arg;
 249             MemberName member = mh.internalMemberName();
 250             if (member != null)
 251                 return member.toString();
 252             return mh.debugString();
 253         }
 254         return arg.toString();
 255     }
 256 
 257     /**
 258      * Extract the number of constant pool entries from a given class file.
 259      *
 260      * @param classFile the bytes of the class file in question.
 261      * @return the number of entries in the constant pool.
 262      */
 263     private static int getConstantPoolSize(byte[] classFile) {
 264         // The first few bytes:
 265         // u4 magic;
 266         // u2 minor_version;
 267         // u2 major_version;
 268         // u2 constant_pool_count;
 269         return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF);
 270     }
 271 
 272     /**
 273      * Extract the MemberName of a newly-defined method.
 274      */
 275     private MemberName loadMethod(byte[] classFile) {
 276         Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile));
 277         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 278     }
 279 
 280     /**
 281      * Define a given class as anonymous class in the runtime system.
 282      */
 283     private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) {
 284         Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches);
 285         UNSAFE.ensureClassInitialized(invokerClass);  // Make sure the class is initialized; VM might complain.
 286         return invokerClass;
 287     }
 288 
 289     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 290         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 291         //System.out.println("resolveInvokerMember => "+member);
 292         //for (Method m : invokerClass.getDeclaredMethods())  System.out.println("  "+m);
 293         try {
 294             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
 295         } catch (ReflectiveOperationException e) {
 296             throw newInternalError(e);
 297         }
 298         //System.out.println("resolveInvokerMember => "+member);
 299         return member;
 300     }
 301 
 302     /**
 303      * Set up class file generation.
 304      */
 305     private void classFilePrologue() {
 306         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 307         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 308         cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null);
 309         cw.visitSource(sourceFile, null);
 310 
 311         String invokerDesc = invokerType.toMethodDescriptorString();
 312         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 313     }
 314 
 315     /**
 316      * Tear down class file generation.
 317      */
 318     private void classFileEpilogue() {
 319         mv.visitMaxs(0, 0);
 320         mv.visitEnd();
 321     }
 322 
 323     /*
 324      * Low-level emit helpers.
 325      */
 326     private void emitConst(Object con) {
 327         if (con == null) {
 328             mv.visitInsn(Opcodes.ACONST_NULL);
 329             return;
 330         }
 331         if (con instanceof Integer) {
 332             emitIconstInsn((int) con);
 333             return;
 334         }
 335         if (con instanceof Long) {
 336             long x = (long) con;
 337             if (x == (short) x) {
 338                 emitIconstInsn((int) x);
 339                 mv.visitInsn(Opcodes.I2L);
 340                 return;
 341             }
 342         }
 343         if (con instanceof Float) {
 344             float x = (float) con;
 345             if (x == (short) x) {
 346                 emitIconstInsn((int) x);
 347                 mv.visitInsn(Opcodes.I2F);
 348                 return;
 349             }
 350         }
 351         if (con instanceof Double) {
 352             double x = (double) con;
 353             if (x == (short) x) {
 354                 emitIconstInsn((int) x);
 355                 mv.visitInsn(Opcodes.I2D);
 356                 return;
 357             }
 358         }
 359         if (con instanceof Boolean) {
 360             emitIconstInsn((boolean) con ? 1 : 0);
 361             return;
 362         }
 363         // fall through:
 364         mv.visitLdcInsn(con);
 365     }
 366 
 367     private void emitIconstInsn(int i) {
 368         int opcode;
 369         switch (i) {
 370         case 0:  opcode = Opcodes.ICONST_0;  break;
 371         case 1:  opcode = Opcodes.ICONST_1;  break;
 372         case 2:  opcode = Opcodes.ICONST_2;  break;
 373         case 3:  opcode = Opcodes.ICONST_3;  break;
 374         case 4:  opcode = Opcodes.ICONST_4;  break;
 375         case 5:  opcode = Opcodes.ICONST_5;  break;
 376         default:
 377             if (i == (byte) i) {
 378                 mv.visitIntInsn(Opcodes.BIPUSH, i & 0xFF);
 379             } else if (i == (short) i) {
 380                 mv.visitIntInsn(Opcodes.SIPUSH, (char) i);
 381             } else {
 382                 mv.visitLdcInsn(i);
 383             }
 384             return;
 385         }
 386         mv.visitInsn(opcode);
 387     }
 388 
 389     /*
 390      * NOTE: These load/store methods use the localsMap to find the correct index!
 391      */
 392     private void emitLoadInsn(BasicType type, int index) {
 393         int opcode = loadInsnOpcode(type);
 394         mv.visitVarInsn(opcode, localsMap[index]);
 395     }
 396 
 397     private int loadInsnOpcode(BasicType type) throws InternalError {
 398         switch (type) {
 399             case I_TYPE: return Opcodes.ILOAD;
 400             case J_TYPE: return Opcodes.LLOAD;
 401             case F_TYPE: return Opcodes.FLOAD;
 402             case D_TYPE: return Opcodes.DLOAD;
 403             case L_TYPE: return Opcodes.ALOAD;
 404             default:
 405                 throw new InternalError("unknown type: " + type);
 406         }
 407     }
 408     private void emitAloadInsn(int index) {
 409         emitLoadInsn(L_TYPE, index);
 410     }
 411 
 412     private void emitStoreInsn(BasicType type, int index) {
 413         int opcode = storeInsnOpcode(type);
 414         mv.visitVarInsn(opcode, localsMap[index]);
 415     }
 416 
 417     private int storeInsnOpcode(BasicType type) throws InternalError {
 418         switch (type) {
 419             case I_TYPE: return Opcodes.ISTORE;
 420             case J_TYPE: return Opcodes.LSTORE;
 421             case F_TYPE: return Opcodes.FSTORE;
 422             case D_TYPE: return Opcodes.DSTORE;
 423             case L_TYPE: return Opcodes.ASTORE;
 424             default:
 425                 throw new InternalError("unknown type: " + type);
 426         }
 427     }
 428     private void emitAstoreInsn(int index) {
 429         emitStoreInsn(L_TYPE, index);
 430     }
 431 
 432     private byte arrayTypeCode(Wrapper elementType) {
 433         switch (elementType) {
 434             case BOOLEAN: return Opcodes.T_BOOLEAN;
 435             case BYTE:    return Opcodes.T_BYTE;
 436             case CHAR:    return Opcodes.T_CHAR;
 437             case SHORT:   return Opcodes.T_SHORT;
 438             case INT:     return Opcodes.T_INT;
 439             case LONG:    return Opcodes.T_LONG;
 440             case FLOAT:   return Opcodes.T_FLOAT;
 441             case DOUBLE:  return Opcodes.T_DOUBLE;
 442             case OBJECT:  return 0; // in place of Opcodes.T_OBJECT
 443             default:      throw new InternalError();
 444         }
 445     }
 446 
 447     private int arrayInsnOpcode(byte tcode, int aaop) throws InternalError {
 448         assert(aaop == Opcodes.AASTORE || aaop == Opcodes.AALOAD);
 449         int xas;
 450         switch (tcode) {
 451             case Opcodes.T_BOOLEAN: xas = Opcodes.BASTORE; break;
 452             case Opcodes.T_BYTE:    xas = Opcodes.BASTORE; break;
 453             case Opcodes.T_CHAR:    xas = Opcodes.CASTORE; break;
 454             case Opcodes.T_SHORT:   xas = Opcodes.SASTORE; break;
 455             case Opcodes.T_INT:     xas = Opcodes.IASTORE; break;
 456             case Opcodes.T_LONG:    xas = Opcodes.LASTORE; break;
 457             case Opcodes.T_FLOAT:   xas = Opcodes.FASTORE; break;
 458             case Opcodes.T_DOUBLE:  xas = Opcodes.DASTORE; break;
 459             case 0:                 xas = Opcodes.AASTORE; break;
 460             default:      throw new InternalError();
 461         }
 462         return xas - Opcodes.AASTORE + aaop;
 463     }
 464 
 465 
 466     private void freeFrameLocal(int oldFrameLocal) {
 467         int i = indexForFrameLocal(oldFrameLocal);
 468         if (i < 0)  return;
 469         BasicType type = localTypes[i];
 470         int newFrameLocal = makeLocalTemp(type);
 471         mv.visitVarInsn(loadInsnOpcode(type), oldFrameLocal);
 472         mv.visitVarInsn(storeInsnOpcode(type), newFrameLocal);
 473         assert(localsMap[i] == oldFrameLocal);
 474         localsMap[i] = newFrameLocal;
 475         assert(indexForFrameLocal(oldFrameLocal) < 0);
 476     }
 477     private int indexForFrameLocal(int frameLocal) {
 478         for (int i = 0; i < localsMap.length; i++) {
 479             if (localsMap[i] == frameLocal && localTypes[i] != V_TYPE)
 480                 return i;
 481         }
 482         return -1;
 483     }
 484     private int makeLocalTemp(BasicType type) {
 485         int frameLocal = localsMap[localsMap.length - 1];
 486         localsMap[localsMap.length - 1] = frameLocal + type.basicTypeSlots();
 487         return frameLocal;
 488     }
 489 
 490     /**
 491      * Emit a boxing call.
 492      *
 493      * @param wrapper primitive type class to box.
 494      */
 495     private void emitBoxing(Wrapper wrapper) {
 496         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 497         String name  = "valueOf";
 498         String desc  = "(" + wrapper.basicTypeChar() + ")L" + owner + ";";
 499         mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false);
 500     }
 501 
 502     /**
 503      * Emit an unboxing call (plus preceding checkcast).
 504      *
 505      * @param wrapper wrapper type class to unbox.
 506      */
 507     private void emitUnboxing(Wrapper wrapper) {
 508         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 509         String name  = wrapper.primitiveSimpleName() + "Value";
 510         String desc  = "()" + wrapper.basicTypeChar();
 511         emitReferenceCast(wrapper.wrapperType(), null);
 512         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false);
 513     }
 514 
 515     /**
 516      * Emit an implicit conversion for an argument which must be of the given pclass.
 517      * This is usually a no-op, except when pclass is a subword type or a reference other than Object or an interface.
 518      *
 519      * @param ptype type of value present on stack
 520      * @param pclass type of value required on stack
 521      * @param arg compile-time representation of value on stack (Node, constant) or null if none
 522      */
 523     private void emitImplicitConversion(BasicType ptype, Class<?> pclass, Object arg) {
 524         assert(basicType(pclass) == ptype);  // boxing/unboxing handled by caller
 525         if (pclass == ptype.basicTypeClass() && ptype != L_TYPE)
 526             return;   // nothing to do
 527         switch (ptype) {
 528             case L_TYPE:
 529                 if (VerifyType.isNullConversion(Object.class, pclass, false)) {
 530                     if (PROFILE_LEVEL > 0)
 531                         emitReferenceCast(Object.class, arg);
 532                     return;
 533                 }
 534                 emitReferenceCast(pclass, arg);
 535                 return;
 536             case I_TYPE:
 537                 if (!VerifyType.isNullConversion(int.class, pclass, false))
 538                     emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass));
 539                 return;
 540         }
 541         throw newInternalError("bad implicit conversion: tc="+ptype+": "+pclass);
 542     }
 543 
 544     /** Update localClasses type map.  Return true if the information is already present. */
 545     private boolean assertStaticType(Class<?> cls, Name n) {
 546         int local = n.index();
 547         Class<?> aclass = localClasses[local];
 548         if (aclass != null && (aclass == cls || cls.isAssignableFrom(aclass))) {
 549             return true;  // type info is already present
 550         } else if (aclass == null || aclass.isAssignableFrom(cls)) {
 551             localClasses[local] = cls;  // type info can be improved
 552         }
 553         return false;
 554     }
 555 
 556     private void emitReferenceCast(Class<?> cls, Object arg) {
 557         Name writeBack = null;  // local to write back result
 558         if (arg instanceof Name) {
 559             Name n = (Name) arg;
 560             if (assertStaticType(cls, n))
 561                 return;  // this cast was already performed
 562             if (lambdaForm.useCount(n) > 1) {
 563                 // This guy gets used more than once.
 564                 writeBack = n;
 565             }
 566         }
 567         if (isStaticallyNameable(cls)) {
 568             String sig = getInternalName(cls);
 569             mv.visitTypeInsn(Opcodes.CHECKCAST, sig);
 570         } else {
 571             mv.visitLdcInsn(constantPlaceholder(cls));
 572             mv.visitTypeInsn(Opcodes.CHECKCAST, CLS);
 573             mv.visitInsn(Opcodes.SWAP);
 574             mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "castReference", CLL_SIG, false);
 575             if (Object[].class.isAssignableFrom(cls))
 576                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 577             else if (PROFILE_LEVEL > 0)
 578                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ);
 579         }
 580         if (writeBack != null) {
 581             mv.visitInsn(Opcodes.DUP);
 582             emitAstoreInsn(writeBack.index());
 583         }
 584     }
 585 
 586     /**
 587      * Emits an actual return instruction conforming to the given return type.
 588      */
 589     private void emitReturnInsn(BasicType type) {
 590         int opcode;
 591         switch (type) {
 592         case I_TYPE:  opcode = Opcodes.IRETURN;  break;
 593         case J_TYPE:  opcode = Opcodes.LRETURN;  break;
 594         case F_TYPE:  opcode = Opcodes.FRETURN;  break;
 595         case D_TYPE:  opcode = Opcodes.DRETURN;  break;
 596         case L_TYPE:  opcode = Opcodes.ARETURN;  break;
 597         case V_TYPE:  opcode = Opcodes.RETURN;   break;
 598         default:
 599             throw new InternalError("unknown return type: " + type);
 600         }
 601         mv.visitInsn(opcode);
 602     }
 603 
 604     private static String getInternalName(Class<?> c) {
 605         if (c == Object.class)             return OBJ;
 606         else if (c == Object[].class)      return OBJARY;
 607         else if (c == Class.class)         return CLS;
 608         else if (c == MethodHandle.class)  return MH;
 609         assert(VerifyAccess.isTypeVisible(c, Object.class)) : c.getName();
 610         return c.getName().replace('.', '/');
 611     }
 612 
 613     /**
 614      * Generate customized bytecode for a given LambdaForm.
 615      */
 616     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 617         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 618         return g.loadMethod(g.generateCustomizedCodeBytes());
 619     }
 620 
 621     /** Determines whether a LambdaForm being compiled contains an intrinsic of some particular type. */
 622     private boolean containsIntrinsic(MethodHandleImpl.Intrinsic intr) {
 623         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 624             Name name = lambdaForm.names[i];
 625             if (name.function.intrinsicName() == intr) {
 626                 return true;
 627             }
 628         }
 629         return false;
 630     }
 631 
 632     /** Generates code to check that actual receiver and LambdaForm matches */
 633     private boolean checkActualReceiver() {
 634         // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0
 635         mv.visitInsn(Opcodes.DUP);
 636         mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]);
 637         mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false);
 638         return true;
 639     }
 640 
 641     /**
 642      * Generate an invoker method for the passed {@link LambdaForm}.
 643      */
 644     private byte[] generateCustomizedCodeBytes() {
 645         classFilePrologue();
 646 
 647         // Suppress this method in backtraces displayed to the user.
 648         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
 649 
 650         // Mark this method as a compiled LambdaForm
 651         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Compiled;", true);
 652 
 653         if (PROFILE_GWT && containsIntrinsic(MethodHandleImpl.Intrinsic.SELECT_ALTERNATIVE)) {
 654             // For now, mark only GWT LambdaForms as @Shared.
 655             // TODO: consider marking other non-customized LambdaForms as @Shared
 656             mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Shared;", true);
 657         }
 658 
 659         if (lambdaForm.forceInline) {
 660             // Force inlining of this invoker method.
 661             mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
 662         } else {
 663             mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true);
 664         }
 665 
 666         if (lambdaForm.customized != null) {
 667             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 668             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 669             // It enables more efficient code generation in some situations, since embedded constants
 670             // are compile-time constants for JIT compiler.
 671             mv.visitLdcInsn(constantPlaceholder(lambdaForm.customized));
 672             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 673             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 674             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 675         }
 676 
 677         // iterate over the form's names, generating bytecode instructions for each
 678         // start iterating at the first name following the arguments
 679         Name onStack = null;
 680         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 681             Name name = lambdaForm.names[i];
 682 
 683             emitStoreResult(onStack);
 684             onStack = name;  // unless otherwise modified below
 685             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 686             switch (intr) {
 687                 case SELECT_ALTERNATIVE:
 688                     assert isSelectAlternative(i);
 689                     onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
 690                     i++;  // skip MH.invokeBasic of the selectAlternative result
 691                     continue;
 692                 case GUARD_WITH_CATCH:
 693                     assert isGuardWithCatch(i);
 694                     onStack = emitGuardWithCatch(i);
 695                     i = i+2; // Jump to the end of GWC idiom
 696                     continue;
 697                 case NEW_ARRAY:
 698                     Class<?> rtype = name.function.methodType().returnType();
 699                     if (isStaticallyNameable(rtype)) {
 700                         emitNewArray(name);
 701                         continue;
 702                     }
 703                     break;
 704                 case ARRAY_LOAD:
 705                     emitArrayLoad(name);
 706                     continue;
 707                 case ARRAY_STORE:
 708                     emitArrayStore(name);
 709                     continue;
 710                 case IDENTITY:
 711                     assert(name.arguments.length == 1);
 712                     emitPushArguments(name);
 713                     continue;
 714                 case ZERO:
 715                     assert(name.arguments.length == 0);
 716                     emitConst(name.type.basicTypeWrapper().zero());
 717                     continue;
 718                 case NONE:
 719                     // no intrinsic associated
 720                     break;
 721                 default:
 722                     throw newInternalError("Unknown intrinsic: "+intr);
 723             }
 724 
 725             MemberName member = name.function.member();
 726             if (isStaticallyInvocable(member)) {
 727                 emitStaticInvoke(member, name);
 728             } else {
 729                 emitInvoke(name);
 730             }
 731         }
 732 
 733         // return statement
 734         emitReturn(onStack);
 735 
 736         classFileEpilogue();
 737         bogusMethod(lambdaForm);
 738 
 739         final byte[] classFile = cw.toByteArray();
 740         maybeDump(className, classFile);
 741         return classFile;
 742     }
 743 
 744     void emitArrayLoad(Name name)  { emitArrayOp(name, Opcodes.AALOAD);  }
 745     void emitArrayStore(Name name) { emitArrayOp(name, Opcodes.AASTORE); }
 746 
 747     void emitArrayOp(Name name, int arrayOpcode) {
 748         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE;
 749         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 750         assert elementType != null;
 751         emitPushArguments(name);
 752         if (elementType.isPrimitive()) {
 753             Wrapper w = Wrapper.forPrimitiveType(elementType);
 754             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 755         }
 756         mv.visitInsn(arrayOpcode);
 757     }
 758 
 759     /**
 760      * Emit an invoke for the given name.
 761      */
 762     void emitInvoke(Name name) {
 763         assert(!isLinkerMethodInvoke(name));  // should use the static path for these
 764         if (true) {
 765             // push receiver
 766             MethodHandle target = name.function.resolvedHandle;
 767             assert(target != null) : name.exprString();
 768             mv.visitLdcInsn(constantPlaceholder(target));
 769             emitReferenceCast(MethodHandle.class, target);
 770         } else {
 771             // load receiver
 772             emitAloadInsn(0);
 773             emitReferenceCast(MethodHandle.class, null);
 774             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 775             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 776             // TODO more to come
 777         }
 778 
 779         // push arguments
 780         emitPushArguments(name);
 781 
 782         // invocation
 783         MethodType type = name.function.methodType();
 784         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 785     }
 786 
 787     static private Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 788         // Sample classes from each package we are willing to bind to statically:
 789         java.lang.Object.class,
 790         java.util.Arrays.class,
 791         sun.misc.Unsafe.class
 792         //MethodHandle.class already covered
 793     };
 794 
 795     static boolean isStaticallyInvocable(Name name) {
 796         return isStaticallyInvocable(name.function.member());
 797     }
 798 
 799     static boolean isStaticallyInvocable(MemberName member) {
 800         if (member == null)  return false;
 801         if (member.isConstructor())  return false;
 802         Class<?> cls = member.getDeclaringClass();
 803         if (cls.isArray() || cls.isPrimitive())
 804             return false;  // FIXME
 805         if (cls.isAnonymousClass() || cls.isLocalClass())
 806             return false;  // inner class of some sort
 807         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 808             return false;  // not on BCP
 809         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 810             return false;
 811         MethodType mtype = member.getMethodOrFieldType();
 812         if (!isStaticallyNameable(mtype.returnType()))
 813             return false;
 814         for (Class<?> ptype : mtype.parameterArray())
 815             if (!isStaticallyNameable(ptype))
 816                 return false;
 817         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 818             return true;   // in java.lang.invoke package
 819         if (member.isPublic() && isStaticallyNameable(cls))
 820             return true;
 821         return false;
 822     }
 823 
 824     static boolean isStaticallyNameable(Class<?> cls) {
 825         if (cls == Object.class)
 826             return true;
 827         while (cls.isArray())
 828             cls = cls.getComponentType();
 829         if (cls.isPrimitive())
 830             return true;  // int[].class, for example
 831         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 832             return false;
 833         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 834         if (cls.getClassLoader() != Object.class.getClassLoader())
 835             return false;
 836         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 837             return true;
 838         if (!Modifier.isPublic(cls.getModifiers()))
 839             return false;
 840         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 841             if (VerifyAccess.isSamePackage(pkgcls, cls))
 842                 return true;
 843         }
 844         return false;
 845     }
 846 
 847     void emitStaticInvoke(Name name) {
 848         emitStaticInvoke(name.function.member(), name);
 849     }
 850 
 851     /**
 852      * Emit an invoke for the given name, using the MemberName directly.
 853      */
 854     void emitStaticInvoke(MemberName member, Name name) {
 855         assert(member.equals(name.function.member()));
 856         Class<?> defc = member.getDeclaringClass();
 857         String cname = getInternalName(defc);
 858         String mname = member.getName();
 859         String mtype;
 860         byte refKind = member.getReferenceKind();
 861         if (refKind == REF_invokeSpecial) {
 862             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
 863             assert(member.canBeStaticallyBound()) : member;
 864             refKind = REF_invokeVirtual;
 865         }
 866 
 867         if (member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual) {
 868             // Methods from Object declared in an interface can be resolved by JVM to invokevirtual kind.
 869             // Need to convert it back to invokeinterface to pass verification and make the invocation works as expected.
 870             refKind = REF_invokeInterface;
 871         }
 872 
 873         // push arguments
 874         emitPushArguments(name);
 875 
 876         // invocation
 877         if (member.isMethod()) {
 878             mtype = member.getMethodType().toMethodDescriptorString();
 879             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
 880                                member.getDeclaringClass().isInterface());
 881         } else {
 882             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
 883             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
 884         }
 885         // Issue a type assertion for the result, so we can avoid casts later.
 886         if (name.type == L_TYPE) {
 887             Class<?> rtype = member.getInvocationType().returnType();
 888             assert(!rtype.isPrimitive());
 889             if (rtype != Object.class && !rtype.isInterface()) {
 890                 assertStaticType(rtype, name);
 891             }
 892         }
 893     }
 894 
 895     void emitNewArray(Name name) throws InternalError {
 896         Class<?> rtype = name.function.methodType().returnType();
 897         if (name.arguments.length == 0) {
 898             // The array will be a constant.
 899             Object emptyArray;
 900             try {
 901                 emptyArray = name.function.resolvedHandle.invoke();
 902             } catch (Throwable ex) {
 903                 throw newInternalError(ex);
 904             }
 905             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
 906             assert(emptyArray.getClass() == rtype);  // exact typing
 907             mv.visitLdcInsn(constantPlaceholder(emptyArray));
 908             emitReferenceCast(rtype, emptyArray);
 909             return;
 910         }
 911         Class<?> arrayElementType = rtype.getComponentType();
 912         assert(arrayElementType != null);
 913         emitIconstInsn(name.arguments.length);
 914         int xas = Opcodes.AASTORE;
 915         if (!arrayElementType.isPrimitive()) {
 916             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
 917         } else {
 918             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
 919             xas = arrayInsnOpcode(tc, xas);
 920             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
 921         }
 922         // store arguments
 923         for (int i = 0; i < name.arguments.length; i++) {
 924             mv.visitInsn(Opcodes.DUP);
 925             emitIconstInsn(i);
 926             emitPushArgument(name, i);
 927             mv.visitInsn(xas);
 928         }
 929         // the array is left on the stack
 930         assertStaticType(rtype, name);
 931     }
 932     int refKindOpcode(byte refKind) {
 933         switch (refKind) {
 934         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
 935         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
 936         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
 937         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
 938         case REF_getField:           return Opcodes.GETFIELD;
 939         case REF_putField:           return Opcodes.PUTFIELD;
 940         case REF_getStatic:          return Opcodes.GETSTATIC;
 941         case REF_putStatic:          return Opcodes.PUTSTATIC;
 942         }
 943         throw new InternalError("refKind="+refKind);
 944     }
 945 
 946     /**
 947      * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}.
 948      */
 949     private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) {
 950         return member != null &&
 951                member.getDeclaringClass() == declaringClass &&
 952                member.getName().equals(name);
 953     }
 954     private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) {
 955         return name.function != null &&
 956                memberRefersTo(name.function.member(), declaringClass, methodName);
 957     }
 958 
 959     /**
 960      * Check if MemberName is a call to MethodHandle.invokeBasic.
 961      */
 962     private boolean isInvokeBasic(Name name) {
 963         if (name.function == null)
 964             return false;
 965         if (name.arguments.length < 1)
 966             return false;  // must have MH argument
 967         MemberName member = name.function.member();
 968         return memberRefersTo(member, MethodHandle.class, "invokeBasic") &&
 969                !member.isPublic() && !member.isStatic();
 970     }
 971 
 972     /**
 973      * Check if MemberName is a call to MethodHandle.linkToStatic, etc.
 974      */
 975     private boolean isLinkerMethodInvoke(Name name) {
 976         if (name.function == null)
 977             return false;
 978         if (name.arguments.length < 1)
 979             return false;  // must have MH argument
 980         MemberName member = name.function.member();
 981         return member != null &&
 982                member.getDeclaringClass() == MethodHandle.class &&
 983                !member.isPublic() && member.isStatic() &&
 984                member.getName().startsWith("linkTo");
 985     }
 986 
 987     /**
 988      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 989      */
 990     private boolean isSelectAlternative(int pos) {
 991         // selectAlternative idiom:
 992         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
 993         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 994         if (pos+1 >= lambdaForm.names.length)  return false;
 995         Name name0 = lambdaForm.names[pos];
 996         Name name1 = lambdaForm.names[pos+1];
 997         return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") &&
 998                isInvokeBasic(name1) &&
 999                name1.lastUseIndex(name0) == 0 &&        // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
1000                lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1}
1001     }
1002 
1003     /**
1004      * Check if i-th name is a start of GuardWithCatch idiom.
1005      */
1006     private boolean isGuardWithCatch(int pos) {
1007         // GuardWithCatch idiom:
1008         //   t_{n}:L=MethodHandle.invokeBasic(...)
1009         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
1010         //   t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
1011         if (pos+2 >= lambdaForm.names.length)  return false;
1012         Name name0 = lambdaForm.names[pos];
1013         Name name1 = lambdaForm.names[pos+1];
1014         Name name2 = lambdaForm.names[pos+2];
1015         return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") &&
1016                isInvokeBasic(name0) &&
1017                isInvokeBasic(name2) &&
1018                name1.lastUseIndex(name0) == 3 &&          // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
1019                lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1}
1020                name2.lastUseIndex(name1) == 1 &&          // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
1021                lambdaForm.lastUseIndex(name1) == pos+2;   // t_{n+1} is local: used only in t_{n+2}
1022     }
1023 
1024     /**
1025      * Emit bytecode for the selectAlternative idiom.
1026      *
1027      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
1028      * <blockquote><pre>{@code
1029      *   Lambda(a0:L,a1:I)=>{
1030      *     t2:I=foo.test(a1:I);
1031      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
1032      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
1033      * }</pre></blockquote>
1034      */
1035     private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
1036         assert isStaticallyInvocable(invokeBasicName);
1037 
1038         Name receiver = (Name) invokeBasicName.arguments[0];
1039 
1040         Label L_fallback = new Label();
1041         Label L_done     = new Label();
1042 
1043         // load test result
1044         emitPushArgument(selectAlternativeName, 0);
1045 
1046         if (PROFILE_GWT) {
1047             emitPushArgument(selectAlternativeName, 3);
1048             mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "profileBranch", "(Z[I)Z", false);
1049         }
1050 
1051         // if_icmpne L_fallback
1052         mv.visitJumpInsn(Opcodes.IFEQ, L_fallback);
1053 
1054         // invoke selectAlternativeName.arguments[1]
1055         Class<?>[] preForkClasses = localClasses.clone();
1056         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
1057         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1058         emitStaticInvoke(invokeBasicName);
1059 
1060         // goto L_done
1061         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1062 
1063         // L_fallback:
1064         mv.visitLabel(L_fallback);
1065 
1066         // invoke selectAlternativeName.arguments[2]
1067         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1068         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
1069         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1070         emitStaticInvoke(invokeBasicName);
1071 
1072         // L_done:
1073         mv.visitLabel(L_done);
1074         // for now do not bother to merge typestate; just reset to the dominator state
1075         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1076 
1077         return invokeBasicName;  // return what's on stack
1078     }
1079 
1080     /**
1081       * Emit bytecode for the guardWithCatch idiom.
1082       *
1083       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
1084       * <blockquote><pre>{@code
1085       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
1086       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
1087       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
1088       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
1089       * }</pre></blockquote>
1090       *
1091       * It is compiled into bytecode equivalent of the following code:
1092       * <blockquote><pre>{@code
1093       *  try {
1094       *      return a1.invokeBasic(a6, a7);
1095       *  } catch (Throwable e) {
1096       *      if (!a2.isInstance(e)) throw e;
1097       *      return a3.invokeBasic(ex, a6, a7);
1098       *  }}
1099       */
1100     private Name emitGuardWithCatch(int pos) {
1101         Name args    = lambdaForm.names[pos];
1102         Name invoker = lambdaForm.names[pos+1];
1103         Name result  = lambdaForm.names[pos+2];
1104 
1105         Label L_startBlock = new Label();
1106         Label L_endBlock = new Label();
1107         Label L_handler = new Label();
1108         Label L_done = new Label();
1109 
1110         Class<?> returnType = result.function.resolvedHandle.type().returnType();
1111         MethodType type = args.function.resolvedHandle.type()
1112                               .dropParameterTypes(0,1)
1113                               .changeReturnType(returnType);
1114 
1115         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
1116 
1117         // Normal case
1118         mv.visitLabel(L_startBlock);
1119         // load target
1120         emitPushArgument(invoker, 0);
1121         emitPushArguments(args, 1); // skip 1st argument: method handle
1122         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1123         mv.visitLabel(L_endBlock);
1124         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1125 
1126         // Exceptional case
1127         mv.visitLabel(L_handler);
1128 
1129         // Check exception's type
1130         mv.visitInsn(Opcodes.DUP);
1131         // load exception class
1132         emitPushArgument(invoker, 1);
1133         mv.visitInsn(Opcodes.SWAP);
1134         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
1135         Label L_rethrow = new Label();
1136         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
1137 
1138         // Invoke catcher
1139         // load catcher
1140         emitPushArgument(invoker, 2);
1141         mv.visitInsn(Opcodes.SWAP);
1142         emitPushArguments(args, 1); // skip 1st argument: method handle
1143         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
1144         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
1145         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1146 
1147         mv.visitLabel(L_rethrow);
1148         mv.visitInsn(Opcodes.ATHROW);
1149 
1150         mv.visitLabel(L_done);
1151 
1152         return result;
1153     }
1154 
1155     private void emitPushArguments(Name args) {
1156         emitPushArguments(args, 0);
1157     }
1158 
1159     private void emitPushArguments(Name args, int start) {
1160         for (int i = start; i < args.arguments.length; i++) {
1161             emitPushArgument(args, i);
1162         }
1163     }
1164 
1165     private void emitPushArgument(Name name, int paramIndex) {
1166         Object arg = name.arguments[paramIndex];
1167         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1168         emitPushArgument(ptype, arg);
1169     }
1170 
1171     private void emitPushArgument(Class<?> ptype, Object arg) {
1172         BasicType bptype = basicType(ptype);
1173         if (arg instanceof Name) {
1174             Name n = (Name) arg;
1175             emitLoadInsn(n.type, n.index());
1176             emitImplicitConversion(n.type, ptype, n);
1177         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1178             emitConst(arg);
1179         } else {
1180             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1181                 emitConst(arg);
1182             } else {
1183                 mv.visitLdcInsn(constantPlaceholder(arg));
1184                 emitImplicitConversion(L_TYPE, ptype, arg);
1185             }
1186         }
1187     }
1188 
1189     /**
1190      * Store the name to its local, if necessary.
1191      */
1192     private void emitStoreResult(Name name) {
1193         if (name != null && name.type != V_TYPE) {
1194             // non-void: actually assign
1195             emitStoreInsn(name.type, name.index());
1196         }
1197     }
1198 
1199     /**
1200      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1201      */
1202     private void emitReturn(Name onStack) {
1203         // return statement
1204         Class<?> rclass = invokerType.returnType();
1205         BasicType rtype = lambdaForm.returnType();
1206         assert(rtype == basicType(rclass));  // must agree
1207         if (rtype == V_TYPE) {
1208             // void
1209             mv.visitInsn(Opcodes.RETURN);
1210             // it doesn't matter what rclass is; the JVM will discard any value
1211         } else {
1212             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
1213 
1214             // put return value on the stack if it is not already there
1215             if (rn != onStack) {
1216                 emitLoadInsn(rtype, lambdaForm.result);
1217             }
1218 
1219             emitImplicitConversion(rtype, rclass, rn);
1220 
1221             // generate actual return statement
1222             emitReturnInsn(rtype);
1223         }
1224     }
1225 
1226     /**
1227      * Emit a type conversion bytecode casting from "from" to "to".
1228      */
1229     private void emitPrimCast(Wrapper from, Wrapper to) {
1230         // Here's how.
1231         // -   indicates forbidden
1232         // <-> indicates implicit
1233         //      to ----> boolean  byte     short    char     int      long     float    double
1234         // from boolean    <->        -        -        -        -        -        -        -
1235         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
1236         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
1237         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
1238         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
1239         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
1240         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
1241         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
1242         if (from == to) {
1243             // no cast required, should be dead code anyway
1244             return;
1245         }
1246         if (from.isSubwordOrInt()) {
1247             // cast from {byte,short,char,int} to anything
1248             emitI2X(to);
1249         } else {
1250             // cast from {long,float,double} to anything
1251             if (to.isSubwordOrInt()) {
1252                 // cast to {byte,short,char,int}
1253                 emitX2I(from);
1254                 if (to.bitWidth() < 32) {
1255                     // targets other than int require another conversion
1256                     emitI2X(to);
1257                 }
1258             } else {
1259                 // cast to {long,float,double} - this is verbose
1260                 boolean error = false;
1261                 switch (from) {
1262                 case LONG:
1263                     switch (to) {
1264                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
1265                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
1266                     default:      error = true;               break;
1267                     }
1268                     break;
1269                 case FLOAT:
1270                     switch (to) {
1271                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
1272                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
1273                     default:      error = true;               break;
1274                     }
1275                     break;
1276                 case DOUBLE:
1277                     switch (to) {
1278                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
1279                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
1280                     default:      error = true;               break;
1281                     }
1282                     break;
1283                 default:
1284                     error = true;
1285                     break;
1286                 }
1287                 if (error) {
1288                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
1289                 }
1290             }
1291         }
1292     }
1293 
1294     private void emitI2X(Wrapper type) {
1295         switch (type) {
1296         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
1297         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
1298         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
1299         case INT:     /* naught */                break;
1300         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
1301         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
1302         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
1303         case BOOLEAN:
1304             // For compatibility with ValueConversions and explicitCastArguments:
1305             mv.visitInsn(Opcodes.ICONST_1);
1306             mv.visitInsn(Opcodes.IAND);
1307             break;
1308         default:   throw new InternalError("unknown type: " + type);
1309         }
1310     }
1311 
1312     private void emitX2I(Wrapper type) {
1313         switch (type) {
1314         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1315         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1316         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1317         default:      throw new InternalError("unknown type: " + type);
1318         }
1319     }
1320 
1321     /**
1322      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1323      */
1324     static MemberName generateLambdaFormInterpreterEntryPoint(String sig) {
1325         assert(isValidSignature(sig));
1326         String name = "interpret_"+signatureReturn(sig).basicTypeChar();
1327         MethodType type = signatureType(sig);  // sig includes leading argument
1328         type = type.changeParameterType(0, MethodHandle.class);
1329         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1330         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1331     }
1332 
1333     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1334         classFilePrologue();
1335 
1336         // Suppress this method in backtraces displayed to the user.
1337         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
1338 
1339         // Don't inline the interpreter entry.
1340         mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true);
1341 
1342         // create parameter array
1343         emitIconstInsn(invokerType.parameterCount());
1344         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1345 
1346         // fill parameter array
1347         for (int i = 0; i < invokerType.parameterCount(); i++) {
1348             Class<?> ptype = invokerType.parameterType(i);
1349             mv.visitInsn(Opcodes.DUP);
1350             emitIconstInsn(i);
1351             emitLoadInsn(basicType(ptype), i);
1352             // box if primitive type
1353             if (ptype.isPrimitive()) {
1354                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1355             }
1356             mv.visitInsn(Opcodes.AASTORE);
1357         }
1358         // invoke
1359         emitAloadInsn(0);
1360         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1361         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1362         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1363 
1364         // maybe unbox
1365         Class<?> rtype = invokerType.returnType();
1366         if (rtype.isPrimitive() && rtype != void.class) {
1367             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1368         }
1369 
1370         // return statement
1371         emitReturnInsn(basicType(rtype));
1372 
1373         classFileEpilogue();
1374         bogusMethod(invokerType);
1375 
1376         final byte[] classFile = cw.toByteArray();
1377         maybeDump(className, classFile);
1378         return classFile;
1379     }
1380 
1381     /**
1382      * Generate bytecode for a NamedFunction invoker.
1383      */
1384     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1385         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1386         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1387         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1388         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1389     }
1390 
1391     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1392         MethodType dstType = typeForm.erasedType();
1393         classFilePrologue();
1394 
1395         // Suppress this method in backtraces displayed to the user.
1396         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
1397 
1398         // Force inlining of this invoker method.
1399         mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
1400 
1401         // Load receiver
1402         emitAloadInsn(0);
1403 
1404         // Load arguments from array
1405         for (int i = 0; i < dstType.parameterCount(); i++) {
1406             emitAloadInsn(1);
1407             emitIconstInsn(i);
1408             mv.visitInsn(Opcodes.AALOAD);
1409 
1410             // Maybe unbox
1411             Class<?> dptype = dstType.parameterType(i);
1412             if (dptype.isPrimitive()) {
1413                 Class<?> sptype = dstType.basicType().wrap().parameterType(i);
1414                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1415                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1416                 emitUnboxing(srcWrapper);
1417                 emitPrimCast(srcWrapper, dstWrapper);
1418             }
1419         }
1420 
1421         // Invoke
1422         String targetDesc = dstType.basicType().toMethodDescriptorString();
1423         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1424 
1425         // Box primitive types
1426         Class<?> rtype = dstType.returnType();
1427         if (rtype != void.class && rtype.isPrimitive()) {
1428             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1429             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1430             // boolean casts not allowed
1431             emitPrimCast(srcWrapper, dstWrapper);
1432             emitBoxing(dstWrapper);
1433         }
1434 
1435         // If the return type is void we return a null reference.
1436         if (rtype == void.class) {
1437             mv.visitInsn(Opcodes.ACONST_NULL);
1438         }
1439         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1440 
1441         classFileEpilogue();
1442         bogusMethod(dstType);
1443 
1444         final byte[] classFile = cw.toByteArray();
1445         maybeDump(className, classFile);
1446         return classFile;
1447     }
1448 
1449     /**
1450      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1451      * for debugging purposes.
1452      */
1453     private void bogusMethod(Object... os) {
1454         if (DUMP_CLASS_FILES) {
1455             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1456             for (Object o : os) {
1457                 mv.visitLdcInsn(o.toString());
1458                 mv.visitInsn(Opcodes.POP);
1459             }
1460             mv.visitInsn(Opcodes.RETURN);
1461             mv.visitMaxs(0, 0);
1462             mv.visitEnd();
1463         }
1464     }
1465 }