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