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