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.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     List<Object> classDataValues() {
 289         final List<ClassData> cd = classData;
 290         return switch(cd.size()) {
 291             case 0 -> List.of();
 292             case 1 -> List.of(cd.get(0).value);
 293             case 2 -> List.of(cd.get(0).value, cd.get(1).value);
 294             case 3 -> List.of(cd.get(0).value, cd.get(1).value, cd.get(2).value);
 295             case 4 -> List.of(cd.get(0).value, cd.get(1).value, cd.get(2).value, cd.get(3).value);
 296             default -> {
 297                 Object[] data = new Object[classData.size()];
 298                 for (int i = 0; i < classData.size(); i++) {
 299                     data[i] = classData.get(i).value;
 300                 }
 301                 yield List.of(data);
 302             }
 303         };
 304     }
 305 
 306     private static String debugString(Object arg) {
 307         if (arg instanceof MethodHandle mh) {
 308             MemberName member = mh.internalMemberName();
 309             if (member != null)
 310                 return member.toString();
 311             return mh.debugString();
 312         }
 313         return arg.toString();
 314     }
 315 
 316     /**
 317      * Extract the MemberName of a newly-defined method.
 318      */
 319     private MemberName loadMethod(byte[] classFile) {
 320         Class<?> invokerClass = LOOKUP.makeHiddenClassDefiner(className, classFile, Set.of())
 321                                       .defineClass(true, classDataValues());
 322         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 323     }
 324 
 325     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 326         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 327         try {
 328             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member,
 329                                                       HOST_CLASS, LM_TRUSTED,
 330                                                       ReflectiveOperationException.class);
 331         } catch (ReflectiveOperationException e) {
 332             throw newInternalError(e);
 333         }
 334         return member;
 335     }
 336 
 337     /**
 338      * Set up class file generation.
 339      */
 340     private ClassWriter classFilePrologue() {
 341         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 342         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 343         setClassWriter(cw);
 344         cw.visit(CLASSFILE_VERSION, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
 345                 className, null, INVOKER_SUPER_NAME, null);
 346         cw.visitSource(SOURCE_PREFIX + name, null);
 347         return cw;
 348     }
 349 
 350     private void methodPrologue() {
 351         String invokerDesc = invokerType.toMethodDescriptorString();
 352         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 353     }
 354 
 355     /**
 356      * Tear down class file generation.
 357      */
 358     private void methodEpilogue() {
 359         mv.visitMaxs(0, 0);
 360         mv.visitEnd();
 361     }
 362 
 363     /*
 364      * <clinit> to initialize the static final fields with the live class data
 365      * LambdaForms can't use condy due to bootstrapping issue.
 366      */
 367     static void clinit(ClassWriter cw, String className, List<ClassData> classData) {
 368         if (classData.isEmpty())
 369             return;
 370 
 371         for (ClassData p : classData) {
 372             // add the static field
 373             FieldVisitor fv = cw.visitField(Opcodes.ACC_STATIC|Opcodes.ACC_FINAL, p.name, p.desc, null, null);
 374             fv.visitEnd();
 375         }
 376 
 377         MethodVisitor mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
 378         mv.visitCode();
 379         mv.visitLdcInsn(Type.getType("L" + className + ";"));
 380         mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles",
 381                            "classData", "(Ljava/lang/Class;)Ljava/lang/Object;", false);
 382         // we should optimize one single element case that does not need to create a List
 383         mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/List");
 384         mv.visitVarInsn(Opcodes.ASTORE, 0);
 385         int index = 0;
 386         for (ClassData p : classData) {
 387             // initialize the static field
 388             mv.visitVarInsn(Opcodes.ALOAD, 0);
 389             emitIconstInsn(mv, index++);
 390             mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List",
 391                                "get", "(I)Ljava/lang/Object;", true);
 392             mv.visitTypeInsn(Opcodes.CHECKCAST, p.desc.substring(1, p.desc.length()-1));
 393             mv.visitFieldInsn(Opcodes.PUTSTATIC, className, p.name, p.desc);
 394         }
 395         mv.visitInsn(Opcodes.RETURN);
 396         mv.visitMaxs(2, 1);
 397         mv.visitEnd();
 398     }
 399 
 400     /*
 401      * Low-level emit helpers.
 402      */
 403     private void emitConst(Object con) {
 404         if (con == null) {
 405             mv.visitInsn(Opcodes.ACONST_NULL);
 406             return;
 407         }
 408         if (con instanceof Integer) {
 409             emitIconstInsn((int) con);
 410             return;
 411         }
 412         if (con instanceof Byte) {
 413             emitIconstInsn((byte)con);
 414             return;
 415         }
 416         if (con instanceof Short) {
 417             emitIconstInsn((short)con);
 418             return;
 419         }
 420         if (con instanceof Character) {
 421             emitIconstInsn((char)con);
 422             return;
 423         }
 424         if (con instanceof Long) {
 425             long x = (long) con;
 426             short sx = (short)x;
 427             if (x == sx) {
 428                 if (sx >= 0 && sx <= 1) {
 429                     mv.visitInsn(Opcodes.LCONST_0 + (int) sx);
 430                 } else {
 431                     emitIconstInsn((int) x);
 432                     mv.visitInsn(Opcodes.I2L);
 433                 }
 434                 return;
 435             }
 436         }
 437         if (con instanceof Float) {
 438             float x = (float) con;
 439             short sx = (short)x;
 440             if (x == sx) {
 441                 if (sx >= 0 && sx <= 2) {
 442                     mv.visitInsn(Opcodes.FCONST_0 + (int) sx);
 443                 } else {
 444                     emitIconstInsn((int) x);
 445                     mv.visitInsn(Opcodes.I2F);
 446                 }
 447                 return;
 448             }
 449         }
 450         if (con instanceof Double) {
 451             double x = (double) con;
 452             short sx = (short)x;
 453             if (x == sx) {
 454                 if (sx >= 0 && sx <= 1) {
 455                     mv.visitInsn(Opcodes.DCONST_0 + (int) sx);
 456                 } else {
 457                     emitIconstInsn((int) x);
 458                     mv.visitInsn(Opcodes.I2D);
 459                 }
 460                 return;
 461             }
 462         }
 463         if (con instanceof Boolean) {
 464             emitIconstInsn((boolean) con ? 1 : 0);
 465             return;
 466         }
 467         // fall through:
 468         mv.visitLdcInsn(con);
 469     }
 470 
 471     private void emitIconstInsn(final int cst) {
 472         emitIconstInsn(mv, cst);
 473     }
 474 
 475     private static void emitIconstInsn(MethodVisitor mv, int cst) {
 476         if (cst >= -1 && cst <= 5) {
 477             mv.visitInsn(Opcodes.ICONST_0 + cst);
 478         } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) {
 479             mv.visitIntInsn(Opcodes.BIPUSH, cst);
 480         } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) {
 481             mv.visitIntInsn(Opcodes.SIPUSH, cst);
 482         } else {
 483             mv.visitLdcInsn(cst);
 484         }
 485     }
 486 
 487     /*
 488      * NOTE: These load/store methods use the localsMap to find the correct index!
 489      */
 490     private void emitLoadInsn(BasicType type, int index) {
 491         int opcode = loadInsnOpcode(type);
 492         mv.visitVarInsn(opcode, localsMap[index]);
 493     }
 494 
 495     private int loadInsnOpcode(BasicType type) throws InternalError {
 496         return switch (type) {
 497             case I_TYPE -> Opcodes.ILOAD;
 498             case J_TYPE -> Opcodes.LLOAD;
 499             case F_TYPE -> Opcodes.FLOAD;
 500             case D_TYPE -> Opcodes.DLOAD;
 501             case L_TYPE -> Opcodes.ALOAD;
 502             default -> throw new InternalError("unknown type: " + type);
 503         };
 504     }
 505     private void emitAloadInsn(int index) {
 506         emitLoadInsn(L_TYPE, index);
 507     }
 508 
 509     private void emitStoreInsn(BasicType type, int index) {
 510         int opcode = storeInsnOpcode(type);
 511         mv.visitVarInsn(opcode, localsMap[index]);
 512     }
 513 
 514     private int storeInsnOpcode(BasicType type) throws InternalError {
 515         return switch (type) {
 516             case I_TYPE -> Opcodes.ISTORE;
 517             case J_TYPE -> Opcodes.LSTORE;
 518             case F_TYPE -> Opcodes.FSTORE;
 519             case D_TYPE -> Opcodes.DSTORE;
 520             case L_TYPE -> Opcodes.ASTORE;
 521             default -> throw new InternalError("unknown type: " + type);
 522         };
 523     }
 524     private void emitAstoreInsn(int index) {
 525         emitStoreInsn(L_TYPE, index);
 526     }
 527 
 528     private byte arrayTypeCode(Wrapper elementType) {
 529         return (byte) switch (elementType) {
 530             case BOOLEAN -> Opcodes.T_BOOLEAN;
 531             case BYTE    -> Opcodes.T_BYTE;
 532             case CHAR    -> Opcodes.T_CHAR;
 533             case SHORT   -> Opcodes.T_SHORT;
 534             case INT     -> Opcodes.T_INT;
 535             case LONG    -> Opcodes.T_LONG;
 536             case FLOAT   -> Opcodes.T_FLOAT;
 537             case DOUBLE  -> Opcodes.T_DOUBLE;
 538             case OBJECT  -> 0; // in place of Opcodes.T_OBJECT
 539             default -> throw new InternalError();
 540         };
 541     }
 542 
 543     private int arrayInsnOpcode(byte tcode, int aaop) throws InternalError {
 544         assert(aaop == Opcodes.AASTORE || aaop == Opcodes.AALOAD);
 545         int xas = switch (tcode) {
 546             case Opcodes.T_BOOLEAN -> Opcodes.BASTORE;
 547             case Opcodes.T_BYTE    -> Opcodes.BASTORE;
 548             case Opcodes.T_CHAR    -> Opcodes.CASTORE;
 549             case Opcodes.T_SHORT   -> Opcodes.SASTORE;
 550             case Opcodes.T_INT     -> Opcodes.IASTORE;
 551             case Opcodes.T_LONG    -> Opcodes.LASTORE;
 552             case Opcodes.T_FLOAT   -> Opcodes.FASTORE;
 553             case Opcodes.T_DOUBLE  -> Opcodes.DASTORE;
 554             case 0                 -> Opcodes.AASTORE;
 555             default -> throw new InternalError();
 556         };
 557         return xas - Opcodes.AASTORE + aaop;
 558     }
 559 
 560     /**
 561      * Emit a boxing call.
 562      *
 563      * @param wrapper primitive type class to box.
 564      */
 565     private void emitBoxing(Wrapper wrapper) {
 566         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 567         String name  = "valueOf";
 568         String desc  = "(" + wrapper.basicTypeChar() + ")L" + owner + ";";
 569         mv.visitMethodInsn(Opcodes.INVOKESTATIC, owner, name, desc, false);
 570     }
 571 
 572     /**
 573      * Emit an unboxing call (plus preceding checkcast).
 574      *
 575      * @param wrapper wrapper type class to unbox.
 576      */
 577     private void emitUnboxing(Wrapper wrapper) {
 578         String owner = "java/lang/" + wrapper.wrapperType().getSimpleName();
 579         String name  = wrapper.primitiveSimpleName() + "Value";
 580         String desc  = "()" + wrapper.basicTypeChar();
 581         emitReferenceCast(wrapper.wrapperType(), null);
 582         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, owner, name, desc, false);
 583     }
 584 
 585     /**
 586      * Emit an implicit conversion for an argument which must be of the given pclass.
 587      * This is usually a no-op, except when pclass is a subword type or a reference other than Object or an interface.
 588      *
 589      * @param ptype type of value present on stack
 590      * @param pclass type of value required on stack
 591      * @param arg compile-time representation of value on stack (Node, constant) or null if none
 592      */
 593     private void emitImplicitConversion(BasicType ptype, Class<?> pclass, Object arg) {
 594         assert(basicType(pclass) == ptype);  // boxing/unboxing handled by caller
 595         if (pclass == ptype.basicTypeClass() && ptype != L_TYPE)
 596             return;   // nothing to do
 597         switch (ptype) {
 598             case L_TYPE:
 599                 if (VerifyType.isNullConversion(Object.class, pclass, false)) {
 600                     if (PROFILE_LEVEL > 0)
 601                         emitReferenceCast(Object.class, arg);
 602                     return;
 603                 }
 604                 emitReferenceCast(pclass, arg);
 605                 return;
 606             case I_TYPE:
 607                 if (!VerifyType.isNullConversion(int.class, pclass, false))
 608                     emitPrimCast(ptype.basicTypeWrapper(), Wrapper.forPrimitiveType(pclass));
 609                 return;
 610         }
 611         throw newInternalError("bad implicit conversion: tc="+ptype+": "+pclass);
 612     }
 613 
 614     /** Update localClasses type map.  Return true if the information is already present. */
 615     private boolean assertStaticType(Class<?> cls, Name n) {
 616         int local = n.index();
 617         Class<?> aclass = localClasses[local];
 618         if (aclass != null && (aclass == cls || cls.isAssignableFrom(aclass))) {
 619             return true;  // type info is already present
 620         } else if (aclass == null || aclass.isAssignableFrom(cls)) {
 621             localClasses[local] = cls;  // type info can be improved
 622         }
 623         return false;
 624     }
 625 
 626     private void emitReferenceCast(Class<?> cls, Object arg) {
 627         Name writeBack = null;  // local to write back result
 628         if (arg instanceof Name n) {
 629             if (lambdaForm.useCount(n) > 1) {
 630                 // This guy gets used more than once.
 631                 writeBack = n;
 632                 if (assertStaticType(cls, n)) {
 633                     return; // this cast was already performed
 634                 }
 635             }
 636         }
 637         if (isStaticallyNameable(cls)) {
 638             String sig = getInternalName(cls);
 639             mv.visitTypeInsn(Opcodes.CHECKCAST, sig);
 640         } else {
 641             mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(cls), "Ljava/lang/Class;");
 642             mv.visitInsn(Opcodes.SWAP);
 643             mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLS, "cast", LL_SIG, false);
 644             if (Object[].class.isAssignableFrom(cls))
 645                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 646             else if (PROFILE_LEVEL > 0)
 647                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ);
 648         }
 649         if (writeBack != null) {
 650             mv.visitInsn(Opcodes.DUP);
 651             emitAstoreInsn(writeBack.index());
 652         }
 653     }
 654 
 655     /**
 656      * Emits an actual return instruction conforming to the given return type.
 657      */
 658     private void emitReturnInsn(BasicType type) {
 659         int opcode = switch (type) {
 660             case I_TYPE -> Opcodes.IRETURN;
 661             case J_TYPE -> Opcodes.LRETURN;
 662             case F_TYPE -> Opcodes.FRETURN;
 663             case D_TYPE -> Opcodes.DRETURN;
 664             case L_TYPE -> Opcodes.ARETURN;
 665             case V_TYPE -> Opcodes.RETURN;
 666             default -> throw new InternalError("unknown return type: " + type);
 667         };
 668         mv.visitInsn(opcode);
 669     }
 670 
 671     private String getInternalName(Class<?> c) {
 672         if (c == Object.class)             return OBJ;
 673         else if (c == Object[].class)      return OBJARY;
 674         else if (c == Class.class)         return CLS;
 675         else if (c == MethodHandle.class)  return MH;
 676         assert(VerifyAccess.isTypeVisible(c, Object.class)) : c.getName();
 677 
 678         if (c == lastClass) {
 679             return lastInternalName;
 680         }
 681         lastClass = c;
 682         return lastInternalName = c.getName().replace('.', '/');
 683     }
 684 
 685     private static MemberName resolveFrom(String name, MethodType type, Class<?> holder) {
 686         MemberName member = new MemberName(holder, name, type, REF_invokeStatic);
 687         MemberName resolvedMember = MemberName.getFactory().resolveOrNull(REF_invokeStatic, member, holder, LM_TRUSTED);
 688         traceLambdaForm(name, type, holder, resolvedMember);
 689         return resolvedMember;
 690     }
 691 
 692     private static MemberName lookupPregenerated(LambdaForm form, MethodType invokerType) {
 693         if (form.customized != null) {
 694             // No pre-generated version for customized LF
 695             return null;
 696         }
 697         String name = form.kind.methodName;
 698         switch (form.kind) {
 699             case BOUND_REINVOKER: {
 700                 name = name + "_" + BoundMethodHandle.speciesDataFor(form).key();
 701                 return resolveFrom(name, invokerType, DelegatingMethodHandle.Holder.class);
 702             }
 703             case DELEGATE:                  return resolveFrom(name, invokerType, DelegatingMethodHandle.Holder.class);
 704             case ZERO:                      // fall-through
 705             case IDENTITY: {
 706                 name = name + "_" + form.returnType().basicTypeChar();
 707                 return resolveFrom(name, invokerType, LambdaForm.Holder.class);
 708             }
 709             case EXACT_INVOKER:             // fall-through
 710             case EXACT_LINKER:              // fall-through
 711             case LINK_TO_CALL_SITE:         // fall-through
 712             case LINK_TO_TARGET_METHOD:     // fall-through
 713             case GENERIC_INVOKER:           // fall-through
 714             case GENERIC_LINKER:            return resolveFrom(name, invokerType, Invokers.Holder.class);
 715             case GET_REFERENCE:             // fall-through
 716             case GET_BOOLEAN:               // fall-through
 717             case GET_BYTE:                  // fall-through
 718             case GET_CHAR:                  // fall-through
 719             case GET_SHORT:                 // fall-through
 720             case GET_INT:                   // fall-through
 721             case GET_LONG:                  // fall-through
 722             case GET_FLOAT:                 // fall-through
 723             case GET_DOUBLE:                // fall-through
 724             case PUT_REFERENCE:             // fall-through
 725             case PUT_BOOLEAN:               // fall-through
 726             case PUT_BYTE:                  // fall-through
 727             case PUT_CHAR:                  // fall-through
 728             case PUT_SHORT:                 // fall-through
 729             case PUT_INT:                   // fall-through
 730             case PUT_LONG:                  // fall-through
 731             case PUT_FLOAT:                 // fall-through
 732             case PUT_DOUBLE:                // fall-through
 733             case DIRECT_NEW_INVOKE_SPECIAL: // fall-through
 734             case DIRECT_INVOKE_INTERFACE:   // fall-through
 735             case DIRECT_INVOKE_SPECIAL:     // fall-through
 736             case DIRECT_INVOKE_SPECIAL_IFC: // fall-through
 737             case DIRECT_INVOKE_STATIC:      // fall-through
 738             case DIRECT_INVOKE_STATIC_INIT: // fall-through
 739             case DIRECT_INVOKE_VIRTUAL:     return resolveFrom(name, invokerType, DirectMethodHandle.Holder.class);
 740         }
 741         return null;
 742     }
 743 
 744     /**
 745      * Generate customized bytecode for a given LambdaForm.
 746      */
 747     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 748         MemberName pregenerated = lookupPregenerated(form, invokerType);
 749         if (pregenerated != null)  return pregenerated; // pre-generated bytecode
 750 
 751         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 752         return g.loadMethod(g.generateCustomizedCodeBytes());
 753     }
 754 
 755     /** Generates code to check that actual receiver and LambdaForm matches */
 756     private boolean checkActualReceiver() {
 757         // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0
 758         mv.visitInsn(Opcodes.DUP);
 759         mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]);
 760         mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false);
 761         return true;
 762     }
 763 
 764     static String className(String cn) {
 765         assert checkClassName(cn): "Class not found: " + cn;
 766         return cn;
 767     }
 768 
 769     static boolean checkClassName(String cn) {
 770         Type tp = Type.getType(cn);
 771         // additional sanity so only valid "L;" descriptors work
 772         if (tp.getSort() != Type.OBJECT) {
 773             return false;
 774         }
 775         try {
 776             Class<?> c = Class.forName(tp.getClassName(), false, null);
 777             return true;
 778         } catch (ClassNotFoundException e) {
 779             return false;
 780         }
 781     }
 782 
 783     static final String      DONTINLINE_SIG = className("Ljdk/internal/vm/annotation/DontInline;");
 784     static final String     FORCEINLINE_SIG = className("Ljdk/internal/vm/annotation/ForceInline;");
 785     static final String          HIDDEN_SIG = className("Ljdk/internal/vm/annotation/Hidden;");
 786     static final String INJECTEDPROFILE_SIG = className("Ljava/lang/invoke/InjectedProfile;");
 787     static final String     LF_COMPILED_SIG = className("Ljava/lang/invoke/LambdaForm$Compiled;");
 788 
 789     /**
 790      * Generate an invoker method for the passed {@link LambdaForm}.
 791      */
 792     private byte[] generateCustomizedCodeBytes() {
 793         classFilePrologue();
 794         addMethod();
 795         clinit(cw, className, classData);
 796         bogusMethod(lambdaForm);
 797 
 798         final byte[] classFile = toByteArray();
 799         maybeDump(classFile);
 800         return classFile;
 801     }
 802 
 803     void setClassWriter(ClassWriter cw) {
 804         this.cw = cw;
 805     }
 806 
 807     void addMethod() {
 808         methodPrologue();
 809 
 810         // Suppress this method in backtraces displayed to the user.
 811         mv.visitAnnotation(HIDDEN_SIG, true);
 812 
 813         // Mark this method as a compiled LambdaForm
 814         mv.visitAnnotation(LF_COMPILED_SIG, true);
 815 
 816         if (lambdaForm.forceInline) {
 817             // Force inlining of this invoker method.
 818             mv.visitAnnotation(FORCEINLINE_SIG, true);
 819         } else {
 820             mv.visitAnnotation(DONTINLINE_SIG, true);
 821         }
 822 
 823         classData(lambdaForm); // keep LambdaForm instance & its compiled form lifetime tightly coupled.
 824 
 825         if (lambdaForm.customized != null) {
 826             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 827             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 828             // It enables more efficient code generation in some situations, since embedded constants
 829             // are compile-time constants for JIT compiler.
 830             mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(lambdaForm.customized), MH_SIG);
 831             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 832             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 833             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 834         }
 835 
 836         // iterate over the form's names, generating bytecode instructions for each
 837         // start iterating at the first name following the arguments
 838         Name onStack = null;
 839         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 840             Name name = lambdaForm.names[i];
 841 
 842             emitStoreResult(onStack);
 843             onStack = name;  // unless otherwise modified below
 844             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 845             switch (intr) {
 846                 case SELECT_ALTERNATIVE:
 847                     assert lambdaForm.isSelectAlternative(i);
 848                     if (PROFILE_GWT) {
 849                         assert(name.arguments[0] instanceof Name &&
 850                                 ((Name)name.arguments[0]).refersTo(MethodHandleImpl.class, "profileBoolean"));
 851                         mv.visitAnnotation(INJECTEDPROFILE_SIG, true);
 852                     }
 853                     onStack = emitSelectAlternative(name, lambdaForm.names[i+1]);
 854                     i++;  // skip MH.invokeBasic of the selectAlternative result
 855                     continue;
 856                 case GUARD_WITH_CATCH:
 857                     assert lambdaForm.isGuardWithCatch(i);
 858                     onStack = emitGuardWithCatch(i);
 859                     i += 2; // jump to the end of GWC idiom
 860                     continue;
 861                 case TRY_FINALLY:
 862                     assert lambdaForm.isTryFinally(i);
 863                     onStack = emitTryFinally(i);
 864                     i += 2; // jump to the end of the TF idiom
 865                     continue;
 866                 case TABLE_SWITCH:
 867                     assert lambdaForm.isTableSwitch(i);
 868                     int numCases = (Integer) name.function.intrinsicData();
 869                     onStack = emitTableSwitch(i, numCases);
 870                     i += 2; // jump to the end of the TS idiom
 871                     continue;
 872                 case LOOP:
 873                     assert lambdaForm.isLoop(i);
 874                     onStack = emitLoop(i);
 875                     i += 2; // jump to the end of the LOOP idiom
 876                     continue;
 877                 case ARRAY_LOAD:
 878                     emitArrayLoad(name);
 879                     continue;
 880                 case ARRAY_STORE:
 881                     emitArrayStore(name);
 882                     continue;
 883                 case ARRAY_LENGTH:
 884                     emitArrayLength(name);
 885                     continue;
 886                 case IDENTITY:
 887                     assert(name.arguments.length == 1);
 888                     emitPushArguments(name, 0);
 889                     continue;
 890                 case ZERO:
 891                     assert(name.arguments.length == 0);
 892                     emitConst(name.type.basicTypeWrapper().zero());
 893                     continue;
 894                 case NONE:
 895                     // no intrinsic associated
 896                     break;
 897                 default:
 898                     throw newInternalError("Unknown intrinsic: "+intr);
 899             }
 900 
 901             MemberName member = name.function.member();
 902             if (isStaticallyInvocable(member)) {
 903                 emitStaticInvoke(member, name);
 904             } else {
 905                 emitInvoke(name);
 906             }
 907         }
 908 
 909         // return statement
 910         emitReturn(onStack);
 911 
 912         methodEpilogue();
 913     }
 914 
 915     /*
 916      * @throws BytecodeGenerationException if something goes wrong when
 917      *         generating the byte code
 918      */
 919     private byte[] toByteArray() {
 920         try {
 921             return cw.toByteArray();
 922         } catch (RuntimeException e) {
 923             throw new BytecodeGenerationException(e);
 924         }
 925     }
 926 
 927     /**
 928      * The BytecodeGenerationException.
 929      */
 930     @SuppressWarnings("serial")
 931     static final class BytecodeGenerationException extends RuntimeException {
 932         BytecodeGenerationException(Exception cause) {
 933             super(cause);
 934         }
 935     }
 936 
 937     void emitArrayLoad(Name name)   { emitArrayOp(name, Opcodes.AALOAD);      }
 938     void emitArrayStore(Name name)  { emitArrayOp(name, Opcodes.AASTORE);     }
 939     void emitArrayLength(Name name) { emitArrayOp(name, Opcodes.ARRAYLENGTH); }
 940 
 941     void emitArrayOp(Name name, int arrayOpcode) {
 942         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
 943         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 944         assert elementType != null;
 945         emitPushArguments(name, 0);
 946         if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
 947             Wrapper w = Wrapper.forPrimitiveType(elementType);
 948             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 949         }
 950         mv.visitInsn(arrayOpcode);
 951     }
 952 
 953     /**
 954      * Emit an invoke for the given name.
 955      */
 956     void emitInvoke(Name name) {
 957         assert(!name.isLinkerMethodInvoke());  // should use the static path for these
 958         if (true) {
 959             // push receiver
 960             MethodHandle target = name.function.resolvedHandle();
 961             assert(target != null) : name.exprString();
 962             mv.visitFieldInsn(Opcodes.GETSTATIC, className, classData(target), MH_SIG);
 963             emitReferenceCast(MethodHandle.class, target);
 964         } else {
 965             // load receiver
 966             emitAloadInsn(0);
 967             emitReferenceCast(MethodHandle.class, null);
 968             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 969             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 970             // TODO more to come
 971         }
 972 
 973         // push arguments
 974         emitPushArguments(name, 0);
 975 
 976         // invocation
 977         MethodType type = name.function.methodType();
 978         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 979     }
 980 
 981     private static final Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 982         // Sample classes from each package we are willing to bind to statically:
 983         java.lang.Object.class,
 984         java.util.Arrays.class,
 985         jdk.internal.misc.Unsafe.class
 986         //MethodHandle.class already covered
 987     };
 988 
 989     static boolean isStaticallyInvocable(NamedFunction ... functions) {
 990         for (NamedFunction nf : functions) {
 991             if (!isStaticallyInvocable(nf.member())) {
 992                 return false;
 993             }
 994         }
 995         return true;
 996     }
 997 
 998     static boolean isStaticallyInvocable(Name name) {
 999         return isStaticallyInvocable(name.function.member());
1000     }
1001 
1002     static boolean isStaticallyInvocable(MemberName member) {
1003         if (member == null)  return false;
1004         if (member.isConstructor())  return false;
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 }