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_INVOKE_INTERFACE:   // fall-through
 673             case DIRECT_INVOKE_SPECIAL:     // fall-through
 674             case DIRECT_INVOKE_STATIC:      // fall-through
 675             case DIRECT_INVOKE_STATIC_INIT: // fall-through
 676             case DIRECT_INVOKE_VIRTUAL:     return resolveFrom(name, invokerType, DirectMethodHandle.Holder.class);
 677         }
 678         return null;
 679     }
 680 
 681     /**
 682      * Generate customized bytecode for a given LambdaForm.
 683      */
 684     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 685         MemberName pregenerated = lookupPregenerated(form, invokerType);
 686         if (pregenerated != null)  return pregenerated; // pre-generated bytecode
 687 
 688         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 689         return g.loadMethod(g.generateCustomizedCodeBytes());
 690     }
 691 
 692     /** Generates code to check that actual receiver and LambdaForm matches */
 693     private boolean checkActualReceiver() {
 694         // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0
 695         mv.visitInsn(Opcodes.DUP);
 696         mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]);
 697         mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false);
 698         return true;
 699     }
 700 
 701     static String className(String cn) {
 702         assert checkClassName(cn): "Class not found: " + cn;
 703         return cn;
 704     }
 705 
 706     static boolean checkClassName(String cn) {
 707         Type tp = Type.getType(cn);
 708         // additional sanity so only valid "L;" descriptors work
 709         if (tp.getSort() != Type.OBJECT) {
 710             return false;
 711         }
 712         try {
 713             Class<?> c = Class.forName(tp.getClassName(), false, null);
 714             return true;
 715         } catch (ClassNotFoundException e) {
 716             return false;
 717         }
 718     }
 719 
 720     static final String  LF_HIDDEN_SIG = className("Ljava/lang/invoke/LambdaForm$Hidden;");
 721     static final String  LF_COMPILED_SIG = className("Ljava/lang/invoke/LambdaForm$Compiled;");
 722     static final String  FORCEINLINE_SIG = className("Ljdk/internal/vm/annotation/ForceInline;");
 723     static final String  DONTINLINE_SIG = className("Ljdk/internal/vm/annotation/DontInline;");
 724     static final String  INJECTEDPROFILE_SIG = className("Ljava/lang/invoke/InjectedProfile;");
 725 
 726     /**
 727      * Generate an invoker method for the passed {@link LambdaForm}.
 728      */
 729     private byte[] generateCustomizedCodeBytes() {
 730         classFilePrologue();
 731         addMethod();
 732         bogusMethod(lambdaForm);
 733 
 734         final byte[] classFile = toByteArray();
 735         maybeDump(classFile);
 736         return classFile;
 737     }
 738 
 739     void setClassWriter(ClassWriter cw) {
 740         this.cw = cw;
 741     }
 742 
 743     void addMethod() {
 744         methodPrologue();
 745 
 746         // Suppress this method in backtraces displayed to the user.
 747         mv.visitAnnotation(LF_HIDDEN_SIG, true);
 748 
 749         // Mark this method as a compiled LambdaForm
 750         mv.visitAnnotation(LF_COMPILED_SIG, true);
 751 
 752         if (lambdaForm.forceInline) {
 753             // Force inlining of this invoker method.
 754             mv.visitAnnotation(FORCEINLINE_SIG, true);
 755         } else {
 756             mv.visitAnnotation(DONTINLINE_SIG, true);
 757         }
 758 
 759         constantPlaceholder(lambdaForm); // keep LambdaForm instance & its compiled form lifetime tightly coupled.
 760 
 761         if (lambdaForm.customized != null) {
 762             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 763             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 764             // It enables more efficient code generation in some situations, since embedded constants
 765             // are compile-time constants for JIT compiler.
 766             mv.visitLdcInsn(constantPlaceholder(lambdaForm.customized));
 767             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 768             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 769             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 770         }
 771 
 772         // iterate over the form's names, generating bytecode instructions for each
 773         // start iterating at the first name following the arguments
 774         Name onStack = null;
 775         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 776             Name name = lambdaForm.names[i];
 777 
 778             emitStoreResult(onStack);
 779             onStack = name;  // unless otherwise modified below
 780             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 781             switch (intr) {
 782                 case SELECT_ALTERNATIVE:
 783                     assert lambdaForm.isSelectAlternative(i);
 784                     if (PROFILE_GWT) {
 785                         assert(name.arguments[0] instanceof Name &&
 786                                 ((Name)name.arguments[0]).refersTo(MethodHandleImpl.class, "profileBoolean"));
 787                         mv.visitAnnotation(INJECTEDPROFILE_SIG, true);
 788                     }
 789                     onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
 790                     i++;  // skip MH.invokeBasic of the selectAlternative result
 791                     continue;
 792                 case GUARD_WITH_CATCH:
 793                     assert lambdaForm.isGuardWithCatch(i);
 794                     onStack = emitGuardWithCatch(i);
 795                     i += 2; // jump to the end of GWC idiom
 796                     continue;
 797                 case TRY_FINALLY:
 798                     assert lambdaForm.isTryFinally(i);
 799                     onStack = emitTryFinally(i);
 800                     i += 2; // jump to the end of the TF idiom
 801                     continue;
 802                 case LOOP:
 803                     assert lambdaForm.isLoop(i);
 804                     onStack = emitLoop(i);
 805                     i += 2; // jump to the end of the LOOP idiom
 806                     continue;
 807                 case NEW_ARRAY:
 808                     Class<?> rtype = name.function.methodType().returnType();
 809                     if (isStaticallyNameable(rtype)) {
 810                         emitNewArray(name);
 811                         continue;
 812                     }
 813                     break;
 814                 case ARRAY_LOAD:
 815                     emitArrayLoad(name);
 816                     continue;
 817                 case ARRAY_STORE:
 818                     emitArrayStore(name);
 819                     continue;
 820                 case ARRAY_LENGTH:
 821                     emitArrayLength(name);
 822                     continue;
 823                 case IDENTITY:
 824                     assert(name.arguments.length == 1);
 825                     emitPushArguments(name, 0);
 826                     continue;
 827                 case ZERO:
 828                     assert(name.arguments.length == 0);
 829                     emitConst(name.type.basicTypeWrapper().zero());
 830                     continue;
 831                 case NONE:
 832                     // no intrinsic associated
 833                     break;
 834                 default:
 835                     throw newInternalError("Unknown intrinsic: "+intr);
 836             }
 837 
 838             MemberName member = name.function.member();
 839             if (isStaticallyInvocable(member)) {
 840                 emitStaticInvoke(member, name);
 841             } else {
 842                 emitInvoke(name);
 843             }
 844         }
 845 
 846         // return statement
 847         emitReturn(onStack);
 848 
 849         methodEpilogue();
 850     }
 851 
 852     /*
 853      * @throws BytecodeGenerationException if something goes wrong when
 854      *         generating the byte code
 855      */
 856     private byte[] toByteArray() {
 857         try {
 858             return cw.toByteArray();
 859         } catch (RuntimeException e) {
 860             throw new BytecodeGenerationException(e);
 861         }
 862     }
 863 
 864     @SuppressWarnings("serial")
 865     static final class BytecodeGenerationException extends RuntimeException {
 866         BytecodeGenerationException(Exception cause) {
 867             super(cause);
 868         }
 869     }
 870 
 871     void emitArrayLoad(Name name)   { emitArrayOp(name, Opcodes.AALOAD);      }
 872     void emitArrayStore(Name name)  { emitArrayOp(name, Opcodes.AASTORE);     }
 873     void emitArrayLength(Name name) { emitArrayOp(name, Opcodes.ARRAYLENGTH); }
 874 
 875     void emitArrayOp(Name name, int arrayOpcode) {
 876         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
 877         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 878         assert elementType != null;
 879         emitPushArguments(name, 0);
 880         if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
 881             Wrapper w = Wrapper.forPrimitiveType(elementType);
 882             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 883         }
 884         mv.visitInsn(arrayOpcode);
 885     }
 886 
 887     /**
 888      * Emit an invoke for the given name.
 889      */
 890     void emitInvoke(Name name) {
 891         assert(!name.isLinkerMethodInvoke());  // should use the static path for these
 892         if (true) {
 893             // push receiver
 894             MethodHandle target = name.function.resolvedHandle();
 895             assert(target != null) : name.exprString();
 896             mv.visitLdcInsn(constantPlaceholder(target));
 897             emitReferenceCast(MethodHandle.class, target);
 898         } else {
 899             // load receiver
 900             emitAloadInsn(0);
 901             emitReferenceCast(MethodHandle.class, null);
 902             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 903             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 904             // TODO more to come
 905         }
 906 
 907         // push arguments
 908         emitPushArguments(name, 0);
 909 
 910         // invocation
 911         MethodType type = name.function.methodType();
 912         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 913     }
 914 
 915     private static Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 916         // Sample classes from each package we are willing to bind to statically:
 917         java.lang.Object.class,
 918         java.util.Arrays.class,
 919         jdk.internal.misc.Unsafe.class
 920         //MethodHandle.class already covered
 921     };
 922 
 923     static boolean isStaticallyInvocable(NamedFunction ... functions) {
 924         for (NamedFunction nf : functions) {
 925             if (!isStaticallyInvocable(nf.member())) {
 926                 return false;
 927             }
 928         }
 929         return true;
 930     }
 931 
 932     static boolean isStaticallyInvocable(Name name) {
 933         return isStaticallyInvocable(name.function.member());
 934     }
 935 
 936     static boolean isStaticallyInvocable(MemberName member) {
 937         if (member == null)  return false;
 938         if (member.isConstructor())  return false;
 939         Class<?> cls = member.getDeclaringClass();
 940         // Fast-path non-private members declared by MethodHandles, which is a common
 941         // case
 942         if (MethodHandle.class.isAssignableFrom(cls) && !member.isPrivate()) {
 943             assert(isStaticallyInvocableType(member.getMethodOrFieldType()));
 944             return true;
 945         }
 946         if (cls.isArray() || cls.isPrimitive())
 947             return false;  // FIXME
 948         if (cls.isAnonymousClass() || cls.isLocalClass())
 949             return false;  // inner class of some sort
 950         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 951             return false;  // not on BCP
 952         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 953             return false;
 954         if (!isStaticallyInvocableType(member.getMethodOrFieldType()))
 955             return false;
 956         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 957             return true;   // in java.lang.invoke package
 958         if (member.isPublic() && isStaticallyNameable(cls))
 959             return true;
 960         return false;
 961     }
 962 
 963     private static boolean isStaticallyInvocableType(MethodType mtype) {
 964         if (!isStaticallyNameable(mtype.returnType()))
 965             return false;
 966         for (Class<?> ptype : mtype.parameterArray())
 967             if (!isStaticallyNameable(ptype))
 968                 return false;
 969         return true;
 970     }
 971 
 972     static boolean isStaticallyNameable(Class<?> cls) {
 973         if (cls == Object.class)
 974             return true;
 975         if (MethodHandle.class.isAssignableFrom(cls)) {
 976             assert(!ReflectUtil.isVMAnonymousClass(cls));
 977             return true;
 978         }
 979         while (cls.isArray())
 980             cls = cls.getComponentType();
 981         if (cls.isPrimitive())
 982             return true;  // int[].class, for example
 983         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 984             return false;
 985         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 986         if (cls.getClassLoader() != Object.class.getClassLoader())
 987             return false;
 988         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 989             return true;
 990         if (!Modifier.isPublic(cls.getModifiers()))
 991             return false;
 992         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 993             if (VerifyAccess.isSamePackage(pkgcls, cls))
 994                 return true;
 995         }
 996         return false;
 997     }
 998 
 999     void emitStaticInvoke(Name name) {
1000         emitStaticInvoke(name.function.member(), name);
1001     }
1002 
1003     /**
1004      * Emit an invoke for the given name, using the MemberName directly.
1005      */
1006     void emitStaticInvoke(MemberName member, Name name) {
1007         assert(member.equals(name.function.member()));
1008         Class<?> defc = member.getDeclaringClass();
1009         String cname = getInternalName(defc);
1010         String mname = member.getName();
1011         String mtype;
1012         byte refKind = member.getReferenceKind();
1013         if (refKind == REF_invokeSpecial) {
1014             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
1015             assert(member.canBeStaticallyBound()) : member;
1016             refKind = REF_invokeVirtual;
1017         }
1018 
1019         assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual));
1020 
1021         // push arguments
1022         emitPushArguments(name, 0);
1023 
1024         // invocation
1025         if (member.isMethod()) {
1026             mtype = member.getMethodType().toMethodDescriptorString();
1027             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
1028                                member.getDeclaringClass().isInterface());
1029         } else {
1030             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
1031             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
1032         }
1033         // Issue a type assertion for the result, so we can avoid casts later.
1034         if (name.type == L_TYPE) {
1035             Class<?> rtype = member.getInvocationType().returnType();
1036             assert(!rtype.isPrimitive());
1037             if (rtype != Object.class && !rtype.isInterface()) {
1038                 assertStaticType(rtype, name);
1039             }
1040         }
1041     }
1042 
1043     void emitNewArray(Name name) throws InternalError {
1044         Class<?> rtype = name.function.methodType().returnType();
1045         if (name.arguments.length == 0) {
1046             // The array will be a constant.
1047             Object emptyArray;
1048             try {
1049                 emptyArray = name.function.resolvedHandle().invoke();
1050             } catch (Throwable ex) {
1051                 throw uncaughtException(ex);
1052             }
1053             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
1054             assert(emptyArray.getClass() == rtype);  // exact typing
1055             mv.visitLdcInsn(constantPlaceholder(emptyArray));
1056             emitReferenceCast(rtype, emptyArray);
1057             return;
1058         }
1059         Class<?> arrayElementType = rtype.getComponentType();
1060         assert(arrayElementType != null);
1061         emitIconstInsn(name.arguments.length);
1062         int xas = Opcodes.AASTORE;
1063         if (!arrayElementType.isPrimitive()) {
1064             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
1065         } else {
1066             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
1067             xas = arrayInsnOpcode(tc, xas);
1068             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
1069         }
1070         // store arguments
1071         for (int i = 0; i < name.arguments.length; i++) {
1072             mv.visitInsn(Opcodes.DUP);
1073             emitIconstInsn(i);
1074             emitPushArgument(name, i);
1075             mv.visitInsn(xas);
1076         }
1077         // the array is left on the stack
1078         assertStaticType(rtype, name);
1079     }
1080     int refKindOpcode(byte refKind) {
1081         switch (refKind) {
1082         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
1083         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
1084         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
1085         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
1086         case REF_getField:           return Opcodes.GETFIELD;
1087         case REF_putField:           return Opcodes.PUTFIELD;
1088         case REF_getStatic:          return Opcodes.GETSTATIC;
1089         case REF_putStatic:          return Opcodes.PUTSTATIC;
1090         }
1091         throw new InternalError("refKind="+refKind);
1092     }
1093 
1094     /**
1095      * Emit bytecode for the selectAlternative idiom.
1096      *
1097      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
1098      * <blockquote><pre>{@code
1099      *   Lambda(a0:L,a1:I)=>{
1100      *     t2:I=foo.test(a1:I);
1101      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
1102      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
1103      * }</pre></blockquote>
1104      */
1105     private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
1106         assert isStaticallyInvocable(invokeBasicName);
1107 
1108         Name receiver = (Name) invokeBasicName.arguments[0];
1109 
1110         Label L_fallback = new Label();
1111         Label L_done     = new Label();
1112 
1113         // load test result
1114         emitPushArgument(selectAlternativeName, 0);
1115 
1116         // if_icmpne L_fallback
1117         mv.visitJumpInsn(Opcodes.IFEQ, L_fallback);
1118 
1119         // invoke selectAlternativeName.arguments[1]
1120         Class<?>[] preForkClasses = localClasses.clone();
1121         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
1122         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1123         emitStaticInvoke(invokeBasicName);
1124 
1125         // goto L_done
1126         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1127 
1128         // L_fallback:
1129         mv.visitLabel(L_fallback);
1130 
1131         // invoke selectAlternativeName.arguments[2]
1132         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1133         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
1134         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1135         emitStaticInvoke(invokeBasicName);
1136 
1137         // L_done:
1138         mv.visitLabel(L_done);
1139         // for now do not bother to merge typestate; just reset to the dominator state
1140         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1141 
1142         return invokeBasicName;  // return what's on stack
1143     }
1144 
1145     /**
1146       * Emit bytecode for the guardWithCatch idiom.
1147       *
1148       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
1149       * <blockquote><pre>{@code
1150       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
1151       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
1152       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
1153       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
1154       * }</pre></blockquote>
1155       *
1156       * It is compiled into bytecode equivalent of the following code:
1157       * <blockquote><pre>{@code
1158       *  try {
1159       *      return a1.invokeBasic(a6, a7);
1160       *  } catch (Throwable e) {
1161       *      if (!a2.isInstance(e)) throw e;
1162       *      return a3.invokeBasic(ex, a6, a7);
1163       *  }}
1164       */
1165     private Name emitGuardWithCatch(int pos) {
1166         Name args    = lambdaForm.names[pos];
1167         Name invoker = lambdaForm.names[pos+1];
1168         Name result  = lambdaForm.names[pos+2];
1169 
1170         Label L_startBlock = new Label();
1171         Label L_endBlock = new Label();
1172         Label L_handler = new Label();
1173         Label L_done = new Label();
1174 
1175         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1176         MethodType type = args.function.resolvedHandle().type()
1177                               .dropParameterTypes(0,1)
1178                               .changeReturnType(returnType);
1179 
1180         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
1181 
1182         // Normal case
1183         mv.visitLabel(L_startBlock);
1184         // load target
1185         emitPushArgument(invoker, 0);
1186         emitPushArguments(args, 1); // skip 1st argument: method handle
1187         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1188         mv.visitLabel(L_endBlock);
1189         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1190 
1191         // Exceptional case
1192         mv.visitLabel(L_handler);
1193 
1194         // Check exception's type
1195         mv.visitInsn(Opcodes.DUP);
1196         // load exception class
1197         emitPushArgument(invoker, 1);
1198         mv.visitInsn(Opcodes.SWAP);
1199         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
1200         Label L_rethrow = new Label();
1201         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
1202 
1203         // Invoke catcher
1204         // load catcher
1205         emitPushArgument(invoker, 2);
1206         mv.visitInsn(Opcodes.SWAP);
1207         emitPushArguments(args, 1); // skip 1st argument: method handle
1208         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
1209         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
1210         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1211 
1212         mv.visitLabel(L_rethrow);
1213         mv.visitInsn(Opcodes.ATHROW);
1214 
1215         mv.visitLabel(L_done);
1216 
1217         return result;
1218     }
1219 
1220     /**
1221      * Emit bytecode for the tryFinally idiom.
1222      * <p>
1223      * The pattern looks like (Cf. MethodHandleImpl.makeTryFinally):
1224      * <blockquote><pre>{@code
1225      * // a0: BMH
1226      * // a1: target, a2: cleanup
1227      * // a3: box, a4: unbox
1228      * // a5 (and following): arguments
1229      * tryFinally=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L)=>{
1230      *   t6:L=MethodHandle.invokeBasic(a3:L,a5:L);         // box the arguments into an Object[]
1231      *   t7:L=MethodHandleImpl.tryFinally(a1:L,a2:L,t6:L); // call the tryFinally executor
1232      *   t8:L=MethodHandle.invokeBasic(a4:L,t7:L);t8:L}    // unbox the result; return the result
1233      * }</pre></blockquote>
1234      * <p>
1235      * It is compiled into bytecode equivalent to the following code:
1236      * <blockquote><pre>{@code
1237      * Throwable t;
1238      * Object r;
1239      * try {
1240      *     r = a1.invokeBasic(a5);
1241      * } catch (Throwable thrown) {
1242      *     t = thrown;
1243      *     throw t;
1244      * } finally {
1245      *     r = a2.invokeBasic(t, r, a5);
1246      * }
1247      * return r;
1248      * }</pre></blockquote>
1249      * <p>
1250      * Specifically, the bytecode will have the following form (the stack effects are given for the beginnings of
1251      * blocks, and for the situations after executing the given instruction - the code will have a slightly different
1252      * shape if the return type is {@code void}):
1253      * <blockquote><pre>{@code
1254      * TRY:                 (--)
1255      *                      load target                             (-- target)
1256      *                      load args                               (-- args... target)
1257      *                      INVOKEVIRTUAL MethodHandle.invokeBasic  (depends)
1258      * FINALLY_NORMAL:      (-- r)
1259      *                      load cleanup                            (-- cleanup r)
1260      *                      SWAP                                    (-- r cleanup)
1261      *                      ACONST_NULL                             (-- t r cleanup)
1262      *                      SWAP                                    (-- r t cleanup)
1263      *                      load args                               (-- args... r t cleanup)
1264      *                      INVOKEVIRTUAL MethodHandle.invokeBasic  (-- r)
1265      *                      GOTO DONE
1266      * CATCH:               (-- t)
1267      *                      DUP                                     (-- t t)
1268      * FINALLY_EXCEPTIONAL: (-- t t)
1269      *                      load cleanup                            (-- cleanup t t)
1270      *                      SWAP                                    (-- t cleanup t)
1271      *                      load default for r                      (-- r t cleanup t)
1272      *                      load args                               (-- args... r t cleanup t)
1273      *                      INVOKEVIRTUAL MethodHandle.invokeBasic  (-- r t)
1274      *                      POP                                     (-- t)
1275      *                      ATHROW
1276      * DONE:                (-- r)
1277      * }</pre></blockquote>
1278      */
1279     private Name emitTryFinally(int pos) {
1280         Name args    = lambdaForm.names[pos];
1281         Name invoker = lambdaForm.names[pos+1];
1282         Name result  = lambdaForm.names[pos+2];
1283 
1284         Label lFrom = new Label();
1285         Label lTo = new Label();
1286         Label lCatch = new Label();
1287         Label lDone = new Label();
1288 
1289         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1290         boolean isNonVoid = returnType != void.class;
1291         MethodType type = args.function.resolvedHandle().type()
1292                 .dropParameterTypes(0,1)
1293                 .changeReturnType(returnType);
1294         MethodType cleanupType = type.insertParameterTypes(0, Throwable.class);
1295         if (isNonVoid) {
1296             cleanupType = cleanupType.insertParameterTypes(1, returnType);
1297         }
1298         String cleanupDesc = cleanupType.basicType().toMethodDescriptorString();
1299 
1300         // exception handler table
1301         mv.visitTryCatchBlock(lFrom, lTo, lCatch, "java/lang/Throwable");
1302 
1303         // TRY:
1304         mv.visitLabel(lFrom);
1305         emitPushArgument(invoker, 0); // load target
1306         emitPushArguments(args, 1); // load args (skip 0: method handle)
1307         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1308         mv.visitLabel(lTo);
1309 
1310         // FINALLY_NORMAL:
1311         emitPushArgument(invoker, 1); // load cleanup
1312         if (isNonVoid) {
1313             mv.visitInsn(Opcodes.SWAP);
1314         }
1315         mv.visitInsn(Opcodes.ACONST_NULL);
1316         if (isNonVoid) {
1317             mv.visitInsn(Opcodes.SWAP);
1318         }
1319         emitPushArguments(args, 1); // load args (skip 0: method handle)
1320         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", cleanupDesc, false);
1321         mv.visitJumpInsn(Opcodes.GOTO, lDone);
1322 
1323         // CATCH:
1324         mv.visitLabel(lCatch);
1325         mv.visitInsn(Opcodes.DUP);
1326 
1327         // FINALLY_EXCEPTIONAL:
1328         emitPushArgument(invoker, 1); // load cleanup
1329         mv.visitInsn(Opcodes.SWAP);
1330         if (isNonVoid) {
1331             emitZero(BasicType.basicType(returnType)); // load default for result
1332         }
1333         emitPushArguments(args, 1); // load args (skip 0: method handle)
1334         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", cleanupDesc, false);
1335         if (isNonVoid) {
1336             mv.visitInsn(Opcodes.POP);
1337         }
1338         mv.visitInsn(Opcodes.ATHROW);
1339 
1340         // DONE:
1341         mv.visitLabel(lDone);
1342 
1343         return result;
1344     }
1345 
1346     /**
1347      * Emit bytecode for the loop idiom.
1348      * <p>
1349      * The pattern looks like (Cf. MethodHandleImpl.loop):
1350      * <blockquote><pre>{@code
1351      * // a0: BMH
1352      * // a1: LoopClauses (containing an array of arrays: inits, steps, preds, finis)
1353      * // a2: box, a3: unbox
1354      * // a4 (and following): arguments
1355      * loop=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L)=>{
1356      *   t5:L=MethodHandle.invokeBasic(a2:L,a4:L);          // box the arguments into an Object[]
1357      *   t6:L=MethodHandleImpl.loop(bt:L,a1:L,t5:L);        // call the loop executor (with supplied types in bt)
1358      *   t7:L=MethodHandle.invokeBasic(a3:L,t6:L);t7:L}     // unbox the result; return the result
1359      * }</pre></blockquote>
1360      * <p>
1361      * It is compiled into bytecode equivalent to the code seen in {@link MethodHandleImpl#loop(BasicType[],
1362      * MethodHandleImpl.LoopClauses, Object...)}, with the difference that no arrays
1363      * will be used for local state storage. Instead, the local state will be mapped to actual stack slots.
1364      * <p>
1365      * Bytecode generation applies an unrolling scheme to enable better bytecode generation regarding local state type
1366      * handling. The generated bytecode will have the following form ({@code void} types are ignored for convenience).
1367      * Assume there are {@code C} clauses in the loop.
1368      * <blockquote><pre>{@code
1369      * PREINIT: ALOAD_1
1370      *          CHECKCAST LoopClauses
1371      *          GETFIELD LoopClauses.clauses
1372      *          ASTORE clauseDataIndex          // place the clauses 2-dimensional array on the stack
1373      * INIT:    (INIT_SEQ for clause 1)
1374      *          ...
1375      *          (INIT_SEQ for clause C)
1376      * LOOP:    (LOOP_SEQ for clause 1)
1377      *          ...
1378      *          (LOOP_SEQ for clause C)
1379      *          GOTO LOOP
1380      * DONE:    ...
1381      * }</pre></blockquote>
1382      * <p>
1383      * The {@code INIT_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has
1384      * the following shape. Assume slot {@code vx} is used to hold the state for clause {@code x}.
1385      * <blockquote><pre>{@code
1386      * INIT_SEQ_x:  ALOAD clauseDataIndex
1387      *              ICONST_0
1388      *              AALOAD      // load the inits array
1389      *              ICONST x
1390      *              AALOAD      // load the init handle for clause x
1391      *              load args
1392      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1393      *              store vx
1394      * }</pre></blockquote>
1395      * <p>
1396      * The {@code LOOP_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has
1397      * the following shape. Again, assume slot {@code vx} is used to hold the state for clause {@code x}.
1398      * <blockquote><pre>{@code
1399      * LOOP_SEQ_x:  ALOAD clauseDataIndex
1400      *              ICONST_1
1401      *              AALOAD              // load the steps array
1402      *              ICONST x
1403      *              AALOAD              // load the step handle for clause x
1404      *              load locals
1405      *              load args
1406      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1407      *              store vx
1408      *              ALOAD clauseDataIndex
1409      *              ICONST_2
1410      *              AALOAD              // load the preds array
1411      *              ICONST x
1412      *              AALOAD              // load the pred handle for clause x
1413      *              load locals
1414      *              load args
1415      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1416      *              IFNE LOOP_SEQ_x+1   // predicate returned false -> jump to next clause
1417      *              ALOAD clauseDataIndex
1418      *              ICONST_3
1419      *              AALOAD              // load the finis array
1420      *              ICONST x
1421      *              AALOAD              // load the fini handle for clause x
1422      *              load locals
1423      *              load args
1424      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1425      *              GOTO DONE           // jump beyond end of clauses to return from loop
1426      * }</pre></blockquote>
1427      */
1428     private Name emitLoop(int pos) {
1429         Name args    = lambdaForm.names[pos];
1430         Name invoker = lambdaForm.names[pos+1];
1431         Name result  = lambdaForm.names[pos+2];
1432 
1433         // extract clause and loop-local state types
1434         // find the type info in the loop invocation
1435         BasicType[] loopClauseTypes = (BasicType[]) invoker.arguments[0];
1436         Class<?>[] loopLocalStateTypes = Stream.of(loopClauseTypes).
1437                 filter(bt -> bt != BasicType.V_TYPE).map(BasicType::basicTypeClass).toArray(Class<?>[]::new);
1438         Class<?>[] localTypes = new Class<?>[loopLocalStateTypes.length + 1];
1439         localTypes[0] = MethodHandleImpl.LoopClauses.class;
1440         System.arraycopy(loopLocalStateTypes, 0, localTypes, 1, loopLocalStateTypes.length);
1441 
1442         final int clauseDataIndex = extendLocalsMap(localTypes);
1443         final int firstLoopStateIndex = clauseDataIndex + 1;
1444 
1445         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1446         MethodType loopType = args.function.resolvedHandle().type()
1447                 .dropParameterTypes(0,1)
1448                 .changeReturnType(returnType);
1449         MethodType loopHandleType = loopType.insertParameterTypes(0, loopLocalStateTypes);
1450         MethodType predType = loopHandleType.changeReturnType(boolean.class);
1451         MethodType finiType = loopHandleType;
1452 
1453         final int nClauses = loopClauseTypes.length;
1454 
1455         // indices to invoker arguments to load method handle arrays
1456         final int inits = 1;
1457         final int steps = 2;
1458         final int preds = 3;
1459         final int finis = 4;
1460 
1461         Label lLoop = new Label();
1462         Label lDone = new Label();
1463         Label lNext;
1464 
1465         // PREINIT:
1466         emitPushArgument(MethodHandleImpl.LoopClauses.class, invoker.arguments[1]);
1467         mv.visitFieldInsn(Opcodes.GETFIELD, LOOP_CLAUSES, "clauses", MHARY2);
1468         emitAstoreInsn(clauseDataIndex);
1469 
1470         // INIT:
1471         for (int c = 0, state = 0; c < nClauses; ++c) {
1472             MethodType cInitType = loopType.changeReturnType(loopClauseTypes[c].basicTypeClass());
1473             emitLoopHandleInvoke(invoker, inits, c, args, false, cInitType, loopLocalStateTypes, clauseDataIndex,
1474                     firstLoopStateIndex);
1475             if (cInitType.returnType() != void.class) {
1476                 emitStoreInsn(BasicType.basicType(cInitType.returnType()), firstLoopStateIndex + state);
1477                 ++state;
1478             }
1479         }
1480 
1481         // LOOP:
1482         mv.visitLabel(lLoop);
1483 
1484         for (int c = 0, state = 0; c < nClauses; ++c) {
1485             lNext = new Label();
1486 
1487             MethodType stepType = loopHandleType.changeReturnType(loopClauseTypes[c].basicTypeClass());
1488             boolean isVoid = stepType.returnType() == void.class;
1489 
1490             // invoke loop step
1491             emitLoopHandleInvoke(invoker, steps, c, args, true, stepType, loopLocalStateTypes, clauseDataIndex,
1492                     firstLoopStateIndex);
1493             if (!isVoid) {
1494                 emitStoreInsn(BasicType.basicType(stepType.returnType()), firstLoopStateIndex + state);
1495                 ++state;
1496             }
1497 
1498             // invoke loop predicate
1499             emitLoopHandleInvoke(invoker, preds, c, args, true, predType, loopLocalStateTypes, clauseDataIndex,
1500                     firstLoopStateIndex);
1501             mv.visitJumpInsn(Opcodes.IFNE, lNext);
1502 
1503             // invoke fini
1504             emitLoopHandleInvoke(invoker, finis, c, args, true, finiType, loopLocalStateTypes, clauseDataIndex,
1505                     firstLoopStateIndex);
1506             mv.visitJumpInsn(Opcodes.GOTO, lDone);
1507 
1508             // this is the beginning of the next loop clause
1509             mv.visitLabel(lNext);
1510         }
1511 
1512         mv.visitJumpInsn(Opcodes.GOTO, lLoop);
1513 
1514         // DONE:
1515         mv.visitLabel(lDone);
1516 
1517         return result;
1518     }
1519 
1520     private int extendLocalsMap(Class<?>[] types) {
1521         int firstSlot = localsMap.length - 1;
1522         localsMap = Arrays.copyOf(localsMap, localsMap.length + types.length);
1523         localClasses = Arrays.copyOf(localClasses, localClasses.length + types.length);
1524         System.arraycopy(types, 0, localClasses, firstSlot, types.length);
1525         int index = localsMap[firstSlot - 1] + 1;
1526         int lastSlots = 0;
1527         for (int i = 0; i < types.length; ++i) {
1528             localsMap[firstSlot + i] = index;
1529             lastSlots = BasicType.basicType(localClasses[firstSlot + i]).basicTypeSlots();
1530             index += lastSlots;
1531         }
1532         localsMap[localsMap.length - 1] = index - lastSlots;
1533         return firstSlot;
1534     }
1535 
1536     private void emitLoopHandleInvoke(Name holder, int handles, int clause, Name args, boolean pushLocalState,
1537                                       MethodType type, Class<?>[] loopLocalStateTypes, int clauseDataSlot,
1538                                       int firstLoopStateSlot) {
1539         // load handle for clause
1540         emitPushClauseArray(clauseDataSlot, handles);
1541         emitIconstInsn(clause);
1542         mv.visitInsn(Opcodes.AALOAD);
1543         // load loop state (preceding the other arguments)
1544         if (pushLocalState) {
1545             for (int s = 0; s < loopLocalStateTypes.length; ++s) {
1546                 emitLoadInsn(BasicType.basicType(loopLocalStateTypes[s]), firstLoopStateSlot + s);
1547             }
1548         }
1549         // load loop args (skip 0: method handle)
1550         emitPushArguments(args, 1);
1551         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.toMethodDescriptorString(), false);
1552     }
1553 
1554     private void emitPushClauseArray(int clauseDataSlot, int which) {
1555         emitAloadInsn(clauseDataSlot);
1556         emitIconstInsn(which - 1);
1557         mv.visitInsn(Opcodes.AALOAD);
1558     }
1559 
1560     private void emitZero(BasicType type) {
1561         switch (type) {
1562             case I_TYPE: mv.visitInsn(Opcodes.ICONST_0); break;
1563             case J_TYPE: mv.visitInsn(Opcodes.LCONST_0); break;
1564             case F_TYPE: mv.visitInsn(Opcodes.FCONST_0); break;
1565             case D_TYPE: mv.visitInsn(Opcodes.DCONST_0); break;
1566             case L_TYPE: mv.visitInsn(Opcodes.ACONST_NULL); break;
1567             default: throw new InternalError("unknown type: " + type);
1568         }
1569     }
1570 
1571     private void emitPushArguments(Name args, int start) {
1572         MethodType type = args.function.methodType();
1573         for (int i = start; i < args.arguments.length; i++) {
1574             emitPushArgument(type.parameterType(i), args.arguments[i]);
1575         }
1576     }
1577 
1578     private void emitPushArgument(Name name, int paramIndex) {
1579         Object arg = name.arguments[paramIndex];
1580         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1581         emitPushArgument(ptype, arg);
1582     }
1583 
1584     private void emitPushArgument(Class<?> ptype, Object arg) {
1585         BasicType bptype = basicType(ptype);
1586         if (arg instanceof Name) {
1587             Name n = (Name) arg;
1588             emitLoadInsn(n.type, n.index());
1589             emitImplicitConversion(n.type, ptype, n);
1590         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1591             emitConst(arg);
1592         } else {
1593             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1594                 emitConst(arg);
1595             } else {
1596                 mv.visitLdcInsn(constantPlaceholder(arg));
1597                 emitImplicitConversion(L_TYPE, ptype, arg);
1598             }
1599         }
1600     }
1601 
1602     /**
1603      * Store the name to its local, if necessary.
1604      */
1605     private void emitStoreResult(Name name) {
1606         if (name != null && name.type != V_TYPE) {
1607             // non-void: actually assign
1608             emitStoreInsn(name.type, name.index());
1609         }
1610     }
1611 
1612     /**
1613      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1614      */
1615     private void emitReturn(Name onStack) {
1616         // return statement
1617         Class<?> rclass = invokerType.returnType();
1618         BasicType rtype = lambdaForm.returnType();
1619         assert(rtype == basicType(rclass));  // must agree
1620         if (rtype == V_TYPE) {
1621             // void
1622             mv.visitInsn(Opcodes.RETURN);
1623             // it doesn't matter what rclass is; the JVM will discard any value
1624         } else {
1625             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
1626 
1627             // put return value on the stack if it is not already there
1628             if (rn != onStack) {
1629                 emitLoadInsn(rtype, lambdaForm.result);
1630             }
1631 
1632             emitImplicitConversion(rtype, rclass, rn);
1633 
1634             // generate actual return statement
1635             emitReturnInsn(rtype);
1636         }
1637     }
1638 
1639     /**
1640      * Emit a type conversion bytecode casting from "from" to "to".
1641      */
1642     private void emitPrimCast(Wrapper from, Wrapper to) {
1643         // Here's how.
1644         // -   indicates forbidden
1645         // <-> indicates implicit
1646         //      to ----> boolean  byte     short    char     int      long     float    double
1647         // from boolean    <->        -        -        -        -        -        -        -
1648         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
1649         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
1650         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
1651         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
1652         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
1653         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
1654         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
1655         if (from == to) {
1656             // no cast required, should be dead code anyway
1657             return;
1658         }
1659         if (from.isSubwordOrInt()) {
1660             // cast from {byte,short,char,int} to anything
1661             emitI2X(to);
1662         } else {
1663             // cast from {long,float,double} to anything
1664             if (to.isSubwordOrInt()) {
1665                 // cast to {byte,short,char,int}
1666                 emitX2I(from);
1667                 if (to.bitWidth() < 32) {
1668                     // targets other than int require another conversion
1669                     emitI2X(to);
1670                 }
1671             } else {
1672                 // cast to {long,float,double} - this is verbose
1673                 boolean error = false;
1674                 switch (from) {
1675                 case LONG:
1676                     switch (to) {
1677                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
1678                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
1679                     default:      error = true;               break;
1680                     }
1681                     break;
1682                 case FLOAT:
1683                     switch (to) {
1684                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
1685                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
1686                     default:      error = true;               break;
1687                     }
1688                     break;
1689                 case DOUBLE:
1690                     switch (to) {
1691                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
1692                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
1693                     default:      error = true;               break;
1694                     }
1695                     break;
1696                 default:
1697                     error = true;
1698                     break;
1699                 }
1700                 if (error) {
1701                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
1702                 }
1703             }
1704         }
1705     }
1706 
1707     private void emitI2X(Wrapper type) {
1708         switch (type) {
1709         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
1710         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
1711         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
1712         case INT:     /* naught */                break;
1713         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
1714         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
1715         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
1716         case BOOLEAN:
1717             // For compatibility with ValueConversions and explicitCastArguments:
1718             mv.visitInsn(Opcodes.ICONST_1);
1719             mv.visitInsn(Opcodes.IAND);
1720             break;
1721         default:   throw new InternalError("unknown type: " + type);
1722         }
1723     }
1724 
1725     private void emitX2I(Wrapper type) {
1726         switch (type) {
1727         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1728         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1729         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1730         default:      throw new InternalError("unknown type: " + type);
1731         }
1732     }
1733 
1734     /**
1735      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1736      */
1737     static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
1738         assert(isValidSignature(basicTypeSignature(mt)));
1739         String name = "interpret_"+basicTypeChar(mt.returnType());
1740         MethodType type = mt;  // includes leading argument
1741         type = type.changeParameterType(0, MethodHandle.class);
1742         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1743         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1744     }
1745 
1746     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1747         classFilePrologue();
1748         methodPrologue();
1749 
1750         // Suppress this method in backtraces displayed to the user.
1751         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1752 
1753         // Don't inline the interpreter entry.
1754         mv.visitAnnotation(DONTINLINE_SIG, true);
1755 
1756         // create parameter array
1757         emitIconstInsn(invokerType.parameterCount());
1758         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1759 
1760         // fill parameter array
1761         for (int i = 0; i < invokerType.parameterCount(); i++) {
1762             Class<?> ptype = invokerType.parameterType(i);
1763             mv.visitInsn(Opcodes.DUP);
1764             emitIconstInsn(i);
1765             emitLoadInsn(basicType(ptype), i);
1766             // box if primitive type
1767             if (ptype.isPrimitive()) {
1768                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1769             }
1770             mv.visitInsn(Opcodes.AASTORE);
1771         }
1772         // invoke
1773         emitAloadInsn(0);
1774         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1775         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1776         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1777 
1778         // maybe unbox
1779         Class<?> rtype = invokerType.returnType();
1780         if (rtype.isPrimitive() && rtype != void.class) {
1781             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1782         }
1783 
1784         // return statement
1785         emitReturnInsn(basicType(rtype));
1786 
1787         methodEpilogue();
1788         bogusMethod(invokerType);
1789 
1790         final byte[] classFile = cw.toByteArray();
1791         maybeDump(classFile);
1792         return classFile;
1793     }
1794 
1795     /**
1796      * Generate bytecode for a NamedFunction invoker.
1797      */
1798     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1799         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1800         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1801         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1802         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1803     }
1804 
1805     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1806         MethodType dstType = typeForm.erasedType();
1807         classFilePrologue();
1808         methodPrologue();
1809 
1810         // Suppress this method in backtraces displayed to the user.
1811         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1812 
1813         // Force inlining of this invoker method.
1814         mv.visitAnnotation(FORCEINLINE_SIG, true);
1815 
1816         // Load receiver
1817         emitAloadInsn(0);
1818 
1819         // Load arguments from array
1820         for (int i = 0; i < dstType.parameterCount(); i++) {
1821             emitAloadInsn(1);
1822             emitIconstInsn(i);
1823             mv.visitInsn(Opcodes.AALOAD);
1824 
1825             // Maybe unbox
1826             Class<?> dptype = dstType.parameterType(i);
1827             if (dptype.isPrimitive()) {
1828                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1829                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1830                 emitUnboxing(srcWrapper);
1831                 emitPrimCast(srcWrapper, dstWrapper);
1832             }
1833         }
1834 
1835         // Invoke
1836         String targetDesc = dstType.basicType().toMethodDescriptorString();
1837         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1838 
1839         // Box primitive types
1840         Class<?> rtype = dstType.returnType();
1841         if (rtype != void.class && rtype.isPrimitive()) {
1842             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1843             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1844             // boolean casts not allowed
1845             emitPrimCast(srcWrapper, dstWrapper);
1846             emitBoxing(dstWrapper);
1847         }
1848 
1849         // If the return type is void we return a null reference.
1850         if (rtype == void.class) {
1851             mv.visitInsn(Opcodes.ACONST_NULL);
1852         }
1853         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1854 
1855         methodEpilogue();
1856         bogusMethod(dstType);
1857 
1858         final byte[] classFile = cw.toByteArray();
1859         maybeDump(classFile);
1860         return classFile;
1861     }
1862 
1863     /**
1864      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1865      * for debugging purposes.
1866      */
1867     private void bogusMethod(Object... os) {
1868         if (DUMP_CLASS_FILES) {
1869             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1870             for (Object o : os) {
1871                 mv.visitLdcInsn(o.toString());
1872                 mv.visitInsn(Opcodes.POP);
1873             }
1874             mv.visitInsn(Opcodes.RETURN);
1875             mv.visitMaxs(0, 0);
1876             mv.visitEnd();
1877         }
1878     }
1879 }