1 /*
   2  * Copyright (c) 2011, 2025, 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 java.lang.classfile.TypeKind;
  29 import jdk.internal.perf.PerfCounter;
  30 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
  31 import jdk.internal.vm.annotation.DontInline;
  32 import jdk.internal.vm.annotation.Hidden;
  33 import jdk.internal.vm.annotation.Stable;
  34 import sun.invoke.util.Wrapper;
  35 
  36 import java.lang.annotation.ElementType;
  37 import java.lang.annotation.Retention;
  38 import java.lang.annotation.RetentionPolicy;
  39 import java.lang.annotation.Target;
  40 import java.lang.reflect.Method;
  41 import java.util.Arrays;
  42 import java.util.HashMap;
  43 
  44 import static java.lang.invoke.LambdaForm.BasicType.*;
  45 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  46 import static java.lang.invoke.MethodHandleStatics.*;
  47 
  48 /**
  49  * The symbolic, non-executable form of a method handle's invocation semantics.
  50  * It consists of a series of names.
  51  * The first N (N=arity) names are parameters,
  52  * while any remaining names are temporary values.
  53  * Each temporary specifies the application of a function to some arguments.
  54  * The functions are method handles, while the arguments are mixes of
  55  * constant values and local names.
  56  * The result of the lambda is defined as one of the names, often the last one.
  57  * <p>
  58  * Here is an approximate grammar:
  59  * <blockquote><pre>{@code
  60  * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}"
  61  * ArgName = "a" N ":" T
  62  * TempName = "t" N ":" T "=" Function "(" Argument* ");"
  63  * Function = ConstantValue
  64  * Argument = NameRef | ConstantValue
  65  * Result = NameRef | "void"
  66  * NameRef = "a" N | "t" N
  67  * N = (any whole number)
  68  * T = "L" | "I" | "J" | "F" | "D" | "V"
  69  * }</pre></blockquote>
  70  * Names are numbered consecutively from left to right starting at zero.
  71  * (The letters are merely a taste of syntax sugar.)
  72  * Thus, the first temporary (if any) is always numbered N (where N=arity).
  73  * Every occurrence of a name reference in an argument list must refer to
  74  * a name previously defined within the same lambda.
  75  * A lambda has a void result if and only if its result index is -1.
  76  * If a temporary has the type "V", it cannot be the subject of a NameRef,
  77  * even though possesses a number.
  78  * Note that all reference types are erased to "L", which stands for {@code Object}.
  79  * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}.
  80  * The other types stand for the usual primitive types.
  81  * <p>
  82  * Function invocation closely follows the static rules of the Java verifier.
  83  * Arguments and return values must exactly match when their "Name" types are
  84  * considered.
  85  * Conversions are allowed only if they do not change the erased type.
  86  * <ul>
  87  * <li>L = Object: casts are used freely to convert into and out of reference types
  88  * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments})
  89  * <li>J = long: no implicit conversions
  90  * <li>F = float: no implicit conversions
  91  * <li>D = double: no implicit conversions
  92  * <li>V = void: a function result may be void if and only if its Name is of type "V"
  93  * </ul>
  94  * Although implicit conversions are not allowed, explicit ones can easily be
  95  * encoded by using temporary expressions which call type-transformed identity functions.
  96  * <p>
  97  * Examples:
  98  * <blockquote><pre>{@code
  99  * (a0:J)=>{ a0 }
 100  *     == identity(long)
 101  * (a0:I)=>{ t1:V = System.out#println(a0); void }
 102  *     == System.out#println(int)
 103  * (a0:L)=>{ t1:V = System.out#println(a0); a0 }
 104  *     == identity, with printing side-effect
 105  * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
 106  *                 t3:L = BoundMethodHandle#target(a0);
 107  *                 t4:L = MethodHandle#invoke(t3, t2, a1); t4 }
 108  *     == general invoker for unary insertArgument combination
 109  * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0);
 110  *                 t3:L = MethodHandle#invoke(t2, a1);
 111  *                 t4:L = FilterMethodHandle#target(a0);
 112  *                 t5:L = MethodHandle#invoke(t4, t3); t5 }
 113  *     == general invoker for unary filterArgument combination
 114  * (a0:L, a1:L)=>{ ...(same as previous example)...
 115  *                 t5:L = MethodHandle#invoke(t4, t3, a1); t5 }
 116  *     == general invoker for unary/unary foldArgument combination
 117  * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 }
 118  *     == invoker for identity method handle which performs i2l
 119  * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
 120  *                 t3:L = Class#cast(t2,a1); t3 }
 121  *     == invoker for identity method handle which performs cast
 122  * }</pre></blockquote>
 123  * <p>
 124  * @author John Rose, JSR 292 EG
 125  */
 126 @AOTSafeClassInitializer
 127 class LambdaForm {
 128     final int arity;
 129     final int result;
 130     final boolean forceInline;
 131     final MethodHandle customized;
 132     @Stable final Name[] names;
 133     final Kind kind;
 134     MemberName vmentry;   // low-level behavior, or null if not yet prepared
 135     private boolean isCompiled;
 136 
 137     // Either a LambdaForm cache (managed by LambdaFormEditor) or a link to uncustomized version (for customized LF)
 138     volatile Object transformCache;
 139 
 140     public static final int VOID_RESULT = -1, LAST_RESULT = -2;
 141 
 142     enum BasicType {
 143         L_TYPE('L', Object.class, Wrapper.OBJECT, TypeKind.REFERENCE), // all reference types
 144         I_TYPE('I', int.class,    Wrapper.INT,    TypeKind.INT),
 145         J_TYPE('J', long.class,   Wrapper.LONG,   TypeKind.LONG),
 146         F_TYPE('F', float.class,  Wrapper.FLOAT,  TypeKind.FLOAT),
 147         D_TYPE('D', double.class, Wrapper.DOUBLE, TypeKind.DOUBLE),  // all primitive types
 148         V_TYPE('V', void.class,   Wrapper.VOID,   TypeKind.VOID);    // not valid in all contexts
 149 
 150         static final @Stable BasicType[] ALL_TYPES = BasicType.values();
 151         static final @Stable BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1);
 152 
 153         static final int ARG_TYPE_LIMIT = ARG_TYPES.length;
 154         static final int TYPE_LIMIT = ALL_TYPES.length;
 155 
 156         final char btChar;
 157         final Class<?> btClass;
 158         final Wrapper btWrapper;
 159         final TypeKind btKind;
 160 
 161         private BasicType(char btChar, Class<?> btClass, Wrapper wrapper, TypeKind typeKind) {
 162             this.btChar = btChar;
 163             this.btClass = btClass;
 164             this.btWrapper = wrapper;
 165             this.btKind = typeKind;
 166         }
 167 
 168         char basicTypeChar() {
 169             return btChar;
 170         }
 171         Class<?> basicTypeClass() {
 172             return btClass;
 173         }
 174         Wrapper basicTypeWrapper() {
 175             return btWrapper;
 176         }
 177         TypeKind basicTypeKind() {
 178             return btKind;
 179         }
 180         int basicTypeSlots() {
 181             return btWrapper.stackSlots();
 182         }
 183 
 184         static BasicType basicType(byte type) {
 185             return ALL_TYPES[type];
 186         }
 187         static BasicType basicType(char type) {
 188             return switch (type) {
 189                 case 'L' -> L_TYPE;
 190                 case 'I' -> I_TYPE;
 191                 case 'J' -> J_TYPE;
 192                 case 'F' -> F_TYPE;
 193                 case 'D' -> D_TYPE;
 194                 case 'V' -> V_TYPE;
 195                 // all subword types are represented as ints
 196                 case 'Z', 'B', 'S', 'C' -> I_TYPE;
 197                 default -> throw newInternalError("Unknown type char: '" + type + "'");
 198             };
 199         }
 200         static BasicType basicType(Class<?> type) {
 201             return basicType(Wrapper.basicTypeChar(type));
 202         }
 203         static int[] basicTypeOrds(BasicType[] types) {
 204             if (types == null) {
 205                 return null;
 206             }
 207             int[] a = new int[types.length];
 208             for(int i = 0; i < types.length; ++i) {
 209                 a[i] = types[i].ordinal();
 210             }
 211             return a;
 212         }
 213 
 214         static char basicTypeChar(Class<?> type) {
 215             return basicType(type).btChar;
 216         }
 217 
 218         static int[] basicTypesOrd(Class<?>[] types) {
 219             int[] ords = new int[types.length];
 220             for (int i = 0; i < ords.length; i++) {
 221                 ords[i] = basicType(types[i]).ordinal();
 222             }
 223             return ords;
 224         }
 225 
 226         static boolean isBasicTypeChar(char c) {
 227             return "LIJFDV".indexOf(c) >= 0;
 228         }
 229         static boolean isArgBasicTypeChar(char c) {
 230             return "LIJFD".indexOf(c) >= 0;
 231         }
 232 
 233         static { assert(checkBasicType()); }
 234         private static boolean checkBasicType() {
 235             for (int i = 0; i < ARG_TYPE_LIMIT; i++) {
 236                 assert ARG_TYPES[i].ordinal() == i;
 237                 assert ARG_TYPES[i] == ALL_TYPES[i];
 238             }
 239             for (int i = 0; i < TYPE_LIMIT; i++) {
 240                 assert ALL_TYPES[i].ordinal() == i;
 241             }
 242             assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE;
 243             assert !Arrays.asList(ARG_TYPES).contains(V_TYPE);
 244             return true;
 245         }
 246     }
 247 
 248     enum Kind {
 249         GENERIC("invoke"),
 250         IDENTITY("identity"),
 251         CONSTANT("constant"),
 252         BOUND_REINVOKER("BMH.reinvoke", "reinvoke"),
 253         REINVOKER("MH.reinvoke", "reinvoke"),
 254         DELEGATE("MH.delegate", "delegate"),
 255         EXACT_LINKER("MH.invokeExact_MT", "invokeExact_MT"),
 256         EXACT_INVOKER("MH.exactInvoker", "exactInvoker"),
 257         GENERIC_LINKER("MH.invoke_MT", "invoke_MT"),
 258         GENERIC_INVOKER("MH.invoker", "invoker"),
 259         LINK_TO_TARGET_METHOD("linkToTargetMethod"),
 260         LINK_TO_CALL_SITE("linkToCallSite"),
 261         DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual", "invokeVirtual"),
 262         DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial", "invokeSpecial"),
 263         DIRECT_INVOKE_SPECIAL_IFC("DMH.invokeSpecialIFC", "invokeSpecialIFC"),
 264         DIRECT_INVOKE_STATIC("DMH.invokeStatic", "invokeStatic"),
 265         DIRECT_NEW_INVOKE_SPECIAL("DMH.newInvokeSpecial", "newInvokeSpecial"),
 266         DIRECT_INVOKE_INTERFACE("DMH.invokeInterface", "invokeInterface"),
 267         DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit", "invokeStaticInit"),
 268         // Start field forms
 269         // IJFDL, instance/static differ in method type, can share form
 270         // init form only applicable to static
 271         FIELD_ACCESS("fieldAccess"),
 272         FIELD_ACCESS_INIT("fieldAccessInit"),
 273         VOLATILE_FIELD_ACCESS("volatileFieldAccess"),
 274         VOLATILE_FIELD_ACCESS_INIT("volatileFieldAccessInit"),
 275         // BCSZ need own forms to avoid clashing with basic type I, +-init/volatile
 276         FIELD_ACCESS_B("fieldAccessB"),
 277         FIELD_ACCESS_INIT_B("fieldAccessInitB"),
 278         VOLATILE_FIELD_ACCESS_B("volatileFieldAccessB"),
 279         VOLATILE_FIELD_ACCESS_INIT_B("volatileFieldAccessInitB"),
 280         FIELD_ACCESS_C("fieldAccessC"),
 281         FIELD_ACCESS_INIT_C("fieldAccessInitC"),
 282         VOLATILE_FIELD_ACCESS_C("volatileFieldAccessC"),
 283         VOLATILE_FIELD_ACCESS_INIT_C("volatileFieldAccessInitC"),
 284         FIELD_ACCESS_S("fieldAccessS"),
 285         FIELD_ACCESS_INIT_S("fieldAccessInitS"),
 286         VOLATILE_FIELD_ACCESS_S("volatileFieldAccessS"),
 287         VOLATILE_FIELD_ACCESS_INIT_S("volatileFieldAccessInitS"),
 288         FIELD_ACCESS_Z("fieldAccessZ"),
 289         FIELD_ACCESS_INIT_Z("fieldAccessInitZ"),
 290         VOLATILE_FIELD_ACCESS_Z("volatileFieldAccessZ"),
 291         VOLATILE_FIELD_ACCESS_INIT_Z("volatileFieldAccessInitZ"),
 292         // cast, nr, flat need their own forms to avoid clashing with L
 293         FIELD_ACCESS_CAST("fieldAccessCast"),
 294         FIELD_ACCESS_INIT_CAST("fieldAccessInitCast"),
 295         VOLATILE_FIELD_ACCESS_CAST("volatileFieldAccessCast"),
 296         VOLATILE_FIELD_ACCESS_INIT_CAST("volatileFieldAccessInitCast"),
 297         // null-check and put reference, +-cast, +-init/volatile
 298         // non-cast forms serve bytecode emulation purpose, which always enforces null checks
 299         PUT_NULL_RESTRICTED_REFERENCE("putNullRestrictedReference"),
 300         PUT_NULL_RESTRICTED_REFERENCE_INIT("putNullRestrictedReferenceInit"),
 301         VOLATILE_PUT_NULL_RESTRICTED_REFERENCE("volatilePutNullRestrictedReference"),
 302         VOLATILE_PUT_NULL_RESTRICTED_REFERENCE_INIT("volatilePutNullRestrictedReferenceInit"),
 303         PUT_NULL_RESTRICTED_REFERENCE_CAST("putNullRestrictedReferenceCast"),
 304         PUT_NULL_RESTRICTED_REFERENCE_CAST_INIT("putNullRestrictedReferenceInitCast"),
 305         VOLATILE_PUT_NULL_RESTRICTED_REFERENCE_CAST("volatilePutNullRestrictedReferenceCast"),
 306         VOLATILE_PUT_NULL_RESTRICTED_REFERENCE_CAST_INIT("volatilePutNullRestrictedReferenceCastInit"),
 307         // flat implies cast, +-init/volatile
 308         FIELD_ACCESS_FLAT("fieldAccessFlat"),
 309         FIELD_ACCESS_INIT_FLAT("fieldAccessInitFlat"),
 310         VOLATILE_FIELD_ACCESS_FLAT("volatileFieldAccessFlat"),
 311         VOLATILE_FIELD_ACCESS_INIT_FLAT("volatileFieldAccessInitFlat"),
 312         // write guard NR flat, implies cast; +-volatile; no init forms - no flat in static fields yet
 313         PUT_NULL_RESTRICTED_FLAT_VALUE("putNullRestrictedFlatValue"),
 314         VOLATILE_PUT_NULL_RESTRICTED_FLAT_VALUE("volatilePutNullRestrictedFlatValue"),
 315         // End fields
 316         TRY_FINALLY("tryFinally"),
 317         TABLE_SWITCH("tableSwitch"),
 318         COLLECTOR("collector"),
 319         LOOP("loop"),
 320         GUARD("guard"),
 321         GUARD_WITH_CATCH("guardWithCatch"),
 322         VARHANDLE_EXACT_INVOKER("VH.exactInvoker"),
 323         VARHANDLE_INVOKER("VH.invoker", "invoker"),
 324         VARHANDLE_LINKER("VH.invoke_MT", "invoke_MT");
 325 
 326         final String defaultLambdaName;
 327         final String methodName;
 328 
 329         private Kind(String defaultLambdaName) {
 330             this(defaultLambdaName, defaultLambdaName);
 331         }
 332 
 333         private Kind(String defaultLambdaName, String methodName) {
 334             this.defaultLambdaName = defaultLambdaName;
 335             this.methodName = methodName;
 336         }
 337     }
 338 
 339     // private version that doesn't do checks or defensive copies
 340     private LambdaForm(int arity, int result, boolean forceInline, MethodHandle customized, Name[] names, Kind kind) {
 341         this.arity = arity;
 342         this.result = result;
 343         this.forceInline = forceInline;
 344         this.customized = customized;
 345         this.names = names;
 346         this.kind = kind;
 347         this.vmentry = null;
 348         this.isCompiled = false;
 349     }
 350 
 351     // root factory pre/post processing and calls simple constructor
 352     private static LambdaForm create(int arity, Name[] names, int result, boolean forceInline, MethodHandle customized, Kind kind) {
 353         names = names.clone();
 354         assert(namesOK(arity, names));
 355         result = fixResult(result, names);
 356 
 357         boolean canInterpret = normalizeNames(arity, names);
 358         LambdaForm form = new LambdaForm(arity, result, forceInline, customized, names, kind);
 359         assert(form.nameRefsAreLegal());
 360         if (!canInterpret) {
 361             form.compileToBytecode();
 362         }
 363         return form;
 364     }
 365 
 366     // derived factories with defaults
 367     private static final int DEFAULT_RESULT = LAST_RESULT;
 368     private static final boolean DEFAULT_FORCE_INLINE = true;
 369     private static final MethodHandle DEFAULT_CUSTOMIZED = null;
 370     private static final Kind DEFAULT_KIND = Kind.GENERIC;
 371 
 372     static LambdaForm create(int arity, Name[] names, int result) {
 373         return create(arity, names, result, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, DEFAULT_KIND);
 374     }
 375     static LambdaForm create(int arity, Name[] names, int result, Kind kind) {
 376         return create(arity, names, result, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, kind);
 377     }
 378     static LambdaForm create(int arity, Name[] names) {
 379         return create(arity, names, DEFAULT_RESULT, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, DEFAULT_KIND);
 380     }
 381     static LambdaForm create(int arity, Name[] names, Kind kind) {
 382         return create(arity, names, DEFAULT_RESULT, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, kind);
 383     }
 384     static LambdaForm create(int arity, Name[] names, boolean forceInline, Kind kind) {
 385         return create(arity, names, DEFAULT_RESULT, forceInline, DEFAULT_CUSTOMIZED, kind);
 386     }
 387 
 388     private static int fixResult(int result, Name[] names) {
 389         if (result == LAST_RESULT)
 390             result = names.length - 1;  // might still be void
 391         if (result >= 0 && names[result].type == V_TYPE)
 392             result = VOID_RESULT;
 393         return result;
 394     }
 395 
 396     static boolean debugNames() {
 397         return DEBUG_NAME_COUNTERS != null;
 398     }
 399 
 400     static void associateWithDebugName(LambdaForm form, String name) {
 401         assert (debugNames());
 402         synchronized (DEBUG_NAMES) {
 403             DEBUG_NAMES.put(form, name);
 404         }
 405     }
 406 
 407     String lambdaName() {
 408         if (DEBUG_NAMES != null) {
 409             synchronized (DEBUG_NAMES) {
 410                 String name = DEBUG_NAMES.get(this);
 411                 if (name == null) {
 412                     name = generateDebugName();
 413                 }
 414                 return name;
 415             }
 416         }
 417         return kind.defaultLambdaName;
 418     }
 419 
 420     private String generateDebugName() {
 421         assert (debugNames());
 422         String debugNameStem = kind.defaultLambdaName;
 423         Integer ctr = DEBUG_NAME_COUNTERS.getOrDefault(debugNameStem, 0);
 424         DEBUG_NAME_COUNTERS.put(debugNameStem, ctr + 1);
 425         StringBuilder buf = new StringBuilder(debugNameStem);
 426         int leadingZero = buf.length();
 427         buf.append((int) ctr);
 428         for (int i = buf.length() - leadingZero; i < 3; i++) {
 429             buf.insert(leadingZero, '0');
 430         }
 431         buf.append('_');
 432         buf.append(basicTypeSignature());
 433         String name = buf.toString();
 434         associateWithDebugName(this, name);
 435         return name;
 436     }
 437 
 438     private static boolean namesOK(int arity, Name[] names) {
 439         for (int i = 0; i < names.length; i++) {
 440             Name n = names[i];
 441             assert(n != null) : "n is null";
 442             if (i < arity)
 443                 assert( n.isParam()) : n + " is not param at " + i;
 444             else
 445                 assert(!n.isParam()) : n + " is param at " + i;
 446         }
 447         return true;
 448     }
 449 
 450     /** Customize LambdaForm for a particular MethodHandle */
 451     LambdaForm customize(MethodHandle mh) {
 452         if (customized == mh) {
 453             return this;
 454         }
 455         LambdaForm customForm = LambdaForm.create(arity, names, result, forceInline, mh, kind);
 456         if (COMPILE_THRESHOLD >= 0 && isCompiled) {
 457             // If shared LambdaForm has been compiled, compile customized version as well.
 458             customForm.compileToBytecode();
 459         }
 460         customForm.transformCache = this; // LambdaFormEditor should always use uncustomized form.
 461         return customForm;
 462     }
 463 
 464     /** Get uncustomized flavor of the LambdaForm */
 465     LambdaForm uncustomize() {
 466         if (customized == null) {
 467             return this;
 468         }
 469         assert(transformCache != null); // Customized LambdaForm should always has a link to uncustomized version.
 470         LambdaForm uncustomizedForm = (LambdaForm)transformCache;
 471         if (COMPILE_THRESHOLD >= 0 && isCompiled) {
 472             // If customized LambdaForm has been compiled, compile uncustomized version as well.
 473             uncustomizedForm.compileToBytecode();
 474         }
 475         return uncustomizedForm;
 476     }
 477 
 478     /** Renumber and/or replace params so that they are interned and canonically numbered.
 479      *  @return true if we can interpret
 480      */
 481     private static boolean normalizeNames(int arity, Name[] names) {
 482         Name[] oldNames = names.clone();
 483         int maxOutArity = 0;
 484         for (int i = 0; i < names.length; i++) {
 485             Name n = names[i];
 486             names[i] = n.withIndex(i);
 487             if (n.arguments != null && maxOutArity < n.arguments.length)
 488                 maxOutArity = n.arguments.length;
 489         }
 490         if (oldNames != null) {
 491             for (int i = Math.max(1, arity); i < names.length; i++) {
 492                 Name fixed = names[i].replaceNames(oldNames, names, 0, i);
 493                 names[i] = fixed.withIndex(i);
 494             }
 495         }
 496         int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
 497         boolean needIntern = false;
 498         for (int i = 0; i < maxInterned; i++) {
 499             Name n = names[i], n2 = internArgument(n);
 500             if (n != n2) {
 501                 names[i] = n2;
 502                 needIntern = true;
 503             }
 504         }
 505         if (needIntern) {
 506             for (int i = arity; i < names.length; i++) {
 507                 names[i].internArguments();
 508             }
 509         }
 510 
 511         // return true if we can interpret
 512         if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) {
 513             // Cannot use LF interpreter on very high arity expressions.
 514             assert(maxOutArity <= MethodType.MAX_JVM_ARITY);
 515             return false;
 516         }
 517         return true;
 518     }
 519 
 520     /**
 521      * Check that all embedded Name references are localizable to this lambda,
 522      * and are properly ordered after their corresponding definitions.
 523      * <p>
 524      * Note that a Name can be local to multiple lambdas, as long as
 525      * it possesses the same index in each use site.
 526      * This allows Name references to be freely reused to construct
 527      * fresh lambdas, without confusion.
 528      */
 529     boolean nameRefsAreLegal() {
 530         assert(arity >= 0 && arity <= names.length);
 531         assert(result >= -1 && result < names.length);
 532         // Do all names possess an index consistent with their local definition order?
 533         for (int i = 0; i < arity; i++) {
 534             Name n = names[i];
 535             assert(n.index() == i) : Arrays.asList(n.index(), i);
 536             assert(n.isParam());
 537         }
 538         // Also, do all local name references
 539         for (int i = arity; i < names.length; i++) {
 540             Name n = names[i];
 541             assert(n.index() == i);
 542             for (Object arg : n.arguments) {
 543                 if (arg instanceof Name n2) {
 544                     int i2 = n2.index;
 545                     assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
 546                     assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
 547                     assert(i2 < i);  // ref must come after def!
 548                 }
 549             }
 550         }
 551         return true;
 552     }
 553 
 554     // /** Invoke this form on the given arguments. */
 555     // final Object invoke(Object... args) throws Throwable {
 556     //     // NYI: fit this into the fast path?
 557     //     return interpretWithArguments(args);
 558     // }
 559 
 560     /** Report the return type. */
 561     BasicType returnType() {
 562         if (result < 0)  return V_TYPE;
 563         Name n = names[result];
 564         return n.type;
 565     }
 566 
 567     /** Report the N-th argument type. */
 568     BasicType parameterType(int n) {
 569         return parameter(n).type;
 570     }
 571 
 572     /** Report the N-th argument name. */
 573     Name parameter(int n) {
 574         Name param = names[n];
 575         assert(n < arity && param.isParam());
 576         return param;
 577     }
 578 
 579     /** Report the N-th argument type constraint. */
 580     Object parameterConstraint(int n) {
 581         return parameter(n).constraint;
 582     }
 583 
 584     /** Report the arity. */
 585     int arity() {
 586         return arity;
 587     }
 588 
 589     /** Report the number of expressions (non-parameter names). */
 590     int expressionCount() {
 591         return names.length - arity;
 592     }
 593 
 594     /** Return the method type corresponding to my basic type signature. */
 595     MethodType methodType() {
 596         Class<?>[] ptypes = new Class<?>[arity];
 597         for (int i = 0; i < arity; ++i) {
 598             ptypes[i] = parameterType(i).btClass;
 599         }
 600         return MethodType.methodType(returnType().btClass, ptypes, true);
 601     }
 602 
 603     /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
 604     final String basicTypeSignature() {
 605         StringBuilder buf = new StringBuilder(arity() + 3);
 606         for (int i = 0, a = arity(); i < a; i++)
 607             buf.append(parameterType(i).basicTypeChar());
 608         return buf.append('_').append(returnType().basicTypeChar()).toString();
 609     }
 610     static int signatureArity(String sig) {
 611         assert(isValidSignature(sig));
 612         return sig.indexOf('_');
 613     }
 614     static boolean isValidSignature(String sig) {
 615         int arity = sig.indexOf('_');
 616         if (arity < 0)  return false;  // must be of the form *_*
 617         int siglen = sig.length();
 618         if (siglen != arity + 2)  return false;  // *_X
 619         for (int i = 0; i < siglen; i++) {
 620             if (i == arity)  continue;  // skip '_'
 621             char c = sig.charAt(i);
 622             if (c == 'V')
 623                 return (i == siglen - 1 && arity == siglen - 2);
 624             if (!isArgBasicTypeChar(c))  return false; // must be [LIJFD]
 625         }
 626         return true;  // [LIJFD]*_[LIJFDV]
 627     }
 628 
 629     /**
 630      * Check if i-th name is a call to MethodHandleImpl.selectAlternative.
 631      */
 632     boolean isSelectAlternative(int pos) {
 633         // selectAlternative idiom:
 634         //   t_{n}:L=MethodHandleImpl.selectAlternative(...)
 635         //   t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 636         if (pos+1 >= names.length)  return false;
 637         Name name0 = names[pos];
 638         Name name1 = names[pos+1];
 639         return name0.refersTo(MethodHandleImpl.class, "selectAlternative") &&
 640                 name1.isInvokeBasic() &&
 641                 name1.lastUseIndex(name0) == 0 && // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...)
 642                 lastUseIndex(name0) == pos+1;     // t_{n} is local: used only in t_{n+1}
 643     }
 644 
 645     private boolean isMatchingIdiom(int pos, String idiomName, int nArgs) {
 646         if (pos+2 >= names.length)  return false;
 647         Name name0 = names[pos];
 648         Name name1 = names[pos+1];
 649         Name name2 = names[pos+2];
 650         return name1.refersTo(MethodHandleImpl.class, idiomName) &&
 651                 name0.isInvokeBasic() &&
 652                 name2.isInvokeBasic() &&
 653                 name1.lastUseIndex(name0) == nArgs && // t_{n+1}:L=MethodHandleImpl.<invoker>(<args>, t_{n});
 654                 lastUseIndex(name0) == pos+1 &&       // t_{n} is local: used only in t_{n+1}
 655                 name2.lastUseIndex(name1) == 1 &&     // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 656                 lastUseIndex(name1) == pos+2;         // t_{n+1} is local: used only in t_{n+2}
 657     }
 658 
 659     /**
 660      * Check if i-th name is a start of GuardWithCatch idiom.
 661      */
 662     boolean isGuardWithCatch(int pos) {
 663         // GuardWithCatch idiom:
 664         //   t_{n}:L=MethodHandle.invokeBasic(...)
 665         //   t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n});
 666         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 667         return isMatchingIdiom(pos, "guardWithCatch", 3);
 668     }
 669 
 670     /**
 671      * Check if i-th name is a start of the tryFinally idiom.
 672      */
 673     boolean isTryFinally(int pos) {
 674         // tryFinally idiom:
 675         //   t_{n}:L=MethodHandle.invokeBasic(...)
 676         //   t_{n+1}:L=MethodHandleImpl.tryFinally(*, *, t_{n})
 677         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 678         return isMatchingIdiom(pos, "tryFinally", 2);
 679     }
 680 
 681     /**
 682      * Check if i-th name is a start of the tableSwitch idiom.
 683      */
 684     boolean isTableSwitch(int pos) {
 685         // tableSwitch idiom:
 686         //   t_{n}:L=MethodHandle.invokeBasic(...)     // args
 687         //   t_{n+1}:L=MethodHandleImpl.tableSwitch(*, *, *, t_{n})
 688         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 689         if (pos + 2 >= names.length)  return false;
 690 
 691         final int POS_COLLECT_ARGS = pos;
 692         final int POS_TABLE_SWITCH = pos + 1;
 693         final int POS_UNBOX_RESULT = pos + 2;
 694 
 695         Name collectArgs = names[POS_COLLECT_ARGS];
 696         Name tableSwitch = names[POS_TABLE_SWITCH];
 697         Name unboxResult = names[POS_UNBOX_RESULT];
 698         return tableSwitch.refersTo(MethodHandleImpl.class, "tableSwitch") &&
 699                 collectArgs.isInvokeBasic() &&
 700                 unboxResult.isInvokeBasic() &&
 701                 tableSwitch.lastUseIndex(collectArgs) == 3 &&     // t_{n+1}:L=MethodHandleImpl.<invoker>(*, *, *, t_{n});
 702                 lastUseIndex(collectArgs) == POS_TABLE_SWITCH &&  // t_{n} is local: used only in t_{n+1}
 703                 unboxResult.lastUseIndex(tableSwitch) == 1 &&     // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 704                 lastUseIndex(tableSwitch) == POS_UNBOX_RESULT;    // t_{n+1} is local: used only in t_{n+2}
 705     }
 706 
 707     /**
 708      * Check if i-th name is a start of the loop idiom.
 709      */
 710     boolean isLoop(int pos) {
 711         // loop idiom:
 712         //   t_{n}:L=MethodHandle.invokeBasic(...)
 713         //   t_{n+1}:L=MethodHandleImpl.loop(types, *, t_{n})
 714         //   t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1})
 715         return isMatchingIdiom(pos, "loop", 2);
 716     }
 717 
 718     /*
 719      * Code generation issues:
 720      *
 721      * Compiled LFs should be reusable in general.
 722      * The biggest issue is how to decide when to pull a name into
 723      * the bytecode, versus loading a reified form from the MH data.
 724      *
 725      * For example, an asType wrapper may require execution of a cast
 726      * after a call to a MH.  The target type of the cast can be placed
 727      * as a constant in the LF itself.  This will force the cast type
 728      * to be compiled into the bytecodes and native code for the MH.
 729      * Or, the target type of the cast can be erased in the LF, and
 730      * loaded from the MH data.  (Later on, if the MH as a whole is
 731      * inlined, the data will flow into the inlined instance of the LF,
 732      * as a constant, and the end result will be an optimal cast.)
 733      *
 734      * This erasure of cast types can be done with any use of
 735      * reference types.  It can also be done with whole method
 736      * handles.  Erasing a method handle might leave behind
 737      * LF code that executes correctly for any MH of a given
 738      * type, and load the required MH from the enclosing MH's data.
 739      * Or, the erasure might even erase the expected MT.
 740      *
 741      * Also, for direct MHs, the MemberName of the target
 742      * could be erased, and loaded from the containing direct MH.
 743      * As a simple case, a LF for all int-valued non-static
 744      * field getters would perform a cast on its input argument
 745      * (to non-constant base type derived from the MemberName)
 746      * and load an integer value from the input object
 747      * (at a non-constant offset also derived from the MemberName).
 748      * Such MN-erased LFs would be inlinable back to optimized
 749      * code, whenever a constant enclosing DMH is available
 750      * to supply a constant MN from its data.
 751      *
 752      * The main problem here is to keep LFs reasonably generic,
 753      * while ensuring that hot spots will inline good instances.
 754      * "Reasonably generic" means that we don't end up with
 755      * repeated versions of bytecode or machine code that do
 756      * not differ in their optimized form.  Repeated versions
 757      * of machine would have the undesirable overheads of
 758      * (a) redundant compilation work and (b) extra I$ pressure.
 759      * To control repeated versions, we need to be ready to
 760      * erase details from LFs and move them into MH data,
 761      * whenever those details are not relevant to significant
 762      * optimization.  "Significant" means optimization of
 763      * code that is actually hot.
 764      *
 765      * Achieving this may require dynamic splitting of MHs, by replacing
 766      * a generic LF with a more specialized one, on the same MH,
 767      * if (a) the MH is frequently executed and (b) the MH cannot
 768      * be inlined into a containing caller, such as an invokedynamic.
 769      *
 770      * Compiled LFs that are no longer used should be GC-able.
 771      * If they contain non-BCP references, they should be properly
 772      * interlinked with the class loader(s) that their embedded types
 773      * depend on.  This probably means that reusable compiled LFs
 774      * will be tabulated (indexed) on relevant class loaders,
 775      * or else that the tables that cache them will have weak links.
 776      */
 777 
 778     /**
 779      * Make this LF directly executable, as part of a MethodHandle.
 780      * Invariant:  Every MH which is invoked must prepare its LF
 781      * before invocation.
 782      * (In principle, the JVM could do this very lazily,
 783      * as a sort of pre-invocation linkage step.)
 784      */
 785     public void prepare() {
 786         if (COMPILE_THRESHOLD == 0 && !forceInterpretation() && !isCompiled) {
 787             compileToBytecode();
 788         }
 789         if (this.vmentry != null) {
 790             // already prepared (e.g., a primitive DMH invoker form)
 791             return;
 792         }
 793         MethodType mtype = methodType();
 794         MethodTypeForm form = mtype.form();
 795 
 796         MemberName entry = form.cachedInterpretEntry();
 797         if (entry == null) {
 798             assert (isValidSignature(basicTypeSignature()));
 799             entry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(mtype);
 800             entry = form.setCachedInterpretEntry(entry);
 801         }
 802         this.vmentry = entry;
 803         // TO DO: Maybe add invokeGeneric, invokeWithArguments
 804     }
 805 
 806     private static @Stable PerfCounter LF_FAILED;
 807 
 808     private static PerfCounter failedCompilationCounter() {
 809         if (LF_FAILED == null) {
 810             LF_FAILED = PerfCounter.newPerfCounter("java.lang.invoke.failedLambdaFormCompilations");
 811         }
 812         return LF_FAILED;
 813     }
 814 
 815     /** Generate optimizable bytecode for this form. */
 816     void compileToBytecode() {
 817         if (forceInterpretation()) {
 818             return; // this should not be compiled
 819         }
 820         if (vmentry != null && isCompiled) {
 821             return;  // already compiled somehow
 822         }
 823 
 824         // Obtain the invoker MethodType outside of the following try block.
 825         // This ensures that an IllegalArgumentException is directly thrown if the
 826         // type would have 256 or more parameters
 827         MethodType invokerType = methodType();
 828         assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
 829         try {
 830             vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
 831             if (TRACE_INTERPRETER)
 832                 traceInterpreter("compileToBytecode", this);
 833             isCompiled = true;
 834         } catch (InvokerBytecodeGenerator.BytecodeGenerationException bge) {
 835             // bytecode generation failed - mark this LambdaForm as to be run in interpretation mode only
 836             invocationCounter = -1;
 837             failedCompilationCounter().increment();
 838             if (LOG_LF_COMPILATION_FAILURE) {
 839                 System.out.println("LambdaForm compilation failed: " + this);
 840                 bge.printStackTrace(System.out);
 841             }
 842         } catch (Error e) {
 843             // Pass through any error
 844             throw e;
 845         } catch (Exception e) {
 846             // Wrap any exception
 847             throw newInternalError(this.toString(), e);
 848         }
 849     }
 850 
 851     // The next few routines are called only from assert expressions
 852     // They verify that the built-in invokers process the correct raw data types.
 853     private static boolean argumentTypesMatch(String sig, Object[] av) {
 854         int arity = signatureArity(sig);
 855         assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
 856         assert(av[0] instanceof MethodHandle) : "av[0] not instance of MethodHandle: " + av[0];
 857         MethodHandle mh = (MethodHandle) av[0];
 858         MethodType mt = mh.type();
 859         assert(mt.parameterCount() == arity-1);
 860         for (int i = 0; i < av.length; i++) {
 861             Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
 862             assert(valueMatches(basicType(sig.charAt(i)), pt, av[i]));
 863         }
 864         return true;
 865     }
 866     private static boolean valueMatches(BasicType tc, Class<?> type, Object x) {
 867         // The following line is needed because (...)void method handles can use non-void invokers
 868         if (type == void.class)  tc = V_TYPE;   // can drop any kind of value
 869         assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
 870         switch (tc) {
 871         case I_TYPE: assert checkInt(type, x)   : "checkInt(" + type + "," + x +")";   break;
 872         case J_TYPE: assert x instanceof Long   : "instanceof Long: " + x;             break;
 873         case F_TYPE: assert x instanceof Float  : "instanceof Float: " + x;            break;
 874         case D_TYPE: assert x instanceof Double : "instanceof Double: " + x;           break;
 875         case L_TYPE: assert checkRef(type, x)   : "checkRef(" + type + "," + x + ")";  break;
 876         case V_TYPE: break;  // allow anything here; will be dropped
 877         default:  assert(false);
 878         }
 879         return true;
 880     }
 881     private static boolean checkInt(Class<?> type, Object x) {
 882         assert(x instanceof Integer);
 883         if (type == int.class)  return true;
 884         Wrapper w = Wrapper.forBasicType(type);
 885         assert(w.isSubwordOrInt());
 886         Object x1 = Wrapper.INT.wrap(w.wrap(x));
 887         return x.equals(x1);
 888     }
 889     private static boolean checkRef(Class<?> type, Object x) {
 890         assert(!type.isPrimitive());
 891         if (x == null)  return true;
 892         if (type.isInterface())  return true;
 893         return type.isInstance(x);
 894     }
 895 
 896     /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
 897     private static final int COMPILE_THRESHOLD;
 898     static {
 899         COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD);
 900     }
 901     private int invocationCounter = 0; // a value of -1 indicates LambdaForm interpretation mode forever
 902 
 903     private boolean forceInterpretation() {
 904         return invocationCounter == -1;
 905     }
 906 
 907     /** Interpretively invoke this form on the given arguments. */
 908     @Hidden
 909     @DontInline
 910     Object interpretWithArguments(Object... argumentValues) throws Throwable {
 911         if (TRACE_INTERPRETER)
 912             return interpretWithArgumentsTracing(argumentValues);
 913         checkInvocationCounter();
 914         assert(arityCheck(argumentValues));
 915         Object[] values = Arrays.copyOf(argumentValues, names.length);
 916         for (int i = argumentValues.length; i < values.length; i++) {
 917             values[i] = interpretName(names[i], values);
 918         }
 919         Object rv = (result < 0) ? null : values[result];
 920         assert(resultCheck(argumentValues, rv));
 921         return rv;
 922     }
 923 
 924     /** Evaluate a single Name within this form, applying its function to its arguments. */
 925     @Hidden
 926     @DontInline
 927     Object interpretName(Name name, Object[] values) throws Throwable {
 928         if (TRACE_INTERPRETER)
 929             traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
 930         Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
 931         for (int i = 0; i < arguments.length; i++) {
 932             Object a = arguments[i];
 933             if (a instanceof Name n) {
 934                 int i2 = n.index();
 935                 assert(names[i2] == a);
 936                 a = values[i2];
 937                 arguments[i] = a;
 938             }
 939         }
 940         return name.function.invokeWithArguments(arguments);
 941     }
 942 
 943     private void checkInvocationCounter() {
 944         if (COMPILE_THRESHOLD != 0 &&
 945             !forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) {
 946             invocationCounter++;  // benign race
 947             if (invocationCounter >= COMPILE_THRESHOLD) {
 948                 // Replace vmentry with a bytecode version of this LF.
 949                 compileToBytecode();
 950             }
 951         }
 952     }
 953     Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable {
 954         traceInterpreter("[ interpretWithArguments", this, argumentValues);
 955         if (!forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) {
 956             int ctr = invocationCounter++;  // benign race
 957             traceInterpreter("| invocationCounter", ctr);
 958             if (invocationCounter >= COMPILE_THRESHOLD) {
 959                 compileToBytecode();
 960             }
 961         }
 962         Object rval;
 963         try {
 964             assert(arityCheck(argumentValues));
 965             Object[] values = Arrays.copyOf(argumentValues, names.length);
 966             for (int i = argumentValues.length; i < values.length; i++) {
 967                 values[i] = interpretName(names[i], values);
 968             }
 969             rval = (result < 0) ? null : values[result];
 970         } catch (Throwable ex) {
 971             traceInterpreter("] throw =>", ex);
 972             throw ex;
 973         }
 974         traceInterpreter("] return =>", rval);
 975         return rval;
 976     }
 977 
 978     static void traceInterpreter(String event, Object obj, Object... args) {
 979         if (TRACE_INTERPRETER) {
 980             System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
 981         }
 982     }
 983     static void traceInterpreter(String event, Object obj) {
 984         traceInterpreter(event, obj, (Object[])null);
 985     }
 986     private boolean arityCheck(Object[] argumentValues) {
 987         assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
 988         // also check that the leading (receiver) argument is somehow bound to this LF:
 989         assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
 990         MethodHandle mh = (MethodHandle) argumentValues[0];
 991         assert(mh.internalForm() == this);
 992         // note:  argument #0 could also be an interface wrapper, in the future
 993         argumentTypesMatch(basicTypeSignature(), argumentValues);
 994         return true;
 995     }
 996     private boolean resultCheck(Object[] argumentValues, Object result) {
 997         MethodHandle mh = (MethodHandle) argumentValues[0];
 998         MethodType mt = mh.type();
 999         assert(valueMatches(returnType(), mt.returnType(), result));
1000         return true;
1001     }
1002 
1003     public String toString() {
1004         return debugString(-1);
1005     }
1006 
1007     String debugString(int indentLevel) {
1008         String prefix = MethodHandle.debugPrefix(indentLevel);
1009         String lambdaName = lambdaName();
1010         StringBuilder buf = new StringBuilder(lambdaName);
1011         buf.append("=Lambda(");
1012         for (int i = 0; i < names.length; i++) {
1013             if (i == arity)  buf.append(")=>{");
1014             Name n = names[i];
1015             if (i >= arity)  buf.append("\n    ").append(prefix);
1016             buf.append(n.paramString());
1017             if (i < arity) {
1018                 if (i+1 < arity)  buf.append(",");
1019                 continue;
1020             }
1021             buf.append("=").append(n.exprString());
1022             buf.append(";");
1023         }
1024         if (arity == names.length)  buf.append(")=>{");
1025         buf.append(result < 0 ? "void" : names[result]).append("}");
1026         if (TRACE_INTERPRETER) {
1027             // Extra verbosity:
1028             buf.append(":").append(basicTypeSignature());
1029             buf.append("/").append(vmentry);
1030         }
1031         return buf.toString();
1032     }
1033 
1034     @Override
1035     public boolean equals(Object obj) {
1036         return obj instanceof LambdaForm lf && equals(lf);
1037     }
1038     public boolean equals(LambdaForm that) {
1039         if (this.result != that.result)  return false;
1040         return Arrays.equals(this.names, that.names);
1041     }
1042     public int hashCode() {
1043         return result + 31 * Arrays.hashCode(names);
1044     }
1045     LambdaFormEditor editor() {
1046         return LambdaFormEditor.lambdaFormEditor(this);
1047     }
1048 
1049     boolean contains(Name name) {
1050         int pos = name.index();
1051         if (pos >= 0) {
1052             return pos < names.length && name.equals(names[pos]);
1053         }
1054         for (int i = arity; i < names.length; i++) {
1055             if (name.equals(names[i]))
1056                 return true;
1057         }
1058         return false;
1059     }
1060 
1061     @AOTSafeClassInitializer
1062     static class NamedFunction {
1063         final MemberName member;
1064         private @Stable MethodHandle resolvedHandle;
1065         private @Stable MethodType type;
1066 
1067         NamedFunction(MethodHandle resolvedHandle) {
1068             this(resolvedHandle.internalMemberName(), resolvedHandle);
1069         }
1070         NamedFunction(MemberName member, MethodHandle resolvedHandle) {
1071             this.member = member;
1072             this.resolvedHandle = resolvedHandle;
1073              // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
1074              //assert(!isInvokeBasic(member));
1075         }
1076         NamedFunction(MethodType basicInvokerType) {
1077             assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
1078             if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
1079                 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
1080                 this.member = resolvedHandle.internalMemberName();
1081             } else {
1082                 // necessary to pass BigArityTest
1083                 this.member = Invokers.invokeBasicMethod(basicInvokerType);
1084             }
1085             assert(isInvokeBasic(member));
1086         }
1087 
1088         private static boolean isInvokeBasic(MemberName member) {
1089             return member != null &&
1090                    member.getDeclaringClass() == MethodHandle.class &&
1091                   "invokeBasic".equals(member.getName());
1092         }
1093 
1094         // The next 2 constructors are used to break circular dependencies on MH.invokeStatic, etc.
1095         // Any LambdaForm containing such a member is not interpretable.
1096         // This is OK, since all such LFs are prepared with special primitive vmentry points.
1097         // And even without the resolvedHandle, the name can still be compiled and optimized.
1098         NamedFunction(Method method) {
1099             this(new MemberName(method));
1100         }
1101         NamedFunction(MemberName member) {
1102             this(member, null);
1103         }
1104 
1105         MethodHandle resolvedHandle() {
1106             if (resolvedHandle == null)  resolve();
1107             return resolvedHandle;
1108         }
1109 
1110         synchronized void resolve() {
1111             if (resolvedHandle == null) {
1112                 resolvedHandle = DirectMethodHandle.make(member);
1113             }
1114         }
1115 
1116         @Override
1117         public boolean equals(Object other) {
1118             if (this == other) return true;
1119             if (other == null) return false;
1120             return (other instanceof NamedFunction that)
1121                     && this.member != null
1122                     && this.member.equals(that.member);
1123         }
1124 
1125         @Override
1126         public int hashCode() {
1127             if (member != null)
1128                 return member.hashCode();
1129             return super.hashCode();
1130         }
1131 
1132         static final MethodType INVOKER_METHOD_TYPE =
1133             MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1134 
1135         private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1136             typeForm = typeForm.basicType().form();  // normalize to basic type
1137             MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1138             if (mh != null)  return mh;
1139             MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm);  // this could take a while
1140             mh = DirectMethodHandle.make(invoker);
1141             MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1142             if (mh2 != null)  return mh2;  // benign race
1143             if (!mh.type().equals(INVOKER_METHOD_TYPE))
1144                 throw newInternalError(mh.debugString());
1145             return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh);
1146         }
1147 
1148         @Hidden
1149         Object invokeWithArguments(Object... arguments) throws Throwable {
1150             // If we have a cached invoker, call it right away.
1151             // NOTE: The invoker always returns a reference value.
1152             if (TRACE_INTERPRETER)  return invokeWithArgumentsTracing(arguments);
1153             return invoker().invokeBasic(resolvedHandle(), arguments);
1154         }
1155 
1156         @Hidden
1157         Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
1158             Object rval;
1159             try {
1160                 traceInterpreter("[ call", this, arguments);
1161                 // resolvedHandle might be uninitialized, ok for tracing
1162                 if (resolvedHandle == null) {
1163                     traceInterpreter("| resolve", this);
1164                     resolvedHandle();
1165                 }
1166                 rval = invoker().invokeBasic(resolvedHandle(), arguments);
1167             } catch (Throwable ex) {
1168                 traceInterpreter("] throw =>", ex);
1169                 throw ex;
1170             }
1171             traceInterpreter("] return =>", rval);
1172             return rval;
1173         }
1174 
1175         private MethodHandle invoker() {
1176             return computeInvoker(methodType().form());
1177         }
1178 
1179         MethodType methodType() {
1180             MethodType type = this.type;
1181             if (type == null) {
1182                 this.type = type = calculateMethodType(member, resolvedHandle);
1183             }
1184             return type;
1185         }
1186 
1187         private static MethodType calculateMethodType(MemberName member, MethodHandle resolvedHandle) {
1188             if (resolvedHandle != null) {
1189                 return resolvedHandle.type();
1190             } else {
1191                 // only for certain internal LFs during bootstrapping
1192                 return member.getInvocationType();
1193             }
1194         }
1195 
1196         MemberName member() {
1197             assert(assertMemberIsConsistent());
1198             return member;
1199         }
1200 
1201         // Called only from assert.
1202         private boolean assertMemberIsConsistent() {
1203             if (resolvedHandle instanceof DirectMethodHandle) {
1204                 MemberName m = resolvedHandle.internalMemberName();
1205                 assert(m.equals(member));
1206             }
1207             return true;
1208         }
1209 
1210         Class<?> memberDeclaringClassOrNull() {
1211             return (member == null) ? null : member.getDeclaringClass();
1212         }
1213 
1214         BasicType returnType() {
1215             return basicType(methodType().returnType());
1216         }
1217 
1218         BasicType parameterType(int n) {
1219             return basicType(methodType().parameterType(n));
1220         }
1221 
1222         int arity() {
1223             return methodType().parameterCount();
1224         }
1225 
1226         public String toString() {
1227             if (member == null)  return String.valueOf(resolvedHandle);
1228             return member.getDeclaringClass().getSimpleName()+"."+member.getName();
1229         }
1230 
1231         public boolean isIdentity() {
1232             return this.equals(identity(returnType()));
1233         }
1234 
1235         public MethodHandleImpl.Intrinsic intrinsicName() {
1236             return resolvedHandle != null
1237                 ? resolvedHandle.intrinsicName()
1238                 : MethodHandleImpl.Intrinsic.NONE;
1239         }
1240 
1241         public Object intrinsicData() {
1242             return resolvedHandle != null
1243                 ? resolvedHandle.intrinsicData()
1244                 : null;
1245         }
1246     }
1247 
1248     public static String basicTypeSignature(MethodType type) {
1249         int params = type.parameterCount();
1250         char[] sig = new char[params + 2];
1251         int sigp = 0;
1252         while (sigp < params) {
1253             sig[sigp] = basicTypeChar(type.parameterType(sigp++));
1254         }
1255         sig[sigp++] = '_';
1256         sig[sigp++] = basicTypeChar(type.returnType());
1257         assert(sigp == sig.length);
1258         return String.valueOf(sig);
1259     }
1260 
1261     /** Hack to make signatures more readable when they show up in method names.
1262      * Signature should start with a sequence of uppercase ASCII letters.
1263      * Runs of three or more are replaced by a single letter plus a decimal repeat count.
1264      * A tail of anything other than uppercase ASCII is passed through unchanged.
1265      * @param signature sequence of uppercase ASCII letters with possible repetitions
1266      * @return same sequence, with repetitions counted by decimal numerals
1267      */
1268     public static String shortenSignature(String signature) {
1269         final int NO_CHAR = -1, MIN_RUN = 3;
1270         int c0, c1 = NO_CHAR, c1reps = 0;
1271         StringBuilder buf = null;
1272         int len = signature.length();
1273         if (len < MIN_RUN)  return signature;
1274         for (int i = 0; i <= len; i++) {
1275             if (c1 != NO_CHAR && !('A' <= c1 && c1 <= 'Z')) {
1276                 // wrong kind of char; bail out here
1277                 if (buf != null) {
1278                     buf.append(signature, i - c1reps, len);
1279                 }
1280                 break;
1281             }
1282             // shift in the next char:
1283             c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i));
1284             if (c1 == c0) { ++c1reps; continue; }
1285             // shift in the next count:
1286             int c0reps = c1reps; c1reps = 1;
1287             // end of a  character run
1288             if (c0reps < MIN_RUN) {
1289                 if (buf != null) {
1290                     while (--c0reps >= 0)
1291                         buf.append((char)c0);
1292                 }
1293                 continue;
1294             }
1295             // found three or more in a row
1296             if (buf == null)
1297                 buf = new StringBuilder().append(signature, 0, i - c0reps);
1298             buf.append((char)c0).append(c0reps);
1299         }
1300         return (buf == null) ? signature : buf.toString();
1301     }
1302 
1303     static final class Name {
1304         final BasicType type;
1305         final short index;
1306         final NamedFunction function;
1307         final Object constraint;  // additional type information, if not null
1308         @Stable final Object[] arguments;
1309 
1310         private static final Object[] EMPTY_ARGS = new Object[0];
1311 
1312         private Name(int index, BasicType type, NamedFunction function, Object[] arguments, Object constraint) {
1313             this.index = (short)index;
1314             this.type = type;
1315             this.function = function;
1316             this.arguments = arguments;
1317             this.constraint = constraint;
1318             assert(this.index == index && typesMatch(function, arguments));
1319             assert(constraint == null || isParam());  // only params have constraints
1320             assert(constraint == null || constraint instanceof ClassSpecializer.SpeciesData || constraint instanceof Class);
1321         }
1322 
1323         Name(MethodHandle function, Object... arguments) {
1324             this(new NamedFunction(function), arguments);
1325         }
1326         Name(MethodType functionType, Object... arguments) {
1327             this(new NamedFunction(functionType), arguments);
1328             assert(arguments[0] instanceof Name name && name.type == L_TYPE);
1329         }
1330         Name(MemberName function, Object... arguments) {
1331             this(new NamedFunction(function), arguments);
1332         }
1333         Name(NamedFunction function) {
1334             this(-1, function.returnType(), function, EMPTY_ARGS, null);
1335         }
1336         Name(NamedFunction function, Object arg) {
1337             this(-1, function.returnType(), function, new Object[] { arg }, null);
1338         }
1339         Name(NamedFunction function, Object arg0, Object arg1) {
1340             this(-1, function.returnType(), function, new Object[] { arg0, arg1 }, null);
1341         }
1342         Name(NamedFunction function, Object... arguments) {
1343             this(-1, function.returnType(), function, Arrays.copyOf(arguments, arguments.length, Object[].class), null);
1344         }
1345         /** Create a raw parameter of the given type, with an expected index. */
1346         Name(int index, BasicType type) {
1347             this(index, type, null, null, null);
1348         }
1349         /** Create a raw parameter of the given type. */
1350         Name(BasicType type) { this(-1, type); }
1351 
1352         BasicType type() { return type; }
1353         int index() { return index; }
1354 
1355         char typeChar() {
1356             return type.btChar;
1357         }
1358 
1359         Name withIndex(int i) {
1360             if (i == this.index) return this;
1361             return new Name(i, type, function, arguments, constraint);
1362         }
1363 
1364         Name withConstraint(Object constraint) {
1365             if (constraint == this.constraint)  return this;
1366             return new Name(index, type, function, arguments, constraint);
1367         }
1368 
1369         Name replaceName(Name oldName, Name newName) {  // FIXME: use replaceNames uniformly
1370             if (oldName == newName)  return this;
1371             @SuppressWarnings("LocalVariableHidesMemberVariable")
1372             Object[] arguments = this.arguments;
1373             if (arguments == null)  return this;
1374             boolean replaced = false;
1375             for (int j = 0; j < arguments.length; j++) {
1376                 if (arguments[j] == oldName) {
1377                     if (!replaced) {
1378                         replaced = true;
1379                         arguments = arguments.clone();
1380                     }
1381                     arguments[j] = newName;
1382                 }
1383             }
1384             if (!replaced)  return this;
1385             return new Name(function, arguments);
1386         }
1387         /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i].
1388          *  Limit such replacements to {@code start<=i<end}.  Return possibly changed self.
1389          */
1390         Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
1391             if (start >= end)  return this;
1392             @SuppressWarnings("LocalVariableHidesMemberVariable")
1393             Object[] arguments = this.arguments;
1394             boolean replaced = false;
1395         eachArg:
1396             for (int j = 0; j < arguments.length; j++) {
1397                 if (arguments[j] instanceof Name n) {
1398                     int check = n.index;
1399                     // harmless check to see if the thing is already in newNames:
1400                     if (check >= 0 && check < newNames.length && n == newNames[check])
1401                         continue eachArg;
1402                     // n might not have the correct index: n != oldNames[n.index].
1403                     for (int i = start; i < end; i++) {
1404                         if (n == oldNames[i]) {
1405                             if (n == newNames[i])
1406                                 continue eachArg;
1407                             if (!replaced) {
1408                                 replaced = true;
1409                                 arguments = arguments.clone();
1410                             }
1411                             arguments[j] = newNames[i];
1412                             continue eachArg;
1413                         }
1414                     }
1415                 }
1416             }
1417             if (!replaced)  return this;
1418             return new Name(function, arguments);
1419         }
1420         void internArguments() {
1421             @SuppressWarnings("LocalVariableHidesMemberVariable")
1422             Object[] arguments = this.arguments;
1423             for (int j = 0; j < arguments.length; j++) {
1424                 if (arguments[j] instanceof Name n) {
1425                     if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
1426                         arguments[j] = internArgument(n);
1427                 }
1428             }
1429         }
1430         boolean isParam() {
1431             return function == null;
1432         }
1433 
1434         boolean refersTo(Class<?> declaringClass, String methodName) {
1435             return function != null &&
1436                     function.member() != null && function.member().refersTo(declaringClass, methodName);
1437         }
1438 
1439         /**
1440          * Check if MemberName is a call to MethodHandle.invokeBasic.
1441          */
1442         boolean isInvokeBasic() {
1443             if (function == null)
1444                 return false;
1445             if (arguments.length < 1)
1446                 return false;  // must have MH argument
1447             MemberName member = function.member();
1448             return member != null && member.refersTo(MethodHandle.class, "invokeBasic") &&
1449                     !member.isPublic() && !member.isStatic();
1450         }
1451 
1452         /**
1453          * Check if MemberName is a call to MethodHandle.linkToStatic, etc.
1454          */
1455         boolean isLinkerMethodInvoke() {
1456             if (function == null)
1457                 return false;
1458             if (arguments.length < 1)
1459                 return false;  // must have MH argument
1460             MemberName member = function.member();
1461             return member != null &&
1462                     member.getDeclaringClass() == MethodHandle.class &&
1463                     !member.isPublic() && member.isStatic() &&
1464                     member.getName().startsWith("linkTo");
1465         }
1466 
1467         public String toString() {
1468             return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar();
1469         }
1470         public String debugString() {
1471             String s = paramString();
1472             return (function == null) ? s : s + "=" + exprString();
1473         }
1474         public String paramString() {
1475             String s = toString();
1476             Object c = constraint;
1477             if (c == null)
1478                 return s;
1479             if (c instanceof Class<?> cl)  c = cl.getSimpleName();
1480             return s + "/" + c;
1481         }
1482         public String exprString() {
1483             if (function == null)  return toString();
1484             StringBuilder buf = new StringBuilder(function.toString());
1485             buf.append("(");
1486             String cma = "";
1487             for (Object a : arguments) {
1488                 buf.append(cma); cma = ",";
1489                 if (a instanceof Name || a instanceof Integer)
1490                     buf.append(a);
1491                 else
1492                     buf.append("(").append(a).append(")");
1493             }
1494             buf.append(")");
1495             return buf.toString();
1496         }
1497 
1498         private boolean typesMatch(NamedFunction function, Object ... arguments) {
1499             if (arguments == null) {
1500                 assert(function == null);
1501                 return true;
1502             }
1503             assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
1504             for (int i = 0; i < arguments.length; i++) {
1505                 assert (typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
1506             }
1507             return true;
1508         }
1509 
1510         private static boolean typesMatch(BasicType parameterType, Object object) {
1511             if (object instanceof Name name) {
1512                 return name.type == parameterType;
1513             }
1514             switch (parameterType) {
1515                 case I_TYPE:  return object instanceof Integer;
1516                 case J_TYPE:  return object instanceof Long;
1517                 case F_TYPE:  return object instanceof Float;
1518                 case D_TYPE:  return object instanceof Double;
1519             }
1520             assert(parameterType == L_TYPE);
1521             return true;
1522         }
1523 
1524         /** Return the index of the last occurrence of n in the argument array.
1525          *  Return -1 if the name is not used.
1526          */
1527         int lastUseIndex(Name n) {
1528             Object[] arguments = this.arguments;
1529             if (arguments == null)  return -1;
1530             for (int i = arguments.length; --i >= 0; ) {
1531                 if (arguments[i] == n)  return i;
1532             }
1533             return -1;
1534         }
1535 
1536         public boolean equals(Name that) {
1537             if (this == that)  return true;
1538             if (isParam())
1539                 // each parameter is a unique atom
1540                 return false;  // this != that
1541             return
1542                 //this.index == that.index &&
1543                 this.type == that.type &&
1544                 this.function.equals(that.function) &&
1545                 Arrays.equals(this.arguments, that.arguments);
1546         }
1547         @Override
1548         public boolean equals(Object x) {
1549             return x instanceof Name n && equals(n);
1550         }
1551         @Override
1552         public int hashCode() {
1553             if (isParam())
1554                 return index | (type.ordinal() << 8);
1555             return function.hashCode() ^ Arrays.hashCode(arguments);
1556         }
1557     }
1558 
1559     /** Return the index of the last name which contains n as an argument.
1560      *  Return -1 if the name is not used.  Return names.length if it is the return value.
1561      */
1562     int lastUseIndex(Name n) {
1563         int ni = n.index, nmax = names.length;
1564         assert(names[ni] == n);
1565         if (result == ni)  return nmax;  // live all the way beyond the end
1566         for (int i = nmax; --i > ni; ) {
1567             if (names[i].lastUseIndex(n) >= 0)
1568                 return i;
1569         }
1570         return -1;
1571     }
1572 
1573     /** Return the number of times n is used as an argument or return value. */
1574     int useCount(Name n) {
1575         int count = (result == n.index) ? 1 : 0;
1576         int i = Math.max(n.index + 1, arity);
1577         Name[] names = this.names;
1578         while (i < names.length) {
1579             Object[] arguments = names[i++].arguments;
1580             if (arguments != null) {
1581                 for (Object argument : arguments) {
1582                     if (argument == n) {
1583                         count++;
1584                     }
1585                 }
1586             }
1587         }
1588         return count;
1589     }
1590 
1591     static Name argument(int which, BasicType type) {
1592         if (which >= INTERNED_ARGUMENT_LIMIT)
1593             return new Name(which, type);
1594         return INTERNED_ARGUMENTS[type.ordinal()][which];
1595     }
1596     static Name internArgument(Name n) {
1597         assert(n.isParam()) : "not param: " + n;
1598         assert(n.index < INTERNED_ARGUMENT_LIMIT);
1599         if (n.constraint != null)  return n;
1600         return argument(n.index, n.type);
1601     }
1602     static Name[] arguments(int extra, MethodType types) {
1603         int length = types.parameterCount();
1604         Name[] names = new Name[length + extra];
1605         for (int i = 0; i < length; i++)
1606             names[i] = argument(i, basicType(types.parameterType(i)));
1607         return names;
1608     }
1609 
1610     static Name[] invokeArguments(int extra, MethodType types) {
1611         int length = types.parameterCount();
1612         Name[] names = new Name[length + extra + 1];
1613         names[0] = argument(0, L_TYPE);
1614         for (int i = 0; i < length; i++)
1615             names[i + 1] = argument(i + 1, basicType(types.parameterType(i)));
1616         return names;
1617     }
1618 
1619     static final int INTERNED_ARGUMENT_LIMIT = 10;
1620     private static final Name[][] INTERNED_ARGUMENTS
1621             = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT];
1622     static {
1623         for (BasicType type : BasicType.ARG_TYPES) {
1624             int ord = type.ordinal();
1625             for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) {
1626                 INTERNED_ARGUMENTS[ord][i] = new Name(i, type);
1627             }
1628         }
1629     }
1630 
1631     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1632 
1633     static LambdaForm identityForm(BasicType type) {
1634         int ord = type.ordinal();
1635         LambdaForm form = LF_identity[ord];
1636         if (form != null) {
1637             return form;
1638         }
1639         createIdentityForm(type);
1640         return LF_identity[ord];
1641     }
1642 
1643     static NamedFunction identity(BasicType type) {
1644         int ord = type.ordinal();
1645         NamedFunction function = NF_identity[ord];
1646         if (function != null) {
1647             return function;
1648         }
1649         createIdentityForm(type);
1650         return NF_identity[ord];
1651     }
1652 
1653     static LambdaForm constantForm(BasicType type) {
1654         assert type != null && type != V_TYPE : type;
1655         var cached = LF_constant[type.ordinal()];
1656         if (cached != null)
1657             return cached;
1658         return createConstantForm(type);
1659     }
1660 
1661     private static LambdaForm createConstantForm(BasicType type) {
1662         UNSAFE.ensureClassInitialized(BoundMethodHandle.class); // defend access to SimpleMethodHandle
1663         var species = SimpleMethodHandle.BMH_SPECIES.extendWith(type);
1664         var carrier = argument(0, L_TYPE).withConstraint(species); // BMH bound with data
1665         Name[] constNames = new Name[] { carrier, new Name(species.getterFunction(0), carrier) };
1666         return LF_constant[type.ordinal()] = create(1, constNames, Kind.CONSTANT);
1667     }
1668 
1669     private static final @Stable LambdaForm[] LF_identity = new LambdaForm[TYPE_LIMIT];
1670     private static final @Stable NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT];
1671     private static final @Stable LambdaForm[] LF_constant = new LambdaForm[ARG_TYPE_LIMIT]; // no void
1672 
1673     private static final Object createIdentityFormLock = new Object();
1674     private static void createIdentityForm(BasicType type) {
1675         // Avoid racy initialization during bootstrap
1676         UNSAFE.ensureClassInitialized(BoundMethodHandle.class);
1677         synchronized (createIdentityFormLock) {
1678             final int ord = type.ordinal();
1679             LambdaForm idForm = LF_identity[ord];
1680             if (idForm != null) {
1681                 return;
1682             }
1683             char btChar = type.basicTypeChar();
1684             boolean isVoid = (type == V_TYPE);
1685             Class<?> btClass = type.btClass;
1686             MethodType idType = (isVoid) ? MethodType.methodType(btClass) : MethodType.methodType(btClass, btClass);
1687 
1688             // Look up symbolic names.  It might not be necessary to have these,
1689             // but if we need to emit direct references to bytecodes, it helps.
1690             MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic);
1691             try {
1692                 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, LM_TRUSTED, NoSuchMethodException.class);
1693             } catch (IllegalAccessException|NoSuchMethodException ex) {
1694                 throw newInternalError(ex);
1695             }
1696 
1697             NamedFunction idFun;
1698 
1699             // Create the LFs and NamedFunctions. Precompiling LFs to byte code is needed to break circular
1700             // bootstrap dependency on this method in case we're interpreting LFs
1701             if (isVoid) {
1702                 Name[] idNames = new Name[] { argument(0, L_TYPE) };
1703                 idForm = LambdaForm.create(1, idNames, VOID_RESULT, Kind.IDENTITY);
1704                 idForm.compileToBytecode();
1705                 idFun = new NamedFunction(idMem, SimpleMethodHandle.make(idMem.getInvocationType(), idForm));
1706             } else {
1707                 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
1708                 idForm = LambdaForm.create(2, idNames, 1, Kind.IDENTITY);
1709                 idForm.compileToBytecode();
1710                 idFun = new NamedFunction(idMem, MethodHandleImpl.makeIntrinsic(idMem.getInvocationType(), idForm,
1711                             MethodHandleImpl.Intrinsic.IDENTITY));
1712             }
1713 
1714             LF_identity[ord] = idForm;
1715             NF_identity[ord] = idFun;
1716 
1717             assert(idFun.isIdentity());
1718         }
1719     }
1720 
1721     // Avoid appealing to ValueConversions at bootstrap time:
1722     private static int identity_I(int x) { return x; }
1723     private static long identity_J(long x) { return x; }
1724     private static float identity_F(float x) { return x; }
1725     private static double identity_D(double x) { return x; }
1726     private static Object identity_L(Object x) { return x; }
1727     private static void identity_V() { return; }
1728     /**
1729      * Internal marker for byte-compiled LambdaForms.
1730      */
1731     /*non-public*/
1732     @Target(ElementType.METHOD)
1733     @Retention(RetentionPolicy.RUNTIME)
1734     @interface Compiled {
1735     }
1736 
1737     private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1738     private static final HashMap<LambdaForm,String> DEBUG_NAMES;
1739     static {
1740         if (debugEnabled()) {
1741             DEBUG_NAME_COUNTERS = new HashMap<>();
1742             DEBUG_NAMES = new HashMap<>();
1743         } else {
1744             DEBUG_NAME_COUNTERS = null;
1745             DEBUG_NAMES = null;
1746         }
1747     }
1748 
1749     static {
1750         // The Holder class will contain pre-generated forms resolved
1751         // using MemberName.getFactory(). However, that doesn't initialize the
1752         // class, which subtly breaks inlining etc. By forcing
1753         // initialization of the Holder class we avoid these issues.
1754         UNSAFE.ensureClassInitialized(Holder.class);
1755     }
1756 
1757     /* Placeholder class for identity and constant forms generated ahead of time */
1758     @AOTSafeClassInitializer
1759     final class Holder {}
1760 
1761     // The following hack is necessary in order to suppress TRACE_INTERPRETER
1762     // during execution of the static initializes of this class.
1763     // Turning on TRACE_INTERPRETER too early will cause
1764     // stack overflows and other misbehavior during attempts to trace events
1765     // that occur during LambdaForm.<clinit>.
1766     // Therefore, do not move this line higher in this file, and do not remove.
1767     private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
1768 }