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