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