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