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         if (cls.isArray() || cls.isPrimitive())
 932             return false;  // FIXME
 933         if (cls.isAnonymousClass() || cls.isLocalClass())
 934             return false;  // inner class of some sort
 935         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 936             return false;  // not on BCP
 937         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 938             return false;
 939         MethodType mtype = member.getMethodOrFieldType();
 940         if (!isStaticallyNameable(mtype.returnType()))
 941             return false;
 942         for (Class<?> ptype : mtype.parameterArray())
 943             if (!isStaticallyNameable(ptype))
 944                 return false;
 945         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 946             return true;   // in java.lang.invoke package
 947         if (member.isPublic() && isStaticallyNameable(cls))
 948             return true;
 949         return false;
 950     }
 951 
 952     static boolean isStaticallyNameable(Class<?> cls) {
 953         if (cls == Object.class)
 954             return true;
 955         while (cls.isArray())
 956             cls = cls.getComponentType();
 957         if (cls.isPrimitive())
 958             return true;  // int[].class, for example
 959         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 960             return false;
 961         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 962         if (cls.getClassLoader() != Object.class.getClassLoader())
 963             return false;
 964         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 965             return true;
 966         if (!Modifier.isPublic(cls.getModifiers()))
 967             return false;
 968         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 969             if (VerifyAccess.isSamePackage(pkgcls, cls))
 970                 return true;
 971         }
 972         return false;
 973     }
 974 
 975     void emitStaticInvoke(Name name) {
 976         emitStaticInvoke(name.function.member(), name);
 977     }
 978 
 979     /**
 980      * Emit an invoke for the given name, using the MemberName directly.
 981      */
 982     void emitStaticInvoke(MemberName member, Name name) {
 983         assert(member.equals(name.function.member()));
 984         Class<?> defc = member.getDeclaringClass();
 985         String cname = getInternalName(defc);
 986         String mname = member.getName();
 987         String mtype;
 988         byte refKind = member.getReferenceKind();
 989         if (refKind == REF_invokeSpecial) {
 990             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
 991             assert(member.canBeStaticallyBound()) : member;
 992             refKind = REF_invokeVirtual;
 993         }
 994 
 995         assert(!(member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual));
 996 
 997         // push arguments
 998         emitPushArguments(name, 0);
 999 
1000         // invocation
1001         if (member.isMethod()) {
1002             mtype = member.getMethodType().toMethodDescriptorString();
1003             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
1004                                member.getDeclaringClass().isInterface());
1005         } else {
1006             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
1007             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
1008         }
1009         // Issue a type assertion for the result, so we can avoid casts later.
1010         if (name.type == L_TYPE) {
1011             Class<?> rtype = member.getInvocationType().returnType();
1012             assert(!rtype.isPrimitive());
1013             if (rtype != Object.class && !rtype.isInterface()) {
1014                 assertStaticType(rtype, name);
1015             }
1016         }
1017     }
1018 
1019     void emitNewArray(Name name) throws InternalError {
1020         Class<?> rtype = name.function.methodType().returnType();
1021         if (name.arguments.length == 0) {
1022             // The array will be a constant.
1023             Object emptyArray;
1024             try {
1025                 emptyArray = name.function.resolvedHandle().invoke();
1026             } catch (Throwable ex) {
1027                 throw uncaughtException(ex);
1028             }
1029             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
1030             assert(emptyArray.getClass() == rtype);  // exact typing
1031             mv.visitLdcInsn(constantPlaceholder(emptyArray));
1032             emitReferenceCast(rtype, emptyArray);
1033             return;
1034         }
1035         Class<?> arrayElementType = rtype.getComponentType();
1036         assert(arrayElementType != null);
1037         emitIconstInsn(name.arguments.length);
1038         int xas = Opcodes.AASTORE;
1039         if (!arrayElementType.isPrimitive()) {
1040             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
1041         } else {
1042             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
1043             xas = arrayInsnOpcode(tc, xas);
1044             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
1045         }
1046         // store arguments
1047         for (int i = 0; i < name.arguments.length; i++) {
1048             mv.visitInsn(Opcodes.DUP);
1049             emitIconstInsn(i);
1050             emitPushArgument(name, i);
1051             mv.visitInsn(xas);
1052         }
1053         // the array is left on the stack
1054         assertStaticType(rtype, name);
1055     }
1056     int refKindOpcode(byte refKind) {
1057         switch (refKind) {
1058         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
1059         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
1060         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
1061         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
1062         case REF_getField:           return Opcodes.GETFIELD;
1063         case REF_putField:           return Opcodes.PUTFIELD;
1064         case REF_getStatic:          return Opcodes.GETSTATIC;
1065         case REF_putStatic:          return Opcodes.PUTSTATIC;
1066         }
1067         throw new InternalError("refKind="+refKind);
1068     }
1069 
1070     /**
1071      * Emit bytecode for the selectAlternative idiom.
1072      *
1073      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
1074      * <blockquote><pre>{@code
1075      *   Lambda(a0:L,a1:I)=>{
1076      *     t2:I=foo.test(a1:I);
1077      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
1078      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
1079      * }</pre></blockquote>
1080      */
1081     private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
1082         assert isStaticallyInvocable(invokeBasicName);
1083 
1084         Name receiver = (Name) invokeBasicName.arguments[0];
1085 
1086         Label L_fallback = new Label();
1087         Label L_done     = new Label();
1088 
1089         // load test result
1090         emitPushArgument(selectAlternativeName, 0);
1091 
1092         // if_icmpne L_fallback
1093         mv.visitJumpInsn(Opcodes.IFEQ, L_fallback);
1094 
1095         // invoke selectAlternativeName.arguments[1]
1096         Class<?>[] preForkClasses = localClasses.clone();
1097         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
1098         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1099         emitStaticInvoke(invokeBasicName);
1100 
1101         // goto L_done
1102         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1103 
1104         // L_fallback:
1105         mv.visitLabel(L_fallback);
1106 
1107         // invoke selectAlternativeName.arguments[2]
1108         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1109         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
1110         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1111         emitStaticInvoke(invokeBasicName);
1112 
1113         // L_done:
1114         mv.visitLabel(L_done);
1115         // for now do not bother to merge typestate; just reset to the dominator state
1116         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1117 
1118         return invokeBasicName;  // return what's on stack
1119     }
1120 
1121     /**
1122       * Emit bytecode for the guardWithCatch idiom.
1123       *
1124       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
1125       * <blockquote><pre>{@code
1126       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
1127       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
1128       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
1129       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
1130       * }</pre></blockquote>
1131       *
1132       * It is compiled into bytecode equivalent of the following code:
1133       * <blockquote><pre>{@code
1134       *  try {
1135       *      return a1.invokeBasic(a6, a7);
1136       *  } catch (Throwable e) {
1137       *      if (!a2.isInstance(e)) throw e;
1138       *      return a3.invokeBasic(ex, a6, a7);
1139       *  }}
1140       */
1141     private Name emitGuardWithCatch(int pos) {
1142         Name args    = lambdaForm.names[pos];
1143         Name invoker = lambdaForm.names[pos+1];
1144         Name result  = lambdaForm.names[pos+2];
1145 
1146         Label L_startBlock = new Label();
1147         Label L_endBlock = new Label();
1148         Label L_handler = new Label();
1149         Label L_done = new Label();
1150 
1151         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1152         MethodType type = args.function.resolvedHandle().type()
1153                               .dropParameterTypes(0,1)
1154                               .changeReturnType(returnType);
1155 
1156         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
1157 
1158         // Normal case
1159         mv.visitLabel(L_startBlock);
1160         // load target
1161         emitPushArgument(invoker, 0);
1162         emitPushArguments(args, 1); // skip 1st argument: method handle
1163         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1164         mv.visitLabel(L_endBlock);
1165         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1166 
1167         // Exceptional case
1168         mv.visitLabel(L_handler);
1169 
1170         // Check exception's type
1171         mv.visitInsn(Opcodes.DUP);
1172         // load exception class
1173         emitPushArgument(invoker, 1);
1174         mv.visitInsn(Opcodes.SWAP);
1175         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
1176         Label L_rethrow = new Label();
1177         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
1178 
1179         // Invoke catcher
1180         // load catcher
1181         emitPushArgument(invoker, 2);
1182         mv.visitInsn(Opcodes.SWAP);
1183         emitPushArguments(args, 1); // skip 1st argument: method handle
1184         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
1185         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
1186         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1187 
1188         mv.visitLabel(L_rethrow);
1189         mv.visitInsn(Opcodes.ATHROW);
1190 
1191         mv.visitLabel(L_done);
1192 
1193         return result;
1194     }
1195 
1196     /**
1197      * Emit bytecode for the tryFinally idiom.
1198      * <p>
1199      * The pattern looks like (Cf. MethodHandleImpl.makeTryFinally):
1200      * <blockquote><pre>{@code
1201      * // a0: BMH
1202      * // a1: target, a2: cleanup
1203      * // a3: box, a4: unbox
1204      * // a5 (and following): arguments
1205      * tryFinally=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L)=>{
1206      *   t6:L=MethodHandle.invokeBasic(a3:L,a5:L);         // box the arguments into an Object[]
1207      *   t7:L=MethodHandleImpl.tryFinally(a1:L,a2:L,t6:L); // call the tryFinally executor
1208      *   t8:L=MethodHandle.invokeBasic(a4:L,t7:L);t8:L}    // unbox the result; return the result
1209      * }</pre></blockquote>
1210      * <p>
1211      * It is compiled into bytecode equivalent to the following code:
1212      * <blockquote><pre>{@code
1213      * Throwable t;
1214      * Object r;
1215      * try {
1216      *     r = a1.invokeBasic(a5);
1217      * } catch (Throwable thrown) {
1218      *     t = thrown;
1219      *     throw t;
1220      * } finally {
1221      *     r = a2.invokeBasic(t, r, a5);
1222      * }
1223      * return r;
1224      * }</pre></blockquote>
1225      * <p>
1226      * Specifically, the bytecode will have the following form (the stack effects are given for the beginnings of
1227      * blocks, and for the situations after executing the given instruction - the code will have a slightly different
1228      * shape if the return type is {@code void}):
1229      * <blockquote><pre>{@code
1230      * TRY:                 (--)
1231      *                      load target                             (-- target)
1232      *                      load args                               (-- args... target)
1233      *                      INVOKEVIRTUAL MethodHandle.invokeBasic  (depends)
1234      * FINALLY_NORMAL:      (-- r)
1235      *                      load cleanup                            (-- cleanup r)
1236      *                      SWAP                                    (-- r cleanup)
1237      *                      ACONST_NULL                             (-- t r cleanup)
1238      *                      SWAP                                    (-- r t cleanup)
1239      *                      load args                               (-- args... r t cleanup)
1240      *                      INVOKEVIRTUAL MethodHandle.invokeBasic  (-- r)
1241      *                      GOTO DONE
1242      * CATCH:               (-- t)
1243      *                      DUP                                     (-- t t)
1244      * FINALLY_EXCEPTIONAL: (-- t t)
1245      *                      load cleanup                            (-- cleanup t t)
1246      *                      SWAP                                    (-- t cleanup t)
1247      *                      load default for r                      (-- r t cleanup t)
1248      *                      load args                               (-- args... r t cleanup t)
1249      *                      INVOKEVIRTUAL MethodHandle.invokeBasic  (-- r t)
1250      *                      POP                                     (-- t)
1251      *                      ATHROW
1252      * DONE:                (-- r)
1253      * }</pre></blockquote>
1254      */
1255     private Name emitTryFinally(int pos) {
1256         Name args    = lambdaForm.names[pos];
1257         Name invoker = lambdaForm.names[pos+1];
1258         Name result  = lambdaForm.names[pos+2];
1259 
1260         Label lFrom = new Label();
1261         Label lTo = new Label();
1262         Label lCatch = new Label();
1263         Label lDone = new Label();
1264 
1265         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1266         boolean isNonVoid = returnType != void.class;
1267         MethodType type = args.function.resolvedHandle().type()
1268                 .dropParameterTypes(0,1)
1269                 .changeReturnType(returnType);
1270         MethodType cleanupType = type.insertParameterTypes(0, Throwable.class);
1271         if (isNonVoid) {
1272             cleanupType = cleanupType.insertParameterTypes(1, returnType);
1273         }
1274         String cleanupDesc = cleanupType.basicType().toMethodDescriptorString();
1275 
1276         // exception handler table
1277         mv.visitTryCatchBlock(lFrom, lTo, lCatch, "java/lang/Throwable");
1278 
1279         // TRY:
1280         mv.visitLabel(lFrom);
1281         emitPushArgument(invoker, 0); // load target
1282         emitPushArguments(args, 1); // load args (skip 0: method handle)
1283         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1284         mv.visitLabel(lTo);
1285 
1286         // FINALLY_NORMAL:
1287         emitPushArgument(invoker, 1); // load cleanup
1288         if (isNonVoid) {
1289             mv.visitInsn(Opcodes.SWAP);
1290         }
1291         mv.visitInsn(Opcodes.ACONST_NULL);
1292         if (isNonVoid) {
1293             mv.visitInsn(Opcodes.SWAP);
1294         }
1295         emitPushArguments(args, 1); // load args (skip 0: method handle)
1296         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", cleanupDesc, false);
1297         mv.visitJumpInsn(Opcodes.GOTO, lDone);
1298 
1299         // CATCH:
1300         mv.visitLabel(lCatch);
1301         mv.visitInsn(Opcodes.DUP);
1302 
1303         // FINALLY_EXCEPTIONAL:
1304         emitPushArgument(invoker, 1); // load cleanup
1305         mv.visitInsn(Opcodes.SWAP);
1306         if (isNonVoid) {
1307             emitZero(BasicType.basicType(returnType)); // load default for result
1308         }
1309         emitPushArguments(args, 1); // load args (skip 0: method handle)
1310         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", cleanupDesc, false);
1311         if (isNonVoid) {
1312             mv.visitInsn(Opcodes.POP);
1313         }
1314         mv.visitInsn(Opcodes.ATHROW);
1315 
1316         // DONE:
1317         mv.visitLabel(lDone);
1318 
1319         return result;
1320     }
1321 
1322     /**
1323      * Emit bytecode for the loop idiom.
1324      * <p>
1325      * The pattern looks like (Cf. MethodHandleImpl.loop):
1326      * <blockquote><pre>{@code
1327      * // a0: BMH
1328      * // a1: LoopClauses (containing an array of arrays: inits, steps, preds, finis)
1329      * // a2: box, a3: unbox
1330      * // a4 (and following): arguments
1331      * loop=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L)=>{
1332      *   t5:L=MethodHandle.invokeBasic(a2:L,a4:L);          // box the arguments into an Object[]
1333      *   t6:L=MethodHandleImpl.loop(bt:L,a1:L,t5:L);        // call the loop executor (with supplied types in bt)
1334      *   t7:L=MethodHandle.invokeBasic(a3:L,t6:L);t7:L}     // unbox the result; return the result
1335      * }</pre></blockquote>
1336      * <p>
1337      * It is compiled into bytecode equivalent to the code seen in {@link MethodHandleImpl#loop(BasicType[],
1338      * MethodHandleImpl.LoopClauses, Object...)}, with the difference that no arrays
1339      * will be used for local state storage. Instead, the local state will be mapped to actual stack slots.
1340      * <p>
1341      * Bytecode generation applies an unrolling scheme to enable better bytecode generation regarding local state type
1342      * handling. The generated bytecode will have the following form ({@code void} types are ignored for convenience).
1343      * Assume there are {@code C} clauses in the loop.
1344      * <blockquote><pre>{@code
1345      * PREINIT: ALOAD_1
1346      *          CHECKCAST LoopClauses
1347      *          GETFIELD LoopClauses.clauses
1348      *          ASTORE clauseDataIndex          // place the clauses 2-dimensional array on the stack
1349      * INIT:    (INIT_SEQ for clause 1)
1350      *          ...
1351      *          (INIT_SEQ for clause C)
1352      * LOOP:    (LOOP_SEQ for clause 1)
1353      *          ...
1354      *          (LOOP_SEQ for clause C)
1355      *          GOTO LOOP
1356      * DONE:    ...
1357      * }</pre></blockquote>
1358      * <p>
1359      * The {@code INIT_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has
1360      * the following shape. Assume slot {@code vx} is used to hold the state for clause {@code x}.
1361      * <blockquote><pre>{@code
1362      * INIT_SEQ_x:  ALOAD clauseDataIndex
1363      *              ICONST_0
1364      *              AALOAD      // load the inits array
1365      *              ICONST x
1366      *              AALOAD      // load the init handle for clause x
1367      *              load args
1368      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1369      *              store vx
1370      * }</pre></blockquote>
1371      * <p>
1372      * The {@code LOOP_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has
1373      * the following shape. Again, assume slot {@code vx} is used to hold the state for clause {@code x}.
1374      * <blockquote><pre>{@code
1375      * LOOP_SEQ_x:  ALOAD clauseDataIndex
1376      *              ICONST_1
1377      *              AALOAD              // load the steps array
1378      *              ICONST x
1379      *              AALOAD              // load the step handle for clause x
1380      *              load locals
1381      *              load args
1382      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1383      *              store vx
1384      *              ALOAD clauseDataIndex
1385      *              ICONST_2
1386      *              AALOAD              // load the preds array
1387      *              ICONST x
1388      *              AALOAD              // load the pred handle for clause x
1389      *              load locals
1390      *              load args
1391      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1392      *              IFNE LOOP_SEQ_x+1   // predicate returned false -> jump to next clause
1393      *              ALOAD clauseDataIndex
1394      *              ICONST_3
1395      *              AALOAD              // load the finis array
1396      *              ICONST x
1397      *              AALOAD              // load the fini handle for clause x
1398      *              load locals
1399      *              load args
1400      *              INVOKEVIRTUAL MethodHandle.invokeBasic
1401      *              GOTO DONE           // jump beyond end of clauses to return from loop
1402      * }</pre></blockquote>
1403      */
1404     private Name emitLoop(int pos) {
1405         Name args    = lambdaForm.names[pos];
1406         Name invoker = lambdaForm.names[pos+1];
1407         Name result  = lambdaForm.names[pos+2];
1408 
1409         // extract clause and loop-local state types
1410         // find the type info in the loop invocation
1411         BasicType[] loopClauseTypes = (BasicType[]) invoker.arguments[0];
1412         Class<?>[] loopLocalStateTypes = Stream.of(loopClauseTypes).
1413                 filter(bt -> bt != BasicType.V_TYPE).map(BasicType::basicTypeClass).toArray(Class<?>[]::new);
1414         Class<?>[] localTypes = new Class<?>[loopLocalStateTypes.length + 1];
1415         localTypes[0] = MethodHandleImpl.LoopClauses.class;
1416         System.arraycopy(loopLocalStateTypes, 0, localTypes, 1, loopLocalStateTypes.length);
1417 
1418         final int clauseDataIndex = extendLocalsMap(localTypes);
1419         final int firstLoopStateIndex = clauseDataIndex + 1;
1420 
1421         Class<?> returnType = result.function.resolvedHandle().type().returnType();
1422         MethodType loopType = args.function.resolvedHandle().type()
1423                 .dropParameterTypes(0,1)
1424                 .changeReturnType(returnType);
1425         MethodType loopHandleType = loopType.insertParameterTypes(0, loopLocalStateTypes);
1426         MethodType predType = loopHandleType.changeReturnType(boolean.class);
1427         MethodType finiType = loopHandleType;
1428 
1429         final int nClauses = loopClauseTypes.length;
1430 
1431         // indices to invoker arguments to load method handle arrays
1432         final int inits = 1;
1433         final int steps = 2;
1434         final int preds = 3;
1435         final int finis = 4;
1436 
1437         Label lLoop = new Label();
1438         Label lDone = new Label();
1439         Label lNext;
1440 
1441         // PREINIT:
1442         emitPushArgument(MethodHandleImpl.LoopClauses.class, invoker.arguments[1]);
1443         mv.visitFieldInsn(Opcodes.GETFIELD, LOOP_CLAUSES, "clauses", MHARY2);
1444         emitAstoreInsn(clauseDataIndex);
1445 
1446         // INIT:
1447         for (int c = 0, state = 0; c < nClauses; ++c) {
1448             MethodType cInitType = loopType.changeReturnType(loopClauseTypes[c].basicTypeClass());
1449             emitLoopHandleInvoke(invoker, inits, c, args, false, cInitType, loopLocalStateTypes, clauseDataIndex,
1450                     firstLoopStateIndex);
1451             if (cInitType.returnType() != void.class) {
1452                 emitStoreInsn(BasicType.basicType(cInitType.returnType()), firstLoopStateIndex + state);
1453                 ++state;
1454             }
1455         }
1456 
1457         // LOOP:
1458         mv.visitLabel(lLoop);
1459 
1460         for (int c = 0, state = 0; c < nClauses; ++c) {
1461             lNext = new Label();
1462 
1463             MethodType stepType = loopHandleType.changeReturnType(loopClauseTypes[c].basicTypeClass());
1464             boolean isVoid = stepType.returnType() == void.class;
1465 
1466             // invoke loop step
1467             emitLoopHandleInvoke(invoker, steps, c, args, true, stepType, loopLocalStateTypes, clauseDataIndex,
1468                     firstLoopStateIndex);
1469             if (!isVoid) {
1470                 emitStoreInsn(BasicType.basicType(stepType.returnType()), firstLoopStateIndex + state);
1471                 ++state;
1472             }
1473 
1474             // invoke loop predicate
1475             emitLoopHandleInvoke(invoker, preds, c, args, true, predType, loopLocalStateTypes, clauseDataIndex,
1476                     firstLoopStateIndex);
1477             mv.visitJumpInsn(Opcodes.IFNE, lNext);
1478 
1479             // invoke fini
1480             emitLoopHandleInvoke(invoker, finis, c, args, true, finiType, loopLocalStateTypes, clauseDataIndex,
1481                     firstLoopStateIndex);
1482             mv.visitJumpInsn(Opcodes.GOTO, lDone);
1483 
1484             // this is the beginning of the next loop clause
1485             mv.visitLabel(lNext);
1486         }
1487 
1488         mv.visitJumpInsn(Opcodes.GOTO, lLoop);
1489 
1490         // DONE:
1491         mv.visitLabel(lDone);
1492 
1493         return result;
1494     }
1495 
1496     private int extendLocalsMap(Class<?>[] types) {
1497         int firstSlot = localsMap.length - 1;
1498         localsMap = Arrays.copyOf(localsMap, localsMap.length + types.length);
1499         localClasses = Arrays.copyOf(localClasses, localClasses.length + types.length);
1500         System.arraycopy(types, 0, localClasses, firstSlot, types.length);
1501         int index = localsMap[firstSlot - 1] + 1;
1502         int lastSlots = 0;
1503         for (int i = 0; i < types.length; ++i) {
1504             localsMap[firstSlot + i] = index;
1505             lastSlots = BasicType.basicType(localClasses[firstSlot + i]).basicTypeSlots();
1506             index += lastSlots;
1507         }
1508         localsMap[localsMap.length - 1] = index - lastSlots;
1509         return firstSlot;
1510     }
1511 
1512     private void emitLoopHandleInvoke(Name holder, int handles, int clause, Name args, boolean pushLocalState,
1513                                       MethodType type, Class<?>[] loopLocalStateTypes, int clauseDataSlot,
1514                                       int firstLoopStateSlot) {
1515         // load handle for clause
1516         emitPushClauseArray(clauseDataSlot, handles);
1517         emitIconstInsn(clause);
1518         mv.visitInsn(Opcodes.AALOAD);
1519         // load loop state (preceding the other arguments)
1520         if (pushLocalState) {
1521             for (int s = 0; s < loopLocalStateTypes.length; ++s) {
1522                 emitLoadInsn(BasicType.basicType(loopLocalStateTypes[s]), firstLoopStateSlot + s);
1523             }
1524         }
1525         // load loop args (skip 0: method handle)
1526         emitPushArguments(args, 1);
1527         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.toMethodDescriptorString(), false);
1528     }
1529 
1530     private void emitPushClauseArray(int clauseDataSlot, int which) {
1531         emitAloadInsn(clauseDataSlot);
1532         emitIconstInsn(which - 1);
1533         mv.visitInsn(Opcodes.AALOAD);
1534     }
1535 
1536     private void emitZero(BasicType type) {
1537         switch (type) {
1538             case I_TYPE: mv.visitInsn(Opcodes.ICONST_0); break;
1539             case J_TYPE: mv.visitInsn(Opcodes.LCONST_0); break;
1540             case F_TYPE: mv.visitInsn(Opcodes.FCONST_0); break;
1541             case D_TYPE: mv.visitInsn(Opcodes.DCONST_0); break;
1542             case L_TYPE: mv.visitInsn(Opcodes.ACONST_NULL); break;
1543             default: throw new InternalError("unknown type: " + type);
1544         }
1545     }
1546 
1547     private void emitPushArguments(Name args, int start) {
1548         MethodType type = args.function.methodType();
1549         for (int i = start; i < args.arguments.length; i++) {
1550             emitPushArgument(type.parameterType(i), args.arguments[i]);
1551         }
1552     }
1553 
1554     private void emitPushArgument(Name name, int paramIndex) {
1555         Object arg = name.arguments[paramIndex];
1556         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1557         emitPushArgument(ptype, arg);
1558     }
1559 
1560     private void emitPushArgument(Class<?> ptype, Object arg) {
1561         BasicType bptype = basicType(ptype);
1562         if (arg instanceof Name) {
1563             Name n = (Name) arg;
1564             emitLoadInsn(n.type, n.index());
1565             emitImplicitConversion(n.type, ptype, n);
1566         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1567             emitConst(arg);
1568         } else {
1569             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1570                 emitConst(arg);
1571             } else {
1572                 mv.visitLdcInsn(constantPlaceholder(arg));
1573                 emitImplicitConversion(L_TYPE, ptype, arg);
1574             }
1575         }
1576     }
1577 
1578     /**
1579      * Store the name to its local, if necessary.
1580      */
1581     private void emitStoreResult(Name name) {
1582         if (name != null && name.type != V_TYPE) {
1583             // non-void: actually assign
1584             emitStoreInsn(name.type, name.index());
1585         }
1586     }
1587 
1588     /**
1589      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1590      */
1591     private void emitReturn(Name onStack) {
1592         // return statement
1593         Class<?> rclass = invokerType.returnType();
1594         BasicType rtype = lambdaForm.returnType();
1595         assert(rtype == basicType(rclass));  // must agree
1596         if (rtype == V_TYPE) {
1597             // void
1598             mv.visitInsn(Opcodes.RETURN);
1599             // it doesn't matter what rclass is; the JVM will discard any value
1600         } else {
1601             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
1602 
1603             // put return value on the stack if it is not already there
1604             if (rn != onStack) {
1605                 emitLoadInsn(rtype, lambdaForm.result);
1606             }
1607 
1608             emitImplicitConversion(rtype, rclass, rn);
1609 
1610             // generate actual return statement
1611             emitReturnInsn(rtype);
1612         }
1613     }
1614 
1615     /**
1616      * Emit a type conversion bytecode casting from "from" to "to".
1617      */
1618     private void emitPrimCast(Wrapper from, Wrapper to) {
1619         // Here's how.
1620         // -   indicates forbidden
1621         // <-> indicates implicit
1622         //      to ----> boolean  byte     short    char     int      long     float    double
1623         // from boolean    <->        -        -        -        -        -        -        -
1624         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
1625         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
1626         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
1627         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
1628         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
1629         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
1630         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
1631         if (from == to) {
1632             // no cast required, should be dead code anyway
1633             return;
1634         }
1635         if (from.isSubwordOrInt()) {
1636             // cast from {byte,short,char,int} to anything
1637             emitI2X(to);
1638         } else {
1639             // cast from {long,float,double} to anything
1640             if (to.isSubwordOrInt()) {
1641                 // cast to {byte,short,char,int}
1642                 emitX2I(from);
1643                 if (to.bitWidth() < 32) {
1644                     // targets other than int require another conversion
1645                     emitI2X(to);
1646                 }
1647             } else {
1648                 // cast to {long,float,double} - this is verbose
1649                 boolean error = false;
1650                 switch (from) {
1651                 case LONG:
1652                     switch (to) {
1653                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
1654                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
1655                     default:      error = true;               break;
1656                     }
1657                     break;
1658                 case FLOAT:
1659                     switch (to) {
1660                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
1661                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
1662                     default:      error = true;               break;
1663                     }
1664                     break;
1665                 case DOUBLE:
1666                     switch (to) {
1667                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
1668                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
1669                     default:      error = true;               break;
1670                     }
1671                     break;
1672                 default:
1673                     error = true;
1674                     break;
1675                 }
1676                 if (error) {
1677                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
1678                 }
1679             }
1680         }
1681     }
1682 
1683     private void emitI2X(Wrapper type) {
1684         switch (type) {
1685         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
1686         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
1687         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
1688         case INT:     /* naught */                break;
1689         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
1690         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
1691         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
1692         case BOOLEAN:
1693             // For compatibility with ValueConversions and explicitCastArguments:
1694             mv.visitInsn(Opcodes.ICONST_1);
1695             mv.visitInsn(Opcodes.IAND);
1696             break;
1697         default:   throw new InternalError("unknown type: " + type);
1698         }
1699     }
1700 
1701     private void emitX2I(Wrapper type) {
1702         switch (type) {
1703         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1704         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1705         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1706         default:      throw new InternalError("unknown type: " + type);
1707         }
1708     }
1709 
1710     /**
1711      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1712      */
1713     static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
1714         assert(isValidSignature(basicTypeSignature(mt)));
1715         String name = "interpret_"+basicTypeChar(mt.returnType());
1716         MethodType type = mt;  // includes leading argument
1717         type = type.changeParameterType(0, MethodHandle.class);
1718         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1719         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1720     }
1721 
1722     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1723         classFilePrologue();
1724         methodPrologue();
1725 
1726         // Suppress this method in backtraces displayed to the user.
1727         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1728 
1729         // Don't inline the interpreter entry.
1730         mv.visitAnnotation(DONTINLINE_SIG, true);
1731 
1732         // create parameter array
1733         emitIconstInsn(invokerType.parameterCount());
1734         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1735 
1736         // fill parameter array
1737         for (int i = 0; i < invokerType.parameterCount(); i++) {
1738             Class<?> ptype = invokerType.parameterType(i);
1739             mv.visitInsn(Opcodes.DUP);
1740             emitIconstInsn(i);
1741             emitLoadInsn(basicType(ptype), i);
1742             // box if primitive type
1743             if (ptype.isPrimitive()) {
1744                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1745             }
1746             mv.visitInsn(Opcodes.AASTORE);
1747         }
1748         // invoke
1749         emitAloadInsn(0);
1750         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1751         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1752         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1753 
1754         // maybe unbox
1755         Class<?> rtype = invokerType.returnType();
1756         if (rtype.isPrimitive() && rtype != void.class) {
1757             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1758         }
1759 
1760         // return statement
1761         emitReturnInsn(basicType(rtype));
1762 
1763         methodEpilogue();
1764         bogusMethod(invokerType);
1765 
1766         final byte[] classFile = cw.toByteArray();
1767         maybeDump(classFile);
1768         return classFile;
1769     }
1770 
1771     /**
1772      * Generate bytecode for a NamedFunction invoker.
1773      */
1774     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1775         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1776         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1777         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1778         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1779     }
1780 
1781     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1782         MethodType dstType = typeForm.erasedType();
1783         classFilePrologue();
1784         methodPrologue();
1785 
1786         // Suppress this method in backtraces displayed to the user.
1787         mv.visitAnnotation(LF_HIDDEN_SIG, true);
1788 
1789         // Force inlining of this invoker method.
1790         mv.visitAnnotation(FORCEINLINE_SIG, true);
1791 
1792         // Load receiver
1793         emitAloadInsn(0);
1794 
1795         // Load arguments from array
1796         for (int i = 0; i < dstType.parameterCount(); i++) {
1797             emitAloadInsn(1);
1798             emitIconstInsn(i);
1799             mv.visitInsn(Opcodes.AALOAD);
1800 
1801             // Maybe unbox
1802             Class<?> dptype = dstType.parameterType(i);
1803             if (dptype.isPrimitive()) {
1804                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1805                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1806                 emitUnboxing(srcWrapper);
1807                 emitPrimCast(srcWrapper, dstWrapper);
1808             }
1809         }
1810 
1811         // Invoke
1812         String targetDesc = dstType.basicType().toMethodDescriptorString();
1813         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1814 
1815         // Box primitive types
1816         Class<?> rtype = dstType.returnType();
1817         if (rtype != void.class && rtype.isPrimitive()) {
1818             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1819             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1820             // boolean casts not allowed
1821             emitPrimCast(srcWrapper, dstWrapper);
1822             emitBoxing(dstWrapper);
1823         }
1824 
1825         // If the return type is void we return a null reference.
1826         if (rtype == void.class) {
1827             mv.visitInsn(Opcodes.ACONST_NULL);
1828         }
1829         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1830 
1831         methodEpilogue();
1832         bogusMethod(dstType);
1833 
1834         final byte[] classFile = cw.toByteArray();
1835         maybeDump(classFile);
1836         return classFile;
1837     }
1838 
1839     /**
1840      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1841      * for debugging purposes.
1842      */
1843     private void bogusMethod(Object... os) {
1844         if (DUMP_CLASS_FILES) {
1845             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1846             for (Object o : os) {
1847                 mv.visitLdcInsn(o.toString());
1848                 mv.visitInsn(Opcodes.POP);
1849             }
1850             mv.visitInsn(Opcodes.RETURN);
1851             mv.visitMaxs(0, 0);
1852             mv.visitEnd();
1853         }
1854     }
1855 }