1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import sun.invoke.util.VerifyAccess;
  29 import static java.lang.invoke.LambdaForm.*;
  30 
  31 import sun.invoke.util.Wrapper;
  32 
  33 import java.io.*;
  34 import java.util.*;
  35 
  36 import jdk.internal.org.objectweb.asm.*;
  37 
  38 import java.lang.reflect.*;
  39 import static java.lang.invoke.MethodHandleStatics.*;
  40 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  41 import static java.lang.invoke.LambdaForm.BasicType.*;
  42 import sun.invoke.util.VerifyType;
  43 import sun.reflect.misc.ReflectUtil;
  44 
  45 /**
  46  * Code generation backend for LambdaForm.
  47  * <p>
  48  * @author John Rose, JSR 292 EG
  49  */
  50 class InvokerBytecodeGenerator {
  51     /** Define class names for convenience. */
  52     private static final String MH      = "java/lang/invoke/MethodHandle";
  53     private static final String MHI     = "java/lang/invoke/MethodHandleImpl";
  54     private static final String LF      = "java/lang/invoke/LambdaForm";
  55     private static final String LFN     = "java/lang/invoke/LambdaForm$Name";
  56     private static final String CLS     = "java/lang/Class";
  57     private static final String OBJ     = "java/lang/Object";
  58     private static final String OBJARY  = "[Ljava/lang/Object;";
  59 
  60     private static final String LF_SIG  = "L" + LF + ";";
  61     private static final String LFN_SIG = "L" + LFN + ";";
  62     private static final String LL_SIG  = "(L" + OBJ + ";)L" + OBJ + ";";
  63     private static final String CLL_SIG = "(L" + CLS + ";L" + OBJ + ";)L" + OBJ + ";";
  64 
  65     /** Name of its super class*/
  66     private static final String superName = LF;
  67 
  68     /** Name of new class */
  69     private final String className;
  70 
  71     /** Name of the source file (for stack trace printing). */
  72     private final String sourceFile;
  73 
  74     private final LambdaForm lambdaForm;
  75     private final String     invokerName;
  76     private final MethodType invokerType;
  77     private final int[] localsMap;
  78 
  79     /** ASM bytecode generation. */
  80     private ClassWriter cw;
  81     private MethodVisitor mv;
  82 
  83     private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory();
  84     private static final Class<?> HOST_CLASS = LambdaForm.class;
  85 
  86     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
  87                                      String className, String invokerName, MethodType invokerType) {
  88         if (invokerName.contains(".")) {
  89             int p = invokerName.indexOf('.');
  90             className = invokerName.substring(0, p);
  91             invokerName = invokerName.substring(p+1);
  92         }
  93         if (DUMP_CLASS_FILES) {
  94             className = makeDumpableClassName(className);
  95         }
  96         this.className  = superName + "$" + className;
  97         this.sourceFile = "LambdaForm$" + className;
  98         this.lambdaForm = lambdaForm;
  99         this.invokerName = invokerName;
 100         this.invokerType = invokerType;
 101         this.localsMap = new int[localsMapSize];
 102     }
 103 
 104     private InvokerBytecodeGenerator(String className, String invokerName, MethodType invokerType) {
 105         this(null, invokerType.parameterCount(),
 106              className, invokerName, invokerType);
 107         // Create an array to map name indexes to locals indexes.
 108         for (int i = 0; i < localsMap.length; i++) {
 109             localsMap[i] = invokerType.parameterSlotCount() - invokerType.parameterSlotDepth(i);
 110         }
 111     }
 112 
 113     private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
 114         this(form, form.names.length,
 115              className, form.debugName, invokerType);
 116         // Create an array to map name indexes to locals indexes.
 117         Name[] names = form.names;
 118         for (int i = 0, index = 0; i < localsMap.length; i++) {
 119             localsMap[i] = index;
 120             index += names[i].type.basicTypeSlots();
 121         }
 122     }
 123 
 124 
 125     /** instance counters for dumped classes */
 126     private final static HashMap<String,Integer> DUMP_CLASS_FILES_COUNTERS;
 127     /** debugging flag for saving generated class files */
 128     private final static File DUMP_CLASS_FILES_DIR;
 129 
 130     static {
 131         if (DUMP_CLASS_FILES) {
 132             DUMP_CLASS_FILES_COUNTERS = new HashMap<>();
 133             try {
 134                 File dumpDir = new File("DUMP_CLASS_FILES");
 135                 if (!dumpDir.exists()) {
 136                     dumpDir.mkdirs();
 137                 }
 138                 DUMP_CLASS_FILES_DIR = dumpDir;
 139                 System.out.println("Dumping class files to "+DUMP_CLASS_FILES_DIR+"/...");
 140             } catch (Exception e) {
 141                 throw newInternalError(e);
 142             }
 143         } else {
 144             DUMP_CLASS_FILES_COUNTERS = null;
 145             DUMP_CLASS_FILES_DIR = null;
 146         }
 147     }
 148 
 149     static void maybeDump(final String className, final byte[] classFile) {
 150         if (DUMP_CLASS_FILES) {
 151             System.out.println("dump: " + className);
 152             java.security.AccessController.doPrivileged(
 153             new java.security.PrivilegedAction<Void>() {
 154                 public Void run() {
 155                     try {
 156                         String dumpName = className;
 157                         //dumpName = dumpName.replace('/', '-');
 158                         File dumpFile = new File(DUMP_CLASS_FILES_DIR, dumpName+".class");
 159                         dumpFile.getParentFile().mkdirs();
 160                         FileOutputStream file = new FileOutputStream(dumpFile);
 161                         file.write(classFile);
 162                         file.close();
 163                         return null;
 164                     } catch (IOException ex) {
 165                         throw newInternalError(ex);
 166                     }
 167                 }
 168             });
 169         }
 170 
 171     }
 172 
 173     private static String makeDumpableClassName(String className) {
 174         Integer ctr;
 175         synchronized (DUMP_CLASS_FILES_COUNTERS) {
 176             ctr = DUMP_CLASS_FILES_COUNTERS.get(className);
 177             if (ctr == null)  ctr = 0;
 178             DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1);
 179         }
 180         String sfx = ctr.toString();
 181         while (sfx.length() < 3)
 182             sfx = "0"+sfx;
 183         className += sfx;
 184         return className;
 185     }
 186 
 187     class CpPatch {
 188         final int index;
 189         final String placeholder;
 190         final Object value;
 191         CpPatch(int index, String placeholder, Object value) {
 192             this.index = index;
 193             this.placeholder = placeholder;
 194             this.value = value;
 195         }
 196         public String toString() {
 197             return "CpPatch/index="+index+",placeholder="+placeholder+",value="+value;
 198         }
 199     }
 200 
 201     Map<Object, CpPatch> cpPatches = new HashMap<>();
 202 
 203     int cph = 0;  // for counting constant placeholders
 204 
 205     String constantPlaceholder(Object arg) {
 206         String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++;
 207         if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + arg.toString() + ">>";  // debugging aid
 208         if (cpPatches.containsKey(cpPlaceholder)) {
 209             throw new InternalError("observed CP placeholder twice: " + cpPlaceholder);
 210         }
 211         // insert placeholder in CP and remember the patch
 212         int index = cw.newConst((Object) cpPlaceholder);  // TODO check if already in the constant pool
 213         cpPatches.put(cpPlaceholder, new CpPatch(index, cpPlaceholder, arg));
 214         return cpPlaceholder;
 215     }
 216 
 217     Object[] cpPatches(byte[] classFile) {
 218         int size = getConstantPoolSize(classFile);
 219         Object[] res = new Object[size];
 220         for (CpPatch p : cpPatches.values()) {
 221             if (p.index >= size)
 222                 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20)));
 223             res[p.index] = p.value;
 224         }
 225         return res;
 226     }
 227 
 228     /**
 229      * Extract the number of constant pool entries from a given class file.
 230      *
 231      * @param classFile the bytes of the class file in question.
 232      * @return the number of entries in the constant pool.
 233      */
 234     private static int getConstantPoolSize(byte[] classFile) {
 235         // The first few bytes:
 236         // u4 magic;
 237         // u2 minor_version;
 238         // u2 major_version;
 239         // u2 constant_pool_count;
 240         return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF);
 241     }
 242 
 243     /**
 244      * Extract the MemberName of a newly-defined method.
 245      */
 246     private MemberName loadMethod(byte[] classFile) {
 247         Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile));
 248         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 249     }
 250 
 251     /**
 252      * Define a given class as anonymous class in the runtime system.
 253      */
 254     private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) {
 255         Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches);
 256         UNSAFE.ensureClassInitialized(invokerClass);  // Make sure the class is initialized; VM might complain.
 257         return invokerClass;
 258     }
 259 
 260     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 261         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 262         //System.out.println("resolveInvokerMember => "+member);
 263         //for (Method m : invokerClass.getDeclaredMethods())  System.out.println("  "+m);
 264         try {
 265             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
 266         } catch (ReflectiveOperationException e) {
 267             throw newInternalError(e);
 268         }
 269         //System.out.println("resolveInvokerMember => "+member);
 270         return member;
 271     }
 272 
 273     /**
 274      * Set up class file generation.
 275      */
 276     private void classFilePrologue() {
 277         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 278         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 279         cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, className, null, superName, null);
 280         cw.visitSource(sourceFile, null);
 281 
 282         String invokerDesc = invokerType.toMethodDescriptorString();
 283         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 284     }
 285 
 286     /**
 287      * Tear down class file generation.
 288      */
 289     private void classFileEpilogue() {
 290         mv.visitMaxs(0, 0);
 291         mv.visitEnd();
 292     }
 293 
 294     /*
 295      * Low-level emit helpers.
 296      */
 297     private void emitConst(Object con) {
 298         if (con == null) {
 299             mv.visitInsn(Opcodes.ACONST_NULL);
 300             return;
 301         }
 302         if (con instanceof Integer) {
 303             emitIconstInsn((int) con);
 304             return;
 305         }
 306         if (con instanceof Long) {
 307             long x = (long) con;
 308             if (x == (short) x) {
 309                 emitIconstInsn((int) x);
 310                 mv.visitInsn(Opcodes.I2L);
 311                 return;
 312             }
 313         }
 314         if (con instanceof Float) {
 315             float x = (float) con;
 316             if (x == (short) x) {
 317                 emitIconstInsn((int) x);
 318                 mv.visitInsn(Opcodes.I2F);
 319                 return;
 320             }
 321         }
 322         if (con instanceof Double) {
 323             double x = (double) con;
 324             if (x == (short) x) {
 325                 emitIconstInsn((int) x);
 326                 mv.visitInsn(Opcodes.I2D);
 327                 return;
 328             }
 329         }
 330         if (con instanceof Boolean) {
 331             emitIconstInsn((boolean) con ? 1 : 0);
 332             return;
 333         }
 334         // fall through:
 335         mv.visitLdcInsn(con);
 336     }
 337 
 338     private void emitIconstInsn(int i) {
 339         int opcode;
 340         switch (i) {
 341         case 0:  opcode = Opcodes.ICONST_0;  break;
 342         case 1:  opcode = Opcodes.ICONST_1;  break;
 343         case 2:  opcode = Opcodes.ICONST_2;  break;
 344         case 3:  opcode = Opcodes.ICONST_3;  break;
 345         case 4:  opcode = Opcodes.ICONST_4;  break;
 346         case 5:  opcode = Opcodes.ICONST_5;  break;
 347         default:
 348             if (i == (byte) i) {
 349                 mv.visitIntInsn(Opcodes.BIPUSH, i & 0xFF);
 350             } else if (i == (short) i) {
 351                 mv.visitIntInsn(Opcodes.SIPUSH, (char) i);
 352             } else {
 353                 mv.visitLdcInsn(i);
 354             }
 355             return;
 356         }
 357         mv.visitInsn(opcode);
 358     }
 359 
 360     /*
 361      * NOTE: These load/store methods use the localsMap to find the correct index!
 362      */
 363     private void emitLoadInsn(BasicType type, int index) {
 364         int opcode = loadInsnOpcode(type);
 365         mv.visitVarInsn(opcode, localsMap[index]);
 366     }
 367 
 368     private int loadInsnOpcode(BasicType type) throws InternalError {
 369         switch (type) {
 370             case I_TYPE: return Opcodes.ILOAD;
 371             case J_TYPE: return Opcodes.LLOAD;
 372             case F_TYPE: return Opcodes.FLOAD;
 373             case D_TYPE: return Opcodes.DLOAD;
 374             case L_TYPE: return Opcodes.ALOAD;
 375             default:
 376                 throw new InternalError("unknown type: " + type);
 377         }
 378     }
 379     private void emitAloadInsn(int index) {
 380         emitLoadInsn(L_TYPE, index);
 381     }
 382 
 383     private void emitStoreInsn(BasicType type, int index) {
 384         int opcode = storeInsnOpcode(type);
 385         mv.visitVarInsn(opcode, localsMap[index]);
 386     }
 387 
 388     private int storeInsnOpcode(BasicType type) throws InternalError {
 389         switch (type) {
 390             case I_TYPE: return Opcodes.ISTORE;
 391             case J_TYPE: return Opcodes.LSTORE;
 392             case F_TYPE: return Opcodes.FSTORE;
 393             case D_TYPE: return Opcodes.DSTORE;
 394             case L_TYPE: return Opcodes.ASTORE;
 395             default:
 396                 throw new InternalError("unknown type: " + type);
 397         }
 398     }
 399     private void emitAstoreInsn(int index) {
 400         emitStoreInsn(L_TYPE, index);
 401     }
 402 
 403     /**
 404      * Emit a boxing call.
 405      *
 406      * @param wrapper primitive type class to box.
 407      */
 408     private void emitBoxing(Wrapper wrapper) {
 409         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 410         String name  = "valueOf";
 411         String desc  = "(" + wrapper.basicTypeChar() + ")L" + owner + ";";
 412         mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false);
 413     }
 414 
 415     /**
 416      * Emit an unboxing call (plus preceding checkcast).
 417      *
 418      * @param wrapper wrapper type class to unbox.
 419      */
 420     private void emitUnboxing(Wrapper wrapper) {
 421         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 422         String name  = wrapper.primitiveSimpleName() + "Value";
 423         String desc  = "()" + wrapper.basicTypeChar();
 424         mv.visitTypeInsn(Opcodes.CHECKCAST, owner);
 425         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false);
 426     }
 427 
 428     /**
 429      * Emit an implicit conversion.
 430      *
 431      * @param ptype type of value present on stack
 432      * @param pclass type of value required on stack
 433      */
 434     private void emitImplicitConversion(BasicType ptype, Class<?> pclass) {
 435         assert(basicType(pclass) == ptype);  // boxing/unboxing handled by caller
 436         if (pclass == ptype.basicTypeClass() && ptype != L_TYPE)
 437             return;   // nothing to do
 438         switch (ptype) {
 439         case L_TYPE:
 440             if (VerifyType.isNullConversion(Object.class, pclass))
 441                 return;
 442             if (isStaticallyNameable(pclass)) {
 443                 mv.visitTypeInsn(Opcodes.CHECKCAST, getInternalName(pclass));
 444             } else {
 445                 mv.visitLdcInsn(constantPlaceholder(pclass));
 446                 mv.visitTypeInsn(Opcodes.CHECKCAST, CLS);
 447                 mv.visitInsn(Opcodes.SWAP);
 448                 mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "castReference", CLL_SIG, false);
 449                 if (pclass.isArray())
 450                     mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 451             }
 452             return;
 453         case I_TYPE:
 454             if (!VerifyType.isNullConversion(int.class, pclass))
 455                 emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass));
 456             return;
 457         }
 458         throw new InternalError("bad implicit conversion: tc="+ptype+": "+pclass);
 459     }
 460 
 461     /**
 462      * Emits an actual return instruction conforming to the given return type.
 463      */
 464     private void emitReturnInsn(BasicType type) {
 465         int opcode;
 466         switch (type) {
 467         case I_TYPE:  opcode = Opcodes.IRETURN;  break;
 468         case J_TYPE:  opcode = Opcodes.LRETURN;  break;
 469         case F_TYPE:  opcode = Opcodes.FRETURN;  break;
 470         case D_TYPE:  opcode = Opcodes.DRETURN;  break;
 471         case L_TYPE:  opcode = Opcodes.ARETURN;  break;
 472         case V_TYPE:  opcode = Opcodes.RETURN;   break;
 473         default:
 474             throw new InternalError("unknown return type: " + type);
 475         }
 476         mv.visitInsn(opcode);
 477     }
 478 
 479     private static String getInternalName(Class<?> c) {
 480         assert(VerifyAccess.isTypeVisible(c, Object.class));
 481         return c.getName().replace('.', '/');
 482     }
 483 
 484     /**
 485      * Generate customized bytecode for a given LambdaForm.
 486      */
 487     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 488         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 489         return g.loadMethod(g.generateCustomizedCodeBytes());
 490     }
 491 
 492     /**
 493      * Generate an invoker method for the passed {@link LambdaForm}.
 494      */
 495     private byte[] generateCustomizedCodeBytes() {
 496         classFilePrologue();
 497 
 498         // Suppress this method in backtraces displayed to the user.
 499         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
 500 
 501         // Mark this method as a compiled LambdaForm
 502         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Compiled;", true);
 503 
 504         // Force inlining of this invoker method.
 505         mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
 506 
 507         // iterate over the form's names, generating bytecode instructions for each
 508         // start iterating at the first name following the arguments
 509         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 510             Name name = lambdaForm.names[i];
 511             MemberName member = name.function.member();
 512 
 513             if (isSelectAlternative(i)) {
 514                 emitSelectAlternative(name, lambdaForm.names[i + 1]);
 515                 i++;  // skip MH.invokeBasic of the selectAlternative result
 516             } else if (isGuardWithCatch(i)) {
 517                 emitGuardWithCatch(i);
 518                 i = i+2; // Jump to the end of GWC idiom
 519             } else if (isStaticallyInvocable(member)) {
 520                 emitStaticInvoke(member, name);
 521             } else {
 522                 emitInvoke(name);
 523             }
 524 
 525             // Update cached form name's info in case an intrinsic spanning multiple names was encountered.
 526             name = lambdaForm.names[i];
 527             member = name.function.member();
 528 
 529             // store the result from evaluating to the target name in a local if required
 530             // (if this is the last value, i.e., the one that is going to be returned,
 531             // avoid store/load/return and just return)
 532             if (i == lambdaForm.names.length - 1 && i == lambdaForm.result) {
 533                 // return value - do nothing
 534             } else if (name.type != V_TYPE) {
 535                 // non-void: actually assign
 536                 emitStoreInsn(name.type, name.index());
 537             }
 538         }
 539 
 540         // return statement
 541         emitReturn();
 542 
 543         classFileEpilogue();
 544         bogusMethod(lambdaForm);
 545 
 546         final byte[] classFile = cw.toByteArray();
 547         maybeDump(className, classFile);
 548         return classFile;
 549     }
 550 
 551     /**
 552      * Emit an invoke for the given name.
 553      */
 554     void emitInvoke(Name name) {
 555         if (true) {
 556             // push receiver
 557             MethodHandle target = name.function.resolvedHandle;
 558             assert(target != null) : name.exprString();
 559             mv.visitLdcInsn(constantPlaceholder(target));
 560             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 561         } else {
 562             // load receiver
 563             emitAloadInsn(0);
 564             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 565             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 566             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 567             // TODO more to come
 568         }
 569 
 570         // push arguments
 571         for (int i = 0; i < name.arguments.length; i++) {
 572             emitPushArgument(name, i);
 573         }
 574 
 575         // invocation
 576         MethodType type = name.function.methodType();
 577         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 578     }
 579 
 580     static private Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 581         // Sample classes from each package we are willing to bind to statically:
 582         java.lang.Object.class,
 583         java.util.Arrays.class,
 584         sun.misc.Unsafe.class
 585         //MethodHandle.class already covered
 586     };
 587 
 588     static boolean isStaticallyInvocable(MemberName member) {
 589         if (member == null)  return false;
 590         if (member.isConstructor())  return false;
 591         Class<?> cls = member.getDeclaringClass();
 592         if (cls.isArray() || cls.isPrimitive())
 593             return false;  // FIXME
 594         if (cls.isAnonymousClass() || cls.isLocalClass())
 595             return false;  // inner class of some sort
 596         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 597             return false;  // not on BCP
 598         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 599             return false;
 600         MethodType mtype = member.getMethodOrFieldType();
 601         if (!isStaticallyNameable(mtype.returnType()))
 602             return false;
 603         for (Class<?> ptype : mtype.parameterArray())
 604             if (!isStaticallyNameable(ptype))
 605                 return false;
 606         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 607             return true;   // in java.lang.invoke package
 608         if (member.isPublic() && isStaticallyNameable(cls))
 609             return true;
 610         return false;
 611     }
 612 
 613     static boolean isStaticallyNameable(Class<?> cls) {
 614         while (cls.isArray())
 615             cls = cls.getComponentType();
 616         if (cls.isPrimitive())
 617             return true;  // int[].class, for example
 618         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 619             return false;
 620         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 621         if (cls.getClassLoader() != Object.class.getClassLoader())
 622             return false;
 623         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 624             return true;
 625         if (!Modifier.isPublic(cls.getModifiers()))
 626             return false;
 627         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 628             if (VerifyAccess.isSamePackage(pkgcls, cls))
 629                 return true;
 630         }
 631         return false;
 632     }
 633 
 634     /**
 635      * Emit an invoke for the given name, using the MemberName directly.
 636      */
 637     void emitStaticInvoke(MemberName member, Name name) {
 638         assert(member.equals(name.function.member()));
 639         String cname = getInternalName(member.getDeclaringClass());
 640         String mname = member.getName();
 641         String mtype;
 642         byte refKind = member.getReferenceKind();
 643         if (refKind == REF_invokeSpecial) {
 644             // in order to pass the verifier, we need to convert this to invokevirtual in all cases
 645             assert(member.canBeStaticallyBound()) : member;
 646             refKind = REF_invokeVirtual;
 647         }
 648 
 649         if (member.getDeclaringClass().isInterface() && refKind == REF_invokeVirtual) {
 650             // Methods from Object declared in an interface can be resolved by JVM to invokevirtual kind.
 651             // Need to convert it back to invokeinterface to pass verification and make the invocation works as expected.
 652             refKind = REF_invokeInterface;
 653         }
 654 
 655         // push arguments
 656         for (int i = 0; i < name.arguments.length; i++) {
 657             emitPushArgument(name, i);
 658         }
 659 
 660         // invocation
 661         if (member.isMethod()) {
 662             mtype = member.getMethodType().toMethodDescriptorString();
 663             mv.visitMethodInsn(refKindOpcode(refKind), cname, mname, mtype,
 664                                member.getDeclaringClass().isInterface());
 665         } else {
 666             mtype = MethodType.toFieldDescriptorString(member.getFieldType());
 667             mv.visitFieldInsn(refKindOpcode(refKind), cname, mname, mtype);
 668         }
 669     }
 670     int refKindOpcode(byte refKind) {
 671         switch (refKind) {
 672         case REF_invokeVirtual:      return Opcodes.INVOKEVIRTUAL;
 673         case REF_invokeStatic:       return Opcodes.INVOKESTATIC;
 674         case REF_invokeSpecial:      return Opcodes.INVOKESPECIAL;
 675         case REF_invokeInterface:    return Opcodes.INVOKEINTERFACE;
 676         case REF_getField:           return Opcodes.GETFIELD;
 677         case REF_putField:           return Opcodes.PUTFIELD;
 678         case REF_getStatic:          return Opcodes.GETSTATIC;
 679         case REF_putStatic:          return Opcodes.PUTSTATIC;
 680         }
 681         throw new InternalError("refKind="+refKind);
 682     }
 683 
 684     /**
 685      * Check if MemberName is a call to a method named {@code name} in class {@code declaredClass}.
 686      */
 687     private boolean memberRefersTo(MemberName member, Class<?> declaringClass, String name) {
 688         return member != null &&
 689                member.getDeclaringClass() == declaringClass &&
 690                member.getName().equals(name);
 691     }
 692     private boolean nameRefersTo(Name name, Class<?> declaringClass, String methodName) {
 693         return name.function != null &&
 694                memberRefersTo(name.function.member(), declaringClass, methodName);
 695     }
 696 
 697     /**
 698      * Check if MemberName is a call to MethodHandle.invokeBasic.
 699      */
 700     private boolean isInvokeBasic(Name name) {
 701         if (name.function == null)
 702             return false;
 703         if (name.arguments.length < 1)
 704             return false;  // must have MH argument
 705         MemberName member = name.function.member();
 706         return memberRefersTo(member, MethodHandle.class, "invokeBasic") &&
 707                !member.isPublic() && !member.isStatic();
 708     }
 709 
 710     /**
 711      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 712      */
 713     private boolean isSelectAlternative(int pos) {
 714         // selectAlternative idiom:
 715         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
 716         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 717         if (pos+1 >= lambdaForm.names.length)  return false;
 718         Name name0 = lambdaForm.names[pos];
 719         Name name1 = lambdaForm.names[pos+1];
 720         return nameRefersTo(name0, MethodHandleImpl.class, "selectAlternative") &&
 721                isInvokeBasic(name1) &&
 722                name1.lastUseIndex(name0) == 0 &&        // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 723                lambdaForm.lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1}
 724     }
 725 
 726     /**
 727      * Check if i-th name is a start of GuardWithCatch idiom.
 728      */
 729     private boolean isGuardWithCatch(int pos) {
 730         // GuardWithCatch idiom:
 731         //   t_{n}:L=MethodHandle.invokeBasic(...)
 732         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
 733         //   t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
 734         if (pos+2 >= lambdaForm.names.length)  return false;
 735         Name name0 = lambdaForm.names[pos];
 736         Name name1 = lambdaForm.names[pos+1];
 737         Name name2 = lambdaForm.names[pos+2];
 738         return nameRefersTo(name1, MethodHandleImpl.class, "guardWithCatch") &&
 739                isInvokeBasic(name0) &&
 740                isInvokeBasic(name2) &&
 741                name1.lastUseIndex(name0) == 3 &&          // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
 742                lambdaForm.lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1}
 743                name2.lastUseIndex(name1) == 1 &&          // t_{n+2}:?=MethodHandle.invokeBasic(t_{n+1})
 744                lambdaForm.lastUseIndex(name1) == pos+2;   // t_{n+1} is local: used only in t_{n+2}
 745     }
 746 
 747     /**
 748      * Emit bytecode for the selectAlternative idiom.
 749      *
 750      * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithTest):
 751      * <blockquote><pre>{@code
 752      *   Lambda(a0:L,a1:I)=>{
 753      *     t2:I=foo.test(a1:I);
 754      *     t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
 755      *     t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
 756      * }</pre></blockquote>
 757      */
 758     private void emitSelectAlternative(Name selectAlternativeName, Name invokeBasicName) {
 759         Name receiver = (Name) invokeBasicName.arguments[0];
 760 
 761         Label L_fallback = new Label();
 762         Label L_done     = new Label();
 763 
 764         // load test result
 765         emitPushArgument(selectAlternativeName, 0);
 766         mv.visitInsn(Opcodes.ICONST_1);
 767 
 768         // if_icmpne L_fallback
 769         mv.visitJumpInsn(Opcodes.IF_ICMPNE, L_fallback);
 770 
 771         // invoke selectAlternativeName.arguments[1]
 772         emitPushArgument(selectAlternativeName, 1);  // get 2nd argument of selectAlternative
 773         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
 774         emitInvoke(invokeBasicName);
 775 
 776         // goto L_done
 777         mv.visitJumpInsn(Opcodes.GOTO, L_done);
 778 
 779         // L_fallback:
 780         mv.visitLabel(L_fallback);
 781 
 782         // invoke selectAlternativeName.arguments[2]
 783         emitPushArgument(selectAlternativeName, 2);  // get 3rd argument of selectAlternative
 784         emitAstoreInsn(receiver.index());  // store the MH in the receiver slot
 785         emitInvoke(invokeBasicName);
 786 
 787         // L_done:
 788         mv.visitLabel(L_done);
 789     }
 790 
 791     /**
 792       * Emit bytecode for the guardWithCatch idiom.
 793       *
 794       * The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
 795       * <blockquote><pre>{@code
 796       *  guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
 797       *    t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
 798       *    t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
 799       *   t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
 800       * }</pre></blockquote>
 801       *
 802       * It is compiled into bytecode equivalent of the following code:
 803       * <blockquote><pre>{@code
 804       *  try {
 805       *      return a1.invokeBasic(a6, a7);
 806       *  } catch (Throwable e) {
 807       *      if (!a2.isInstance(e)) throw e;
 808       *      return a3.invokeBasic(ex, a6, a7);
 809       *  }}
 810       */
 811     private void emitGuardWithCatch(int pos) {
 812         Name args    = lambdaForm.names[pos];
 813         Name invoker = lambdaForm.names[pos+1];
 814         Name result  = lambdaForm.names[pos+2];
 815 
 816         Label L_startBlock = new Label();
 817         Label L_endBlock = new Label();
 818         Label L_handler = new Label();
 819         Label L_done = new Label();
 820 
 821         Class<?> returnType = result.function.resolvedHandle.type().returnType();
 822         MethodType type = args.function.resolvedHandle.type()
 823                               .dropParameterTypes(0,1)
 824                               .changeReturnType(returnType);
 825 
 826         mv.visitTryCatchBlock(L_startBlock, L_endBlock, L_handler, "java/lang/Throwable");
 827 
 828         // Normal case
 829         mv.visitLabel(L_startBlock);
 830         // load target
 831         emitPushArgument(invoker, 0);
 832         emitPushArguments(args, 1); // skip 1st argument: method handle
 833         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 834         mv.visitLabel(L_endBlock);
 835         mv.visitJumpInsn(Opcodes.GOTO, L_done);
 836 
 837         // Exceptional case
 838         mv.visitLabel(L_handler);
 839 
 840         // Check exception's type
 841         mv.visitInsn(Opcodes.DUP);
 842         // load exception class
 843         emitPushArgument(invoker, 1);
 844         mv.visitInsn(Opcodes.SWAP);
 845         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "isInstance", "(Ljava/lang/Object;)Z", false);
 846         Label L_rethrow = new Label();
 847         mv.visitJumpInsn(Opcodes.IFEQ, L_rethrow);
 848 
 849         // Invoke catcher
 850         // load catcher
 851         emitPushArgument(invoker, 2);
 852         mv.visitInsn(Opcodes.SWAP);
 853         emitPushArguments(args, 1); // skip 1st argument: method handle
 854         MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
 855         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", catcherType.basicType().toMethodDescriptorString(), false);
 856         mv.visitJumpInsn(Opcodes.GOTO, L_done);
 857 
 858         mv.visitLabel(L_rethrow);
 859         mv.visitInsn(Opcodes.ATHROW);
 860 
 861         mv.visitLabel(L_done);
 862     }
 863 
 864     private void emitPushArguments(Name args, int start) {
 865         for (int i = start; i < args.arguments.length; i++) {
 866             emitPushArgument(args, i);
 867         }
 868     }
 869 
 870     private void emitPushArgument(Name name, int paramIndex) {
 871         Object arg = name.arguments[paramIndex];
 872         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
 873         emitPushArgument(ptype, arg);
 874     }
 875 
 876     private void emitPushArgument(Class<?> ptype, Object arg) {
 877         BasicType bptype = basicType(ptype);
 878         if (arg instanceof Name) {
 879             Name n = (Name) arg;
 880             emitLoadInsn(n.type, n.index());
 881             emitImplicitConversion(n.type, ptype);
 882         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
 883             emitConst(arg);
 884         } else {
 885             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
 886                 emitConst(arg);
 887             } else {
 888                 mv.visitLdcInsn(constantPlaceholder(arg));
 889                 emitImplicitConversion(L_TYPE, ptype);
 890             }
 891         }
 892     }
 893 
 894     /**
 895      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
 896      */
 897     private void emitReturn() {
 898         // return statement
 899         Class<?> rclass = invokerType.returnType();
 900         BasicType rtype = lambdaForm.returnType();
 901         assert(rtype == basicType(rclass));  // must agree
 902         if (rtype == V_TYPE) {
 903             // void
 904             mv.visitInsn(Opcodes.RETURN);
 905             // it doesn't matter what rclass is; the JVM will discard any value
 906         } else {
 907             LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
 908 
 909             // put return value on the stack if it is not already there
 910             if (lambdaForm.result != lambdaForm.names.length - 1 ||
 911                     lambdaForm.result < lambdaForm.arity) {
 912                 emitLoadInsn(rn.type, lambdaForm.result);
 913             }
 914 
 915             emitImplicitConversion(rtype, rclass);
 916 
 917             // generate actual return statement
 918             emitReturnInsn(rtype);
 919         }
 920     }
 921 
 922     /**
 923      * Emit a type conversion bytecode casting from "from" to "to".
 924      */
 925     private void emitPrimCast(Wrapper from, Wrapper to) {
 926         // Here's how.
 927         // -   indicates forbidden
 928         // <-> indicates implicit
 929         //      to ----> boolean  byte     short    char     int      long     float    double
 930         // from boolean    <->        -        -        -        -        -        -        -
 931         //      byte        -       <->       i2s      i2c      <->      i2l      i2f      i2d
 932         //      short       -       i2b       <->      i2c      <->      i2l      i2f      i2d
 933         //      char        -       i2b       i2s      <->      <->      i2l      i2f      i2d
 934         //      int         -       i2b       i2s      i2c      <->      i2l      i2f      i2d
 935         //      long        -     l2i,i2b   l2i,i2s  l2i,i2c    l2i      <->      l2f      l2d
 936         //      float       -     f2i,i2b   f2i,i2s  f2i,i2c    f2i      f2l      <->      f2d
 937         //      double      -     d2i,i2b   d2i,i2s  d2i,i2c    d2i      d2l      d2f      <->
 938         if (from == to) {
 939             // no cast required, should be dead code anyway
 940             return;
 941         }
 942         if (from.isSubwordOrInt()) {
 943             // cast from {byte,short,char,int} to anything
 944             emitI2X(to);
 945         } else {
 946             // cast from {long,float,double} to anything
 947             if (to.isSubwordOrInt()) {
 948                 // cast to {byte,short,char,int}
 949                 emitX2I(from);
 950                 if (to.bitWidth() < 32) {
 951                     // targets other than int require another conversion
 952                     emitI2X(to);
 953                 }
 954             } else {
 955                 // cast to {long,float,double} - this is verbose
 956                 boolean error = false;
 957                 switch (from) {
 958                 case LONG:
 959                     switch (to) {
 960                     case FLOAT:   mv.visitInsn(Opcodes.L2F);  break;
 961                     case DOUBLE:  mv.visitInsn(Opcodes.L2D);  break;
 962                     default:      error = true;               break;
 963                     }
 964                     break;
 965                 case FLOAT:
 966                     switch (to) {
 967                     case LONG :   mv.visitInsn(Opcodes.F2L);  break;
 968                     case DOUBLE:  mv.visitInsn(Opcodes.F2D);  break;
 969                     default:      error = true;               break;
 970                     }
 971                     break;
 972                 case DOUBLE:
 973                     switch (to) {
 974                     case LONG :   mv.visitInsn(Opcodes.D2L);  break;
 975                     case FLOAT:   mv.visitInsn(Opcodes.D2F);  break;
 976                     default:      error = true;               break;
 977                     }
 978                     break;
 979                 default:
 980                     error = true;
 981                     break;
 982                 }
 983                 if (error) {
 984                     throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
 985                 }
 986             }
 987         }
 988     }
 989 
 990     private void emitI2X(Wrapper type) {
 991         switch (type) {
 992         case BYTE:    mv.visitInsn(Opcodes.I2B);  break;
 993         case SHORT:   mv.visitInsn(Opcodes.I2S);  break;
 994         case CHAR:    mv.visitInsn(Opcodes.I2C);  break;
 995         case INT:     /* naught */                break;
 996         case LONG:    mv.visitInsn(Opcodes.I2L);  break;
 997         case FLOAT:   mv.visitInsn(Opcodes.I2F);  break;
 998         case DOUBLE:  mv.visitInsn(Opcodes.I2D);  break;
 999         case BOOLEAN:
1000             // For compatibility with ValueConversions and explicitCastArguments:
1001             mv.visitInsn(Opcodes.ICONST_1);
1002             mv.visitInsn(Opcodes.IAND);
1003             break;
1004         default:   throw new InternalError("unknown type: " + type);
1005         }
1006     }
1007 
1008     private void emitX2I(Wrapper type) {
1009         switch (type) {
1010         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1011         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1012         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1013         default:      throw new InternalError("unknown type: " + type);
1014         }
1015     }
1016 
1017     /**
1018      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1019      */
1020     static MemberName generateLambdaFormInterpreterEntryPoint(String sig) {
1021         assert(isValidSignature(sig));
1022         String name = "interpret_"+signatureReturn(sig).basicTypeChar();
1023         MethodType type = signatureType(sig);  // sig includes leading argument
1024         type = type.changeParameterType(0, MethodHandle.class);
1025         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1026         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1027     }
1028 
1029     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1030         classFilePrologue();
1031 
1032         // Suppress this method in backtraces displayed to the user.
1033         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
1034 
1035         // Don't inline the interpreter entry.
1036         mv.visitAnnotation("Ljava/lang/invoke/DontInline;", true);
1037 
1038         // create parameter array
1039         emitIconstInsn(invokerType.parameterCount());
1040         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1041 
1042         // fill parameter array
1043         for (int i = 0; i < invokerType.parameterCount(); i++) {
1044             Class<?> ptype = invokerType.parameterType(i);
1045             mv.visitInsn(Opcodes.DUP);
1046             emitIconstInsn(i);
1047             emitLoadInsn(basicType(ptype), i);
1048             // box if primitive type
1049             if (ptype.isPrimitive()) {
1050                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1051             }
1052             mv.visitInsn(Opcodes.AASTORE);
1053         }
1054         // invoke
1055         emitAloadInsn(0);
1056         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1057         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1058         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1059 
1060         // maybe unbox
1061         Class<?> rtype = invokerType.returnType();
1062         if (rtype.isPrimitive() && rtype != void.class) {
1063             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1064         }
1065 
1066         // return statement
1067         emitReturnInsn(basicType(rtype));
1068 
1069         classFileEpilogue();
1070         bogusMethod(invokerType);
1071 
1072         final byte[] classFile = cw.toByteArray();
1073         maybeDump(className, classFile);
1074         return classFile;
1075     }
1076 
1077     /**
1078      * Generate bytecode for a NamedFunction invoker.
1079      */
1080     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1081         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1082         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1083         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1084         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1085     }
1086 
1087     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1088         MethodType dstType = typeForm.erasedType();
1089         classFilePrologue();
1090 
1091         // Suppress this method in backtraces displayed to the user.
1092         mv.visitAnnotation("Ljava/lang/invoke/LambdaForm$Hidden;", true);
1093 
1094         // Force inlining of this invoker method.
1095         mv.visitAnnotation("Ljava/lang/invoke/ForceInline;", true);
1096 
1097         // Load receiver
1098         emitAloadInsn(0);
1099 
1100         // Load arguments from array
1101         for (int i = 0; i < dstType.parameterCount(); i++) {
1102             emitAloadInsn(1);
1103             emitIconstInsn(i);
1104             mv.visitInsn(Opcodes.AALOAD);
1105 
1106             // Maybe unbox
1107             Class<?> dptype = dstType.parameterType(i);
1108             if (dptype.isPrimitive()) {
1109                 Class<?> sptype = dstType.basicType().wrap().parameterType(i);
1110                 Wrapper dstWrapper = Wrapper.forBasicType(dptype);
1111                 Wrapper srcWrapper = dstWrapper.isSubwordOrInt() ? Wrapper.INT : dstWrapper;  // narrow subword from int
1112                 emitUnboxing(srcWrapper);
1113                 emitPrimCast(srcWrapper, dstWrapper);
1114             }
1115         }
1116 
1117         // Invoke
1118         String targetDesc = dstType.basicType().toMethodDescriptorString();
1119         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1120 
1121         // Box primitive types
1122         Class<?> rtype = dstType.returnType();
1123         if (rtype != void.class && rtype.isPrimitive()) {
1124             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1125             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1126             // boolean casts not allowed
1127             emitPrimCast(srcWrapper, dstWrapper);
1128             emitBoxing(dstWrapper);
1129         }
1130 
1131         // If the return type is void we return a null reference.
1132         if (rtype == void.class) {
1133             mv.visitInsn(Opcodes.ACONST_NULL);
1134         }
1135         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1136 
1137         classFileEpilogue();
1138         bogusMethod(dstType);
1139 
1140         final byte[] classFile = cw.toByteArray();
1141         maybeDump(className, classFile);
1142         return classFile;
1143     }
1144 
1145     /**
1146      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1147      * for debugging purposes.
1148      */
1149     private void bogusMethod(Object... os) {
1150         if (DUMP_CLASS_FILES) {
1151             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1152             for (Object o : os) {
1153                 mv.visitLdcInsn(o.toString());
1154                 mv.visitInsn(Opcodes.POP);
1155             }
1156             mv.visitInsn(Opcodes.RETURN);
1157             mv.visitMaxs(0, 0);
1158             mv.visitEnd();
1159         }
1160     }
1161 }