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