1 /*
   2  * Copyright (c) 2012, 2013, 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 java.io.*;
  29 import java.util.*;
  30 import java.lang.reflect.Modifier;
  31 
  32 import jdk.internal.org.objectweb.asm.*;
  33 
  34 import static java.lang.invoke.LambdaForm.*;
  35 import static java.lang.invoke.LambdaForm.BasicType.*;
  36 import static java.lang.invoke.MethodHandleStatics.*;
  37 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  38 
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 import sun.reflect.misc.ReflectUtil;
  43 
  44 /**
  45  * Code generation backend for LambdaForm.
  46  * <p>
  47  * @author John Rose, JSR 292 EG
  48  */
  49 class InvokerBytecodeGenerator {
  50     /** Define class names for convenience. */
  51     private static final String MH      = "java/lang/invoke/MethodHandle";
  52     private static final String MHI     = "java/lang/invoke/MethodHandleImpl";
  53     private static final String LF      = "java/lang/invoke/LambdaForm";
  54     private static final String LFN     = "java/lang/invoke/LambdaForm$Name";
  55     private static final String CLS     = "java/lang/Class";
  56     private static final String OBJ     = "java/lang/Object";
  57     private static final String OBJARY  = "[Ljava/lang/Object;";
  58 
  59     private static final String LF_SIG  = "L" + LF + ";";
  60     private static final String LFN_SIG = "L" + LFN + ";";
  61     private static final String LL_SIG  = "(L" + OBJ + ";)L" + OBJ + ";";
  62     private static final String CLL_SIG = "(L" + CLS + ";L" + OBJ + ";)L" + OBJ + ";";
  63 
  64     /** Name of its super class*/
  65     private static final String superName = OBJ;
  66 
  67     /** Name of new class */
  68     private final String className;
  69 
  70     /** Name of the source file (for stack trace printing). */
  71     private final String sourceFile;
  72 
  73     private final LambdaForm lambdaForm;
  74     private final String     invokerName;
  75     private final MethodType invokerType;
  76 
  77     /** Info about local variables in compiled lambda form */
  78     private final int[]       localsMap;    // index
  79     private final BasicType[] localTypes;   // basic type
  80     private final Class<?>[]  localClasses; // type
  81 
  82     /** ASM bytecode generation. */
  83     private ClassWriter cw;
  84     private MethodVisitor mv;
  85 
  86     private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory();
  87     private static final Class<?> HOST_CLASS = LambdaForm.class;
  88 
  89     /** Main constructor; other constructors delegate to this one. */
  90     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
  91                                      String className, String invokerName, MethodType invokerType) {
  92         if (invokerName.contains(".")) {
  93             int p = invokerName.indexOf('.');
  94             className = invokerName.substring(0, p);
  95             invokerName = invokerName.substring(p+1);
  96         }
  97         if (DUMP_CLASS_FILES) {
  98             className = makeDumpableClassName(className);
  99         }
 100         this.className  = LF + "$" + className;
 101         this.sourceFile = "LambdaForm$" + className;
 102         this.lambdaForm = lambdaForm;
 103         this.invokerName = invokerName;
 104         this.invokerType = invokerType;
 105         this.localsMap = new int[localsMapSize+1];
 106         // last entry of localsMap is count of allocated local slots
 107         this.localTypes = new BasicType[localsMapSize+1];
 108         this.localClasses = new Class<?>[localsMapSize+1];
 109     }
 110 
 111     /** For generating LambdaForm interpreter entry points. */
 112     private InvokerBytecodeGenerator(String className, String invokerName, MethodType invokerType) {
 113         this(null, invokerType.parameterCount(),
 114              className, invokerName, invokerType);
 115         // Create an array to map name indexes to locals indexes.
 116         localTypes[localTypes.length - 1] = V_TYPE;
 117         for (int i = 0; i < localsMap.length; i++) {
 118             localsMap[i] = invokerType.parameterSlotCount() - invokerType.parameterSlotDepth(i);
 119             if (i < invokerType.parameterCount())
 120                 localTypes[i] = basicType(invokerType.parameterType(i));
 121         }
 122     }
 123 
 124     /** For generating customized code for a single LambdaForm. */
 125     private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
 126         this(form, form.names.length,
 127              className, form.debugName, invokerType);
 128         // Create an array to map name indexes to locals indexes.
 129         Name[] names = form.names;
 130         for (int i = 0, index = 0; i < localsMap.length; i++) {
 131             localsMap[i] = index;
 132             if (i < names.length) {
 133                 BasicType type = names[i].type();
 134                 index += type.basicTypeSlots();
 135                 localTypes[i] = type;
 136             }
 137         }
 138     }
 139 
 140 
 141     /** instance counters for dumped classes */
 142     private final static HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS;
 143     /** debugging flag for saving generated class files */
 144     private final static File DUMP_CLASS_FILES_DIR;
 145 
 146     static {
 147         if (DUMP_CLASS_FILES) {
 148             DUMP_CLASS_FILES_COUNTERS = new HashMap<>();
 149             try {
 150                 File dumpDir = new File("DUMP_CLASS_FILES");
 151                 if (!dumpDir.exists()) {
 152                     dumpDir.mkdirs();
 153                 }
 154                 DUMP_CLASS_FILES_DIR = dumpDir;
 155                 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/...");
 156             } catch (Exception e) {
 157                 throw newInternalError(e);
 158             }
 159         } else {
 160             DUMP_CLASS_FILES_COUNTERS = null;
 161             DUMP_CLASS_FILES_DIR = null;
 162         }
 163     }
 164 
 165     static void maybeDump(final String className, final byte[] classFile) {
 166         if (DUMP_CLASS_FILES) {
 167             java.security.AccessController.doPrivileged(
 168             new java.security.PrivilegedAction<Void>() {
 169                 public Void run() {
 170                     try {
 171                         String dumpName = className;
 172                         //dumpName = dumpName.replace('/', '-');
 173                         File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class");
 174                         System.out.println("dump: " + dumpFile);
 175                         dumpFile.getParentFile().mkdirs();
 176                         FileOutputStream file = new FileOutputStream(dumpFile);
 177                         file.write(classFile);
 178                         file.close();
 179                         return null;
 180                     } catch (IOException ex) {
 181                         throw newInternalError(ex);
 182                     }
 183                 }
 184             });
 185         }
 186 
 187     }
 188 
 189     private static String makeDumpableClassName(String className) {
 190         Integer ctr;
 191         synchronized (DUMP_CLASS_FILES_COUNTERS) {
 192             ctr = DUMP_CLASS_FILES_COUNTERS.get(className);
 193             if (ctr == null)  ctr = 0;
 194             DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1);
 195         }
 196         String sfx = ctr.toString();
 197         while (sfx.length() < 3)
 198             sfx = "0"+sfx;
 199         className += sfx;
 200         return className;
 201     }
 202 
 203     class CpPatch {
 204         final int index;
 205         final String placeholder;
 206         final Object value;
 207         CpPatch(int index, String placeholder, Object value) {
 208             this.index = index;
 209             this.placeholder = placeholder;
 210             this.value = value;
 211         }
 212         public String toString() {
 213             return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value;
 214         }
 215     }
 216 
 217     Map<Object, CpPatch> cpPatches = new HashMap<>();
 218 
 219     int cph = 0;  // for counting constant placeholders
 220 
 221     String constantPlaceholder(Object arg) {
 222         String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++;
 223         if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>";  // debugging aid
 224         if (cpPatches.containsKey(cpPlaceholder)) {
 225             throw new InternalError("observed CP placeholder twice: " + cpPlaceholder);
 226         }
 227         // insert placeholder in CP and remember the patch
 228         int index = cw.newConst((Object) cpPlaceholder);  // TODO check if already in the constant pool
 229         cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg));
 230         return cpPlaceholder;
 231     }
 232 
 233     Object[] cpPatches(byte[] classFile) {
 234         int size = getConstantPoolSize(classFile);
 235         Object[] res = new Object[size];
 236         for (CpPatch p : cpPatches.values()) {
 237             if (p.index >= size)
 238                 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20)));
 239             res[p.index] = p.value;
 240         }
 241         return res;
 242     }
 243 
 244     private static String debugString(Object arg) {
 245         if (arg instanceof MethodHandle) {
 246             MethodHandle mh = (MethodHandle) arg;
 247             MemberName member = mh.internalMemberName();
 248             if (member != null)
 249                 return member.toString();
 250             return mh.debugString();
 251         }
 252         return arg.toString();
 253     }
 254 
 255     /**
 256      * Extract the number of constant pool entries from a given class file.
 257      *
 258      * @param classFile the bytes of the class file in question.
 259      * @return the number of entries in the constant pool.
 260      */
 261     private static int getConstantPoolSize(byte[] classFile) {
 262         // The first few bytes:
 263         // u4 magic;
 264         // u2 minor_version;
 265         // u2 major_version;
 266         // u2 constant_pool_count;
 267         return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF);
 268     }
 269 
 270     /**
 271      * Extract the MemberName of a newly-defined method.
 272      */
 273     private MemberName loadMethod(byte[] classFile) {
 274         Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile));
 275         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 276     }
 277 
 278     /**
 279      * Define a given class as anonymous class in the runtime system.
 280      */
 281     private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) {
 282         Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches);
 283         UNSAFE.ensureClassInitialized(invokerClass);  // Make sure the class is initialized; VM might complain.
 284         return invokerClass;
 285     }
 286 
 287     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 288         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 289         //System.out.println("resolveInvokerMember => "+member);
 290         //for (Method m : invokerClass.getDeclaredMethods())  System.out.println("  "+m);
 291         try {
 292             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
 293         } catch (ReflectiveOperationException e) {
 294             throw newInternalError(e);
 295         }
 296         //System.out.println("resolveInvokerMember => "+member);
 297         return member;
 298     }
 299 
 300     /**
 301      * Set up class file generation.
 302      */
 303     private void classFilePrologue() {
 304         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 305         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 306         cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null);
 307         cw.visitSource(sourceFile, null);
 308 
 309         String invokerDesc = invokerType.toMethodDescriptorString();
 310         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 311     }
 312 
 313     /**
 314      * Tear down class file generation.
 315      */
 316     private void classFileEpilogue() {
 317         mv.visitMaxs(0, 0);
 318         mv.visitEnd();
 319     }
 320 
 321     /*
 322      * Low-level emit helpers.
 323      */
 324     private void emitConst(Object con) {
 325         if (con == null) {
 326             mv.visitInsn(Opcodes.ACONST_NULL);
 327             return;
 328         }
 329         if (con instanceof Integer) {
 330             emitIconstInsn((int) con);
 331             return;
 332         }
 333         if (con instanceof Long) {
 334             long x = (long) con;
 335             if (x == (short) x) {
 336                 emitIconstInsn((int) x);
 337                 mv.visitInsn(Opcodes.I2L);
 338                 return;
 339             }
 340         }
 341         if (con instanceof Float) {
 342             float x = (float) con;
 343             if (x == (short) x) {
 344                 emitIconstInsn((int) x);
 345                 mv.visitInsn(Opcodes.I2F);
 346                 return;
 347             }
 348         }
 349         if (con instanceof Double) {
 350             double x = (double) con;
 351             if (x == (short) x) {
 352                 emitIconstInsn((int) x);
 353                 mv.visitInsn(Opcodes.I2D);
 354                 return;
 355             }
 356         }
 357         if (con instanceof Boolean) {
 358             emitIconstInsn((boolean) con ? 1 : 0);
 359             return;
 360         }
 361         // fall through:
 362         mv.visitLdcInsn(con);
 363     }
 364 
 365     private void emitIconstInsn(int i) {
 366         int opcode;
 367         switch (i) {
 368         case 0:  opcode = Opcodes.ICONST_0;  break;
 369         case 1:  opcode = Opcodes.ICONST_1;  break;
 370         case 2:  opcode = Opcodes.ICONST_2;  break;
 371         case 3:  opcode = Opcodes.ICONST_3;  break;
 372         case 4:  opcode = Opcodes.ICONST_4;  break;
 373         case 5:  opcode = Opcodes.ICONST_5;  break;
 374         default:
 375             if (i == (byte) i) {
 376                 mv.visitIntInsn(Opcodes.BIPUSH, i & 0xFF);
 377             } else if (i == (short) i) {
 378                 mv.visitIntInsn(Opcodes.SIPUSH, (char) i);
 379             } else {
 380                 mv.visitLdcInsn(i);
 381             }
 382             return;
 383         }
 384         mv.visitInsn(opcode);
 385     }
 386 
 387     /*
 388      * NOTE: These load/store methods use the localsMap to find the correct index!
 389      */
 390     private void emitLoadInsn(BasicType type, int index) {
 391         int opcode = loadInsnOpcode(type);
 392         mv.visitVarInsn(opcode, localsMap[index]);
 393     }
 394 
 395     private int loadInsnOpcode(BasicType type) throws InternalError {
 396         switch (type) {
 397             case I_TYPE: return Opcodes.ILOAD;
 398             case J_TYPE: return Opcodes.LLOAD;
 399             case F_TYPE: return Opcodes.FLOAD;
 400             case D_TYPE: return Opcodes.DLOAD;
 401             case L_TYPE: return Opcodes.ALOAD;
 402             default:
 403                 throw new InternalError("unknown type: " + type);
 404         }
 405     }
 406     private void emitAloadInsn(int index) {
 407         emitLoadInsn(L_TYPE, index);
 408     }
 409 
 410     private void emitStoreInsn(BasicType type, int index) {
 411         int opcode = storeInsnOpcode(type);
 412         mv.visitVarInsn(opcode, localsMap[index]);
 413     }
 414 
 415     private int storeInsnOpcode(BasicType type) throws InternalError {
 416         switch (type) {
 417             case I_TYPE: return Opcodes.ISTORE;
 418             case J_TYPE: return Opcodes.LSTORE;
 419             case F_TYPE: return Opcodes.FSTORE;
 420             case D_TYPE: return Opcodes.DSTORE;
 421             case L_TYPE: return Opcodes.ASTORE;
 422             default:
 423                 throw new InternalError("unknown type: " + type);
 424         }
 425     }
 426     private void emitAstoreInsn(int index) {
 427         emitStoreInsn(L_TYPE, index);
 428     }
 429 
 430     private byte arrayTypeCode(Wrapper elementType) {
 431         switch (elementType) {
 432             case BOOLEAN: return Opcodes.T_BOOLEAN;
 433             case BYTE:    return Opcodes.T_BYTE;
 434             case CHAR:    return Opcodes.T_CHAR;
 435             case SHORT:   return Opcodes.T_SHORT;
 436             case INT:     return Opcodes.T_INT;
 437             case LONG:    return Opcodes.T_LONG;
 438             case FLOAT:   return Opcodes.T_FLOAT;
 439             case DOUBLE:  return Opcodes.T_DOUBLE;
 440             case OBJECT:  return 0; // in place of Opcodes.T_OBJECT
 441             default:      throw new InternalError();
 442         }
 443     }
 444 
 445     private int arrayInsnOpcode(byte tcode, int aaop) throws InternalError {
 446         assert(aaop == Opcodes.AASTORE || aaop == Opcodes.AALOAD);
 447         int xas;
 448         switch (tcode) {
 449             case Opcodes.T_BOOLEAN: xas = Opcodes.BASTORE; break;
 450             case Opcodes.T_BYTE:    xas = Opcodes.BASTORE; break;
 451             case Opcodes.T_CHAR:    xas = Opcodes.CASTORE; break;
 452             case Opcodes.T_SHORT:   xas = Opcodes.SASTORE; break;
 453             case Opcodes.T_INT:     xas = Opcodes.IASTORE; break;
 454             case Opcodes.T_LONG:    xas = Opcodes.LASTORE; break;
 455             case Opcodes.T_FLOAT:   xas = Opcodes.FASTORE; break;
 456             case Opcodes.T_DOUBLE:  xas = Opcodes.DASTORE; break;
 457             case 0:                 xas = Opcodes.AASTORE; break;
 458             default:      throw new InternalError();
 459         }
 460         return xas - Opcodes.AASTORE + aaop;
 461     }
 462 
 463 
 464     private void freeFrameLocal(int oldFrameLocal) {
 465         int i = indexForFrameLocal(oldFrameLocal);
 466         if (i < 0)  return;
 467         BasicType type = localTypes[i];
 468         int newFrameLocal = makeLocalTemp(type);
 469         mv.visitVarInsn(loadInsnOpcode(type), oldFrameLocal);
 470         mv.visitVarInsn(storeInsnOpcode(type), newFrameLocal);
 471         assert(localsMap[i] == oldFrameLocal);
 472         localsMap[i] = newFrameLocal;
 473         assert(indexForFrameLocal(oldFrameLocal) < 0);
 474     }
 475     private int indexForFrameLocal(int frameLocal) {
 476         for (int i = 0; i < localsMap.length; i++) {
 477             if (localsMap[i] == frameLocal && localTypes[i] != V_TYPE)
 478                 return i;
 479         }
 480         return -1;
 481     }
 482     private int makeLocalTemp(BasicType type) {
 483         int frameLocal = localsMap[localsMap.length - 1];
 484         localsMap[localsMap.length - 1] = frameLocal + type.basicTypeSlots();
 485         return frameLocal;
 486     }
 487 
 488     /**
 489      * Emit a boxing call.
 490      *
 491      * @param wrapper primitive type class to box.
 492      */
 493     private void emitBoxing(Wrapper wrapper) {
 494         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 495         String name  = "valueOf";
 496         String desc  = "(" + wrapper.basicTypeChar() + ")L" + owner + ";";
 497         mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false);
 498     }
 499 
 500     /**
 501      * Emit an unboxing call (plus preceding checkcast).
 502      *
 503      * @param wrapper wrapper type class to unbox.
 504      */
 505     private void emitUnboxing(Wrapper wrapper) {
 506         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 507         String name  = wrapper.primitiveSimpleName() + "Value";
 508         String desc  = "()" + wrapper.basicTypeChar();
 509         emitReferenceCast(wrapper.wrapperType(), null);
 510         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false);
 511     }
 512 
 513     /**
 514      * Emit an implicit conversion for an argument which must be of the given pclass.
 515      * This is usually a no-op, except when pclass is a subword type or a reference other than Object or an interface.
 516      *
 517      * @param ptype type of value present on stack
 518      * @param pclass type of value required on stack
 519      * @param arg compile-time representation of value on stack (Node, constant) or null if none
 520      */
 521     private void emitImplicitConversion(BasicType ptype, Class<?> pclass, Object arg) {
 522         assert(basicType(pclass) == ptype);  // boxing/unboxing handled by caller
 523         if (pclass == ptype.basicTypeClass() && ptype != L_TYPE)
 524             return;   // nothing to do
 525         switch (ptype) {
 526             case L_TYPE:
 527                 if (VerifyType.isNullConversion(Object.class, pclass, false)) {
 528                     if (PROFILE_LEVEL > 0)
 529                         emitReferenceCast(Object.class, arg);
 530                     return;
 531                 }
 532                 emitReferenceCast(pclass, arg);
 533                 return;
 534             case I_TYPE:
 535                 if (!VerifyType.isNullConversion(int.class, pclass, false))
 536                     emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass));
 537                 return;
 538         }
 539         throw newInternalError("bad implicit conversion: tc="+ptype+": "+pclass);
 540     }
 541 
 542     /** Update localClasses type map.  Return true if the information is already present. */
 543     private boolean assertStaticType(Class<?> cls, Name n) {
 544         int local = n.index();
 545         Class<?> aclass = localClasses[local];
 546         if (aclass != null && (aclass == cls || cls.isAssignableFrom(aclass))) {
 547             return true;  // type info is already present
 548         } else if (aclass == null || aclass.isAssignableFrom(cls)) {
 549             localClasses[local] = cls;  // type info can be improved
 550         }
 551         return false;
 552     }
 553 
 554     private void emitReferenceCast(Class<?> cls, Object arg) {
 555         Name writeBack = null;  // local to write back result
 556         if (arg instanceof Name) {
 557             Name n = (Name) arg;
 558             if (assertStaticType(cls, n))
 559                 return;  // this cast was already performed
 560             if (lambdaForm.useCount(n) > 1) {
 561                 // This guy gets used more than once.
 562                 writeBack = n;
 563             }
 564         }
 565         if (isStaticallyNameable(cls)) {
 566             String sig = getInternalName(cls);
 567             mv.visitTypeInsn(Opcodes.CHECKCAST, sig);
 568         } else {
 569             mv.visitLdcInsn(constantPlaceholder(cls));
 570             mv.visitTypeInsn(Opcodes.CHECKCAST, CLS);
 571             mv.visitInsn(Opcodes.SWAP);
 572             mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "castReference", CLL_SIG, false);
 573             if (Object[].class.isAssignableFrom(cls))
 574                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 575             else if (PROFILE_LEVEL > 0)
 576                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ);
 577         }
 578         if (writeBack != null) {
 579             mv.visitInsn(Opcodes.DUP);
 580             emitAstoreInsn(writeBack.index());
 581         }
 582     }
 583 
 584     /**
 585      * Emits an actual return instruction conforming to the given return type.
 586      */
 587     private void emitReturnInsn(BasicType type) {
 588         int opcode;
 589         switch (type) {
 590         case I_TYPE:  opcode = Opcodes.IRETURN;  break;
 591         case J_TYPE:  opcode = Opcodes.LRETURN;  break;
 592         case F_TYPE:  opcode = Opcodes.FRETURN;  break;
 593         case D_TYPE:  opcode = Opcodes.DRETURN;  break;
 594         case L_TYPE:  opcode = Opcodes.ARETURN;  break;
 595         case V_TYPE:  opcode = Opcodes.RETURN;   break;
 596         default:
 597             throw new InternalError("unknown return type: " + type);
 598         }
 599         mv.visitInsn(opcode);
 600     }
 601 
 602     private static String getInternalName(Class<?> c) {
 603         if (c == Object.class)             return OBJ;
 604         else if (c == Object[].class)      return OBJARY;
 605         else if (c == Class.class)         return CLS;
 606         else if (c == MethodHandle.class)  return MH;
 607         assert(VerifyAccess.isTypeVisible(c, Object.class)) : c.getName();
 608         return c.getName().replace('.', '/');
 609     }
 610 
 611     /**
 612      * Generate customized bytecode for a given LambdaForm.
 613      */
 614     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 615         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 616         return g.loadMethod(g.generateCustomizedCodeBytes());
 617     }
 618 
 619     /** Determines whether a LambdaForm being compiled contains an intrinsic of some particular type. */
 620     private boolean containsIntrinsic(MethodHandleImpl.Intrinsic intr) {
 621         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 622             Name name = lambdaForm.names[i];
 623             if (name.function.intrinsicName() == intr) {
 624                 return true;
 625             }
 626         }
 627         return false;
 628     }
 629 
 630     /**
 631      * Generate an invoker method for the passed {@link LambdaForm}.
 632      */
 633     private byte[] generateCustomizedCodeBytes() {
 634         classFilePrologue();
 635 
 636         // Suppress this method in backtraces displayed to the user.
 637         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
 638 
 639         // Mark this method as a compiled LambdaForm
 640         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Compiled;", true);
 641 
 642         if (PROFILE_GWT && containsIntrinsic(MethodHandleImpl.Intrinsic.SELECT_ALTERNATIVE)) {
 643             // For now, mark only GWT LambdaForms as @Shared.
 644             // TODO: consider marking other non-customized LambdaForms as @Shared
 645             mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Shared;", true);
 646         }
 647 
 648         if (lambdaForm.forceInline) {
 649             // Force inlining of this invoker method.
 650             mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
 651         } else {
 652             mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true);
 653         }
 654 
 655         // iterate over the form's names, generating bytecode instructions for each
 656         // start iterating at the first name following the arguments
 657         Name onStack = null;
 658         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 659             Name name = lambdaForm.names[i];
 660 
 661             emitStoreResult(onStack);
 662             onStack = name;  // unless otherwise modified below
 663             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 664             switch (intr) {
 665                 case SELECT_ALTERNATIVE:
 666                     assert isSelectAlternative(i);
 667                     onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
 668                     i++;  // skip MH.invokeBasic of the selectAlternative result
 669                     continue;
 670                 case GUARD_WITH_CATCH:
 671                     assert isGuardWithCatch(i);
 672                     onStack = emitGuardWithCatch(i);
 673                     i = i+2; // Jump to the end of GWC idiom
 674                     continue;
 675                 case NEW_ARRAY:
 676                     Class<?> rtype = name.function.methodType().returnType();
 677                     if (isStaticallyNameable(rtype)) {
 678                         emitNewArray(name);
 679                         continue;
 680                     }
 681                     break;
 682                 case ARRAY_LOAD:
 683                     emitArrayLoad(name);
 684                     continue;
 685                 case ARRAY_STORE:
 686                     emitArrayStore(name);
 687                     continue;
 688                 case IDENTITY:
 689                     assert(name.arguments.length == 1);
 690                     emitPushArguments(name);
 691                     continue;
 692                 case ZERO:
 693                     assert(name.arguments.length == 0);
 694                     emitConst(name.type.basicTypeWrapper().zero());
 695                     continue;
 696                 case NONE:
 697                     // no intrinsic associated
 698                     break;
 699                 default:
 700                     throw newInternalError("Unknown intrinsic: "+intr);
 701             }
 702 
 703             MemberName member = name.function.member();
 704             if (isStaticallyInvocable(member)) {
 705                 emitStaticInvoke(member, name);
 706             } else {
 707                 emitInvoke(name);
 708             }
 709         }
 710 
 711         // return statement
 712         emitReturn(onStack);
 713 
 714         classFileEpilogue();
 715         bogusMethod(lambdaForm);
 716 
 717         final byte[] classFile = cw.toByteArray();
 718         maybeDump(className, classFile);
 719         return classFile;
 720     }
 721 
 722     void emitArrayLoad(Name name)  { emitArrayOp(name, Opcodes.AALOAD);  }
 723     void emitArrayStore(Name name) { emitArrayOp(name, Opcodes.AASTORE); }
 724 
 725     void emitArrayOp(Name name, int arrayOpcode) {
 726         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE;
 727         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 728         assert elementType != null;
 729         emitPushArguments(name);
 730         if (elementType.isPrimitive()) {
 731             Wrapper w = Wrapper.forPrimitiveType(elementType);
 732             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 733         }
 734         mv.visitInsn(arrayOpcode);
 735     }
 736 
 737     /**
 738      * Emit an invoke for the given name.
 739      */
 740     void emitInvoke(Name name) {
 741         assert(!isLinkerMethodInvoke(name));  // should use the static path for these
 742         if (true) {
 743             // push receiver
 744             MethodHandle target = name.function.resolvedHandle;
 745             assert(target != null) : name.exprString();
 746             mv.visitLdcInsn(constantPlaceholder(target));
 747             emitReferenceCast(MethodHandle.class, target);
 748         } else {
 749             // load receiver
 750             emitAloadInsn(0);
 751             emitReferenceCast(MethodHandle.class, null);
 752             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 753             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 754             // TODO more to come
 755         }
 756 
 757         // push arguments
 758         emitPushArguments(name);
 759 
 760         // invocation
 761         MethodType type = name.function.methodType();
 762         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 763     }
 764 
 765     static private Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 766         // Sample classes from each package we are willing to bind to statically:
 767         java.lang.Object.class,
 768         java.util.Arrays.class,
 769         sun.misc.Unsafe.class
 770         //MethodHandle.class already covered
 771     };
 772 
 773     static boolean isStaticallyInvocable(Name name) {
 774         return isStaticallyInvocable(name.function.member());
 775     }
 776 
 777     static boolean isStaticallyInvocable(MemberName member) {
 778         if (member == null)  return false;
 779         if (member.isConstructor())  return false;
 780         Class<?> cls = member.getDeclaringClass();
 781         if (cls.isArray() || cls.isPrimitive())
 782             return false;  // FIXME
 783         if (cls.isAnonymousClass() || cls.isLocalClass())
 784             return false;  // inner class of some sort
 785         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 786             return false;  // not on BCP
 787         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 788             return false;
 789         MethodType mtype = member.getMethodOrFieldType();
 790         if (!isStaticallyNameable(mtype.returnType()))
 791             return false;
 792         for (Class<?> ptype : mtype.parameterArray())
 793             if (!isStaticallyNameable(ptype))
 794                 return false;
 795         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 796             return true;   // in java.lang.invoke package
 797         if (member.isPublic() && isStaticallyNameable(cls))
 798             return true;
 799         return false;
 800     }
 801 
 802     static boolean isStaticallyNameable(Class<?> cls) {
 803         if (cls == Object.class)
 804             return true;
 805         while (cls.isArray())
 806             cls = cls.getComponentType();
 807         if (cls.isPrimitive())
 808             return true;  // int[].class, for example
 809         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 810             return false;
 811         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 812         if (cls.getClassLoader() != Object.class.getClassLoader())
 813             return false;
 814         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 815             return true;
 816         if (!Modifier.isPublic(cls.getModifiers()))
 817             return false;
 818         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 819             if (VerifyAccess.isSamePackage(pkgcls, cls))
 820                 return true;
 821         }
 822         return false;
 823     }
 824 
 825     void emitStaticInvoke(Name name) {
 826         emitStaticInvoke(name.function.member(), name);
 827     }
 828 
 829     /**
 830      * Emit an invoke for the given name, using the MemberName directly.
 831      */
 832     void emitStaticInvoke(MemberName member, Name name) {
 833         assert(member.equals(name.function.member()));
 834         Class<?> defc = member.getDeclaringClass();
 835         String cname = getInternalName(defc);
 836         String mname = member.getName();
 837         String mtype;
 838         byte refKind = member.getReferenceKind();
 839         if (refKind == REF_invokeSpecial) {
 840             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
 841             assert(member.canBeStaticallyBound()) : member;
 842             refKind = REF_invokeVirtual;
 843         }
 844 
 845         if (member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual) {
 846             // Methods from Object declared in an interface can be resolved by JVM to invokevirtual kind.
 847             // Need to convert it back to invokeinterface to pass verification and make the invocation works as expected.
 848             refKind = REF_invokeInterface;
 849         }
 850 
 851         // push arguments
 852         emitPushArguments(name);
 853 
 854         // invocation
 855         if (member.isMethod()) {
 856             mtype = member.getMethodType().toMethodDescriptorString();
 857             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
 858                                member.getDeclaringClass().isInterface());
 859         } else {
 860             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
 861             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
 862         }
 863         // Issue a type assertion for the result, so we can avoid casts later.
 864         if (name.type == L_TYPE) {
 865             Class<?> rtype = member.getInvocationType().returnType();
 866             assert(!rtype.isPrimitive());
 867             if (rtype != Object.class && !rtype.isInterface()) {
 868                 assertStaticType(rtype, name);
 869             }
 870         }
 871     }
 872 
 873     void emitNewArray(Name name) throws InternalError {
 874         Class<?> rtype = name.function.methodType().returnType();
 875         if (name.arguments.length == 0) {
 876             // The array will be a constant.
 877             Object emptyArray;
 878             try {
 879                 emptyArray = name.function.resolvedHandle.invoke();
 880             } catch (Throwable ex) {
 881                 throw newInternalError(ex);
 882             }
 883             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
 884             assert(emptyArray.getClass() == rtype);  // exact typing
 885             mv.visitLdcInsn(constantPlaceholder(emptyArray));
 886             emitReferenceCast(rtype, emptyArray);
 887             return;
 888         }
 889         Class<?> arrayElementType = rtype.getComponentType();
 890         assert(arrayElementType != null);
 891         emitIconstInsn(name.arguments.length);
 892         int xas = Opcodes.AASTORE;
 893         if (!arrayElementType.isPrimitive()) {
 894             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
 895         } else {
 896             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
 897             xas = arrayInsnOpcode(tc, xas);
 898             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
 899         }
 900         // store arguments
 901         for (int i = 0; i < name.arguments.length; i++) {
 902             mv.visitInsn(Opcodes.DUP);
 903             emitIconstInsn(i);
 904             emitPushArgument(name, i);
 905             mv.visitInsn(xas);
 906         }
 907         // the array is left on the stack
 908         assertStaticType(rtype, name);
 909     }
 910     int refKindOpcode(byte refKind) {
 911         switch (refKind) {
 912         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
 913         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
 914         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
 915         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
 916         case REF_getField:           return Opcodes.GETFIELD;
 917         case REF_putField:           return Opcodes.PUTFIELD;
 918         case REF_getStatic:          return Opcodes.GETSTATIC;
 919         case REF_putStatic:          return Opcodes.PUTSTATIC;
 920         }
 921         throw new InternalError("refKind="+refKind);
 922     }
 923 
 924     /**
 925      * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}.
 926      */
 927     private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) {
 928         return member != null &&
 929                member.getDeclaringClass() == declaringClass &&
 930                member.getName().equals(name);
 931     }
 932     private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) {
 933         return name.function != null &&
 934                memberRefersTo(name.function.member(), declaringClass, methodName);
 935     }
 936 
 937     /**
 938      * Check if MemberName is a call to MethodHandle.invokeBasic.
 939      */
 940     private boolean isInvokeBasic(Name name) {
 941         if (name.function == null)
 942             return false;
 943         if (name.arguments.length < 1)
 944             return false;  // must have MH argument
 945         MemberName member = name.function.member();
 946         return memberRefersTo(member, MethodHandle.class, "invokeBasic") &&
 947                !member.isPublic() && !member.isStatic();
 948     }
 949 
 950     /**
 951      * Check if MemberName is a call to MethodHandle.linkToStatic, etc.
 952      */
 953     private boolean isLinkerMethodInvoke(Name name) {
 954         if (name.function == null)
 955             return false;
 956         if (name.arguments.length < 1)
 957             return false;  // must have MH argument
 958         MemberName member = name.function.member();
 959         return member != null &&
 960                member.getDeclaringClass() == MethodHandle.class &&
 961                !member.isPublic() && member.isStatic() &&
 962                member.getName().startsWith("linkTo");
 963     }
 964 
 965     /**
 966      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 967      */
 968     private boolean isSelectAlternative(int pos) {
 969         // selectAlternative idiom:
 970         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
 971         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 972         if (pos+1 >= lambdaForm.names.length)  return false;
 973         Name name0 = lambdaForm.names[pos];
 974         Name name1 = lambdaForm.names[pos+1];
 975         return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") &&
 976                isInvokeBasic(name1) &&
 977                name1.lastUseIndex(name0) == 0 &&        // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 978                lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1}
 979     }
 980 
 981     /**
 982      * Check if i-th name is a start of GuardWithCatch idiom.
 983      */
 984     private boolean isGuardWithCatch(int pos) {
 985         // GuardWithCatch idiom:
 986         //   t_{n}:L=MethodHandle.invokeBasic(...)
 987         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
 988         //   t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
 989         if (pos+2 >= lambdaForm.names.length)  return false;
 990         Name name0 = lambdaForm.names[pos];
 991         Name name1 = lambdaForm.names[pos+1];
 992         Name name2 = lambdaForm.names[pos+2];
 993         return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") &&
 994                isInvokeBasic(name0) &&
 995                isInvokeBasic(name2) &&
 996                name1.lastUseIndex(name0) == 3 &&          // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
 997                lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1}
 998                name2.lastUseIndex(name1) == 1 &&          // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
 999                lambdaForm.lastUseIndex(name1) == pos+2;   // t_{n+1} is local: used only in t_{n+2}
1000     }
1001 
1002     /**
1003      * Emit bytecode for the selectAlternative idiom.
1004      *
1005      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
1006      * <blockquote><pre>{@code
1007      *   Lambda(a0:L,a1:I)=>{
1008      *     t2:I=foo.test(a1:I);
1009      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
1010      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
1011      * }</pre></blockquote>
1012      */
1013     private Name emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
1014         assert isStaticallyInvocable(invokeBasicName);
1015 
1016         Name receiver = (Name) invokeBasicName.arguments[0];
1017 
1018         Label L_fallback = new Label();
1019         Label L_done     = new Label();
1020 
1021         // load test result
1022         emitPushArgument(selectAlternativeName, 0);
1023 
1024         if (PROFILE_GWT) {
1025             emitPushArgument(selectAlternativeName, 3);
1026             mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "profileBranch", "(Z[I)Z", false);
1027         }
1028 
1029         // if_icmpne L_fallback
1030         mv.visitJumpInsn(Opcodes.IFEQ, L_fallback);
1031 
1032         // invoke selectAlternativeName.arguments[1]
1033         Class<?>[] preForkClasses = localClasses.clone();
1034         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
1035         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1036         emitStaticInvoke(invokeBasicName);
1037 
1038         // goto L_done
1039         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1040 
1041         // L_fallback:
1042         mv.visitLabel(L_fallback);
1043 
1044         // invoke selectAlternativeName.arguments[2]
1045         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1046         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
1047         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
1048         emitStaticInvoke(invokeBasicName);
1049 
1050         // L_done:
1051         mv.visitLabel(L_done);
1052         // for now do not bother to merge typestate; just reset to the dominator state
1053         System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
1054 
1055         return invokeBasicName;  // return what's on stack
1056     }
1057 
1058     /**
1059       * Emit bytecode for the guardWithCatch idiom.
1060       *
1061       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
1062       * <blockquote><pre>{@code
1063       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
1064       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
1065       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
1066       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
1067       * }</pre></blockquote>
1068       *
1069       * It is compiled into bytecode equivalent of the following code:
1070       * <blockquote><pre>{@code
1071       *  try {
1072       *      return a1.invokeBasic(a6, a7);
1073       *  } catch (Throwable e) {
1074       *      if (!a2.isInstance(e)) throw e;
1075       *      return a3.invokeBasic(ex, a6, a7);
1076       *  }}
1077       */
1078     private Name emitGuardWithCatch(int pos) {
1079         Name args    = lambdaForm.names[pos];
1080         Name invoker = lambdaForm.names[pos+1];
1081         Name result  = lambdaForm.names[pos+2];
1082 
1083         Label L_startBlock = new Label();
1084         Label L_endBlock = new Label();
1085         Label L_handler = new Label();
1086         Label L_done = new Label();
1087 
1088         Class<?> returnType = result.function.resolvedHandle.type().returnType();
1089         MethodType type = args.function.resolvedHandle.type()
1090                               .dropParameterTypes(0,1)
1091                               .changeReturnType(returnType);
1092 
1093         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
1094 
1095         // Normal case
1096         mv.visitLabel(L_startBlock);
1097         // load target
1098         emitPushArgument(invoker, 0);
1099         emitPushArguments(args, 1); // skip 1st argument: method handle
1100         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
1101         mv.visitLabel(L_endBlock);
1102         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1103 
1104         // Exceptional case
1105         mv.visitLabel(L_handler);
1106 
1107         // Check exception's type
1108         mv.visitInsn(Opcodes.DUP);
1109         // load exception class
1110         emitPushArgument(invoker, 1);
1111         mv.visitInsn(Opcodes.SWAP);
1112         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
1113         Label L_rethrow = new Label();
1114         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
1115 
1116         // Invoke catcher
1117         // load catcher
1118         emitPushArgument(invoker, 2);
1119         mv.visitInsn(Opcodes.SWAP);
1120         emitPushArguments(args, 1); // skip 1st argument: method handle
1121         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
1122         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
1123         mv.visitJumpInsn(Opcodes.GOTO, L_done);
1124 
1125         mv.visitLabel(L_rethrow);
1126         mv.visitInsn(Opcodes.ATHROW);
1127 
1128         mv.visitLabel(L_done);
1129 
1130         return result;
1131     }
1132 
1133     private void emitPushArguments(Name args) {
1134         emitPushArguments(args, 0);
1135     }
1136 
1137     private void emitPushArguments(Name args, int start) {
1138         for (int i = start; i < args.arguments.length; i++) {
1139             emitPushArgument(args, i);
1140         }
1141     }
1142 
1143     private void emitPushArgument(Name name, int paramIndex) {
1144         Object arg = name.arguments[paramIndex];
1145         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1146         emitPushArgument(ptype, arg);
1147     }
1148 
1149     private void emitPushArgument(Class<?> ptype, Object arg) {
1150         BasicType bptype = basicType(ptype);
1151         if (arg instanceof Name) {
1152             Name n = (Name) arg;
1153             emitLoadInsn(n.type, n.index());
1154             emitImplicitConversion(n.type, ptype, n);
1155         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1156             emitConst(arg);
1157         } else {
1158             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1159                 emitConst(arg);
1160             } else {
1161                 mv.visitLdcInsn(constantPlaceholder(arg));
1162                 emitImplicitConversion(L_TYPE, ptype, arg);
1163             }
1164         }
1165     }
1166 
1167     /**
1168      * Store the name to its local, if necessary.
1169      */
1170     private void emitStoreResult(Name name) {
1171         if (name != null && name.type != V_TYPE) {
1172             // non-void: actually assign
1173             emitStoreInsn(name.type, name.index());
1174         }
1175     }
1176 
1177     /**
1178      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1179      */
1180     private void emitReturn(Name onStack) {
1181         // return statement
1182         Class<?> rclass = invokerType.returnType();
1183         BasicType rtype = lambdaForm.returnType();
1184         assert(rtype == basicType(rclass));  // must agree
1185         if (rtype == V_TYPE) {
1186             // void
1187             mv.visitInsn(Opcodes.RETURN);
1188             // it doesn't matter what rclass is; the JVM will discard any value
1189         } else {
1190             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
1191 
1192             // put return value on the stack if it is not already there
1193             if (rn != onStack) {
1194                 emitLoadInsn(rtype, lambdaForm.result);
1195             }
1196 
1197             emitImplicitConversion(rtype, rclass, rn);
1198 
1199             // generate actual return statement
1200             emitReturnInsn(rtype);
1201         }
1202     }
1203 
1204     /**
1205      * Emit a type conversion bytecode casting from "from" to "to".
1206      */
1207     private void emitPrimCast(Wrapper from, Wrapper to) {
1208         // Here's how.
1209         // -   indicates forbidden
1210         // <-> indicates implicit
1211         //      to ----> boolean  byte     short    char     int      long     float    double
1212         // from boolean    <->        -        -        -        -        -        -        -
1213         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
1214         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
1215         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
1216         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
1217         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
1218         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
1219         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
1220         if (from == to) {
1221             // no cast required, should be dead code anyway
1222             return;
1223         }
1224         if (from.isSubwordOrInt()) {
1225             // cast from {byte,short,char,int} to anything
1226             emitI2X(to);
1227         } else {
1228             // cast from {long,float,double} to anything
1229             if (to.isSubwordOrInt()) {
1230                 // cast to {byte,short,char,int}
1231                 emitX2I(from);
1232                 if (to.bitWidth() < 32) {
1233                     // targets other than int require another conversion
1234                     emitI2X(to);
1235                 }
1236             } else {
1237                 // cast to {long,float,double} - this is verbose
1238                 boolean error = false;
1239                 switch (from) {
1240                 case LONG:
1241                     switch (to) {
1242                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
1243                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
1244                     default:      error = true;               break;
1245                     }
1246                     break;
1247                 case FLOAT:
1248                     switch (to) {
1249                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
1250                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
1251                     default:      error = true;               break;
1252                     }
1253                     break;
1254                 case DOUBLE:
1255                     switch (to) {
1256                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
1257                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
1258                     default:      error = true;               break;
1259                     }
1260                     break;
1261                 default:
1262                     error = true;
1263                     break;
1264                 }
1265                 if (error) {
1266                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
1267                 }
1268             }
1269         }
1270     }
1271 
1272     private void emitI2X(Wrapper type) {
1273         switch (type) {
1274         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
1275         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
1276         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
1277         case INT:     /* naught */                break;
1278         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
1279         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
1280         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
1281         case BOOLEAN:
1282             // For compatibility with ValueConversions and explicitCastArguments:
1283             mv.visitInsn(Opcodes.ICONST_1);
1284             mv.visitInsn(Opcodes.IAND);
1285             break;
1286         default:   throw new InternalError("unknown type: " + type);
1287         }
1288     }
1289 
1290     private void emitX2I(Wrapper type) {
1291         switch (type) {
1292         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1293         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1294         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1295         default:      throw new InternalError("unknown type: " + type);
1296         }
1297     }
1298 
1299     /**
1300      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1301      */
1302     static MemberName generateLambdaFormInterpreterEntryPoint(String sig) {
1303         assert(isValidSignature(sig));
1304         String name = "interpret_"+signatureReturn(sig).basicTypeChar();
1305         MethodType type = signatureType(sig);  // sig includes leading argument
1306         type = type.changeParameterType(0, MethodHandle.class);
1307         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1308         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1309     }
1310 
1311     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1312         classFilePrologue();
1313 
1314         // Suppress this method in backtraces displayed to the user.
1315         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
1316 
1317         // Don't inline the interpreter entry.
1318         mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true);
1319 
1320         // create parameter array
1321         emitIconstInsn(invokerType.parameterCount());
1322         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1323 
1324         // fill parameter array
1325         for (int i = 0; i < invokerType.parameterCount(); i++) {
1326             Class<?> ptype = invokerType.parameterType(i);
1327             mv.visitInsn(Opcodes.DUP);
1328             emitIconstInsn(i);
1329             emitLoadInsn(basicType(ptype), i);
1330             // box if primitive type
1331             if (ptype.isPrimitive()) {
1332                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1333             }
1334             mv.visitInsn(Opcodes.AASTORE);
1335         }
1336         // invoke
1337         emitAloadInsn(0);
1338         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1339         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1340         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1341 
1342         // maybe unbox
1343         Class<?> rtype = invokerType.returnType();
1344         if (rtype.isPrimitive() && rtype != void.class) {
1345             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1346         }
1347 
1348         // return statement
1349         emitReturnInsn(basicType(rtype));
1350 
1351         classFileEpilogue();
1352         bogusMethod(invokerType);
1353 
1354         final byte[] classFile = cw.toByteArray();
1355         maybeDump(className, classFile);
1356         return classFile;
1357     }
1358 
1359     /**
1360      * Generate bytecode for a NamedFunction invoker.
1361      */
1362     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1363         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1364         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1365         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1366         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1367     }
1368 
1369     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1370         MethodType dstType = typeForm.erasedType();
1371         classFilePrologue();
1372 
1373         // Suppress this method in backtraces displayed to the user.
1374         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
1375 
1376         // Force inlining of this invoker method.
1377         mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
1378 
1379         // Load receiver
1380         emitAloadInsn(0);
1381 
1382         // Load arguments from array
1383         for (int i = 0; i < dstType.parameterCount(); i++) {
1384             emitAloadInsn(1);
1385             emitIconstInsn(i);
1386             mv.visitInsn(Opcodes.AALOAD);
1387 
1388             // Maybe unbox
1389             Class<?> dptype = dstType.parameterType(i);
1390             if (dptype.isPrimitive()) {
1391                 Class<?> sptype = dstType.basicType().wrap().parameterType(i);
1392                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1393                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1394                 emitUnboxing(srcWrapper);
1395                 emitPrimCast(srcWrapper, dstWrapper);
1396             }
1397         }
1398 
1399         // Invoke
1400         String targetDesc = dstType.basicType().toMethodDescriptorString();
1401         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1402 
1403         // Box primitive types
1404         Class<?> rtype = dstType.returnType();
1405         if (rtype != void.class && rtype.isPrimitive()) {
1406             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1407             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1408             // boolean casts not allowed
1409             emitPrimCast(srcWrapper, dstWrapper);
1410             emitBoxing(dstWrapper);
1411         }
1412 
1413         // If the return type is void we return a null reference.
1414         if (rtype == void.class) {
1415             mv.visitInsn(Opcodes.ACONST_NULL);
1416         }
1417         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1418 
1419         classFileEpilogue();
1420         bogusMethod(dstType);
1421 
1422         final byte[] classFile = cw.toByteArray();
1423         maybeDump(className, classFile);
1424         return classFile;
1425     }
1426 
1427     /**
1428      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1429      * for debugging purposes.
1430      */
1431     private void bogusMethod(Object... os) {
1432         if (DUMP_CLASS_FILES) {
1433             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1434             for (Object o : os) {
1435                 mv.visitLdcInsn(o.toString());
1436                 mv.visitInsn(Opcodes.POP);
1437             }
1438             mv.visitInsn(Opcodes.RETURN);
1439             mv.visitMaxs(0, 0);
1440             mv.visitEnd();
1441         }
1442     }
1443 }