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