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