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