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