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