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