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