1 /*
   2  * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.JavaLangInvokeAccess;
  29 import jdk.internal.access.SharedSecrets;
  30 import jdk.internal.invoke.NativeEntryPoint;
  31 import jdk.internal.org.objectweb.asm.ClassWriter;
  32 import jdk.internal.org.objectweb.asm.MethodVisitor;
  33 import jdk.internal.reflect.CallerSensitive;
  34 import jdk.internal.reflect.Reflection;
  35 import jdk.internal.vm.annotation.ForceInline;
  36 import jdk.internal.vm.annotation.Hidden;
  37 import jdk.internal.vm.annotation.Stable;
  38 import sun.invoke.empty.Empty;
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 
  43 import java.lang.invoke.MethodHandles.Lookup;
  44 import java.lang.reflect.Array;
  45 import java.nio.ByteOrder;
  46 import java.util.Arrays;
  47 import java.util.Collections;
  48 import java.util.HashMap;
  49 import java.util.Iterator;
  50 import java.util.List;
  51 import java.util.Map;
  52 import java.util.Objects;
  53 import java.util.concurrent.ConcurrentHashMap;
  54 import java.util.function.Function;
  55 import java.util.stream.Stream;
  56 
  57 import static java.lang.invoke.LambdaForm.*;
  58 import static java.lang.invoke.MethodHandleStatics.*;
  59 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  60 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  61 
  62 /**
  63  * Trusted implementation code for MethodHandle.
  64  * @author jrose
  65  */
  66 /*non-public*/
  67 abstract class MethodHandleImpl {
  68 
  69     /// Factory methods to create method handles:
  70 
  71     static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, ArrayAccess access) {
  72         if (arrayClass == Object[].class) {
  73             return ArrayAccess.objectAccessor(access);
  74         }
  75         if (!arrayClass.isArray())
  76             throw newIllegalArgumentException("not an array: "+arrayClass);
  77         MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass);
  78         int cacheIndex = ArrayAccess.cacheIndex(access);
  79         MethodHandle mh = cache[cacheIndex];
  80         if (mh != null)  return mh;
  81         mh = ArrayAccessor.getAccessor(arrayClass, access);
  82         MethodType correctType = ArrayAccessor.correctType(arrayClass, access);
  83         if (mh.type() != correctType) {
  84             assert(mh.type().parameterType(0) == Object[].class);
  85             /* if access == SET */ assert(access != ArrayAccess.SET || mh.type().parameterType(2) == Object.class);
  86             /* if access == GET */ assert(access != ArrayAccess.GET ||
  87                     (mh.type().returnType() == Object.class &&
  88                      correctType.parameterType(0).getComponentType() == correctType.returnType()));
  89             // safe to view non-strictly, because element type follows from array type
  90             mh = mh.viewAsType(correctType, false);
  91         }
  92         mh = makeIntrinsic(mh, ArrayAccess.intrinsic(access));
  93         // Atomically update accessor cache.
  94         synchronized(cache) {
  95             if (cache[cacheIndex] == null) {
  96                 cache[cacheIndex] = mh;
  97             } else {
  98                 // Throw away newly constructed accessor and use cached version.
  99                 mh = cache[cacheIndex];
 100             }
 101         }
 102         return mh;
 103     }
 104 
 105     enum ArrayAccess {
 106         GET, SET, LENGTH;
 107 
 108         // As ArrayAccess and ArrayAccessor have a circular dependency, the ArrayAccess properties cannot be stored in
 109         // final fields.
 110 
 111         static String opName(ArrayAccess a) {
 112             return switch (a) {
 113                 case GET    -> "getElement";
 114                 case SET    -> "setElement";
 115                 case LENGTH -> "length";
 116                 default -> throw unmatchedArrayAccess(a);
 117             };
 118         }
 119 
 120         static MethodHandle objectAccessor(ArrayAccess a) {
 121             return switch (a) {
 122                 case GET    -> ArrayAccessor.OBJECT_ARRAY_GETTER;
 123                 case SET    -> ArrayAccessor.OBJECT_ARRAY_SETTER;
 124                 case LENGTH -> ArrayAccessor.OBJECT_ARRAY_LENGTH;
 125                 default -> throw unmatchedArrayAccess(a);
 126             };
 127         }
 128 
 129         static int cacheIndex(ArrayAccess a) {
 130             return switch (a) {
 131                 case GET    -> ArrayAccessor.GETTER_INDEX;
 132                 case SET    -> ArrayAccessor.SETTER_INDEX;
 133                 case LENGTH -> ArrayAccessor.LENGTH_INDEX;
 134                 default -> throw unmatchedArrayAccess(a);
 135             };
 136         }
 137 
 138         static Intrinsic intrinsic(ArrayAccess a) {
 139             return switch (a) {
 140                 case GET    -> Intrinsic.ARRAY_LOAD;
 141                 case SET    -> Intrinsic.ARRAY_STORE;
 142                 case LENGTH -> Intrinsic.ARRAY_LENGTH;
 143                 default -> throw unmatchedArrayAccess(a);
 144             };
 145         }
 146     }
 147 
 148     static InternalError unmatchedArrayAccess(ArrayAccess a) {
 149         return newInternalError("should not reach here (unmatched ArrayAccess: " + a + ")");
 150     }
 151 
 152     static final class ArrayAccessor {
 153         /// Support for array element and length access
 154         static final int GETTER_INDEX = 0, SETTER_INDEX = 1, LENGTH_INDEX = 2, INDEX_LIMIT = 3;
 155         static final ClassValue<MethodHandle[]> TYPED_ACCESSORS
 156                 = new ClassValue<MethodHandle[]>() {
 157                     @Override
 158                     protected MethodHandle[] computeValue(Class<?> type) {
 159                         return new MethodHandle[INDEX_LIMIT];
 160                     }
 161                 };
 162         static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER, OBJECT_ARRAY_LENGTH;
 163         static {
 164             MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class);
 165             cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.GET),    Intrinsic.ARRAY_LOAD);
 166             cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.SET),    Intrinsic.ARRAY_STORE);
 167             cache[LENGTH_INDEX] = OBJECT_ARRAY_LENGTH = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.LENGTH), Intrinsic.ARRAY_LENGTH);
 168 
 169             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName()));
 170             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName()));
 171             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_LENGTH.internalMemberName()));
 172         }
 173 
 174         static int     getElementI(int[]     a, int i)            { return              a[i]; }
 175         static long    getElementJ(long[]    a, int i)            { return              a[i]; }
 176         static float   getElementF(float[]   a, int i)            { return              a[i]; }
 177         static double  getElementD(double[]  a, int i)            { return              a[i]; }
 178         static boolean getElementZ(boolean[] a, int i)            { return              a[i]; }
 179         static byte    getElementB(byte[]    a, int i)            { return              a[i]; }
 180         static short   getElementS(short[]   a, int i)            { return              a[i]; }
 181         static char    getElementC(char[]    a, int i)            { return              a[i]; }
 182         static Object  getElementL(Object[]  a, int i)            { return              a[i]; }
 183 
 184         static void    setElementI(int[]     a, int i, int     x) {              a[i] = x; }
 185         static void    setElementJ(long[]    a, int i, long    x) {              a[i] = x; }
 186         static void    setElementF(float[]   a, int i, float   x) {              a[i] = x; }
 187         static void    setElementD(double[]  a, int i, double  x) {              a[i] = x; }
 188         static void    setElementZ(boolean[] a, int i, boolean x) {              a[i] = x; }
 189         static void    setElementB(byte[]    a, int i, byte    x) {              a[i] = x; }
 190         static void    setElementS(short[]   a, int i, short   x) {              a[i] = x; }
 191         static void    setElementC(char[]    a, int i, char    x) {              a[i] = x; }
 192         static void    setElementL(Object[]  a, int i, Object  x) {              a[i] = x; }
 193 
 194         static int     lengthI(int[]     a)                       { return a.length; }
 195         static int     lengthJ(long[]    a)                       { return a.length; }
 196         static int     lengthF(float[]   a)                       { return a.length; }
 197         static int     lengthD(double[]  a)                       { return a.length; }
 198         static int     lengthZ(boolean[] a)                       { return a.length; }
 199         static int     lengthB(byte[]    a)                       { return a.length; }
 200         static int     lengthS(short[]   a)                       { return a.length; }
 201         static int     lengthC(char[]    a)                       { return a.length; }
 202         static int     lengthL(Object[]  a)                       { return a.length; }
 203 
 204         static String name(Class<?> arrayClass, ArrayAccess access) {
 205             Class<?> elemClass = arrayClass.getComponentType();
 206             if (elemClass == null)  throw newIllegalArgumentException("not an array", arrayClass);
 207             return ArrayAccess.opName(access) + Wrapper.basicTypeChar(elemClass);
 208         }
 209         static MethodType type(Class<?> arrayClass, ArrayAccess access) {
 210             Class<?> elemClass = arrayClass.getComponentType();
 211             Class<?> arrayArgClass = arrayClass;
 212             if (!elemClass.isPrimitive()) {
 213                 arrayArgClass = Object[].class;
 214                 elemClass = Object.class;
 215             }
 216             return switch (access) {
 217                 case GET    -> MethodType.methodType(elemClass, arrayArgClass, int.class);
 218                 case SET    -> MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
 219                 case LENGTH -> MethodType.methodType(int.class, arrayArgClass);
 220                 default -> throw unmatchedArrayAccess(access);
 221             };
 222         }
 223         static MethodType correctType(Class<?> arrayClass, ArrayAccess access) {
 224             Class<?> elemClass = arrayClass.getComponentType();
 225             return switch (access) {
 226                 case GET    -> MethodType.methodType(elemClass, arrayClass, int.class);
 227                 case SET    -> MethodType.methodType(void.class, arrayClass, int.class, elemClass);
 228                 case LENGTH -> MethodType.methodType(int.class, arrayClass);
 229                 default -> throw unmatchedArrayAccess(access);
 230             };
 231         }
 232         static MethodHandle getAccessor(Class<?> arrayClass, ArrayAccess access) {
 233             String     name = name(arrayClass, access);
 234             MethodType type = type(arrayClass, access);
 235             try {
 236                 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type);
 237             } catch (ReflectiveOperationException ex) {
 238                 throw uncaughtException(ex);
 239             }
 240         }
 241     }
 242 
 243     /**
 244      * Create a JVM-level adapter method handle to conform the given method
 245      * handle to the similar newType, using only pairwise argument conversions.
 246      * For each argument, convert incoming argument to the exact type needed.
 247      * The argument conversions allowed are casting, boxing and unboxing,
 248      * integral widening or narrowing, and floating point widening or narrowing.
 249      * @param srcType required call type
 250      * @param target original method handle
 251      * @param strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed
 252      * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double)
 253      * @return an adapter to the original handle with the desired new type,
 254      *          or the original target if the types are already identical
 255      *          or null if the adaptation cannot be made
 256      */
 257     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 258                                             boolean strict, boolean monobox) {
 259         MethodType dstType = target.type();
 260         if (srcType == dstType)
 261             return target;
 262         return makePairwiseConvertByEditor(target, srcType, strict, monobox);
 263     }
 264 
 265     private static int countNonNull(Object[] array) {
 266         int count = 0;
 267         if (array != null) {
 268             for (Object x : array) {
 269                 if (x != null) ++count;
 270             }
 271         }
 272         return count;
 273     }
 274 
 275     static MethodHandle makePairwiseConvertByEditor(MethodHandle target, MethodType srcType,
 276                                                     boolean strict, boolean monobox) {
 277         // In method types arguments start at index 0, while the LF
 278         // editor have the MH receiver at position 0 - adjust appropriately.
 279         final int MH_RECEIVER_OFFSET = 1;
 280         Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox);
 281         int convCount = countNonNull(convSpecs);
 282         if (convCount == 0)
 283             return target.viewAsType(srcType, strict);
 284         MethodType basicSrcType = srcType.basicType();
 285         MethodType midType = target.type().basicType();
 286         BoundMethodHandle mh = target.rebind();
 287 
 288         // Match each unique conversion to the positions at which it is to be applied
 289         var convSpecMap = new HashMap<Object, int[]>(((4 * convCount) / 3) + 1);
 290         for (int i = 0; i < convSpecs.length - MH_RECEIVER_OFFSET; i++) {
 291             Object convSpec = convSpecs[i];
 292             if (convSpec == null) continue;
 293             int[] positions = convSpecMap.get(convSpec);
 294             if (positions == null) {
 295                 positions = new int[] { i + MH_RECEIVER_OFFSET };
 296             } else {
 297                 positions = Arrays.copyOf(positions, positions.length + 1);
 298                 positions[positions.length - 1] = i + MH_RECEIVER_OFFSET;
 299             }
 300             convSpecMap.put(convSpec, positions);
 301         }
 302         for (var entry : convSpecMap.entrySet()) {
 303             Object convSpec = entry.getKey();
 304 
 305             MethodHandle fn;
 306             if (convSpec instanceof Class) {
 307                 fn = getConstantHandle(MH_cast).bindTo(convSpec);
 308             } else {
 309                 fn = (MethodHandle) convSpec;
 310             }
 311             int[] positions = entry.getValue();
 312             Class<?> newType = basicSrcType.parameterType(positions[0] - MH_RECEIVER_OFFSET);
 313             BasicType newBasicType = BasicType.basicType(newType);
 314             convCount -= positions.length;
 315             if (convCount == 0) {
 316                 midType = srcType;
 317             } else {
 318                 Class<?>[] ptypes = midType.ptypes().clone();
 319                 for (int pos : positions) {
 320                     ptypes[pos - 1] = newType;
 321                 }
 322                 midType = MethodType.makeImpl(midType.rtype(), ptypes, true);
 323             }
 324             LambdaForm form2;
 325             if (positions.length > 1) {
 326                 form2 = mh.editor().filterRepeatedArgumentForm(newBasicType, positions);
 327             } else {
 328                 form2 = mh.editor().filterArgumentForm(positions[0], newBasicType);
 329             }
 330             mh = mh.copyWithExtendL(midType, form2, fn);
 331         }
 332         Object convSpec = convSpecs[convSpecs.length - 1];
 333         if (convSpec != null) {
 334             MethodHandle fn;
 335             if (convSpec instanceof Class) {
 336                 if (convSpec == void.class)
 337                     fn = null;
 338                 else
 339                     fn = getConstantHandle(MH_cast).bindTo(convSpec);
 340             } else {
 341                 fn = (MethodHandle) convSpec;
 342             }
 343             Class<?> newType = basicSrcType.returnType();
 344             assert(--convCount == 0);
 345             midType = srcType;
 346             if (fn != null) {
 347                 mh = mh.rebind();  // rebind if too complex
 348                 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), false);
 349                 mh = mh.copyWithExtendL(midType, form2, fn);
 350             } else {
 351                 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), true);
 352                 mh = mh.copyWith(midType, form2);
 353             }
 354         }
 355         assert(convCount == 0);
 356         assert(mh.type().equals(srcType));
 357         return mh;
 358     }
 359 
 360     static Object[] computeValueConversions(MethodType srcType, MethodType dstType,
 361                                             boolean strict, boolean monobox) {
 362         final int INARG_COUNT = srcType.parameterCount();
 363         Object[] convSpecs = null;
 364         for (int i = 0; i <= INARG_COUNT; i++) {
 365             boolean isRet = (i == INARG_COUNT);
 366             Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i);
 367             Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i);
 368             if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) {
 369                 if (convSpecs == null) {
 370                     convSpecs = new Object[INARG_COUNT + 1];
 371                 }
 372                 convSpecs[i] = valueConversion(src, dst, strict, monobox);
 373             }
 374         }
 375         return convSpecs;
 376     }
 377     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 378                                             boolean strict) {
 379         return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false);
 380     }
 381 
 382     /**
 383      * Find a conversion function from the given source to the given destination.
 384      * This conversion function will be used as a LF NamedFunction.
 385      * Return a Class object if a simple cast is needed.
 386      * Return void.class if void is involved.
 387      */
 388     static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) {
 389         assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict));  // caller responsibility
 390         if (dst == void.class)
 391             return dst;
 392         MethodHandle fn;
 393         if (src.isPrimitive()) {
 394             if (src == void.class) {
 395                 return void.class;  // caller must recognize this specially
 396             } else if (dst.isPrimitive()) {
 397                 // Examples: int->byte, byte->int, boolean->int (!strict)
 398                 fn = ValueConversions.convertPrimitive(src, dst);
 399             } else {
 400                 // Examples: int->Integer, boolean->Object, float->Number
 401                 Wrapper wsrc = Wrapper.forPrimitiveType(src);
 402                 fn = ValueConversions.boxExact(wsrc);
 403                 assert(fn.type().parameterType(0) == wsrc.primitiveType());
 404                 assert(fn.type().returnType() == wsrc.wrapperType());
 405                 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) {
 406                     // Corner case, such as int->Long, which will probably fail.
 407                     MethodType mt = MethodType.methodType(dst, src);
 408                     if (strict)
 409                         fn = fn.asType(mt);
 410                     else
 411                         fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false);
 412                 }
 413             }
 414         } else if (dst.isPrimitive()) {
 415             Wrapper wdst = Wrapper.forPrimitiveType(dst);
 416             if (monobox || src == wdst.wrapperType()) {
 417                 // Use a strongly-typed unboxer, if possible.
 418                 fn = ValueConversions.unboxExact(wdst, strict);
 419             } else {
 420                 // Examples:  Object->int, Number->int, Comparable->int, Byte->int
 421                 // must include additional conversions
 422                 // src must be examined at runtime, to detect Byte, Character, etc.
 423                 fn = (strict
 424                         ? ValueConversions.unboxWiden(wdst)
 425                         : ValueConversions.unboxCast(wdst));
 426             }
 427         } else {
 428             // Simple reference conversion.
 429             // Note:  Do not check for a class hierarchy relation
 430             // between src and dst.  In all cases a 'null' argument
 431             // will pass the cast conversion.
 432             return dst;
 433         }
 434         assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn);
 435         return fn;
 436     }
 437 
 438     static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
 439         MethodType type = target.type();
 440         int last = type.parameterCount() - 1;
 441         if (type.parameterType(last) != arrayType)
 442             target = target.asType(type.changeParameterType(last, arrayType));
 443         target = target.asFixedArity();  // make sure this attribute is turned off
 444         return new AsVarargsCollector(target, arrayType);
 445     }
 446 
 447     private static final class AsVarargsCollector extends DelegatingMethodHandle {
 448         private final MethodHandle target;
 449         private final Class<?> arrayType;
 450         private @Stable MethodHandle asCollectorCache;
 451 
 452         AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
 453             this(target.type(), target, arrayType);
 454         }
 455         AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) {
 456             super(type, target);
 457             this.target = target;
 458             this.arrayType = arrayType;
 459         }
 460 
 461         @Override
 462         public boolean isVarargsCollector() {
 463             return true;
 464         }
 465 
 466         @Override
 467         protected MethodHandle getTarget() {
 468             return target;
 469         }
 470 
 471         @Override
 472         public MethodHandle asFixedArity() {
 473             return target;
 474         }
 475 
 476         @Override
 477         MethodHandle setVarargs(MemberName member) {
 478             if (member.isVarargs())  return this;
 479             return asFixedArity();
 480         }
 481 
 482         @Override
 483         public MethodHandle withVarargs(boolean makeVarargs) {
 484             if (makeVarargs)  return this;
 485             return asFixedArity();
 486         }
 487 
 488         @Override
 489         public MethodHandle asTypeUncached(MethodType newType) {
 490             MethodType type = this.type();
 491             int collectArg = type.parameterCount() - 1;
 492             int newArity = newType.parameterCount();
 493             if (newArity == collectArg+1 &&
 494                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 495                 // if arity and trailing parameter are compatible, do normal thing
 496                 return asFixedArity().asType(newType);
 497             }
 498             // check cache
 499             MethodHandle acc = asCollectorCache;
 500             if (acc != null && acc.type().parameterCount() == newArity)
 501                 return acc.asType(newType);
 502             // build and cache a collector
 503             int arrayLength = newArity - collectArg;
 504             MethodHandle collector;
 505             try {
 506                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 507                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 508             } catch (IllegalArgumentException ex) {
 509                 throw new WrongMethodTypeException("cannot build collector", ex);
 510             }
 511             asCollectorCache = collector;
 512             return collector.asType(newType);
 513         }
 514 
 515         @Override
 516         boolean viewAsTypeChecks(MethodType newType, boolean strict) {
 517             super.viewAsTypeChecks(newType, true);
 518             if (strict) return true;
 519             // extra assertion for non-strict checks:
 520             assert (type().lastParameterType().getComponentType()
 521                     .isAssignableFrom(
 522                             newType.lastParameterType().getComponentType()))
 523                     : Arrays.asList(this, newType);
 524             return true;
 525         }
 526 
 527         @Override
 528         public Object invokeWithArguments(Object... arguments) throws Throwable {
 529             MethodType type = this.type();
 530             int argc;
 531             final int MAX_SAFE = 127;  // 127 longs require 254 slots, which is safe to spread
 532             if (arguments == null
 533                     || (argc = arguments.length) <= MAX_SAFE
 534                     || argc < type.parameterCount()) {
 535                 return super.invokeWithArguments(arguments);
 536             }
 537 
 538             // a jumbo invocation requires more explicit reboxing of the trailing arguments
 539             int uncollected = type.parameterCount() - 1;
 540             Class<?> elemType = arrayType.getComponentType();
 541             int collected = argc - uncollected;
 542             Object collArgs = (elemType == Object.class)
 543                 ? new Object[collected] : Array.newInstance(elemType, collected);
 544             if (!elemType.isPrimitive()) {
 545                 // simple cast:  just do some casting
 546                 try {
 547                     System.arraycopy(arguments, uncollected, collArgs, 0, collected);
 548                 } catch (ArrayStoreException ex) {
 549                     return super.invokeWithArguments(arguments);
 550                 }
 551             } else {
 552                 // corner case of flat array requires reflection (or specialized copy loop)
 553                 MethodHandle arraySetter = MethodHandles.arrayElementSetter(arrayType);
 554                 try {
 555                     for (int i = 0; i < collected; i++) {
 556                         arraySetter.invoke(collArgs, i, arguments[uncollected + i]);
 557                     }
 558                 } catch (WrongMethodTypeException|ClassCastException ex) {
 559                     return super.invokeWithArguments(arguments);
 560                 }
 561             }
 562 
 563             // chop the jumbo list down to size and call in non-varargs mode
 564             Object[] newArgs = new Object[uncollected + 1];
 565             System.arraycopy(arguments, 0, newArgs, 0, uncollected);
 566             newArgs[uncollected] = collArgs;
 567             return asFixedArity().invokeWithArguments(newArgs);
 568         }
 569     }
 570 
 571     static void checkSpreadArgument(Object av, int n) {
 572         if (av == null && n == 0) {
 573             return;
 574         } else if (av == null) {
 575             throw new NullPointerException("null array reference");
 576         } else if (av instanceof Object[]) {
 577             int len = ((Object[])av).length;
 578             if (len == n)  return;
 579         } else {
 580             int len = java.lang.reflect.Array.getLength(av);
 581             if (len == n)  return;
 582         }
 583         // fall through to error:
 584         throw newIllegalArgumentException("array is not of length "+n);
 585     }
 586 
 587     @Hidden
 588     static MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 589         if (testResult) {
 590             return target;
 591         } else {
 592             return fallback;
 593         }
 594     }
 595 
 596     // Intrinsified by C2. Counters are used during parsing to calculate branch frequencies.
 597     @Hidden
 598     @jdk.internal.vm.annotation.IntrinsicCandidate
 599     static boolean profileBoolean(boolean result, int[] counters) {
 600         // Profile is int[2] where [0] and [1] correspond to false and true occurrences respectively.
 601         int idx = result ? 1 : 0;
 602         try {
 603             counters[idx] = Math.addExact(counters[idx], 1);
 604         } catch (ArithmeticException e) {
 605             // Avoid continuous overflow by halving the problematic count.
 606             counters[idx] = counters[idx] / 2;
 607         }
 608         return result;
 609     }
 610 
 611     // Intrinsified by C2. Returns true if obj is a compile-time constant.
 612     @Hidden
 613     @jdk.internal.vm.annotation.IntrinsicCandidate
 614     static boolean isCompileConstant(Object obj) {
 615         return false;
 616     }
 617 
 618     static MethodHandle makeGuardWithTest(MethodHandle test,
 619                                    MethodHandle target,
 620                                    MethodHandle fallback) {
 621         MethodType type = target.type();
 622         assert(test.type().equals(type.changeReturnType(boolean.class)) && fallback.type().equals(type));
 623         MethodType basicType = type.basicType();
 624         LambdaForm form = makeGuardWithTestForm(basicType);
 625         BoundMethodHandle mh;
 626         try {
 627             if (PROFILE_GWT) {
 628                 int[] counts = new int[2];
 629                 mh = (BoundMethodHandle)
 630                         BoundMethodHandle.speciesData_LLLL().factory().invokeBasic(type, form,
 631                                 (Object) test, (Object) profile(target), (Object) profile(fallback), counts);
 632             } else {
 633                 mh = (BoundMethodHandle)
 634                         BoundMethodHandle.speciesData_LLL().factory().invokeBasic(type, form,
 635                                 (Object) test, (Object) profile(target), (Object) profile(fallback));
 636             }
 637         } catch (Throwable ex) {
 638             throw uncaughtException(ex);
 639         }
 640         assert(mh.type() == type);
 641         return mh;
 642     }
 643 
 644 
 645     static MethodHandle profile(MethodHandle target) {
 646         if (DONT_INLINE_THRESHOLD >= 0) {
 647             return makeBlockInliningWrapper(target);
 648         } else {
 649             return target;
 650         }
 651     }
 652 
 653     /**
 654      * Block inlining during JIT-compilation of a target method handle if it hasn't been invoked enough times.
 655      * Corresponding LambdaForm has @DontInline when compiled into bytecode.
 656      */
 657     static MethodHandle makeBlockInliningWrapper(MethodHandle target) {
 658         LambdaForm lform;
 659         if (DONT_INLINE_THRESHOLD > 0) {
 660             lform = Makers.PRODUCE_BLOCK_INLINING_FORM.apply(target);
 661         } else {
 662             lform = Makers.PRODUCE_REINVOKER_FORM.apply(target);
 663         }
 664         return new CountingWrapper(target, lform,
 665                 Makers.PRODUCE_BLOCK_INLINING_FORM, Makers.PRODUCE_REINVOKER_FORM,
 666                                    DONT_INLINE_THRESHOLD);
 667     }
 668 
 669     private static final class Makers {
 670         /** Constructs reinvoker lambda form which block inlining during JIT-compilation for a particular method handle */
 671         static final Function<MethodHandle, LambdaForm> PRODUCE_BLOCK_INLINING_FORM = new Function<MethodHandle, LambdaForm>() {
 672             @Override
 673             public LambdaForm apply(MethodHandle target) {
 674                 return DelegatingMethodHandle.makeReinvokerForm(target,
 675                                    MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, false,
 676                                    DelegatingMethodHandle.NF_getTarget, CountingWrapper.NF_maybeStopCounting);
 677             }
 678         };
 679 
 680         /** Constructs simple reinvoker lambda form for a particular method handle */
 681         static final Function<MethodHandle, LambdaForm> PRODUCE_REINVOKER_FORM = new Function<MethodHandle, LambdaForm>() {
 682             @Override
 683             public LambdaForm apply(MethodHandle target) {
 684                 return DelegatingMethodHandle.makeReinvokerForm(target,
 685                         MethodTypeForm.LF_DELEGATE, DelegatingMethodHandle.class, DelegatingMethodHandle.NF_getTarget);
 686             }
 687         };
 688 
 689         /** Maker of type-polymorphic varargs */
 690         static final ClassValue<MethodHandle[]> TYPED_COLLECTORS = new ClassValue<MethodHandle[]>() {
 691             @Override
 692             protected MethodHandle[] computeValue(Class<?> type) {
 693                 return new MethodHandle[MAX_JVM_ARITY + 1];
 694             }
 695         };
 696     }
 697 
 698     /**
 699      * Counting method handle. It has 2 states: counting and non-counting.
 700      * It is in counting state for the first n invocations and then transitions to non-counting state.
 701      * Behavior in counting and non-counting states is determined by lambda forms produced by
 702      * countingFormProducer & nonCountingFormProducer respectively.
 703      */
 704     static class CountingWrapper extends DelegatingMethodHandle {
 705         private final MethodHandle target;
 706         private int count;
 707         private Function<MethodHandle, LambdaForm> countingFormProducer;
 708         private Function<MethodHandle, LambdaForm> nonCountingFormProducer;
 709         private volatile boolean isCounting;
 710 
 711         private CountingWrapper(MethodHandle target, LambdaForm lform,
 712                                 Function<MethodHandle, LambdaForm> countingFromProducer,
 713                                 Function<MethodHandle, LambdaForm> nonCountingFormProducer,
 714                                 int count) {
 715             super(target.type(), lform);
 716             this.target = target;
 717             this.count = count;
 718             this.countingFormProducer = countingFromProducer;
 719             this.nonCountingFormProducer = nonCountingFormProducer;
 720             this.isCounting = (count > 0);
 721         }
 722 
 723         @Hidden
 724         @Override
 725         protected MethodHandle getTarget() {
 726             return target;
 727         }
 728 
 729         @Override
 730         public MethodHandle asTypeUncached(MethodType newType) {
 731             MethodHandle newTarget = target.asType(newType);
 732             MethodHandle wrapper;
 733             if (isCounting) {
 734                 LambdaForm lform;
 735                 lform = countingFormProducer.apply(newTarget);
 736                 wrapper = new CountingWrapper(newTarget, lform, countingFormProducer, nonCountingFormProducer, DONT_INLINE_THRESHOLD);
 737             } else {
 738                 wrapper = newTarget; // no need for a counting wrapper anymore
 739             }
 740             return wrapper;
 741         }
 742 
 743         boolean countDown() {
 744             int c = count;
 745             target.maybeCustomize(); // customize if counting happens for too long
 746             if (c <= 1) {
 747                 // Try to limit number of updates. MethodHandle.updateForm() doesn't guarantee LF update visibility.
 748                 if (isCounting) {
 749                     isCounting = false;
 750                     return true;
 751                 } else {
 752                     return false;
 753                 }
 754             } else {
 755                 count = c - 1;
 756                 return false;
 757             }
 758         }
 759 
 760         @Hidden
 761         static void maybeStopCounting(Object o1) {
 762              final CountingWrapper wrapper = (CountingWrapper) o1;
 763              if (wrapper.countDown()) {
 764                  // Reached invocation threshold. Replace counting behavior with a non-counting one.
 765                  wrapper.updateForm(new Function<>() {
 766                      public LambdaForm apply(LambdaForm oldForm) {
 767                          LambdaForm lform = wrapper.nonCountingFormProducer.apply(wrapper.target);
 768                          lform.compileToBytecode(); // speed up warmup by avoiding LF interpretation again after transition
 769                          return lform;
 770                      }});
 771              }
 772         }
 773 
 774         static final NamedFunction NF_maybeStopCounting;
 775         static {
 776             Class<?> THIS_CLASS = CountingWrapper.class;
 777             try {
 778                 NF_maybeStopCounting = new NamedFunction(THIS_CLASS.getDeclaredMethod("maybeStopCounting", Object.class));
 779             } catch (ReflectiveOperationException ex) {
 780                 throw newInternalError(ex);
 781             }
 782         }
 783     }
 784 
 785     static LambdaForm makeGuardWithTestForm(MethodType basicType) {
 786         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWT);
 787         if (lform != null)  return lform;
 788         final int THIS_MH      = 0;  // the BMH_LLL
 789         final int ARG_BASE     = 1;  // start of incoming arguments
 790         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 791         int nameCursor = ARG_LIMIT;
 792         final int GET_TEST     = nameCursor++;
 793         final int GET_TARGET   = nameCursor++;
 794         final int GET_FALLBACK = nameCursor++;
 795         final int GET_COUNTERS = PROFILE_GWT ? nameCursor++ : -1;
 796         final int CALL_TEST    = nameCursor++;
 797         final int PROFILE      = (GET_COUNTERS != -1) ? nameCursor++ : -1;
 798         final int TEST         = nameCursor-1; // previous statement: either PROFILE or CALL_TEST
 799         final int SELECT_ALT   = nameCursor++;
 800         final int CALL_TARGET  = nameCursor++;
 801         assert(CALL_TARGET == SELECT_ALT+1);  // must be true to trigger IBG.emitSelectAlternative
 802 
 803         MethodType lambdaType = basicType.invokerType();
 804         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 805 
 806         BoundMethodHandle.SpeciesData data =
 807                 (GET_COUNTERS != -1) ? BoundMethodHandle.speciesData_LLLL()
 808                                      : BoundMethodHandle.speciesData_LLL();
 809         names[THIS_MH] = names[THIS_MH].withConstraint(data);
 810         names[GET_TEST]     = new Name(data.getterFunction(0), names[THIS_MH]);
 811         names[GET_TARGET]   = new Name(data.getterFunction(1), names[THIS_MH]);
 812         names[GET_FALLBACK] = new Name(data.getterFunction(2), names[THIS_MH]);
 813         if (GET_COUNTERS != -1) {
 814             names[GET_COUNTERS] = new Name(data.getterFunction(3), names[THIS_MH]);
 815         }
 816         Object[] invokeArgs = Arrays.copyOfRange(names, 0, ARG_LIMIT, Object[].class);
 817 
 818         // call test
 819         MethodType testType = basicType.changeReturnType(boolean.class).basicType();
 820         invokeArgs[0] = names[GET_TEST];
 821         names[CALL_TEST] = new Name(testType, invokeArgs);
 822 
 823         // profile branch
 824         if (PROFILE != -1) {
 825             names[PROFILE] = new Name(getFunction(NF_profileBoolean), names[CALL_TEST], names[GET_COUNTERS]);
 826         }
 827         // call selectAlternative
 828         names[SELECT_ALT] = new Name(new NamedFunction(
 829                 makeIntrinsic(getConstantHandle(MH_selectAlternative), Intrinsic.SELECT_ALTERNATIVE)),
 830                 names[TEST], names[GET_TARGET], names[GET_FALLBACK]);
 831 
 832         // call target or fallback
 833         invokeArgs[0] = names[SELECT_ALT];
 834         names[CALL_TARGET] = new Name(basicType, invokeArgs);
 835 
 836         lform = new LambdaForm(lambdaType.parameterCount(), names, /*forceInline=*/true, Kind.GUARD);
 837 
 838         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform);
 839     }
 840 
 841     /**
 842      * The LambdaForm shape for catchException combinator is the following:
 843      * <blockquote><pre>{@code
 844      *  guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{
 845      *    t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L);
 846      *    t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L);
 847      *    t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L);
 848      *    t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L);
 849      *    t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L);
 850      *    t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L);
 851      *    t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L);
 852      *   t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I}
 853      * }</pre></blockquote>
 854      *
 855      * argL0 and argL2 are target and catcher method handles. argL1 is exception class.
 856      * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[]
 857      * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()).
 858      *
 859      * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms
 860      * among catchException combinators with the same basic type.
 861      */
 862     private static LambdaForm makeGuardWithCatchForm(MethodType basicType) {
 863         MethodType lambdaType = basicType.invokerType();
 864 
 865         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC);
 866         if (lform != null) {
 867             return lform;
 868         }
 869         final int THIS_MH      = 0;  // the BMH_LLLLL
 870         final int ARG_BASE     = 1;  // start of incoming arguments
 871         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 872 
 873         int nameCursor = ARG_LIMIT;
 874         final int GET_TARGET       = nameCursor++;
 875         final int GET_CLASS        = nameCursor++;
 876         final int GET_CATCHER      = nameCursor++;
 877         final int GET_COLLECT_ARGS = nameCursor++;
 878         final int GET_UNBOX_RESULT = nameCursor++;
 879         final int BOXED_ARGS       = nameCursor++;
 880         final int TRY_CATCH        = nameCursor++;
 881         final int UNBOX_RESULT     = nameCursor++;
 882 
 883         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 884 
 885         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 886         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
 887         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
 888         names[GET_CLASS]        = new Name(data.getterFunction(1), names[THIS_MH]);
 889         names[GET_CATCHER]      = new Name(data.getterFunction(2), names[THIS_MH]);
 890         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]);
 891         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]);
 892 
 893         // FIXME: rework argument boxing/result unboxing logic for LF interpretation
 894 
 895         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
 896         MethodType collectArgsType = basicType.changeReturnType(Object.class);
 897         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
 898         Object[] args = new Object[invokeBasic.type().parameterCount()];
 899         args[0] = names[GET_COLLECT_ARGS];
 900         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
 901         names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH)), args);
 902 
 903         // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L);
 904         Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]};
 905         names[TRY_CATCH] = new Name(getFunction(NF_guardWithCatch), gwcArgs);
 906 
 907         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
 908         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
 909         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
 910         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 911 
 912         lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.GUARD_WITH_CATCH);
 913 
 914         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
 915     }
 916 
 917     static MethodHandle makeGuardWithCatch(MethodHandle target,
 918                                     Class<? extends Throwable> exType,
 919                                     MethodHandle catcher) {
 920         MethodType type = target.type();
 921         LambdaForm form = makeGuardWithCatchForm(type.basicType());
 922 
 923         // Prepare auxiliary method handles used during LambdaForm interpretation.
 924         // Box arguments and wrap them into Object[]: ValueConversions.array().
 925         MethodType varargsType = type.changeReturnType(Object[].class);
 926         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
 927         MethodHandle unboxResult = unboxResultHandle(type.returnType());
 928 
 929         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 930         BoundMethodHandle mh;
 931         try {
 932             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) target, (Object) exType,
 933                     (Object) catcher, (Object) collectArgs, (Object) unboxResult);
 934         } catch (Throwable ex) {
 935             throw uncaughtException(ex);
 936         }
 937         assert(mh.type() == type);
 938         return mh;
 939     }
 940 
 941     /**
 942      * Intrinsified during LambdaForm compilation
 943      * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}).
 944      */
 945     @Hidden
 946     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
 947                                  Object... av) throws Throwable {
 948         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
 949         try {
 950             return target.asFixedArity().invokeWithArguments(av);
 951         } catch (Throwable t) {
 952             if (!exType.isInstance(t)) throw t;
 953             return catcher.asFixedArity().invokeWithArguments(prepend(av, t));
 954         }
 955     }
 956 
 957     /** Prepend elements to an array. */
 958     @Hidden
 959     private static Object[] prepend(Object[] array, Object... elems) {
 960         int nArray = array.length;
 961         int nElems = elems.length;
 962         Object[] newArray = new Object[nArray + nElems];
 963         System.arraycopy(elems, 0, newArray, 0, nElems);
 964         System.arraycopy(array, 0, newArray, nElems, nArray);
 965         return newArray;
 966     }
 967 
 968     static MethodHandle throwException(MethodType type) {
 969         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 970         int arity = type.parameterCount();
 971         if (arity > 1) {
 972             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
 973             mh = MethodHandles.dropArguments(mh, 1, Arrays.copyOfRange(type.parameterArray(), 1, arity));
 974             return mh;
 975         }
 976         return makePairwiseConvert(getFunction(NF_throwException).resolvedHandle(), type, false, true);
 977     }
 978 
 979     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 980 
 981     static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2];
 982     static MethodHandle fakeMethodHandleInvoke(MemberName method) {
 983         assert(method.isMethodHandleInvoke());
 984         int idx = switch (method.getName()) {
 985             case "invoke"      -> 0;
 986             case "invokeExact" -> 1;
 987             default -> throw new InternalError(method.getName());
 988         };
 989         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx];
 990         if (mh != null)  return mh;
 991         MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class,
 992                                                 MethodHandle.class, Object[].class);
 993         mh = throwException(type);
 994         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 995         if (!method.getInvocationType().equals(mh.type()))
 996             throw new InternalError(method.toString());
 997         mh = mh.withInternalMemberName(method, false);
 998         mh = mh.withVarargs(true);
 999         assert(method.isVarargs());
1000         FAKE_METHOD_HANDLE_INVOKE[idx] = mh;
1001         return mh;
1002     }
1003     static MethodHandle fakeVarHandleInvoke(MemberName method) {
1004         // TODO caching, is it necessary?
1005         MethodType type = MethodType.methodType(method.getReturnType(), UnsupportedOperationException.class,
1006                                                 VarHandle.class, Object[].class);
1007         MethodHandle mh = throwException(type);
1008         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke VarHandle"));
1009         if (!method.getInvocationType().equals(mh.type()))
1010             throw new InternalError(method.toString());
1011         mh = mh.withInternalMemberName(method, false);
1012         mh = mh.asVarargsCollector(Object[].class);
1013         assert(method.isVarargs());
1014         return mh;
1015     }
1016 
1017     /**
1018      * Create an alias for the method handle which, when called,
1019      * appears to be called from the same class loader and protection domain
1020      * as hostClass.
1021      * This is an expensive no-op unless the method which is called
1022      * is sensitive to its caller.  A small number of system methods
1023      * are in this category, including Class.forName and Method.invoke.
1024      */
1025     static MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
1026         return BindCaller.bindCaller(mh, hostClass);
1027     }
1028 
1029     // Put the whole mess into its own nested class.
1030     // That way we can lazily load the code and set up the constants.
1031     private static class BindCaller {
1032         private static MethodType INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1033 
1034         static MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
1035             // Code in the boot layer should now be careful while creating method handles or
1036             // functional interface instances created from method references to @CallerSensitive  methods,
1037             // it needs to be ensured the handles or interface instances are kept safe and are not passed
1038             // from the boot layer to untrusted code.
1039             if (hostClass == null
1040                 ||    (hostClass.isArray() ||
1041                        hostClass.isPrimitive() ||
1042                        hostClass.getName().startsWith("java.lang.invoke."))) {
1043                 throw new InternalError();  // does not happen, and should not anyway
1044             }
1045             // For simplicity, convert mh to a varargs-like method.
1046             MethodHandle vamh = prepareForInvoker(mh);
1047             // Cache the result of makeInjectedInvoker once per argument class.
1048             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
1049             return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass);
1050         }
1051 
1052         private static MethodHandle makeInjectedInvoker(Class<?> targetClass) {
1053             try {
1054                 /*
1055                  * The invoker class defined to the same class loader as the lookup class
1056                  * but in an unnamed package so that the class bytes can be cached and
1057                  * reused for any @CSM.
1058                  *
1059                  * @CSM must be public and exported if called by any module.
1060                  */
1061                 String name = targetClass.getName() + "$$InjectedInvoker";
1062                 if (targetClass.isHidden()) {
1063                     // use the original class name
1064                     name = name.replace('/', '_');
1065                 }
1066                 Class<?> invokerClass = new Lookup(targetClass)
1067                         .makeHiddenClassDefiner(name, INJECTED_INVOKER_TEMPLATE)
1068                         .defineClass(true);
1069                 assert checkInjectedInvoker(targetClass, invokerClass);
1070                 return IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT);
1071             } catch (ReflectiveOperationException ex) {
1072                 throw uncaughtException(ex);
1073             }
1074         }
1075 
1076         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
1077             @Override protected MethodHandle computeValue(Class<?> hostClass) {
1078                 return makeInjectedInvoker(hostClass);
1079             }
1080         };
1081 
1082         // Adapt mh so that it can be called directly from an injected invoker:
1083         private static MethodHandle prepareForInvoker(MethodHandle mh) {
1084             mh = mh.asFixedArity();
1085             MethodType mt = mh.type();
1086             int arity = mt.parameterCount();
1087             MethodHandle vamh = mh.asType(mt.generic());
1088             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
1089             vamh = vamh.asSpreader(Object[].class, arity);
1090             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
1091             return vamh;
1092         }
1093 
1094         // Undo the adapter effect of prepareForInvoker:
1095         private static MethodHandle restoreToType(MethodHandle vamh,
1096                                                   MethodHandle original,
1097                                                   Class<?> hostClass) {
1098             MethodType type = original.type();
1099             MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount());
1100             MemberName member = original.internalMemberName();
1101             mh = mh.asType(type);
1102             mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass);
1103             return mh;
1104         }
1105 
1106         private static boolean checkInjectedInvoker(Class<?> hostClass, Class<?> invokerClass) {
1107             assert (hostClass.getClassLoader() == invokerClass.getClassLoader()) : hostClass.getName()+" (CL)";
1108             try {
1109                 assert (hostClass.getProtectionDomain() == invokerClass.getProtectionDomain()) : hostClass.getName()+" (PD)";
1110             } catch (SecurityException ex) {
1111                 // Self-check was blocked by security manager. This is OK.
1112             }
1113             try {
1114                 // Test the invoker to ensure that it really injects into the right place.
1115                 MethodHandle invoker = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT);
1116                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
1117                 return (boolean)invoker.invoke(vamh, new Object[]{ invokerClass });
1118             } catch (Throwable ex) {
1119                 throw new InternalError(ex);
1120             }
1121         }
1122 
1123         private static final MethodHandle MH_checkCallerClass;
1124         static {
1125             final Class<?> THIS_CLASS = BindCaller.class;
1126             assert(checkCallerClass(THIS_CLASS));
1127             try {
1128                 MH_checkCallerClass = IMPL_LOOKUP
1129                     .findStatic(THIS_CLASS, "checkCallerClass",
1130                                 MethodType.methodType(boolean.class, Class.class));
1131                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS));
1132             } catch (Throwable ex) {
1133                 throw new InternalError(ex);
1134             }
1135         }
1136 
1137         @CallerSensitive
1138         @ForceInline // to ensure Reflection.getCallerClass optimization
1139         private static boolean checkCallerClass(Class<?> expected) {
1140             // This method is called via MH_checkCallerClass and so it's correct to ask for the immediate caller here.
1141             Class<?> actual = Reflection.getCallerClass();
1142             if (actual != expected)
1143                 throw new InternalError("found " + actual.getName() + ", expected " + expected.getName());
1144             return true;
1145         }
1146 
1147         private static final byte[] INJECTED_INVOKER_TEMPLATE = generateInvokerTemplate();
1148 
1149         /** Produces byte code for a class that is used as an injected invoker. */
1150         private static byte[] generateInvokerTemplate() {
1151             ClassWriter cw = new ClassWriter(0);
1152 
1153             // private static class InjectedInvoker {
1154             //     @Hidden
1155             //     static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
1156             //        return vamh.invokeExact(args);
1157             //     }
1158             // }
1159             cw.visit(CLASSFILE_VERSION, ACC_PRIVATE | ACC_SUPER, "InjectedInvoker", null, "java/lang/Object", null);
1160 
1161             MethodVisitor mv = cw.visitMethod(ACC_STATIC, "invoke_V",
1162                           "(Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;",
1163                           null, null);
1164 
1165             mv.visitCode();
1166             mv.visitVarInsn(ALOAD, 0);
1167             mv.visitVarInsn(ALOAD, 1);
1168             mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeExact",
1169                                "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1170             mv.visitInsn(ARETURN);
1171             mv.visitMaxs(2, 2);
1172             mv.visitEnd();
1173 
1174             cw.visitEnd();
1175             return cw.toByteArray();
1176         }
1177     }
1178 
1179     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
1180     private static final class WrappedMember extends DelegatingMethodHandle {
1181         private final MethodHandle target;
1182         private final MemberName member;
1183         private final Class<?> callerClass;
1184         private final boolean isInvokeSpecial;
1185 
1186         private WrappedMember(MethodHandle target, MethodType type,
1187                               MemberName member, boolean isInvokeSpecial,
1188                               Class<?> callerClass) {
1189             super(type, target);
1190             this.target = target;
1191             this.member = member;
1192             this.callerClass = callerClass;
1193             this.isInvokeSpecial = isInvokeSpecial;
1194         }
1195 
1196         @Override
1197         MemberName internalMemberName() {
1198             return member;
1199         }
1200         @Override
1201         Class<?> internalCallerClass() {
1202             return callerClass;
1203         }
1204         @Override
1205         boolean isInvokeSpecial() {
1206             return isInvokeSpecial;
1207         }
1208         @Override
1209         protected MethodHandle getTarget() {
1210             return target;
1211         }
1212         @Override
1213         public MethodHandle asTypeUncached(MethodType newType) {
1214             // This MH is an alias for target, except for the MemberName
1215             // Drop the MemberName if there is any conversion.
1216             return target.asType(newType);
1217         }
1218     }
1219 
1220     static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) {
1221         if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial())
1222             return target;
1223         return new WrappedMember(target, target.type(), member, isInvokeSpecial, null);
1224     }
1225 
1226     /** Intrinsic IDs */
1227     /*non-public*/
1228     enum Intrinsic {
1229         SELECT_ALTERNATIVE,
1230         GUARD_WITH_CATCH,
1231         TRY_FINALLY,
1232         TABLE_SWITCH,
1233         LOOP,
1234         ARRAY_LOAD,
1235         ARRAY_STORE,
1236         ARRAY_LENGTH,
1237         IDENTITY,
1238         ZERO,
1239         NONE // no intrinsic associated
1240     }
1241 
1242     /** Mark arbitrary method handle as intrinsic.
1243      * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */
1244     static final class IntrinsicMethodHandle extends DelegatingMethodHandle {
1245         private final MethodHandle target;
1246         private final Intrinsic intrinsicName;
1247         private final Object intrinsicData;
1248 
1249         IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) {
1250            this(target, intrinsicName, null);
1251         }
1252 
1253         IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName, Object intrinsicData) {
1254             super(target.type(), target);
1255             this.target = target;
1256             this.intrinsicName = intrinsicName;
1257             this.intrinsicData = intrinsicData;
1258         }
1259 
1260         @Override
1261         protected MethodHandle getTarget() {
1262             return target;
1263         }
1264 
1265         @Override
1266         Intrinsic intrinsicName() {
1267             return intrinsicName;
1268         }
1269 
1270         @Override
1271         Object intrinsicData() {
1272             return intrinsicData;
1273         }
1274 
1275         @Override
1276         public MethodHandle asTypeUncached(MethodType newType) {
1277             // This MH is an alias for target, except for the intrinsic name
1278             // Drop the name if there is any conversion.
1279             return target.asType(newType);
1280         }
1281 
1282         @Override
1283         String internalProperties() {
1284             return super.internalProperties() +
1285                     "\n& Intrinsic="+intrinsicName;
1286         }
1287 
1288         @Override
1289         public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
1290             if (intrinsicName == Intrinsic.IDENTITY) {
1291                 MethodType resultType = type().asCollectorType(arrayType, type().parameterCount() - 1, arrayLength);
1292                 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength);
1293                 return newArray.asType(resultType);
1294             }
1295             return super.asCollector(arrayType, arrayLength);
1296         }
1297     }
1298 
1299     static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) {
1300         return makeIntrinsic(target, intrinsicName, null);
1301     }
1302 
1303     static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName, Object intrinsicData) {
1304         if (intrinsicName == target.intrinsicName())
1305             return target;
1306         return new IntrinsicMethodHandle(target, intrinsicName, intrinsicData);
1307     }
1308 
1309     static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) {
1310         return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName);
1311     }
1312 
1313     private static final @Stable MethodHandle[] ARRAYS = new MethodHandle[MAX_ARITY + 1];
1314 
1315     /** Return a method handle that takes the indicated number of Object
1316      *  arguments and returns an Object array of them, as if for varargs.
1317      */
1318     static MethodHandle varargsArray(int nargs) {
1319         MethodHandle mh = ARRAYS[nargs];
1320         if (mh != null) {
1321             return mh;
1322         }
1323         mh = makeCollector(Object[].class, nargs);
1324         assert(assertCorrectArity(mh, nargs));
1325         return ARRAYS[nargs] = mh;
1326     }
1327 
1328     /** Return a method handle that takes the indicated number of
1329      *  typed arguments and returns an array of them.
1330      *  The type argument is the array type.
1331      */
1332     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1333         Class<?> elemType = arrayType.getComponentType();
1334         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1335         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1336             int slots = nargs;
1337             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1338             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1339                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1340             if (slots > MAX_ARRAY_SLOTS)
1341                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1342         }
1343         if (elemType == Object.class)
1344             return varargsArray(nargs);
1345         // other cases:  primitive arrays, subtypes of Object[]
1346         MethodHandle cache[] = Makers.TYPED_COLLECTORS.get(elemType);
1347         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1348         if (mh != null)  return mh;
1349         mh = makeCollector(arrayType, nargs);
1350         assert(assertCorrectArity(mh, nargs));
1351         if (nargs < cache.length)
1352             cache[nargs] = mh;
1353         return mh;
1354     }
1355 
1356     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1357         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1358         return true;
1359     }
1360 
1361     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1362 
1363     /*non-public*/
1364     static void assertSame(Object mh1, Object mh2) {
1365         if (mh1 != mh2) {
1366             String msg = String.format("mh1 != mh2: mh1 = %s (form: %s); mh2 = %s (form: %s)",
1367                     mh1, ((MethodHandle)mh1).form,
1368                     mh2, ((MethodHandle)mh2).form);
1369             throw newInternalError(msg);
1370         }
1371     }
1372 
1373     // Local constant functions:
1374 
1375     /* non-public */
1376     static final byte NF_checkSpreadArgument = 0,
1377             NF_guardWithCatch = 1,
1378             NF_throwException = 2,
1379             NF_tryFinally = 3,
1380             NF_loop = 4,
1381             NF_profileBoolean = 5,
1382             NF_tableSwitch = 6,
1383             NF_LIMIT = 7;
1384 
1385     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
1386 
1387     static NamedFunction getFunction(byte func) {
1388         NamedFunction nf = NFS[func];
1389         if (nf != null) {
1390             return nf;
1391         }
1392         return NFS[func] = createFunction(func);
1393     }
1394 
1395     private static NamedFunction createFunction(byte func) {
1396         try {
1397             return switch (func) {
1398                 case NF_checkSpreadArgument -> new NamedFunction(MethodHandleImpl.class
1399                                                 .getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
1400                 case NF_guardWithCatch      -> new NamedFunction(MethodHandleImpl.class
1401                                                 .getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
1402                                                    MethodHandle.class, Object[].class));
1403                 case NF_tryFinally          -> new NamedFunction(MethodHandleImpl.class
1404                                                 .getDeclaredMethod("tryFinally", MethodHandle.class, MethodHandle.class, Object[].class));
1405                 case NF_loop                -> new NamedFunction(MethodHandleImpl.class
1406                                                 .getDeclaredMethod("loop", BasicType[].class, LoopClauses.class, Object[].class));
1407                 case NF_throwException      -> new NamedFunction(MethodHandleImpl.class
1408                                                 .getDeclaredMethod("throwException", Throwable.class));
1409                 case NF_profileBoolean      -> new NamedFunction(MethodHandleImpl.class
1410                                                 .getDeclaredMethod("profileBoolean", boolean.class, int[].class));
1411                 case NF_tableSwitch         -> new NamedFunction(MethodHandleImpl.class
1412                                                 .getDeclaredMethod("tableSwitch", int.class, MethodHandle.class, CasesHolder.class, Object[].class));
1413                 default -> throw new InternalError("Undefined function: " + func);
1414             };
1415         } catch (ReflectiveOperationException ex) {
1416             throw newInternalError(ex);
1417         }
1418     }
1419 
1420     static {
1421         SharedSecrets.setJavaLangInvokeAccess(new JavaLangInvokeAccess() {
1422             @Override
1423             public Object newMemberName() {
1424                 return new MemberName();
1425             }
1426 
1427             @Override
1428             public String getName(Object mname) {
1429                 MemberName memberName = (MemberName)mname;
1430                 return memberName.getName();
1431             }
1432             @Override
1433             public Class<?> getDeclaringClass(Object mname) {
1434                 MemberName memberName = (MemberName)mname;
1435                 return memberName.getDeclaringClass();
1436             }
1437 
1438             @Override
1439             public MethodType getMethodType(Object mname) {
1440                 MemberName memberName = (MemberName)mname;
1441                 return memberName.getMethodType();
1442             }
1443 
1444             @Override
1445             public String getMethodDescriptor(Object mname) {
1446                 MemberName memberName = (MemberName)mname;
1447                 return memberName.getMethodDescriptor();
1448             }
1449 
1450             @Override
1451             public boolean isNative(Object mname) {
1452                 MemberName memberName = (MemberName)mname;
1453                 return memberName.isNative();
1454             }
1455 
1456             @Override
1457             public Map<String, byte[]> generateHolderClasses(Stream<String> traces) {
1458                 return GenerateJLIClassesHelper.generateHolderClasses(traces);
1459             }
1460 
1461             @Override
1462             public VarHandle memoryAccessVarHandle(Class<?> carrier, boolean skipAlignmentMaskCheck, long alignmentMask,
1463                                                    ByteOrder order) {
1464                 return VarHandles.makeMemoryAddressViewHandle(carrier, skipAlignmentMaskCheck, alignmentMask, order);
1465             }
1466 
1467             @Override
1468             public MethodHandle nativeMethodHandle(NativeEntryPoint nep) {
1469                 return NativeMethodHandle.make(nep);
1470             }
1471 
1472             @Override
1473             public VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) {
1474                 return VarHandles.filterValue(target, filterToTarget, filterFromTarget);
1475             }
1476 
1477             @Override
1478             public VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
1479                 return VarHandles.filterCoordinates(target, pos, filters);
1480             }
1481 
1482             @Override
1483             public VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
1484                 return VarHandles.dropCoordinates(target, pos, valueTypes);
1485             }
1486 
1487             @Override
1488             public VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
1489                 return VarHandles.permuteCoordinates(target, newCoordinates, reorder);
1490             }
1491 
1492             @Override
1493             public VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) {
1494                 return VarHandles.collectCoordinates(target, pos, filter);
1495             }
1496 
1497             @Override
1498             public VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
1499                 return VarHandles.insertCoordinates(target, pos, values);
1500             }
1501 
1502             @Override
1503             public Class<?>[] exceptionTypes(MethodHandle handle) {
1504                 return VarHandles.exceptionTypes(handle);
1505             }
1506         });
1507     }
1508 
1509     /** Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore(). */
1510     private static MethodHandle unboxResultHandle(Class<?> returnType) {
1511         if (returnType.isPrimitive()) {
1512             if (returnType == void.class) {
1513                 return ValueConversions.ignore();
1514             } else {
1515                 Wrapper w = Wrapper.forPrimitiveType(returnType);
1516                 return ValueConversions.unboxExact(w);
1517             }
1518         } else {
1519             return MethodHandles.identity(Object.class);
1520         }
1521     }
1522 
1523     /**
1524      * Assembles a loop method handle from the given handles and type information.
1525      *
1526      * @param tloop the return type of the loop.
1527      * @param targs types of the arguments to be passed to the loop.
1528      * @param init sanitized array of initializers for loop-local variables.
1529      * @param step sanitited array of loop bodies.
1530      * @param pred sanitized array of predicates.
1531      * @param fini sanitized array of loop finalizers.
1532      *
1533      * @return a handle that, when invoked, will execute the loop.
1534      */
1535     static MethodHandle makeLoop(Class<?> tloop, List<Class<?>> targs, List<MethodHandle> init, List<MethodHandle> step,
1536                                  List<MethodHandle> pred, List<MethodHandle> fini) {
1537         MethodType type = MethodType.methodType(tloop, targs);
1538         BasicType[] initClauseTypes =
1539                 init.stream().map(h -> h.type().returnType()).map(BasicType::basicType).toArray(BasicType[]::new);
1540         LambdaForm form = makeLoopForm(type.basicType(), initClauseTypes);
1541 
1542         // Prepare auxiliary method handles used during LambdaForm interpretation.
1543         // Box arguments and wrap them into Object[]: ValueConversions.array().
1544         MethodType varargsType = type.changeReturnType(Object[].class);
1545         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
1546         MethodHandle unboxResult = unboxResultHandle(tloop);
1547 
1548         LoopClauses clauseData =
1549                 new LoopClauses(new MethodHandle[][]{toArray(init), toArray(step), toArray(pred), toArray(fini)});
1550         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL();
1551         BoundMethodHandle mh;
1552         try {
1553             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) clauseData,
1554                     (Object) collectArgs, (Object) unboxResult);
1555         } catch (Throwable ex) {
1556             throw uncaughtException(ex);
1557         }
1558         assert(mh.type() == type);
1559         return mh;
1560     }
1561 
1562     private static MethodHandle[] toArray(List<MethodHandle> l) {
1563         return l.toArray(new MethodHandle[0]);
1564     }
1565 
1566     /**
1567      * Loops introduce some complexity as they can have additional local state. Hence, LambdaForms for loops are
1568      * generated from a template. The LambdaForm template shape for the loop combinator is as follows (assuming one
1569      * reference parameter passed in {@code a1}, and a reference return type, with the return value represented by
1570      * {@code t12}):
1571      * <blockquote><pre>{@code
1572      *  loop=Lambda(a0:L,a1:L)=>{
1573      *    t2:L=BoundMethodHandle$Species_L3.argL0(a0:L);    // LoopClauses holding init, step, pred, fini handles
1574      *    t3:L=BoundMethodHandle$Species_L3.argL1(a0:L);    // helper handle to box the arguments into an Object[]
1575      *    t4:L=BoundMethodHandle$Species_L3.argL2(a0:L);    // helper handle to unbox the result
1576      *    t5:L=MethodHandle.invokeBasic(t3:L,a1:L);         // box the arguments into an Object[]
1577      *    t6:L=MethodHandleImpl.loop(null,t2:L,t3:L);       // call the loop executor
1578      *    t7:L=MethodHandle.invokeBasic(t4:L,t6:L);t7:L}    // unbox the result; return the result
1579      * }</pre></blockquote>
1580      * <p>
1581      * {@code argL0} is a LoopClauses instance holding, in a 2-dimensional array, the init, step, pred, and fini method
1582      * handles. {@code argL1} and {@code argL2} are auxiliary method handles: {@code argL1} boxes arguments and wraps
1583      * them into {@code Object[]} ({@code ValueConversions.array()}), and {@code argL2} unboxes the result if necessary
1584      * ({@code ValueConversions.unbox()}).
1585      * <p>
1586      * Having {@code t3} and {@code t4} passed in via a BMH and not hardcoded in the lambda form allows to share lambda
1587      * forms among loop combinators with the same basic type.
1588      * <p>
1589      * The above template is instantiated by using the {@link LambdaFormEditor} to replace the {@code null} argument to
1590      * the {@code loop} invocation with the {@code BasicType} array describing the loop clause types. This argument is
1591      * ignored in the loop invoker, but will be extracted and used in {@linkplain InvokerBytecodeGenerator#emitLoop(int)
1592      * bytecode generation}.
1593      */
1594     private static LambdaForm makeLoopForm(MethodType basicType, BasicType[] localVarTypes) {
1595         MethodType lambdaType = basicType.invokerType();
1596 
1597         final int THIS_MH = 0;  // the BMH_LLL
1598         final int ARG_BASE = 1; // start of incoming arguments
1599         final int ARG_LIMIT = ARG_BASE + basicType.parameterCount();
1600 
1601         int nameCursor = ARG_LIMIT;
1602         final int GET_CLAUSE_DATA = nameCursor++;
1603         final int GET_COLLECT_ARGS = nameCursor++;
1604         final int GET_UNBOX_RESULT = nameCursor++;
1605         final int BOXED_ARGS = nameCursor++;
1606         final int LOOP = nameCursor++;
1607         final int UNBOX_RESULT = nameCursor++;
1608 
1609         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_LOOP);
1610         if (lform == null) {
1611             Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
1612 
1613             BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL();
1614             names[THIS_MH] = names[THIS_MH].withConstraint(data);
1615             names[GET_CLAUSE_DATA] = new Name(data.getterFunction(0), names[THIS_MH]);
1616             names[GET_COLLECT_ARGS] = new Name(data.getterFunction(1), names[THIS_MH]);
1617             names[GET_UNBOX_RESULT] = new Name(data.getterFunction(2), names[THIS_MH]);
1618 
1619             // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
1620             MethodType collectArgsType = basicType.changeReturnType(Object.class);
1621             MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
1622             Object[] args = new Object[invokeBasic.type().parameterCount()];
1623             args[0] = names[GET_COLLECT_ARGS];
1624             System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT - ARG_BASE);
1625             names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.LOOP)), args);
1626 
1627             // t_{i+1}:L=MethodHandleImpl.loop(localTypes:L,clauses:L,t_{i}:L);
1628             Object[] lArgs =
1629                     new Object[]{null, // placeholder for BasicType[] localTypes - will be added by LambdaFormEditor
1630                             names[GET_CLAUSE_DATA], names[BOXED_ARGS]};
1631             names[LOOP] = new Name(getFunction(NF_loop), lArgs);
1632 
1633             // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
1634             MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
1635             Object[] unboxArgs = new Object[]{names[GET_UNBOX_RESULT], names[LOOP]};
1636             names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
1637 
1638             lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_LOOP,
1639                     new LambdaForm(lambdaType.parameterCount(), names, Kind.LOOP));
1640         }
1641 
1642         // BOXED_ARGS is the index into the names array where the loop idiom starts
1643         return lform.editor().noteLoopLocalTypesForm(BOXED_ARGS, localVarTypes);
1644     }
1645 
1646     static class LoopClauses {
1647         @Stable final MethodHandle[][] clauses;
1648         LoopClauses(MethodHandle[][] clauses) {
1649             assert clauses.length == 4;
1650             this.clauses = clauses;
1651         }
1652         @Override
1653         public String toString() {
1654             StringBuilder sb = new StringBuilder("LoopClauses -- ");
1655             for (int i = 0; i < 4; ++i) {
1656                 if (i > 0) {
1657                     sb.append("       ");
1658                 }
1659                 sb.append('<').append(i).append(">: ");
1660                 MethodHandle[] hs = clauses[i];
1661                 for (int j = 0; j < hs.length; ++j) {
1662                     if (j > 0) {
1663                         sb.append("          ");
1664                     }
1665                     sb.append('*').append(j).append(": ").append(hs[j]).append('\n');
1666                 }
1667             }
1668             sb.append(" --\n");
1669             return sb.toString();
1670         }
1671     }
1672 
1673     /**
1674      * Intrinsified during LambdaForm compilation
1675      * (see {@link InvokerBytecodeGenerator#emitLoop(int)}).
1676      */
1677     @Hidden
1678     static Object loop(BasicType[] localTypes, LoopClauses clauseData, Object... av) throws Throwable {
1679         final MethodHandle[] init = clauseData.clauses[0];
1680         final MethodHandle[] step = clauseData.clauses[1];
1681         final MethodHandle[] pred = clauseData.clauses[2];
1682         final MethodHandle[] fini = clauseData.clauses[3];
1683         int varSize = (int) Stream.of(init).filter(h -> h.type().returnType() != void.class).count();
1684         int nArgs = init[0].type().parameterCount();
1685         Object[] varsAndArgs = new Object[varSize + nArgs];
1686         for (int i = 0, v = 0; i < init.length; ++i) {
1687             MethodHandle ih = init[i];
1688             if (ih.type().returnType() == void.class) {
1689                 ih.invokeWithArguments(av);
1690             } else {
1691                 varsAndArgs[v++] = ih.invokeWithArguments(av);
1692             }
1693         }
1694         System.arraycopy(av, 0, varsAndArgs, varSize, nArgs);
1695         final int nSteps = step.length;
1696         for (; ; ) {
1697             for (int i = 0, v = 0; i < nSteps; ++i) {
1698                 MethodHandle p = pred[i];
1699                 MethodHandle s = step[i];
1700                 MethodHandle f = fini[i];
1701                 if (s.type().returnType() == void.class) {
1702                     s.invokeWithArguments(varsAndArgs);
1703                 } else {
1704                     varsAndArgs[v++] = s.invokeWithArguments(varsAndArgs);
1705                 }
1706                 if (!(boolean) p.invokeWithArguments(varsAndArgs)) {
1707                     return f.invokeWithArguments(varsAndArgs);
1708                 }
1709             }
1710         }
1711     }
1712 
1713     /**
1714      * This method is bound as the predicate in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle,
1715      * MethodHandle) counting loops}.
1716      *
1717      * @param limit the upper bound of the parameter, statically bound at loop creation time.
1718      * @param counter the counter parameter, passed in during loop execution.
1719      *
1720      * @return whether the counter has reached the limit.
1721      */
1722     static boolean countedLoopPredicate(int limit, int counter) {
1723         return counter < limit;
1724     }
1725 
1726     /**
1727      * This method is bound as the step function in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle,
1728      * MethodHandle) counting loops} to increment the counter.
1729      *
1730      * @param limit the upper bound of the loop counter (ignored).
1731      * @param counter the loop counter.
1732      *
1733      * @return the loop counter incremented by 1.
1734      */
1735     static int countedLoopStep(int limit, int counter) {
1736         return counter + 1;
1737     }
1738 
1739     /**
1740      * This is bound to initialize the loop-local iterator in {@linkplain MethodHandles#iteratedLoop iterating loops}.
1741      *
1742      * @param it the {@link Iterable} over which the loop iterates.
1743      *
1744      * @return an {@link Iterator} over the argument's elements.
1745      */
1746     static Iterator<?> initIterator(Iterable<?> it) {
1747         return it.iterator();
1748     }
1749 
1750     /**
1751      * This method is bound as the predicate in {@linkplain MethodHandles#iteratedLoop iterating loops}.
1752      *
1753      * @param it the iterator to be checked.
1754      *
1755      * @return {@code true} iff there are more elements to iterate over.
1756      */
1757     static boolean iteratePredicate(Iterator<?> it) {
1758         return it.hasNext();
1759     }
1760 
1761     /**
1762      * This method is bound as the step for retrieving the current value from the iterator in {@linkplain
1763      * MethodHandles#iteratedLoop iterating loops}.
1764      *
1765      * @param it the iterator.
1766      *
1767      * @return the next element from the iterator.
1768      */
1769     static Object iterateNext(Iterator<?> it) {
1770         return it.next();
1771     }
1772 
1773     /**
1774      * Makes a {@code try-finally} handle that conforms to the type constraints.
1775      *
1776      * @param target the target to execute in a {@code try-finally} block.
1777      * @param cleanup the cleanup to execute in the {@code finally} block.
1778      * @param rtype the result type of the entire construct.
1779      * @param argTypes the types of the arguments.
1780      *
1781      * @return a handle on the constructed {@code try-finally} block.
1782      */
1783     static MethodHandle makeTryFinally(MethodHandle target, MethodHandle cleanup, Class<?> rtype, List<Class<?>> argTypes) {
1784         MethodType type = MethodType.methodType(rtype, argTypes);
1785         LambdaForm form = makeTryFinallyForm(type.basicType());
1786 
1787         // Prepare auxiliary method handles used during LambdaForm interpretation.
1788         // Box arguments and wrap them into Object[]: ValueConversions.array().
1789         MethodType varargsType = type.changeReturnType(Object[].class);
1790         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
1791         MethodHandle unboxResult = unboxResultHandle(rtype);
1792 
1793         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL();
1794         BoundMethodHandle mh;
1795         try {
1796             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) target, (Object) cleanup,
1797                     (Object) collectArgs, (Object) unboxResult);
1798         } catch (Throwable ex) {
1799             throw uncaughtException(ex);
1800         }
1801         assert(mh.type() == type);
1802         return mh;
1803     }
1804 
1805     /**
1806      * The LambdaForm shape for the tryFinally combinator is as follows (assuming one reference parameter passed in
1807      * {@code a1}, and a reference return type, with the return value represented by {@code t8}):
1808      * <blockquote><pre>{@code
1809      *  tryFinally=Lambda(a0:L,a1:L)=>{
1810      *    t2:L=BoundMethodHandle$Species_LLLL.argL0(a0:L);  // target method handle
1811      *    t3:L=BoundMethodHandle$Species_LLLL.argL1(a0:L);  // cleanup method handle
1812      *    t4:L=BoundMethodHandle$Species_LLLL.argL2(a0:L);  // helper handle to box the arguments into an Object[]
1813      *    t5:L=BoundMethodHandle$Species_LLLL.argL3(a0:L);  // helper handle to unbox the result
1814      *    t6:L=MethodHandle.invokeBasic(t4:L,a1:L);         // box the arguments into an Object[]
1815      *    t7:L=MethodHandleImpl.tryFinally(t2:L,t3:L,t6:L); // call the tryFinally executor
1816      *    t8:L=MethodHandle.invokeBasic(t5:L,t7:L);t8:L}    // unbox the result; return the result
1817      * }</pre></blockquote>
1818      * <p>
1819      * {@code argL0} and {@code argL1} are the target and cleanup method handles.
1820      * {@code argL2} and {@code argL3} are auxiliary method handles: {@code argL2} boxes arguments and wraps them into
1821      * {@code Object[]} ({@code ValueConversions.array()}), and {@code argL3} unboxes the result if necessary
1822      * ({@code ValueConversions.unbox()}).
1823      * <p>
1824      * Having {@code t4} and {@code t5} passed in via a BMH and not hardcoded in the lambda form allows to share lambda
1825      * forms among tryFinally combinators with the same basic type.
1826      */
1827     private static LambdaForm makeTryFinallyForm(MethodType basicType) {
1828         MethodType lambdaType = basicType.invokerType();
1829 
1830         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_TF);
1831         if (lform != null) {
1832             return lform;
1833         }
1834         final int THIS_MH      = 0;  // the BMH_LLLL
1835         final int ARG_BASE     = 1;  // start of incoming arguments
1836         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
1837 
1838         int nameCursor = ARG_LIMIT;
1839         final int GET_TARGET       = nameCursor++;
1840         final int GET_CLEANUP      = nameCursor++;
1841         final int GET_COLLECT_ARGS = nameCursor++;
1842         final int GET_UNBOX_RESULT = nameCursor++;
1843         final int BOXED_ARGS       = nameCursor++;
1844         final int TRY_FINALLY      = nameCursor++;
1845         final int UNBOX_RESULT     = nameCursor++;
1846 
1847         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
1848 
1849         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL();
1850         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
1851         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
1852         names[GET_CLEANUP]      = new Name(data.getterFunction(1), names[THIS_MH]);
1853         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(2), names[THIS_MH]);
1854         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(3), names[THIS_MH]);
1855 
1856         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
1857         MethodType collectArgsType = basicType.changeReturnType(Object.class);
1858         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
1859         Object[] args = new Object[invokeBasic.type().parameterCount()];
1860         args[0] = names[GET_COLLECT_ARGS];
1861         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
1862         names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.TRY_FINALLY)), args);
1863 
1864         // t_{i+1}:L=MethodHandleImpl.tryFinally(target:L,exType:L,catcher:L,t_{i}:L);
1865         Object[] tfArgs = new Object[] {names[GET_TARGET], names[GET_CLEANUP], names[BOXED_ARGS]};
1866         names[TRY_FINALLY] = new Name(getFunction(NF_tryFinally), tfArgs);
1867 
1868         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
1869         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
1870         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_FINALLY]};
1871         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
1872 
1873         lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.TRY_FINALLY);
1874 
1875         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_TF, lform);
1876     }
1877 
1878     /**
1879      * Intrinsified during LambdaForm compilation
1880      * (see {@link InvokerBytecodeGenerator#emitTryFinally emitTryFinally}).
1881      */
1882     @Hidden
1883     static Object tryFinally(MethodHandle target, MethodHandle cleanup, Object... av) throws Throwable {
1884         Throwable t = null;
1885         Object r = null;
1886         try {
1887             r = target.invokeWithArguments(av);
1888         } catch (Throwable thrown) {
1889             t = thrown;
1890             throw t;
1891         } finally {
1892             Object[] args = target.type().returnType() == void.class ? prepend(av, t) : prepend(av, t, r);
1893             r = cleanup.invokeWithArguments(args);
1894         }
1895         return r;
1896     }
1897 
1898     // see varargsArray method for chaching/package-private version of this
1899     private static MethodHandle makeCollector(Class<?> arrayType, int parameterCount) {
1900         MethodType type = MethodType.methodType(arrayType, Collections.nCopies(parameterCount, arrayType.componentType()));
1901         MethodHandle newArray = MethodHandles.arrayConstructor(arrayType);
1902 
1903         LambdaForm form = makeCollectorForm(type.basicType(), arrayType);
1904 
1905         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_L();
1906         BoundMethodHandle mh;
1907         try {
1908             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) newArray);
1909         } catch (Throwable ex) {
1910             throw uncaughtException(ex);
1911         }
1912         assert(mh.type() == type);
1913         return mh;
1914     }
1915 
1916     private static LambdaForm makeCollectorForm(MethodType basicType, Class<?> arrayType) {
1917         MethodType lambdaType = basicType.invokerType();
1918         int parameterCount = basicType.parameterCount();
1919 
1920         // Only share the lambda form for empty arrays and reference types.
1921         // Sharing based on the basic type alone doesn't work because
1922         // we need a separate lambda form for byte/short/char/int which
1923         // are all erased to int otherwise.
1924         // Other caching for primitive types happens at the MethodHandle level (see varargsArray).
1925         boolean isReferenceType = !arrayType.componentType().isPrimitive();
1926         boolean isSharedLambdaForm = parameterCount == 0 || isReferenceType;
1927         if (isSharedLambdaForm) {
1928             LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_COLLECTOR);
1929             if (lform != null) {
1930                 return lform;
1931             }
1932         }
1933 
1934         // use erased accessor for reference types
1935         MethodHandle storeFunc = isReferenceType
1936                 ? ArrayAccessor.OBJECT_ARRAY_SETTER
1937                 : makeArrayElementAccessor(arrayType, ArrayAccess.SET);
1938 
1939         final int THIS_MH      = 0;  // the BMH_L
1940         final int ARG_BASE     = 1;  // start of incoming arguments
1941         final int ARG_LIMIT    = ARG_BASE + parameterCount;
1942 
1943         int nameCursor = ARG_LIMIT;
1944         final int GET_NEW_ARRAY       = nameCursor++;
1945         final int CALL_NEW_ARRAY      = nameCursor++;
1946         final int STORE_ELEMENT_BASE  = nameCursor;
1947         final int STORE_ELEMENT_LIMIT = STORE_ELEMENT_BASE + parameterCount;
1948         nameCursor = STORE_ELEMENT_LIMIT;
1949 
1950         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
1951 
1952         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_L();
1953         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
1954         names[GET_NEW_ARRAY]    = new Name(data.getterFunction(0), names[THIS_MH]);
1955 
1956         MethodHandle invokeBasic = MethodHandles.basicInvoker(MethodType.methodType(Object.class, int.class));
1957         names[CALL_NEW_ARRAY] = new Name(new NamedFunction(invokeBasic), names[GET_NEW_ARRAY], parameterCount);
1958         for (int storeIndex = 0,
1959              storeNameCursor = STORE_ELEMENT_BASE,
1960              argCursor = ARG_BASE;
1961              storeNameCursor < STORE_ELEMENT_LIMIT;
1962              storeIndex++, storeNameCursor++, argCursor++){
1963 
1964             names[storeNameCursor] = new Name(new NamedFunction(makeIntrinsic(storeFunc, Intrinsic.ARRAY_STORE)),
1965                     names[CALL_NEW_ARRAY], storeIndex, names[argCursor]);
1966         }
1967 
1968         LambdaForm lform = new LambdaForm(lambdaType.parameterCount(), names, CALL_NEW_ARRAY, Kind.COLLECTOR);
1969         if (isSharedLambdaForm) {
1970             lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_COLLECTOR, lform);
1971         }
1972         return lform;
1973     }
1974 
1975     // use a wrapper because we need this array to be @Stable
1976     static class CasesHolder {
1977         @Stable
1978         final MethodHandle[] cases;
1979 
1980         public CasesHolder(MethodHandle[] cases) {
1981             this.cases = cases;
1982         }
1983     }
1984 
1985     static MethodHandle makeTableSwitch(MethodType type, MethodHandle defaultCase, MethodHandle[] caseActions) {
1986         MethodType varargsType = type.changeReturnType(Object[].class);
1987         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
1988 
1989         MethodHandle unboxResult = unboxResultHandle(type.returnType());
1990 
1991         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL();
1992         LambdaForm form = makeTableSwitchForm(type.basicType(), data, caseActions.length);
1993         BoundMethodHandle mh;
1994         CasesHolder caseHolder =  new CasesHolder(caseActions);
1995         try {
1996             mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) defaultCase, (Object) collectArgs,
1997                                                                 (Object) unboxResult, (Object) caseHolder);
1998         } catch (Throwable ex) {
1999             throw uncaughtException(ex);
2000         }
2001         assert(mh.type() == type);
2002         return mh;
2003     }
2004 
2005     private static class TableSwitchCacheKey {
2006         private static final Map<TableSwitchCacheKey, LambdaForm> CACHE = new ConcurrentHashMap<>();
2007 
2008         private final MethodType basicType;
2009         private final int numberOfCases;
2010 
2011         public TableSwitchCacheKey(MethodType basicType, int numberOfCases) {
2012             this.basicType = basicType;
2013             this.numberOfCases = numberOfCases;
2014         }
2015 
2016         @Override
2017         public boolean equals(Object o) {
2018             if (this == o) return true;
2019             if (o == null || getClass() != o.getClass()) return false;
2020             TableSwitchCacheKey that = (TableSwitchCacheKey) o;
2021             return numberOfCases == that.numberOfCases && Objects.equals(basicType, that.basicType);
2022         }
2023         @Override
2024         public int hashCode() {
2025             return Objects.hash(basicType, numberOfCases);
2026         }
2027     }
2028 
2029     private static LambdaForm makeTableSwitchForm(MethodType basicType, BoundMethodHandle.SpeciesData data,
2030                                                   int numCases) {
2031         MethodType lambdaType = basicType.invokerType();
2032 
2033         // We need to cache based on the basic type X number of cases,
2034         // since the number of cases is used when generating bytecode.
2035         // This also means that we can't use the cache in MethodTypeForm,
2036         // which only uses the basic type as a key.
2037         TableSwitchCacheKey key = new TableSwitchCacheKey(basicType, numCases);
2038         LambdaForm lform = TableSwitchCacheKey.CACHE.get(key);
2039         if (lform != null) {
2040             return lform;
2041         }
2042 
2043         final int THIS_MH       = 0;
2044         final int ARG_BASE      = 1;  // start of incoming arguments
2045         final int ARG_LIMIT     = ARG_BASE + basicType.parameterCount();
2046         final int ARG_SWITCH_ON = ARG_BASE;
2047         assert ARG_SWITCH_ON < ARG_LIMIT;
2048 
2049         int nameCursor = ARG_LIMIT;
2050         final int GET_COLLECT_ARGS  = nameCursor++;
2051         final int GET_DEFAULT_CASE  = nameCursor++;
2052         final int GET_UNBOX_RESULT  = nameCursor++;
2053         final int GET_CASES         = nameCursor++;
2054         final int BOXED_ARGS        = nameCursor++;
2055         final int TABLE_SWITCH      = nameCursor++;
2056         final int UNBOXED_RESULT    = nameCursor++;
2057 
2058         int fieldCursor = 0;
2059         final int FIELD_DEFAULT_CASE  = fieldCursor++;
2060         final int FIELD_COLLECT_ARGS  = fieldCursor++;
2061         final int FIELD_UNBOX_RESULT  = fieldCursor++;
2062         final int FIELD_CASES         = fieldCursor++;
2063 
2064         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
2065 
2066         names[THIS_MH] = names[THIS_MH].withConstraint(data);
2067         names[GET_DEFAULT_CASE] = new Name(data.getterFunction(FIELD_DEFAULT_CASE), names[THIS_MH]);
2068         names[GET_COLLECT_ARGS]  = new Name(data.getterFunction(FIELD_COLLECT_ARGS), names[THIS_MH]);
2069         names[GET_UNBOX_RESULT]  = new Name(data.getterFunction(FIELD_UNBOX_RESULT), names[THIS_MH]);
2070         names[GET_CASES] = new Name(data.getterFunction(FIELD_CASES), names[THIS_MH]);
2071 
2072         {
2073             MethodType collectArgsType = basicType.changeReturnType(Object.class);
2074             MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
2075             Object[] args = new Object[invokeBasic.type().parameterCount()];
2076             args[0] = names[GET_COLLECT_ARGS];
2077             System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT - ARG_BASE);
2078             names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.TABLE_SWITCH, numCases)), args);
2079         }
2080 
2081         {
2082             Object[] tfArgs = new Object[]{
2083                 names[ARG_SWITCH_ON], names[GET_DEFAULT_CASE], names[GET_CASES], names[BOXED_ARGS]};
2084             names[TABLE_SWITCH] = new Name(getFunction(NF_tableSwitch), tfArgs);
2085         }
2086 
2087         {
2088             MethodHandle invokeBasic = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
2089             Object[] unboxArgs = new Object[]{names[GET_UNBOX_RESULT], names[TABLE_SWITCH]};
2090             names[UNBOXED_RESULT] = new Name(invokeBasic, unboxArgs);
2091         }
2092 
2093         lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.TABLE_SWITCH);
2094         LambdaForm prev = TableSwitchCacheKey.CACHE.putIfAbsent(key, lform);
2095         return prev != null ? prev : lform;
2096     }
2097 
2098     @Hidden
2099     static Object tableSwitch(int input, MethodHandle defaultCase, CasesHolder holder, Object[] args) throws Throwable {
2100         MethodHandle[] caseActions = holder.cases;
2101         MethodHandle selectedCase;
2102         if (input < 0 || input >= caseActions.length) {
2103             selectedCase = defaultCase;
2104         } else {
2105             selectedCase = caseActions[input];
2106         }
2107         return selectedCase.invokeWithArguments(args);
2108     }
2109 
2110     // Indexes into constant method handles:
2111     static final int
2112             MH_cast                               = 0,
2113             MH_selectAlternative                  = 1,
2114             MH_countedLoopPred                    = 2,
2115             MH_countedLoopStep                    = 3,
2116             MH_initIterator                       = 4,
2117             MH_iteratePred                        = 5,
2118             MH_iterateNext                        = 6,
2119             MH_Array_newInstance                  = 7,
2120             MH_VarHandles_handleCheckedExceptions = 8,
2121             MH_LIMIT                              = 9;
2122 
2123     static MethodHandle getConstantHandle(int idx) {
2124         MethodHandle handle = HANDLES[idx];
2125         if (handle != null) {
2126             return handle;
2127         }
2128         return setCachedHandle(idx, makeConstantHandle(idx));
2129     }
2130 
2131     private static synchronized MethodHandle setCachedHandle(int idx, final MethodHandle method) {
2132         // Simulate a CAS, to avoid racy duplication of results.
2133         MethodHandle prev = HANDLES[idx];
2134         if (prev != null) {
2135             return prev;
2136         }
2137         HANDLES[idx] = method;
2138         return method;
2139     }
2140 
2141     // Local constant method handles:
2142     private static final @Stable MethodHandle[] HANDLES = new MethodHandle[MH_LIMIT];
2143 
2144     private static MethodHandle makeConstantHandle(int idx) {
2145         try {
2146             switch (idx) {
2147                 case MH_cast:
2148                     return IMPL_LOOKUP.findVirtual(Class.class, "cast",
2149                             MethodType.methodType(Object.class, Object.class));
2150                 case MH_selectAlternative:
2151                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative",
2152                             MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class));
2153                 case MH_countedLoopPred:
2154                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopPredicate",
2155                             MethodType.methodType(boolean.class, int.class, int.class));
2156                 case MH_countedLoopStep:
2157                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopStep",
2158                             MethodType.methodType(int.class, int.class, int.class));
2159                 case MH_initIterator:
2160                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "initIterator",
2161                             MethodType.methodType(Iterator.class, Iterable.class));
2162                 case MH_iteratePred:
2163                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iteratePredicate",
2164                             MethodType.methodType(boolean.class, Iterator.class));
2165                 case MH_iterateNext:
2166                     return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iterateNext",
2167                             MethodType.methodType(Object.class, Iterator.class));
2168                 case MH_Array_newInstance:
2169                     return IMPL_LOOKUP.findStatic(Array.class, "newInstance",
2170                             MethodType.methodType(Object.class, Class.class, int.class));
2171                 case MH_VarHandles_handleCheckedExceptions:
2172                     return IMPL_LOOKUP.findStatic(VarHandles.class, "handleCheckedExceptions",
2173                             MethodType.methodType(void.class, Throwable.class));
2174             }
2175         } catch (ReflectiveOperationException ex) {
2176             throw newInternalError(ex);
2177         }
2178         throw newInternalError("Unknown function index: " + idx);
2179     }
2180 }