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