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