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