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