1 /*
   2  * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import java.security.AccessController;
  29 import java.security.PrivilegedAction;
  30 import java.util.ArrayList;
  31 import java.util.Arrays;
  32 import java.util.Collections;
  33 import java.util.List;
  34 
  35 import sun.invoke.empty.Empty;
  36 import sun.invoke.util.ValueConversions;
  37 import sun.invoke.util.VerifyType;
  38 import sun.invoke.util.Wrapper;
  39 import sun.reflect.CallerSensitive;
  40 import sun.reflect.Reflection;
  41 import static java.lang.invoke.LambdaForm.*;
  42 import static java.lang.invoke.MethodHandleStatics.*;
  43 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  44 
  45 /**
  46  * Trusted implementation code for MethodHandle.
  47  * @author jrose
  48  */
  49 /*non-public*/ abstract class MethodHandleImpl {
  50     // Do not adjust this except for special platforms:
  51     private static final int MAX_ARITY;
  52     static {
  53         final Object[] values = { 255 };
  54         AccessController.doPrivileged(new PrivilegedAction<Void>() {
  55             @Override
  56             public Void run() {
  57                 values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255);
  58                 return null;
  59             }
  60         });
  61         MAX_ARITY = (Integer) values[0];
  62     }
  63 
  64     /// Factory methods to create method handles:
  65 
  66     static void initStatics() {
  67         // Trigger selected static initializations.
  68         MemberName.Factory.INSTANCE.getClass();
  69     }
  70 
  71     static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) {
  72         if (arrayClass == Object[].class)
  73             return (isSetter ? ArrayAccessor.OBJECT_ARRAY_SETTER : ArrayAccessor.OBJECT_ARRAY_GETTER);
  74         if (!arrayClass.isArray())
  75             throw newIllegalArgumentException("not an array: "+arrayClass);
  76         MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass);
  77         int cacheIndex = (isSetter ? ArrayAccessor.SETTER_INDEX : ArrayAccessor.GETTER_INDEX);
  78         MethodHandle mh = cache[cacheIndex];
  79         if (mh != null)  return mh;
  80         mh = ArrayAccessor.getAccessor(arrayClass, isSetter);
  81         MethodType correctType = ArrayAccessor.correctType(arrayClass, isSetter);
  82         if (mh.type() != correctType) {
  83             assert(mh.type().parameterType(0) == Object[].class);
  84             assert((isSetter ? mh.type().parameterType(2) : mh.type().returnType()) == Object.class);
  85             assert(isSetter || correctType.parameterType(0).getComponentType() == correctType.returnType());
  86             // safe to view non-strictly, because element type follows from array type
  87             mh = mh.viewAsType(correctType, false);
  88         }
  89         // Atomically update accessor cache.
  90         synchronized(cache) {
  91             if (cache[cacheIndex] == null) {
  92                 cache[cacheIndex] = mh;
  93             } else {
  94                 // Throw away newly constructed accessor and use cached version.
  95                 mh = cache[cacheIndex];
  96             }
  97         }
  98         return mh;
  99     }
 100 
 101     static final class ArrayAccessor {
 102         /// Support for array element access
 103         static final int GETTER_INDEX = 0, SETTER_INDEX = 1, INDEX_LIMIT = 2;
 104         static final ClassValue<MethodHandle[]> TYPED_ACCESSORS
 105                 = new ClassValue<MethodHandle[]>() {
 106                     @Override
 107                     protected MethodHandle[] computeValue(Class<?> type) {
 108                         return new MethodHandle[INDEX_LIMIT];
 109                     }
 110                 };
 111         static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER;
 112         static {
 113             MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class);
 114             cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = getAccessor(Object[].class, false);
 115             cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = getAccessor(Object[].class, true);
 116 
 117             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName()));
 118             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName()));
 119         }
 120 
 121         static int     getElementI(int[]     a, int i)            { return              a[i]; }
 122         static long    getElementJ(long[]    a, int i)            { return              a[i]; }
 123         static float   getElementF(float[]   a, int i)            { return              a[i]; }
 124         static double  getElementD(double[]  a, int i)            { return              a[i]; }
 125         static boolean getElementZ(boolean[] a, int i)            { return              a[i]; }
 126         static byte    getElementB(byte[]    a, int i)            { return              a[i]; }
 127         static short   getElementS(short[]   a, int i)            { return              a[i]; }
 128         static char    getElementC(char[]    a, int i)            { return              a[i]; }
 129         static Object  getElementL(Object[]  a, int i)            { return              a[i]; }
 130 
 131         static void    setElementI(int[]     a, int i, int     x) {              a[i] = x; }
 132         static void    setElementJ(long[]    a, int i, long    x) {              a[i] = x; }
 133         static void    setElementF(float[]   a, int i, float   x) {              a[i] = x; }
 134         static void    setElementD(double[]  a, int i, double  x) {              a[i] = x; }
 135         static void    setElementZ(boolean[] a, int i, boolean x) {              a[i] = x; }
 136         static void    setElementB(byte[]    a, int i, byte    x) {              a[i] = x; }
 137         static void    setElementS(short[]   a, int i, short   x) {              a[i] = x; }
 138         static void    setElementC(char[]    a, int i, char    x) {              a[i] = x; }
 139         static void    setElementL(Object[]  a, int i, Object  x) {              a[i] = x; }
 140 
 141         static String name(Class<?> arrayClass, boolean isSetter) {
 142             Class<?> elemClass = arrayClass.getComponentType();
 143             if (elemClass == null)  throw newIllegalArgumentException("not an array", arrayClass);
 144             return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(elemClass);
 145         }
 146         static MethodType type(Class<?> arrayClass, boolean isSetter) {
 147             Class<?> elemClass = arrayClass.getComponentType();
 148             Class<?> arrayArgClass = arrayClass;
 149             if (!elemClass.isPrimitive()) {
 150                 arrayArgClass = Object[].class;
 151                 elemClass = Object.class;
 152             }
 153             return !isSetter ?
 154                     MethodType.methodType(elemClass,  arrayArgClass, int.class) :
 155                     MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
 156         }
 157         static MethodType correctType(Class<?> arrayClass, boolean isSetter) {
 158             Class<?> elemClass = arrayClass.getComponentType();
 159             return !isSetter ?
 160                     MethodType.methodType(elemClass,  arrayClass, int.class) :
 161                     MethodType.methodType(void.class, arrayClass, int.class, elemClass);
 162         }
 163         static MethodHandle getAccessor(Class<?> arrayClass, boolean isSetter) {
 164             String     name = name(arrayClass, isSetter);
 165             MethodType type = type(arrayClass, isSetter);
 166             try {
 167                 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type);
 168             } catch (ReflectiveOperationException ex) {
 169                 throw uncaughtException(ex);
 170             }
 171         }
 172     }
 173 
 174     /**
 175      * Create a JVM-level adapter method handle to conform the given method
 176      * handle to the similar newType, using only pairwise argument conversions.
 177      * For each argument, convert incoming argument to the exact type needed.
 178      * The argument conversions allowed are casting, boxing and unboxing,
 179      * integral widening or narrowing, and floating point widening or narrowing.
 180      * @param srcType required call type
 181      * @param target original method handle
 182      * @param level which strength of conversion is allowed
 183      * @return an adapter to the original handle with the desired new type,
 184      *          or the original target if the types are already identical
 185      *          or null if the adaptation cannot be made
 186      */
 187     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, int level) {
 188         assert(level >= 0 && level <= 2);
 189         MethodType dstType = target.type();
 190         assert(dstType.parameterCount() == target.type().parameterCount());
 191         if (srcType == dstType)
 192             return target;
 193 
 194         // Calculate extra arguments (temporaries) required in the names array.
 195         // FIXME: Use an ArrayList<Name>.  Some arguments require more than one conversion step.
 196         final int INARG_COUNT = srcType.parameterCount();
 197         int conversions = 0;
 198         boolean[] needConv = new boolean[1+INARG_COUNT];
 199         for (int i = 0; i <= INARG_COUNT; i++) {
 200             Class<?> src = (i == INARG_COUNT) ? dstType.returnType() : srcType.parameterType(i);
 201             Class<?> dst = (i == INARG_COUNT) ? srcType.returnType() : dstType.parameterType(i);
 202             if (!VerifyType.isNullConversion(src, dst, false) ||
 203                 level <= 1 && dst.isInterface() && !dst.isAssignableFrom(src)) {
 204                 needConv[i] = true;
 205                 conversions++;
 206             }
 207         }
 208         boolean retConv = needConv[INARG_COUNT];
 209         if (retConv && srcType.returnType() == void.class) {
 210             retConv = false;
 211             conversions--;
 212         }
 213 
 214         final int IN_MH         = 0;
 215         final int INARG_BASE    = 1;
 216         final int INARG_LIMIT   = INARG_BASE + INARG_COUNT;
 217         final int NAME_LIMIT    = INARG_LIMIT + conversions + 1;
 218         final int RETURN_CONV   = (!retConv ? -1         : NAME_LIMIT - 1);
 219         final int OUT_CALL      = (!retConv ? NAME_LIMIT : RETURN_CONV) - 1;
 220         final int RESULT        = (srcType.returnType() == void.class ? -1 : NAME_LIMIT - 1);
 221 
 222         // Now build a LambdaForm.
 223         MethodType lambdaType = srcType.basicType().invokerType();
 224         Name[] names = arguments(NAME_LIMIT - INARG_LIMIT, lambdaType);
 225 
 226         // Collect the arguments to the outgoing call, maybe with conversions:
 227         final int OUTARG_BASE = 0;  // target MH is Name.function, name Name.arguments[0]
 228         Object[] outArgs = new Object[OUTARG_BASE + INARG_COUNT];
 229 
 230         int nameCursor = INARG_LIMIT;
 231         for (int i = 0; i < INARG_COUNT; i++) {
 232             Class<?> src = srcType.parameterType(i);
 233             Class<?> dst = dstType.parameterType(i);
 234 
 235             if (!needConv[i]) {
 236                 // do nothing: difference is trivial
 237                 outArgs[OUTARG_BASE + i] = names[INARG_BASE + i];
 238                 continue;
 239             }
 240 
 241             // Tricky case analysis follows.
 242             MethodHandle fn = null;
 243             if (src.isPrimitive()) {
 244                 if (dst.isPrimitive()) {
 245                     fn = ValueConversions.convertPrimitive(src, dst);
 246                 } else {
 247                     Wrapper w = Wrapper.forPrimitiveType(src);
 248                     MethodHandle boxMethod = ValueConversions.box(w);
 249                     if (dst == w.wrapperType())
 250                         fn = boxMethod;
 251                     else
 252                         fn = boxMethod.asType(MethodType.methodType(dst, src));
 253                 }
 254             } else {
 255                 if (dst.isPrimitive()) {
 256                     // Caller has boxed a primitive.  Unbox it for the target.
 257                     Wrapper w = Wrapper.forPrimitiveType(dst);
 258                     if (level == 0 || VerifyType.isNullConversion(src, w.wrapperType(), false)) {
 259                         fn = ValueConversions.unbox(dst);
 260                     } else if (src == Object.class || !Wrapper.isWrapperType(src)) {
 261                         // Examples:  Object->int, Number->int, Comparable->int; Byte->int, Character->int
 262                         // must include additional conversions
 263                         // src must be examined at runtime, to detect Byte, Character, etc.
 264                         MethodHandle unboxMethod = (level == 1
 265                                                     ? ValueConversions.unbox(dst)
 266                                                     : ValueConversions.unboxCast(dst));
 267                         fn = unboxMethod;
 268                     } else {
 269                         // Example: Byte->int
 270                         // Do this by reformulating the problem to Byte->byte.
 271                         Class<?> srcPrim = Wrapper.forWrapperType(src).primitiveType();
 272                         MethodHandle unbox = ValueConversions.unbox(srcPrim);
 273                         // Compose the two conversions.  FIXME:  should make two Names for this job
 274                         fn = unbox.asType(MethodType.methodType(dst, src));
 275                     }
 276                 } else {
 277                     // Simple reference conversion.
 278                     // Note:  Do not check for a class hierarchy relation
 279                     // between src and dst.  In all cases a 'null' argument
 280                     // will pass the cast conversion.
 281                     fn = ValueConversions.cast(dst, Lazy.MH_castReference);
 282                 }
 283             }
 284             Name conv = new Name(fn, names[INARG_BASE + i]);
 285             assert(names[nameCursor] == null);
 286             names[nameCursor++] = conv;
 287             assert(outArgs[OUTARG_BASE + i] == null);
 288             outArgs[OUTARG_BASE + i] = conv;
 289         }
 290 
 291         // Build argument array for the call.
 292         assert(nameCursor == OUT_CALL);
 293         names[OUT_CALL] = new Name(target, outArgs);
 294 
 295         if (RETURN_CONV < 0) {
 296             assert(OUT_CALL == names.length-1);
 297         } else {
 298             Class<?> needReturn = srcType.returnType();
 299             Class<?> haveReturn = dstType.returnType();
 300             MethodHandle fn;
 301             Object[] arg = { names[OUT_CALL] };
 302             if (haveReturn == void.class) {
 303                 // synthesize a zero value for the given void
 304                 Object zero = Wrapper.forBasicType(needReturn).zero();
 305                 fn = MethodHandles.constant(needReturn, zero);
 306                 arg = new Object[0];  // don't pass names[OUT_CALL] to conversion
 307             } else {
 308                 MethodHandle identity = MethodHandles.identity(needReturn);
 309                 MethodType needConversion = identity.type().changeParameterType(0, haveReturn);
 310                 fn = makePairwiseConvert(identity, needConversion, level);
 311             }
 312             assert(names[RETURN_CONV] == null);
 313             names[RETURN_CONV] = new Name(fn, arg);
 314             assert(RETURN_CONV == names.length-1);
 315         }
 316 
 317         LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names, RESULT);
 318         return SimpleMethodHandle.make(srcType, form);
 319     }
 320 
 321     /**
 322      * Identity function, with reference cast.
 323      * @param t an arbitrary reference type
 324      * @param x an arbitrary reference value
 325      * @return the same value x
 326      */
 327     @ForceInline
 328     @SuppressWarnings("unchecked")
 329     static <T,U> T castReference(Class<? extends T> t, U x) {
 330         // inlined Class.cast because we can't ForceInline it
 331         if (x != null && !t.isInstance(x))
 332             throw newClassCastException(t, x);
 333         return (T) x;
 334     }
 335 
 336     private static ClassCastException newClassCastException(Class<?> t, Object obj) {
 337         return new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + t.getName());
 338     }
 339 
 340     static MethodHandle makeReferenceIdentity(Class<?> refType) {
 341         MethodType lambdaType = MethodType.genericMethodType(1).invokerType();
 342         Name[] names = arguments(1, lambdaType);
 343         names[names.length - 1] = new Name(ValueConversions.identity(), names[1]);
 344         LambdaForm form = new LambdaForm("identity", lambdaType.parameterCount(), names);
 345         return SimpleMethodHandle.make(MethodType.methodType(refType, refType), form);
 346     }
 347 
 348     static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
 349         MethodType type = target.type();
 350         int last = type.parameterCount() - 1;
 351         if (type.parameterType(last) != arrayType)
 352             target = target.asType(type.changeParameterType(last, arrayType));
 353         target = target.asFixedArity();  // make sure this attribute is turned off
 354         return new AsVarargsCollector(target, arrayType);
 355     }
 356 
 357     private static final class AsVarargsCollector extends DelegatingMethodHandle {
 358         private final MethodHandle target;
 359         private final Class<?> arrayType;
 360         private /*@Stable*/ MethodHandle asCollectorCache;
 361 
 362         AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
 363             this(target.type(), target, arrayType);
 364         }
 365         AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) {
 366             super(type, target);
 367             this.target = target;
 368             this.arrayType = arrayType;
 369             this.asCollectorCache = target.asCollector(arrayType, 0);
 370         }
 371 
 372         @Override
 373         public boolean isVarargsCollector() {
 374             return true;
 375         }
 376 
 377         @Override
 378         protected MethodHandle getTarget() {
 379             return target;
 380         }
 381 
 382         @Override
 383         public MethodHandle asFixedArity() {
 384             return target;
 385         }
 386 
 387         @Override
 388         public MethodHandle asTypeUncached(MethodType newType) {
 389             MethodType type = this.type();
 390             int collectArg = type.parameterCount() - 1;
 391             int newArity = newType.parameterCount();
 392             if (newArity == collectArg+1 &&
 393                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 394                 // if arity and trailing parameter are compatible, do normal thing
 395                 return asTypeCache = asFixedArity().asType(newType);
 396             }
 397             // check cache
 398             MethodHandle acc = asCollectorCache;
 399             if (acc != null && acc.type().parameterCount() == newArity)
 400                 return asTypeCache = acc.asType(newType);
 401             // build and cache a collector
 402             int arrayLength = newArity - collectArg;
 403             MethodHandle collector;
 404             try {
 405                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 406                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 407             } catch (IllegalArgumentException ex) {
 408                 throw new WrongMethodTypeException("cannot build collector", ex);
 409             }
 410             asCollectorCache = collector;
 411             return asTypeCache = collector.asType(newType);
 412         }
 413 
 414         @Override
 415         boolean viewAsTypeChecks(MethodType newType, boolean strict) {
 416             super.viewAsTypeChecks(newType, true);
 417             if (strict) return true;
 418             // extra assertion for non-strict checks:
 419             assert (type().lastParameterType().getComponentType()
 420                     .isAssignableFrom(
 421                             newType.lastParameterType().getComponentType()))
 422                     : Arrays.asList(this, newType);
 423             return true;
 424         }
 425     }
 426 
 427     /** Factory method:  Spread selected argument. */
 428     static MethodHandle makeSpreadArguments(MethodHandle target,
 429                                             Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
 430         MethodType targetType = target.type();
 431 
 432         for (int i = 0; i < spreadArgCount; i++) {
 433             Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i);
 434             if (arg == null)  arg = Object.class;
 435             targetType = targetType.changeParameterType(spreadArgPos + i, arg);
 436         }
 437         target = target.asType(targetType);
 438 
 439         MethodType srcType = targetType
 440                 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType);
 441         // Now build a LambdaForm.
 442         MethodType lambdaType = srcType.invokerType();
 443         Name[] names = arguments(spreadArgCount + 2, lambdaType);
 444         int nameCursor = lambdaType.parameterCount();
 445         int[] indexes = new int[targetType.parameterCount()];
 446 
 447         for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) {
 448             Class<?> src = lambdaType.parameterType(i);
 449             if (i == spreadArgPos) {
 450                 // Spread the array.
 451                 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType);
 452                 Name array = names[argIndex];
 453                 names[nameCursor++] = new Name(Lazy.NF_checkSpreadArgument, array, spreadArgCount);
 454                 for (int j = 0; j < spreadArgCount; i++, j++) {
 455                     indexes[i] = nameCursor;
 456                     names[nameCursor++] = new Name(aload, array, j);
 457                 }
 458             } else if (i < indexes.length) {
 459                 indexes[i] = argIndex;
 460             }
 461         }
 462         assert(nameCursor == names.length-1);  // leave room for the final call
 463 
 464         // Build argument array for the call.
 465         Name[] targetArgs = new Name[targetType.parameterCount()];
 466         for (int i = 0; i < targetType.parameterCount(); i++) {
 467             int idx = indexes[i];
 468             targetArgs[i] = names[idx];
 469         }
 470         names[names.length - 1] = new Name(target, (Object[]) targetArgs);
 471 
 472         LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names);
 473         return SimpleMethodHandle.make(srcType, form);
 474     }
 475 
 476     static void checkSpreadArgument(Object av, int n) {
 477         if (av == null) {
 478             if (n == 0)  return;
 479         } else if (av instanceof Object[]) {
 480             int len = ((Object[])av).length;
 481             if (len == n)  return;
 482         } else {
 483             int len = java.lang.reflect.Array.getLength(av);
 484             if (len == n)  return;
 485         }
 486         // fall through to error:
 487         throw newIllegalArgumentException("array is not of length "+n);
 488     }
 489 
 490     /**
 491      * Pre-initialized NamedFunctions for bootstrapping purposes.
 492      * Factored in an inner class to delay initialization until first usage.
 493      */
 494     private static class Lazy {
 495         private static final Class<?> MHI = MethodHandleImpl.class;
 496 
 497         static final NamedFunction NF_checkSpreadArgument;
 498         static final NamedFunction NF_guardWithCatch;
 499         static final NamedFunction NF_selectAlternative;
 500         static final NamedFunction NF_throwException;
 501 
 502         static final MethodHandle MH_castReference;
 503         static final MethodHandle MH_copyAsPrimitiveArray;
 504         static final MethodHandle MH_fillNewTypedArray;
 505         static final MethodHandle MH_fillNewArray;
 506         static final MethodHandle MH_arrayIdentity;
 507 
 508         static {
 509             try {
 510                 NF_checkSpreadArgument = new NamedFunction(MHI.getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
 511                 NF_guardWithCatch      = new NamedFunction(MHI.getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
 512                                                                                  MethodHandle.class, Object[].class));
 513                 NF_selectAlternative   = new NamedFunction(MHI.getDeclaredMethod("selectAlternative", boolean.class, MethodHandle.class,
 514                                                                                  MethodHandle.class));
 515                 NF_throwException      = new NamedFunction(MHI.getDeclaredMethod("throwException", Throwable.class));
 516 
 517                 NF_checkSpreadArgument.resolve();
 518                 NF_guardWithCatch.resolve();
 519                 NF_selectAlternative.resolve();
 520                 NF_throwException.resolve();
 521 
 522                 MH_castReference        = IMPL_LOOKUP.findStatic(MHI, "castReference",
 523                                             MethodType.methodType(Object.class, Class.class, Object.class));
 524                 MH_copyAsPrimitiveArray = IMPL_LOOKUP.findStatic(MHI, "copyAsPrimitiveArray",
 525                                             MethodType.methodType(Object.class, Wrapper.class, Object[].class));
 526                 MH_arrayIdentity        = IMPL_LOOKUP.findStatic(MHI, "identity",
 527                                             MethodType.methodType(Object[].class, Object[].class));
 528                 MH_fillNewArray         = IMPL_LOOKUP.findStatic(MHI, "fillNewArray",
 529                                             MethodType.methodType(Object[].class, Integer.class, Object[].class));
 530                 MH_fillNewTypedArray    = IMPL_LOOKUP.findStatic(MHI, "fillNewTypedArray",
 531                                             MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class));
 532             } catch (ReflectiveOperationException ex) {
 533                 throw newInternalError(ex);
 534             }
 535         }
 536     }
 537 
 538     /** Factory method:  Collect or filter selected argument(s). */
 539     static MethodHandle makeCollectArguments(MethodHandle target,
 540                 MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) {
 541         MethodType targetType = target.type();          // (a..., c, [b...])=>r
 542         MethodType collectorType = collector.type();    // (b...)=>c
 543         int collectArgCount = collectorType.parameterCount();
 544         Class<?> collectValType = collectorType.returnType();
 545         int collectValCount = (collectValType == void.class ? 0 : 1);
 546         MethodType srcType = targetType                 // (a..., [b...])=>r
 547                 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
 548         if (!retainOriginalArgs) {                      // (a..., b...)=>r
 549             srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList());
 550         }
 551         // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
 552         // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
 553         // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ]
 554 
 555         // Now build a LambdaForm.
 556         MethodType lambdaType = srcType.invokerType();
 557         Name[] names = arguments(2, lambdaType);
 558         final int collectNamePos = names.length - 2;
 559         final int targetNamePos  = names.length - 1;
 560 
 561         Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount);
 562         names[collectNamePos] = new Name(collector, (Object[]) collectorArgs);
 563 
 564         // Build argument array for the target.
 565         // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ].
 566         // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ].
 567         Name[] targetArgs = new Name[targetType.parameterCount()];
 568         int inputArgPos  = 1;  // incoming LF args to copy to target
 569         int targetArgPos = 0;  // fill pointer for targetArgs
 570         int chunk = collectArgPos;  // |headArgs|
 571         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 572         inputArgPos  += chunk;
 573         targetArgPos += chunk;
 574         if (collectValType != void.class) {
 575             targetArgs[targetArgPos++] = names[collectNamePos];
 576         }
 577         chunk = collectArgCount;
 578         if (retainOriginalArgs) {
 579             System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 580             targetArgPos += chunk;   // optionally pass on the collected chunk
 581         }
 582         inputArgPos += chunk;
 583         chunk = targetArgs.length - targetArgPos;  // all the rest
 584         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 585         assert(inputArgPos + chunk == collectNamePos);  // use of rest of input args also
 586         names[targetNamePos] = new Name(target, (Object[]) targetArgs);
 587 
 588         LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names);
 589         return SimpleMethodHandle.make(srcType, form);
 590     }
 591 
 592     @LambdaForm.Hidden
 593     static
 594     MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 595         return testResult ? target : fallback;
 596     }
 597 
 598     static
 599     MethodHandle makeGuardWithTest(MethodHandle test,
 600                                    MethodHandle target,
 601                                    MethodHandle fallback) {
 602         MethodType basicType = target.type().basicType();
 603         MethodHandle invokeBasic = MethodHandles.basicInvoker(basicType);
 604         int arity = basicType.parameterCount();
 605         int extraNames = 3;
 606         MethodType lambdaType = basicType.invokerType();
 607         Name[] names = arguments(extraNames, lambdaType);
 608 
 609         Object[] testArgs   = Arrays.copyOfRange(names, 1, 1 + arity, Object[].class);
 610         Object[] targetArgs = Arrays.copyOfRange(names, 0, 1 + arity, Object[].class);
 611 
 612         // call test
 613         names[arity + 1] = new Name(test, testArgs);
 614 
 615         // call selectAlternative
 616         Object[] selectArgs = { names[arity + 1], target, fallback };
 617         names[arity + 2] = new Name(Lazy.NF_selectAlternative, selectArgs);
 618         targetArgs[0] = names[arity + 2];
 619 
 620         // call target or fallback
 621         names[arity + 3] = new Name(new NamedFunction(invokeBasic), targetArgs);
 622 
 623         LambdaForm form = new LambdaForm("guard", lambdaType.parameterCount(), names);
 624         return SimpleMethodHandle.make(target.type(), form);
 625     }
 626 
 627     /**
 628      * The LambaForm shape for catchException combinator is the following:
 629      * <blockquote><pre>{@code
 630      *  guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{
 631      *    t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L);
 632      *    t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L);
 633      *    t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L);
 634      *    t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L);
 635      *    t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L);
 636      *    t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L);
 637      *    t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L);
 638      *   t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I}
 639      * }</pre></blockquote>
 640      *
 641      * argL0 and argL2 are target and catcher method handles. argL1 is exception class.
 642      * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[]
 643      * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()).
 644      *
 645      * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms
 646      * among catchException combinators with the same basic type.
 647      */
 648     private static LambdaForm makeGuardWithCatchForm(MethodType basicType) {
 649         MethodType lambdaType = basicType.invokerType();
 650 
 651         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC);
 652         if (lform != null) {
 653             return lform;
 654         }
 655         final int THIS_MH      = 0;  // the BMH_LLLLL
 656         final int ARG_BASE     = 1;  // start of incoming arguments
 657         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 658 
 659         int nameCursor = ARG_LIMIT;
 660         final int GET_TARGET       = nameCursor++;
 661         final int GET_CLASS        = nameCursor++;
 662         final int GET_CATCHER      = nameCursor++;
 663         final int GET_COLLECT_ARGS = nameCursor++;
 664         final int GET_UNBOX_RESULT = nameCursor++;
 665         final int BOXED_ARGS       = nameCursor++;
 666         final int TRY_CATCH        = nameCursor++;
 667         final int UNBOX_RESULT     = nameCursor++;
 668 
 669         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 670 
 671         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 672         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
 673         names[GET_CLASS]        = new Name(data.getterFunction(1), names[THIS_MH]);
 674         names[GET_CATCHER]      = new Name(data.getterFunction(2), names[THIS_MH]);
 675         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]);
 676         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]);
 677 
 678         // FIXME: rework argument boxing/result unboxing logic for LF interpretation
 679 
 680         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
 681         MethodType collectArgsType = basicType.changeReturnType(Object.class);
 682         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
 683         Object[] args = new Object[invokeBasic.type().parameterCount()];
 684         args[0] = names[GET_COLLECT_ARGS];
 685         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
 686         names[BOXED_ARGS] = new Name(new NamedFunction(invokeBasic), args);
 687 
 688         // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L);
 689         Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]};
 690         names[TRY_CATCH] = new Name(Lazy.NF_guardWithCatch, gwcArgs);
 691 
 692         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
 693         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
 694         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
 695         names[UNBOX_RESULT] = new Name(new NamedFunction(invokeBasicUnbox), unboxArgs);
 696 
 697         lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names);
 698 
 699         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
 700     }
 701 
 702     static
 703     MethodHandle makeGuardWithCatch(MethodHandle target,
 704                                     Class<? extends Throwable> exType,
 705                                     MethodHandle catcher) {
 706         MethodType type = target.type();
 707         LambdaForm form = makeGuardWithCatchForm(type.basicType());
 708 
 709         // Prepare auxiliary method handles used during LambdaForm interpreation.
 710         // Box arguments and wrap them into Object[]: ValueConversions.array().
 711         MethodType varargsType = type.changeReturnType(Object[].class);
 712         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
 713         // Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore().
 714         MethodHandle unboxResult;
 715         if (type.returnType().isPrimitive()) {
 716             unboxResult = ValueConversions.unbox(type.returnType());
 717         } else {
 718             unboxResult = ValueConversions.identity();
 719         }
 720 
 721         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 722         BoundMethodHandle mh;
 723         try {
 724             mh = (BoundMethodHandle)
 725                     data.constructor().invokeBasic(type, form, (Object) target, (Object) exType, (Object) catcher,
 726                                                    (Object) collectArgs, (Object) unboxResult);
 727         } catch (Throwable ex) {
 728             throw uncaughtException(ex);
 729         }
 730         assert(mh.type() == type);
 731         return mh;
 732     }
 733 
 734     /**
 735      * Intrinsified during LambdaForm compilation
 736      * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}).
 737      */
 738     @LambdaForm.Hidden
 739     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
 740                                  Object... av) throws Throwable {
 741         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
 742         try {
 743             return target.asFixedArity().invokeWithArguments(av);
 744         } catch (Throwable t) {
 745             if (!exType.isInstance(t)) throw t;
 746             return catcher.asFixedArity().invokeWithArguments(prepend(t, av));
 747         }
 748     }
 749 
 750     /** Prepend an element {@code elem} to an {@code array}. */
 751     @LambdaForm.Hidden
 752     private static Object[] prepend(Object elem, Object[] array) {
 753         Object[] newArray = new Object[array.length+1];
 754         newArray[0] = elem;
 755         System.arraycopy(array, 0, newArray, 1, array.length);
 756         return newArray;
 757     }
 758 
 759     static
 760     MethodHandle throwException(MethodType type) {
 761         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 762         int arity = type.parameterCount();
 763         if (arity > 1) {
 764             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
 765             mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity));
 766             return mh;
 767         }
 768         return makePairwiseConvert(Lazy.NF_throwException.resolvedHandle(), type, 2);
 769     }
 770 
 771     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 772 
 773     static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2];
 774     static MethodHandle fakeMethodHandleInvoke(MemberName method) {
 775         int idx;
 776         assert(method.isMethodHandleInvoke());
 777         switch (method.getName()) {
 778         case "invoke":       idx = 0; break;
 779         case "invokeExact":  idx = 1; break;
 780         default:             throw new InternalError(method.getName());
 781         }
 782         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx];
 783         if (mh != null)  return mh;
 784         MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class,
 785                                                 MethodHandle.class, Object[].class);
 786         mh = throwException(type);
 787         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 788         if (!method.getInvocationType().equals(mh.type()))
 789             throw new InternalError(method.toString());
 790         mh = mh.withInternalMemberName(method, false);
 791         mh = mh.asVarargsCollector(Object[].class);
 792         assert(method.isVarargs());
 793         FAKE_METHOD_HANDLE_INVOKE[idx] = mh;
 794         return mh;
 795     }
 796 
 797     /**
 798      * Create an alias for the method handle which, when called,
 799      * appears to be called from the same class loader and protection domain
 800      * as hostClass.
 801      * This is an expensive no-op unless the method which is called
 802      * is sensitive to its caller.  A small number of system methods
 803      * are in this category, including Class.forName and Method.invoke.
 804      */
 805     static
 806     MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 807         return BindCaller.bindCaller(mh, hostClass);
 808     }
 809 
 810     // Put the whole mess into its own nested class.
 811     // That way we can lazily load the code and set up the constants.
 812     private static class BindCaller {
 813         static
 814         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 815             // Do not use this function to inject calls into system classes.
 816             if (hostClass == null
 817                 ||    (hostClass.isArray() ||
 818                        hostClass.isPrimitive() ||
 819                        hostClass.getName().startsWith("java.") ||
 820                        hostClass.getName().startsWith("sun."))) {
 821                 throw new InternalError();  // does not happen, and should not anyway
 822             }
 823             // For simplicity, convert mh to a varargs-like method.
 824             MethodHandle vamh = prepareForInvoker(mh);
 825             // Cache the result of makeInjectedInvoker once per argument class.
 826             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
 827             return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass);
 828         }
 829 
 830         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
 831             Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
 832             if (hostClass.getClassLoader() != bcc.getClassLoader())
 833                 throw new InternalError(hostClass.getName()+" (CL)");
 834             try {
 835                 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
 836                     throw new InternalError(hostClass.getName()+" (PD)");
 837             } catch (SecurityException ex) {
 838                 // Self-check was blocked by security manager.  This is OK.
 839                 // In fact the whole try body could be turned into an assertion.
 840             }
 841             try {
 842                 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
 843                 init.invokeExact();  // force initialization of the class
 844             } catch (Throwable ex) {
 845                 throw uncaughtException(ex);
 846             }
 847             MethodHandle bccInvoker;
 848             try {
 849                 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
 850                 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
 851             } catch (ReflectiveOperationException ex) {
 852                 throw uncaughtException(ex);
 853             }
 854             // Test the invoker, to ensure that it really injects into the right place.
 855             try {
 856                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
 857                 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
 858             } catch (Throwable ex) {
 859                 throw new InternalError(ex);
 860             }
 861             return bccInvoker;
 862         }
 863         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
 864             @Override protected MethodHandle computeValue(Class<?> hostClass) {
 865                 return makeInjectedInvoker(hostClass);
 866             }
 867         };
 868 
 869         // Adapt mh so that it can be called directly from an injected invoker:
 870         private static MethodHandle prepareForInvoker(MethodHandle mh) {
 871             mh = mh.asFixedArity();
 872             MethodType mt = mh.type();
 873             int arity = mt.parameterCount();
 874             MethodHandle vamh = mh.asType(mt.generic());
 875             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 876             vamh = vamh.asSpreader(Object[].class, arity);
 877             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 878             return vamh;
 879         }
 880 
 881         // Undo the adapter effect of prepareForInvoker:
 882         private static MethodHandle restoreToType(MethodHandle vamh,
 883                                                   MethodHandle original,
 884                                                   Class<?> hostClass) {
 885             MethodType type = original.type();
 886             MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount());
 887             MemberName member = original.internalMemberName();
 888             mh = mh.asType(type);
 889             mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass);
 890             return mh;
 891         }
 892 
 893         private static final MethodHandle MH_checkCallerClass;
 894         static {
 895             final Class<?> THIS_CLASS = BindCaller.class;
 896             assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
 897             try {
 898                 MH_checkCallerClass = IMPL_LOOKUP
 899                     .findStatic(THIS_CLASS, "checkCallerClass",
 900                                 MethodType.methodType(boolean.class, Class.class, Class.class));
 901                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
 902             } catch (Throwable ex) {
 903                 throw new InternalError(ex);
 904             }
 905         }
 906 
 907         @CallerSensitive
 908         private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
 909             // This method is called via MH_checkCallerClass and so it's
 910             // correct to ask for the immediate caller here.
 911             Class<?> actual = Reflection.getCallerClass();
 912             if (actual != expected && actual != expected2)
 913                 throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
 914                                         +(expected == expected2 ? "" : ", or else "+expected2.getName()));
 915             return true;
 916         }
 917 
 918         private static final byte[] T_BYTES;
 919         static {
 920             final Object[] values = {null};
 921             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 922                     public Void run() {
 923                         try {
 924                             Class<T> tClass = T.class;
 925                             String tName = tClass.getName();
 926                             String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
 927                             java.net.URLConnection uconn = tClass.getResource(tResource).openConnection();
 928                             int len = uconn.getContentLength();
 929                             byte[] bytes = new byte[len];
 930                             try (java.io.InputStream str = uconn.getInputStream()) {
 931                                 int nr = str.read(bytes);
 932                                 if (nr != len)  throw new java.io.IOException(tResource);
 933                             }
 934                             values[0] = bytes;
 935                         } catch (java.io.IOException ex) {
 936                             throw new InternalError(ex);
 937                         }
 938                         return null;
 939                     }
 940                 });
 941             T_BYTES = (byte[]) values[0];
 942         }
 943 
 944         // The following class is used as a template for Unsafe.defineAnonymousClass:
 945         private static class T {
 946             static void init() { }  // side effect: initializes this class
 947             static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
 948                 return vamh.invokeExact(args);
 949             }
 950         }
 951     }
 952 
 953 
 954     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
 955     private static final class WrappedMember extends DelegatingMethodHandle {
 956         private final MethodHandle target;
 957         private final MemberName member;
 958         private final Class<?> callerClass;
 959         private final boolean isInvokeSpecial;
 960 
 961         private WrappedMember(MethodHandle target, MethodType type,
 962                               MemberName member, boolean isInvokeSpecial,
 963                               Class<?> callerClass) {
 964             super(type, target);
 965             this.target = target;
 966             this.member = member;
 967             this.callerClass = callerClass;
 968             this.isInvokeSpecial = isInvokeSpecial;
 969         }
 970 
 971         @Override
 972         MemberName internalMemberName() {
 973             return member;
 974         }
 975         @Override
 976         Class<?> internalCallerClass() {
 977             return callerClass;
 978         }
 979         @Override
 980         boolean isInvokeSpecial() {
 981             return isInvokeSpecial;
 982         }
 983         @Override
 984         protected MethodHandle getTarget() {
 985             return target;
 986         }
 987         @Override
 988         public MethodHandle asTypeUncached(MethodType newType) {
 989             // This MH is an alias for target, except for the MemberName
 990             // Drop the MemberName if there is any conversion.
 991             return asTypeCache = target.asType(newType);
 992         }
 993     }
 994 
 995     static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) {
 996         if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial())
 997             return target;
 998         return new WrappedMember(target, target.type(), member, isInvokeSpecial, null);
 999     }
1000 
1001     /// Collection of multiple arguments.
1002 
1003     private static MethodHandle findCollector(String name, int nargs, Class<?> rtype, Class<?>... ptypes) {
1004         MethodType type = MethodType.genericMethodType(nargs)
1005                 .changeReturnType(rtype)
1006                 .insertParameterTypes(0, ptypes);
1007         try {
1008             return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, name, type);
1009         } catch (ReflectiveOperationException ex) {
1010             return null;
1011         }
1012     }
1013 
1014     private static final Object[] NO_ARGS_ARRAY = {};
1015     private static Object[] makeArray(Object... args) { return args; }
1016     private static Object[] array() { return NO_ARGS_ARRAY; }
1017     private static Object[] array(Object a0)
1018                 { return makeArray(a0); }
1019     private static Object[] array(Object a0, Object a1)
1020                 { return makeArray(a0, a1); }
1021     private static Object[] array(Object a0, Object a1, Object a2)
1022                 { return makeArray(a0, a1, a2); }
1023     private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1024                 { return makeArray(a0, a1, a2, a3); }
1025     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1026                                   Object a4)
1027                 { return makeArray(a0, a1, a2, a3, a4); }
1028     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1029                                   Object a4, Object a5)
1030                 { return makeArray(a0, a1, a2, a3, a4, a5); }
1031     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1032                                   Object a4, Object a5, Object a6)
1033                 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1034     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1035                                   Object a4, Object a5, Object a6, Object a7)
1036                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1037     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1038                                   Object a4, Object a5, Object a6, Object a7,
1039                                   Object a8)
1040                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1041     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1042                                   Object a4, Object a5, Object a6, Object a7,
1043                                   Object a8, Object a9)
1044                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1045     private static MethodHandle[] makeArrays() {
1046         ArrayList<MethodHandle> mhs = new ArrayList<>();
1047         for (;;) {
1048             MethodHandle mh = findCollector("array", mhs.size(), Object[].class);
1049             if (mh == null)  break;
1050             mhs.add(mh);
1051         }
1052         assert(mhs.size() == 11);  // current number of methods
1053         return mhs.toArray(new MethodHandle[MAX_ARITY+1]);
1054     }
1055     private static final MethodHandle[] ARRAYS = makeArrays();
1056 
1057     // filling versions of the above:
1058     // using Integer len instead of int len and no varargs to avoid bootstrapping problems
1059     private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) {
1060         Object[] a = new Object[len];
1061         fillWithArguments(a, 0, args);
1062         return a;
1063     }
1064     private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) {
1065         Object[] a = Arrays.copyOf(example, len);
1066         assert(a.getClass() != Object[].class);
1067         fillWithArguments(a, 0, args);
1068         return a;
1069     }
1070     private static void fillWithArguments(Object[] a, int pos, Object... args) {
1071         System.arraycopy(args, 0, a, pos, args.length);
1072     }
1073     // using Integer pos instead of int pos to avoid bootstrapping problems
1074     private static Object[] fillArray(Integer pos, Object[] a, Object a0)
1075                 { fillWithArguments(a, pos, a0); return a; }
1076     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1)
1077                 { fillWithArguments(a, pos, a0, a1); return a; }
1078     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2)
1079                 { fillWithArguments(a, pos, a0, a1, a2); return a; }
1080     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3)
1081                 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; }
1082     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1083                                   Object a4)
1084                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; }
1085     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1086                                   Object a4, Object a5)
1087                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); return a; }
1088     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1089                                   Object a4, Object a5, Object a6)
1090                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; }
1091     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1092                                   Object a4, Object a5, Object a6, Object a7)
1093                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; }
1094     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1095                                   Object a4, Object a5, Object a6, Object a7,
1096                                   Object a8)
1097                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; }
1098     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1099                                   Object a4, Object a5, Object a6, Object a7,
1100                                   Object a8, Object a9)
1101                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; }
1102     private static MethodHandle[] makeFillArrays() {
1103         ArrayList<MethodHandle> mhs = new ArrayList<>();
1104         mhs.add(null);  // there is no empty fill; at least a0 is required
1105         for (;;) {
1106             MethodHandle mh = findCollector("fillArray", mhs.size(), Object[].class, Integer.class, Object[].class);
1107             if (mh == null)  break;
1108             mhs.add(mh);
1109         }
1110         assert(mhs.size() == 11);  // current number of methods
1111         return mhs.toArray(new MethodHandle[0]);
1112     }
1113     private static final MethodHandle[] FILL_ARRAYS = makeFillArrays();
1114 
1115     private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) {
1116         Object a = w.makeArray(boxes.length);
1117         w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length);
1118         return a;
1119     }
1120 
1121     /** Return a method handle that takes the indicated number of Object
1122      *  arguments and returns an Object array of them, as if for varargs.
1123      */
1124     static MethodHandle varargsArray(int nargs) {
1125         MethodHandle mh = ARRAYS[nargs];
1126         if (mh != null)  return mh;
1127         mh = findCollector("array", nargs, Object[].class);
1128         if (mh != null)  return ARRAYS[nargs] = mh;
1129         mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs);
1130         assert(assertCorrectArity(mh, nargs));
1131         return ARRAYS[nargs] = mh;
1132     }
1133 
1134     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1135         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1136         return true;
1137     }
1138 
1139     // Array identity function (used as Lazy.MH_arrayIdentity).
1140     static <T> T[] identity(T[] x) {
1141         return x;
1142     }
1143 
1144     private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) {
1145         // Build up the result mh as a sequence of fills like this:
1146         //   finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23))
1147         // The various fill(_,10*I,___*[J]) are reusable.
1148         int leftLen = Math.min(nargs, LEFT_ARGS);  // absorb some arguments immediately
1149         int rightLen = nargs - leftLen;
1150         MethodHandle leftCollector = newArray.bindTo(nargs);
1151         leftCollector = leftCollector.asCollector(Object[].class, leftLen);
1152         MethodHandle mh = finisher;
1153         if (rightLen > 0) {
1154             MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen);
1155             if (mh == Lazy.MH_arrayIdentity)
1156                 mh = rightFiller;
1157             else
1158                 mh = MethodHandles.collectArguments(mh, 0, rightFiller);
1159         }
1160         if (mh == Lazy.MH_arrayIdentity)
1161             mh = leftCollector;
1162         else
1163             mh = MethodHandles.collectArguments(mh, 0, leftCollector);
1164         return mh;
1165     }
1166 
1167     private static final int LEFT_ARGS = (FILL_ARRAYS.length - 1);
1168     private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1];
1169     /** fill_array_to_right(N).invoke(a, argL..arg[N-1])
1170      *  fills a[L]..a[N-1] with corresponding arguments,
1171      *  and then returns a.  The value L is a global constant (LEFT_ARGS).
1172      */
1173     private static MethodHandle fillToRight(int nargs) {
1174         MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs];
1175         if (filler != null)  return filler;
1176         filler = buildFiller(nargs);
1177         assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1));
1178         return FILL_ARRAY_TO_RIGHT[nargs] = filler;
1179     }
1180     private static MethodHandle buildFiller(int nargs) {
1181         if (nargs <= LEFT_ARGS)
1182             return Lazy.MH_arrayIdentity;  // no args to fill; return the array unchanged
1183         // we need room for both mh and a in mh.invoke(a, arg*[nargs])
1184         final int CHUNK = LEFT_ARGS;
1185         int rightLen = nargs % CHUNK;
1186         int midLen = nargs - rightLen;
1187         if (rightLen == 0) {
1188             midLen = nargs - (rightLen = CHUNK);
1189             if (FILL_ARRAY_TO_RIGHT[midLen] == null) {
1190                 // build some precursors from left to right
1191                 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK)
1192                     if (j > LEFT_ARGS)  fillToRight(j);
1193             }
1194         }
1195         if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS);
1196         assert(rightLen > 0);
1197         MethodHandle midFill = fillToRight(midLen);  // recursive fill
1198         MethodHandle rightFill = FILL_ARRAYS[rightLen].bindTo(midLen);  // [midLen..nargs-1]
1199         assert(midFill.type().parameterCount()   == 1 + midLen - LEFT_ARGS);
1200         assert(rightFill.type().parameterCount() == 1 + rightLen);
1201 
1202         // Combine the two fills:
1203         //   right(mid(a, x10..x19), x20..x23)
1204         // The final product will look like this:
1205         //   right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23)
1206         if (midLen == LEFT_ARGS)
1207             return rightFill;
1208         else
1209             return MethodHandles.collectArguments(rightFill, 0, midFill);
1210     }
1211 
1212     // Type-polymorphic version of varargs maker.
1213     private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS
1214         = new ClassValue<MethodHandle[]>() {
1215             @Override
1216             protected MethodHandle[] computeValue(Class<?> type) {
1217                 return new MethodHandle[256];
1218             }
1219     };
1220 
1221     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1222 
1223     /** Return a method handle that takes the indicated number of
1224      *  typed arguments and returns an array of them.
1225      *  The type argument is the array type.
1226      */
1227     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1228         Class<?> elemType = arrayType.getComponentType();
1229         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1230         // FIXME: Need more special casing and caching here.
1231         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1232             int slots = nargs;
1233             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1234             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1235                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1236             if (slots > MAX_ARRAY_SLOTS)
1237                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1238         }
1239         if (elemType == Object.class)
1240             return varargsArray(nargs);
1241         // other cases:  primitive arrays, subtypes of Object[]
1242         MethodHandle cache[] = TYPED_COLLECTORS.get(elemType);
1243         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1244         if (mh != null)  return mh;
1245         if (nargs == 0) {
1246             Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0);
1247             mh = MethodHandles.constant(arrayType, example);
1248         } else if (elemType.isPrimitive()) {
1249             MethodHandle builder = Lazy.MH_fillNewArray;
1250             MethodHandle producer = buildArrayProducer(arrayType);
1251             mh = buildVarargsArray(builder, producer, nargs);
1252         } else {
1253             Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class);
1254             Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType);
1255             MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example);
1256             MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed
1257             mh = buildVarargsArray(builder, producer, nargs);
1258         }
1259         mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)));
1260         assert(assertCorrectArity(mh, nargs));
1261         if (nargs < cache.length)
1262             cache[nargs] = mh;
1263         return mh;
1264     }
1265 
1266     private static MethodHandle buildArrayProducer(Class<?> arrayType) {
1267         Class<?> elemType = arrayType.getComponentType();
1268         assert(elemType.isPrimitive());
1269         return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType));
1270     }
1271 }