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