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