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