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