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     static void traceInterpreter(String event, Object obj, Object... args) {
 806         if (TRACE_INTERPRETER) {
 807             System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
 808         }
 809     }
 810     static void traceInterpreter(String event, Object obj) {
 811         traceInterpreter(event, obj, (Object[])null);
 812     }
 813     private boolean arityCheck(Object[] argumentValues) {
 814         assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
 815         // also check that the leading (receiver) argument is somehow bound to this LF:
 816         assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
 817         MethodHandle mh = (MethodHandle) argumentValues[0];
 818         assert(mh.internalForm() == this);
 819         // note:  argument #0 could also be an interface wrapper, in the future
 820         argumentTypesMatch(basicTypeSignature(), argumentValues);
 821         return true;
 822     }
 823     private boolean resultCheck(Object[] argumentValues, Object result) {
 824         MethodHandle mh = (MethodHandle) argumentValues[0];
 825         MethodType mt = mh.type();
 826         assert(valueMatches(returnType(), mt.returnType(), result));
 827         return true;
 828     }
 829 
 830     private boolean isEmpty() {
 831         if (result < 0)
 832             return (names.length == arity);
 833         else if (result == arity && names.length == arity + 1)
 834             return names[arity].isConstantZero();
 835         else
 836             return false;
 837     }
 838 
 839     public String toString() {
 840         StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
 841         for (int i = 0; i < names.length; i++) {
 842             if (i == arity)  buf.append(")=>{");
 843             Name n = names[i];
 844             if (i >= arity)  buf.append("\n    ");
 845             buf.append(n.paramString());
 846             if (i < arity) {
 847                 if (i+1 < arity)  buf.append(",");
 848                 continue;
 849             }
 850             buf.append("=").append(n.exprString());
 851             buf.append(";");
 852         }
 853         if (arity == names.length)  buf.append(")=>{");
 854         buf.append(result < 0 ? "void" : names[result]).append("}");
 855         if (TRACE_INTERPRETER) {
 856             // Extra verbosity:
 857             buf.append(":").append(basicTypeSignature());
 858             buf.append("/").append(vmentry);
 859         }
 860         return buf.toString();
 861     }
 862 
 863     @Override
 864     public boolean equals(Object obj) {
 865         return obj instanceof LambdaForm && equals((LambdaForm)obj);
 866     }
 867     public boolean equals(LambdaForm that) {
 868         if (this.result != that.result)  return false;
 869         return Arrays.equals(this.names, that.names);
 870     }
 871     public int hashCode() {
 872         return result + 31 * Arrays.hashCode(names);
 873     }
 874     LambdaFormEditor editor() {
 875         return LambdaFormEditor.lambdaFormEditor(this);
 876     }
 877 
 878     boolean contains(Name name) {
 879         int pos = name.index();
 880         if (pos >= 0) {
 881             return pos < names.length && name.equals(names[pos]);
 882         }
 883         for (int i = arity; i < names.length; i++) {
 884             if (name.equals(names[i]))
 885                 return true;
 886         }
 887         return false;
 888     }
 889 
 890     LambdaForm addArguments(int pos, BasicType... types) {
 891         // names array has MH in slot 0; skip it.
 892         int argpos = pos + 1;
 893         assert(argpos <= arity);
 894         int length = names.length;
 895         int inTypes = types.length;
 896         Name[] names2 = Arrays.copyOf(names, length + inTypes);
 897         int arity2 = arity + inTypes;
 898         int result2 = result;
 899         if (result2 >= argpos)
 900             result2 += inTypes;
 901         // Note:  The LF constructor will rename names2[argpos...].
 902         // Make space for new arguments (shift temporaries).
 903         System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
 904         for (int i = 0; i < inTypes; i++) {
 905             names2[argpos + i] = new Name(types[i]);
 906         }
 907         return new LambdaForm(debugName, arity2, names2, result2);
 908     }
 909 
 910     LambdaForm addArguments(int pos, List<Class<?>> types) {
 911         return addArguments(pos, basicTypes(types));
 912     }
 913 
 914     LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) {
 915         // Note:  When inArg = reorder[outArg], outArg is fed by a copy of inArg.
 916         // The types are the types of the new (incoming) arguments.
 917         int length = names.length;
 918         int inTypes = types.length;
 919         int outArgs = reorder.length;
 920         assert(skip+outArgs == arity);
 921         assert(permutedTypesMatch(reorder, types, names, skip));
 922         int pos = 0;
 923         // skip trivial first part of reordering:
 924         while (pos < outArgs && reorder[pos] == pos)  pos += 1;
 925         Name[] names2 = new Name[length - outArgs + inTypes];
 926         System.arraycopy(names, 0, names2, 0, skip+pos);
 927         // copy the body:
 928         int bodyLength = length - arity;
 929         System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength);
 930         int arity2 = names2.length - bodyLength;
 931         int result2 = result;
 932         if (result2 >= 0) {
 933             if (result2 < skip+outArgs) {
 934                 // return the corresponding inArg
 935                 result2 = reorder[result2-skip];
 936             } else {
 937                 result2 = result2 - outArgs + inTypes;
 938             }
 939         }
 940         // rework names in the body:
 941         for (int j = pos; j < outArgs; j++) {
 942             Name n = names[skip+j];
 943             int i = reorder[j];
 944             // replace names[skip+j] by names2[skip+i]
 945             Name n2 = names2[skip+i];
 946             if (n2 == null)
 947                 names2[skip+i] = n2 = new Name(types[i]);
 948             else
 949                 assert(n2.type == types[i]);
 950             for (int k = arity2; k < names2.length; k++) {
 951                 names2[k] = names2[k].replaceName(n, n2);
 952             }
 953         }
 954         // some names are unused, but must be filled in
 955         for (int i = skip+pos; i < arity2; i++) {
 956             if (names2[i] == null)
 957                 names2[i] = argument(i, types[i - skip]);
 958         }
 959         for (int j = arity; j < names.length; j++) {
 960             int i = j - arity + arity2;
 961             // replace names2[i] by names[j]
 962             Name n = names[j];
 963             Name n2 = names2[i];
 964             if (n != n2) {
 965                 for (int k = i+1; k < names2.length; k++) {
 966                     names2[k] = names2[k].replaceName(n, n2);
 967                 }
 968             }
 969         }
 970         return new LambdaForm(debugName, arity2, names2, result2);
 971     }
 972 
 973     static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) {
 974         int inTypes = types.length;
 975         int outArgs = reorder.length;
 976         for (int i = 0; i < outArgs; i++) {
 977             assert(names[skip+i].isParam());
 978             assert(names[skip+i].type == types[reorder[i]]);
 979         }
 980         return true;
 981     }
 982 
 983     static class NamedFunction {
 984         final MemberName member;
 985         @Stable MethodHandle resolvedHandle;
 986         @Stable MethodHandle invoker;
 987 
 988         NamedFunction(MethodHandle resolvedHandle) {
 989             this(resolvedHandle.internalMemberName(), resolvedHandle);
 990         }
 991         NamedFunction(MemberName member, MethodHandle resolvedHandle) {
 992             this.member = member;
 993             this.resolvedHandle = resolvedHandle;
 994              // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
 995              //assert(!isInvokeBasic());
 996         }
 997         NamedFunction(MethodType basicInvokerType) {
 998             assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
 999             if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
1000                 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
1001                 this.member = resolvedHandle.internalMemberName();
1002             } else {
1003                 // necessary to pass BigArityTest
1004                 this.member = Invokers.invokeBasicMethod(basicInvokerType);
1005             }
1006             assert(isInvokeBasic());
1007         }
1008 
1009         private boolean isInvokeBasic() {
1010             return member != null &&
1011                    member.isMethodHandleInvoke() &&
1012                    "invokeBasic".equals(member.getName());
1013         }
1014 
1015         // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc.
1016         // Any LambdaForm containing such a member is not interpretable.
1017         // This is OK, since all such LFs are prepared with special primitive vmentry points.
1018         // And even without the resolvedHandle, the name can still be compiled and optimized.
1019         NamedFunction(Method method) {
1020             this(new MemberName(method));
1021         }
1022         NamedFunction(Field field) {
1023             this(new MemberName(field));
1024         }
1025         NamedFunction(MemberName member) {
1026             this.member = member;
1027             this.resolvedHandle = null;
1028         }
1029 
1030         MethodHandle resolvedHandle() {
1031             if (resolvedHandle == null)  resolve();
1032             return resolvedHandle;
1033         }
1034 
1035         void resolve() {
1036             resolvedHandle = DirectMethodHandle.make(member);
1037         }
1038 
1039         @Override
1040         public boolean equals(Object other) {
1041             if (this == other) return true;
1042             if (other == null) return false;
1043             if (!(other instanceof NamedFunction)) return false;
1044             NamedFunction that = (NamedFunction) other;
1045             return this.member != null && this.member.equals(that.member);
1046         }
1047 
1048         @Override
1049         public int hashCode() {
1050             if (member != null)
1051                 return member.hashCode();
1052             return super.hashCode();
1053         }
1054 
1055         // Put the predefined NamedFunction invokers into the table.
1056         static void initializeInvokers() {
1057             for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
1058                 if (!m.isStatic() || !m.isPackage())  continue;
1059                 MethodType type = m.getMethodType();
1060                 if (type.equals(INVOKER_METHOD_TYPE) &&
1061                     m.getName().startsWith("invoke_")) {
1062                     String sig = m.getName().substring("invoke_".length());
1063                     int arity = LambdaForm.signatureArity(sig);
1064                     MethodType srcType = MethodType.genericMethodType(arity);
1065                     if (LambdaForm.signatureReturn(sig) == V_TYPE)
1066                         srcType = srcType.changeReturnType(void.class);
1067                     MethodTypeForm typeForm = srcType.form();
1068                     typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m));
1069                 }
1070             }
1071         }
1072 
1073         // The following are predefined NamedFunction invokers.  The system must build
1074         // a separate invoker for each distinct signature.
1075         /** void return type invokers. */
1076         @Hidden
1077         static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1078             assert(arityCheck(0, void.class, mh, a));
1079             mh.invokeBasic();
1080             return null;
1081         }
1082         @Hidden
1083         static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1084             assert(arityCheck(1, void.class, mh, a));
1085             mh.invokeBasic(a[0]);
1086             return null;
1087         }
1088         @Hidden
1089         static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
1090             assert(arityCheck(2, void.class, mh, a));
1091             mh.invokeBasic(a[0], a[1]);
1092             return null;
1093         }
1094         @Hidden
1095         static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
1096             assert(arityCheck(3, void.class, mh, a));
1097             mh.invokeBasic(a[0], a[1], a[2]);
1098             return null;
1099         }
1100         @Hidden
1101         static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1102             assert(arityCheck(4, void.class, mh, a));
1103             mh.invokeBasic(a[0], a[1], a[2], a[3]);
1104             return null;
1105         }
1106         @Hidden
1107         static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1108             assert(arityCheck(5, void.class, mh, a));
1109             mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1110             return null;
1111         }
1112         /** Object return type invokers. */
1113         @Hidden
1114         static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
1115             assert(arityCheck(0, mh, a));
1116             return mh.invokeBasic();
1117         }
1118         @Hidden
1119         static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
1120             assert(arityCheck(1, mh, a));
1121             return mh.invokeBasic(a[0]);
1122         }
1123         @Hidden
1124         static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
1125             assert(arityCheck(2, mh, a));
1126             return mh.invokeBasic(a[0], a[1]);
1127         }
1128         @Hidden
1129         static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
1130             assert(arityCheck(3, mh, a));
1131             return mh.invokeBasic(a[0], a[1], a[2]);
1132         }
1133         @Hidden
1134         static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1135             assert(arityCheck(4, mh, a));
1136             return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1137         }
1138         @Hidden
1139         static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1140             assert(arityCheck(5, mh, a));
1141             return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1142         }
1143         private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
1144             return arityCheck(arity, Object.class, mh, a);
1145         }
1146         private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
1147             assert(a.length == arity)
1148                     : Arrays.asList(a.length, arity);
1149             assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
1150                     : Arrays.asList(mh, rtype, arity);
1151             MemberName member = mh.internalMemberName();
1152             if (member != null && member.getName().equals("invokeBasic") && member.isMethodHandleInvoke()) {
1153                 assert(arity > 0);
1154                 assert(a[0] instanceof MethodHandle);
1155                 MethodHandle mh2 = (MethodHandle) a[0];
1156                 assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
1157                         : Arrays.asList(member, mh2, rtype, arity);
1158             }
1159             return true;
1160         }
1161 
1162         static final MethodType INVOKER_METHOD_TYPE =
1163             MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1164 
1165         private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1166             typeForm = typeForm.basicType().form();  // normalize to basic type
1167             MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1168             if (mh != null)  return mh;
1169             MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm);  // this could take a while
1170             mh = DirectMethodHandle.make(invoker);
1171             MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1172             if (mh2 != null)  return mh2;  // benign race
1173             if (!mh.type().equals(INVOKER_METHOD_TYPE))
1174                 throw newInternalError(mh.debugString());
1175             return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh);
1176         }
1177 
1178         @Hidden
1179         Object invokeWithArguments(Object... arguments) throws Throwable {
1180             // If we have a cached invoker, call it right away.
1181             // NOTE: The invoker always returns a reference value.
1182             if (TRACE_INTERPRETER)  return invokeWithArgumentsTracing(arguments);
1183             assert(checkArgumentTypes(arguments, methodType()));
1184             return invoker().invokeBasic(resolvedHandle(), arguments);
1185         }
1186 
1187         @Hidden
1188         Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
1189             Object rval;
1190             try {
1191                 traceInterpreter("[ call", this, arguments);
1192                 if (invoker == null) {
1193                     traceInterpreter("| getInvoker", this);
1194                     invoker();
1195                 }
1196                 if (resolvedHandle == null) {
1197                     traceInterpreter("| resolve", this);
1198                     resolvedHandle();
1199                 }
1200                 assert(checkArgumentTypes(arguments, methodType()));
1201                 rval = invoker().invokeBasic(resolvedHandle(), arguments);
1202             } catch (Throwable ex) {
1203                 traceInterpreter("] throw =>", ex);
1204                 throw ex;
1205             }
1206             traceInterpreter("] return =>", rval);
1207             return rval;
1208         }
1209 
1210         private MethodHandle invoker() {
1211             if (invoker != null)  return invoker;
1212             // Get an invoker and cache it.
1213             return invoker = computeInvoker(methodType().form());
1214         }
1215 
1216         private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) {
1217             if (true)  return true;  // FIXME
1218             MethodType dstType = methodType.form().erasedType();
1219             MethodType srcType = dstType.basicType().wrap();
1220             Class<?>[] ptypes = new Class<?>[arguments.length];
1221             for (int i = 0; i < arguments.length; i++) {
1222                 Object arg = arguments[i];
1223                 Class<?> ptype = arg == null ? Object.class : arg.getClass();
1224                 // If the dest. type is a primitive we keep the
1225                 // argument type.
1226                 ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class;
1227             }
1228             MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap();
1229             assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType;
1230             return true;
1231         }
1232 
1233         MethodType methodType() {
1234             if (resolvedHandle != null)
1235                 return resolvedHandle.type();
1236             else
1237                 // only for certain internal LFs during bootstrapping
1238                 return member.getInvocationType();
1239         }
1240 
1241         MemberName member() {
1242             assert(assertMemberIsConsistent());
1243             return member;
1244         }
1245 
1246         // Called only from assert.
1247         private boolean assertMemberIsConsistent() {
1248             if (resolvedHandle instanceof DirectMethodHandle) {
1249                 MemberName m = resolvedHandle.internalMemberName();
1250                 assert(m.equals(member));
1251             }
1252             return true;
1253         }
1254 
1255         Class<?> memberDeclaringClassOrNull() {
1256             return (member == null) ? null : member.getDeclaringClass();
1257         }
1258 
1259         BasicType returnType() {
1260             return basicType(methodType().returnType());
1261         }
1262 
1263         BasicType parameterType(int n) {
1264             return basicType(methodType().parameterType(n));
1265         }
1266 
1267         int arity() {
1268             return methodType().parameterCount();
1269         }
1270 
1271         public String toString() {
1272             if (member == null)  return String.valueOf(resolvedHandle);
1273             return member.getDeclaringClass().getSimpleName()+"."+member.getName();
1274         }
1275 
1276         public boolean isIdentity() {
1277             return this.equals(identity(returnType()));
1278         }
1279 
1280         public boolean isConstantZero() {
1281             return this.equals(constantZero(returnType()));
1282         }
1283 
1284         public MethodHandleImpl.Intrinsic intrinsicName() {
1285             return resolvedHandle == null ? MethodHandleImpl.Intrinsic.NONE
1286                                           : resolvedHandle.intrinsicName();
1287         }
1288     }
1289 
1290     public static String basicTypeSignature(MethodType type) {
1291         char[] sig = new char[type.parameterCount() + 2];
1292         int sigp = 0;
1293         for (Class<?> pt : type.parameterList()) {
1294             sig[sigp++] = basicTypeChar(pt);
1295         }
1296         sig[sigp++] = '_';
1297         sig[sigp++] = basicTypeChar(type.returnType());
1298         assert(sigp == sig.length);
1299         return String.valueOf(sig);
1300     }
1301     public static String shortenSignature(String signature) {
1302         // Hack to make signatures more readable when they show up in method names.
1303         final int NO_CHAR = -1, MIN_RUN = 3;
1304         int c0, c1 = NO_CHAR, c1reps = 0;
1305         StringBuilder buf = null;
1306         int len = signature.length();
1307         if (len < MIN_RUN)  return signature;
1308         for (int i = 0; i <= len; i++) {
1309             // shift in the next char:
1310             c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i));
1311             if (c1 == c0) { ++c1reps; continue; }
1312             // shift in the next count:
1313             int c0reps = c1reps; c1reps = 1;
1314             // end of a  character run
1315             if (c0reps < MIN_RUN) {
1316                 if (buf != null) {
1317                     while (--c0reps >= 0)
1318                         buf.append((char)c0);
1319                 }
1320                 continue;
1321             }
1322             // found three or more in a row
1323             if (buf == null)
1324                 buf = new StringBuilder().append(signature, 0, i - c0reps);
1325             buf.append((char)c0).append(c0reps);
1326         }
1327         return (buf == null) ? signature : buf.toString();
1328     }
1329 
1330     static final class Name {
1331         final BasicType type;
1332         private short index;
1333         final NamedFunction function;
1334         final Object constraint;  // additional type information, if not null
1335         @Stable final Object[] arguments;
1336 
1337         private Name(int index, BasicType type, NamedFunction function, Object[] arguments) {
1338             this.index = (short)index;
1339             this.type = type;
1340             this.function = function;
1341             this.arguments = arguments;
1342             this.constraint = null;
1343             assert(this.index == index);
1344         }
1345         private Name(Name that, Object constraint) {
1346             this.index = that.index;
1347             this.type = that.type;
1348             this.function = that.function;
1349             this.arguments = that.arguments;
1350             this.constraint = constraint;
1351             assert(constraint == null || isParam());  // only params have constraints
1352             assert(constraint == null || constraint instanceof BoundMethodHandle.SpeciesData || constraint instanceof Class);
1353         }
1354         Name(MethodHandle function, Object... arguments) {
1355             this(new NamedFunction(function), arguments);
1356         }
1357         Name(MethodType functionType, Object... arguments) {
1358             this(new NamedFunction(functionType), arguments);
1359             assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE);
1360         }
1361         Name(MemberName function, Object... arguments) {
1362             this(new NamedFunction(function), arguments);
1363         }
1364         Name(NamedFunction function, Object... arguments) {
1365             this(-1, function.returnType(), function, arguments = Arrays.copyOf(arguments, arguments.length, Object[].class));
1366             assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
1367             for (int i = 0; i < arguments.length; i++)
1368                 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
1369         }
1370         /** Create a raw parameter of the given type, with an expected index. */
1371         Name(int index, BasicType type) {
1372             this(index, type, null, null);
1373         }
1374         /** Create a raw parameter of the given type. */
1375         Name(BasicType type) { this(-1, type); }
1376 
1377         BasicType type() { return type; }
1378         int index() { return index; }
1379         boolean initIndex(int i) {
1380             if (index != i) {
1381                 if (index != -1)  return false;
1382                 index = (short)i;
1383             }
1384             return true;
1385         }
1386         char typeChar() {
1387             return type.btChar;
1388         }
1389 
1390         void resolve() {
1391             if (function != null)
1392                 function.resolve();
1393         }
1394 
1395         Name newIndex(int i) {
1396             if (initIndex(i))  return this;
1397             return cloneWithIndex(i);
1398         }
1399         Name cloneWithIndex(int i) {
1400             Object[] newArguments = (arguments == null) ? null : arguments.clone();
1401             return new Name(i, type, function, newArguments).withConstraint(constraint);
1402         }
1403         Name withConstraint(Object constraint) {
1404             if (constraint == this.constraint)  return this;
1405             return new Name(this, constraint);
1406         }
1407         Name replaceName(Name oldName, Name newName) {  // FIXME: use replaceNames uniformly
1408             if (oldName == newName)  return this;
1409             @SuppressWarnings("LocalVariableHidesMemberVariable")
1410             Object[] arguments = this.arguments;
1411             if (arguments == null)  return this;
1412             boolean replaced = false;
1413             for (int j = 0; j < arguments.length; j++) {
1414                 if (arguments[j] == oldName) {
1415                     if (!replaced) {
1416                         replaced = true;
1417                         arguments = arguments.clone();
1418                     }
1419                     arguments[j] = newName;
1420                 }
1421             }
1422             if (!replaced)  return this;
1423             return new Name(function, arguments);
1424         }
1425         /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i].
1426          *  Limit such replacements to {@code start<=i<end}.  Return possibly changed self.
1427          */
1428         Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
1429             if (start >= end)  return this;
1430             @SuppressWarnings("LocalVariableHidesMemberVariable")
1431             Object[] arguments = this.arguments;
1432             boolean replaced = false;
1433         eachArg:
1434             for (int j = 0; j < arguments.length; j++) {
1435                 if (arguments[j] instanceof Name) {
1436                     Name n = (Name) arguments[j];
1437                     int check = n.index;
1438                     // harmless check to see if the thing is already in newNames:
1439                     if (check >= 0 && check < newNames.length && n == newNames[check])
1440                         continue eachArg;
1441                     // n might not have the correct index: n != oldNames[n.index].
1442                     for (int i = start; i < end; i++) {
1443                         if (n == oldNames[i]) {
1444                             if (n == newNames[i])
1445                                 continue eachArg;
1446                             if (!replaced) {
1447                                 replaced = true;
1448                                 arguments = arguments.clone();
1449                             }
1450                             arguments[j] = newNames[i];
1451                             continue eachArg;
1452                         }
1453                     }
1454                 }
1455             }
1456             if (!replaced)  return this;
1457             return new Name(function, arguments);
1458         }
1459         void internArguments() {
1460             @SuppressWarnings("LocalVariableHidesMemberVariable")
1461             Object[] arguments = this.arguments;
1462             for (int j = 0; j < arguments.length; j++) {
1463                 if (arguments[j] instanceof Name) {
1464                     Name n = (Name) arguments[j];
1465                     if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
1466                         arguments[j] = internArgument(n);
1467                 }
1468             }
1469         }
1470         boolean isParam() {
1471             return function == null;
1472         }
1473         boolean isConstantZero() {
1474             return !isParam() && arguments.length == 0 && function.isConstantZero();
1475         }
1476 
1477         public String toString() {
1478             return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar();
1479         }
1480         public String debugString() {
1481             String s = paramString();
1482             return (function == null) ? s : s + "=" + exprString();
1483         }
1484         public String paramString() {
1485             String s = toString();
1486             Object c = constraint;
1487             if (c == null)
1488                 return s;
1489             if (c instanceof Class)  c = ((Class<?>)c).getSimpleName();
1490             return s + "/" + c;
1491         }
1492         public String exprString() {
1493             if (function == null)  return toString();
1494             StringBuilder buf = new StringBuilder(function.toString());
1495             buf.append("(");
1496             String cma = "";
1497             for (Object a : arguments) {
1498                 buf.append(cma); cma = ",";
1499                 if (a instanceof Name || a instanceof Integer)
1500                     buf.append(a);
1501                 else
1502                     buf.append("(").append(a).append(")");
1503             }
1504             buf.append(")");
1505             return buf.toString();
1506         }
1507 
1508         static boolean typesMatch(BasicType parameterType, Object object) {
1509             if (object instanceof Name) {
1510                 return ((Name)object).type == parameterType;
1511             }
1512             switch (parameterType) {
1513                 case I_TYPE:  return object instanceof Integer;
1514                 case J_TYPE:  return object instanceof Long;
1515                 case F_TYPE:  return object instanceof Float;
1516                 case D_TYPE:  return object instanceof Double;
1517             }
1518             assert(parameterType == L_TYPE);
1519             return true;
1520         }
1521 
1522         /** Return the index of the last occurrence of n in the argument array.
1523          *  Return -1 if the name is not used.
1524          */
1525         int lastUseIndex(Name n) {
1526             if (arguments == null)  return -1;
1527             for (int i = arguments.length; --i >= 0; ) {
1528                 if (arguments[i] == n)  return i;
1529             }
1530             return -1;
1531         }
1532 
1533         /** Return the number of occurrences of n in the argument array.
1534          *  Return 0 if the name is not used.
1535          */
1536         int useCount(Name n) {
1537             if (arguments == null)  return 0;
1538             int count = 0;
1539             for (int i = arguments.length; --i >= 0; ) {
1540                 if (arguments[i] == n)  ++count;
1541             }
1542             return count;
1543         }
1544 
1545         boolean contains(Name n) {
1546             return this == n || lastUseIndex(n) >= 0;
1547         }
1548 
1549         public boolean equals(Name that) {
1550             if (this == that)  return true;
1551             if (isParam())
1552                 // each parameter is a unique atom
1553                 return false;  // this != that
1554             return
1555                 //this.index == that.index &&
1556                 this.type == that.type &&
1557                 this.function.equals(that.function) &&
1558                 Arrays.equals(this.arguments, that.arguments);
1559         }
1560         @Override
1561         public boolean equals(Object x) {
1562             return x instanceof Name && equals((Name)x);
1563         }
1564         @Override
1565         public int hashCode() {
1566             if (isParam())
1567                 return index | (type.ordinal() << 8);
1568             return function.hashCode() ^ Arrays.hashCode(arguments);
1569         }
1570     }
1571 
1572     /** Return the index of the last name which contains n as an argument.
1573      *  Return -1 if the name is not used.  Return names.length if it is the return value.
1574      */
1575     int lastUseIndex(Name n) {
1576         int ni = n.index, nmax = names.length;
1577         assert(names[ni] == n);
1578         if (result == ni)  return nmax;  // live all the way beyond the end
1579         for (int i = nmax; --i > ni; ) {
1580             if (names[i].lastUseIndex(n) >= 0)
1581                 return i;
1582         }
1583         return -1;
1584     }
1585 
1586     /** Return the number of times n is used as an argument or return value. */
1587     int useCount(Name n) {
1588         int ni = n.index, nmax = names.length;
1589         int end = lastUseIndex(n);
1590         if (end < 0)  return 0;
1591         int count = 0;
1592         if (end == nmax) { count++; end--; }
1593         int beg = n.index() + 1;
1594         if (beg < arity)  beg = arity;
1595         for (int i = beg; i <= end; i++) {
1596             count += names[i].useCount(n);
1597         }
1598         return count;
1599     }
1600 
1601     static Name argument(int which, char type) {
1602         return argument(which, basicType(type));
1603     }
1604     static Name argument(int which, BasicType type) {
1605         if (which >= INTERNED_ARGUMENT_LIMIT)
1606             return new Name(which, type);
1607         return INTERNED_ARGUMENTS[type.ordinal()][which];
1608     }
1609     static Name internArgument(Name n) {
1610         assert(n.isParam()) : "not param: " + n;
1611         assert(n.index < INTERNED_ARGUMENT_LIMIT);
1612         if (n.constraint != null)  return n;
1613         return argument(n.index, n.type);
1614     }
1615     static Name[] arguments(int extra, String types) {
1616         int length = types.length();
1617         Name[] names = new Name[length + extra];
1618         for (int i = 0; i < length; i++)
1619             names[i] = argument(i, types.charAt(i));
1620         return names;
1621     }
1622     static Name[] arguments(int extra, char... types) {
1623         int length = types.length;
1624         Name[] names = new Name[length + extra];
1625         for (int i = 0; i < length; i++)
1626             names[i] = argument(i, types[i]);
1627         return names;
1628     }
1629     static Name[] arguments(int extra, List<Class<?>> types) {
1630         int length = types.size();
1631         Name[] names = new Name[length + extra];
1632         for (int i = 0; i < length; i++)
1633             names[i] = argument(i, basicType(types.get(i)));
1634         return names;
1635     }
1636     static Name[] arguments(int extra, Class<?>... types) {
1637         int length = types.length;
1638         Name[] names = new Name[length + extra];
1639         for (int i = 0; i < length; i++)
1640             names[i] = argument(i, basicType(types[i]));
1641         return names;
1642     }
1643     static Name[] arguments(int extra, MethodType types) {
1644         int length = types.parameterCount();
1645         Name[] names = new Name[length + extra];
1646         for (int i = 0; i < length; i++)
1647             names[i] = argument(i, basicType(types.parameterType(i)));
1648         return names;
1649     }
1650     static final int INTERNED_ARGUMENT_LIMIT = 10;
1651     private static final Name[][] INTERNED_ARGUMENTS
1652             = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT];
1653     static {
1654         for (BasicType type : BasicType.ARG_TYPES) {
1655             int ord = type.ordinal();
1656             for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) {
1657                 INTERNED_ARGUMENTS[ord][i] = new Name(i, type);
1658             }
1659         }
1660     }
1661 
1662     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1663 
1664     static LambdaForm identityForm(BasicType type) {
1665         return LF_identityForm[type.ordinal()];
1666     }
1667     static LambdaForm zeroForm(BasicType type) {
1668         return LF_zeroForm[type.ordinal()];
1669     }
1670     static NamedFunction identity(BasicType type) {
1671         return NF_identity[type.ordinal()];
1672     }
1673     static NamedFunction constantZero(BasicType type) {
1674         return NF_zero[type.ordinal()];
1675     }
1676     private static final LambdaForm[] LF_identityForm = new LambdaForm[TYPE_LIMIT];
1677     private static final LambdaForm[] LF_zeroForm = new LambdaForm[TYPE_LIMIT];
1678     private static final NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT];
1679     private static final NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT];
1680     private static void createIdentityForms() {
1681         for (BasicType type : BasicType.ALL_TYPES) {
1682             int ord = type.ordinal();
1683             char btChar = type.basicTypeChar();
1684             boolean isVoid = (type == V_TYPE);
1685             Class<?> btClass = type.btClass;
1686             MethodType zeType = MethodType.methodType(btClass);
1687             MethodType idType = isVoid ? zeType : zeType.appendParameterTypes(btClass);
1688 
1689             // Look up some symbolic names.  It might not be necessary to have these,
1690             // but if we need to emit direct references to bytecodes, it helps.
1691             // Zero is built from a call to an identity function with a constant zero input.
1692             MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic);
1693             MemberName zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic);
1694             try {
1695                 zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class);
1696                 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class);
1697             } catch (IllegalAccessException|NoSuchMethodException ex) {
1698                 throw newInternalError(ex);
1699             }
1700 
1701             NamedFunction idFun = new NamedFunction(idMem);
1702             LambdaForm idForm;
1703             if (isVoid) {
1704                 Name[] idNames = new Name[] { argument(0, L_TYPE) };
1705                 idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT);
1706             } else {
1707                 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
1708                 idForm = new LambdaForm(idMem.getName(), 2, idNames, 1);
1709             }
1710             LF_identityForm[ord] = idForm;
1711             NF_identity[ord] = idFun;
1712 
1713             NamedFunction zeFun = new NamedFunction(zeMem);
1714             LambdaForm zeForm;
1715             if (isVoid) {
1716                 zeForm = idForm;
1717             } else {
1718                 Object zeValue = Wrapper.forBasicType(btChar).zero();
1719                 Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) };
1720                 zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1);
1721             }
1722             LF_zeroForm[ord] = zeForm;
1723             NF_zero[ord] = zeFun;
1724 
1725             assert(idFun.isIdentity());
1726             assert(zeFun.isConstantZero());
1727             assert(new Name(zeFun).isConstantZero());
1728         }
1729 
1730         // Do this in a separate pass, so that SimpleMethodHandle.make can see the tables.
1731         for (BasicType type : BasicType.ALL_TYPES) {
1732             int ord = type.ordinal();
1733             NamedFunction idFun = NF_identity[ord];
1734             LambdaForm idForm = LF_identityForm[ord];
1735             MemberName idMem = idFun.member;
1736             idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm);
1737 
1738             NamedFunction zeFun = NF_zero[ord];
1739             LambdaForm zeForm = LF_zeroForm[ord];
1740             MemberName zeMem = zeFun.member;
1741             zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm);
1742 
1743             assert(idFun.isIdentity());
1744             assert(zeFun.isConstantZero());
1745             assert(new Name(zeFun).isConstantZero());
1746         }
1747     }
1748 
1749     // Avoid appealing to ValueConversions at bootstrap time:
1750     private static int identity_I(int x) { return x; }
1751     private static long identity_J(long x) { return x; }
1752     private static float identity_F(float x) { return x; }
1753     private static double identity_D(double x) { return x; }
1754     private static Object identity_L(Object x) { return x; }
1755     private static void identity_V() { return; }  // same as zeroV, but that's OK
1756     private static int zero_I() { return 0; }
1757     private static long zero_J() { return 0; }
1758     private static float zero_F() { return 0; }
1759     private static double zero_D() { return 0; }
1760     private static Object zero_L() { return null; }
1761     private static void zero_V() { return; }
1762 
1763     /**
1764      * Internal marker for byte-compiled LambdaForms.
1765      */
1766     /*non-public*/
1767     @Target(ElementType.METHOD)
1768     @Retention(RetentionPolicy.RUNTIME)
1769     @interface Compiled {
1770     }
1771 
1772     /**
1773      * Internal marker for LambdaForm interpreter frames.
1774      */
1775     /*non-public*/
1776     @Target(ElementType.METHOD)
1777     @Retention(RetentionPolicy.RUNTIME)
1778     @interface Hidden {
1779     }
1780 
1781     private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1782     static {
1783         if (debugEnabled())
1784             DEBUG_NAME_COUNTERS = new HashMap<>();
1785         else
1786             DEBUG_NAME_COUNTERS = null;
1787     }
1788 
1789     // Put this last, so that previous static inits can run before.
1790     static {
1791         createIdentityForms();
1792         if (USE_PREDEFINED_INTERPRET_METHODS)
1793             computeInitialPreparedForms();
1794         NamedFunction.initializeInvokers();
1795     }
1796 
1797     // The following hack is necessary in order to suppress TRACE_INTERPRETER
1798     // during execution of the static initializes of this class.
1799     // Turning on TRACE_INTERPRETER too early will cause
1800     // stack overflows and other misbehavior during attempts to trace events
1801     // that occur during LambdaForm.<clinit>.
1802     // Therefore, do not move this line higher in this file, and do not remove.
1803     private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
1804 }