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