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