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