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);
  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, target.type(), arrayType);
 355     }
 356 
 357     static class AsVarargsCollector extends MethodHandle {
 358         private final MethodHandle target;
 359         private final Class<?> arrayType;
 360         private @Stable MethodHandle asCollectorCache;
 361 
 362         AsVarargsCollector(MethodHandle target, MethodType type, Class<?> arrayType) {
 363             super(type, reinvokerForm(target));
 364             this.target = target;
 365             this.arrayType = arrayType;
 366             this.asCollectorCache = target.asCollector(arrayType, 0);
 367         }
 368 
 369         @Override MethodHandle reinvokerTarget() { return target; }
 370 
 371         @Override
 372         public boolean isVarargsCollector() {
 373             return true;
 374         }
 375 
 376         @Override
 377         public MethodHandle asFixedArity() {
 378             return target;
 379         }
 380 
 381         @Override
 382         public MethodHandle asTypeUncached(MethodType newType) {
 383             MethodType type = this.type();
 384             int collectArg = type.parameterCount() - 1;
 385             int newArity = newType.parameterCount();
 386             if (newArity == collectArg+1 &&
 387                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 388                 // if arity and trailing parameter are compatible, do normal thing
 389                 return asTypeCache = asFixedArity().asType(newType);
 390             }
 391             // check cache
 392             MethodHandle acc = asCollectorCache;
 393             if (acc != null && acc.type().parameterCount() == newArity)
 394                 return asTypeCache = acc.asType(newType);
 395             // build and cache a collector
 396             int arrayLength = newArity - collectArg;
 397             MethodHandle collector;
 398             try {
 399                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 400                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 401             } catch (IllegalArgumentException ex) {
 402                 throw new WrongMethodTypeException("cannot build collector", ex);
 403             }
 404             asCollectorCache = collector;
 405             return asTypeCache = collector.asType(newType);
 406         }
 407 
 408         @Override
 409         MethodHandle setVarargs(MemberName member) {
 410             if (member.isVarargs())  return this;
 411             return asFixedArity();
 412         }
 413 
 414         @Override
 415         MethodHandle viewAsType(MethodType newType) {
 416             if (newType.lastParameterType() != type().lastParameterType())
 417                 throw new InternalError();
 418             MethodHandle newTarget = asFixedArity().viewAsType(newType);
 419             // put back the varargs bit:
 420             return new AsVarargsCollector(newTarget, newType, arrayType);
 421         }
 422 
 423         @Override
 424         MemberName internalMemberName() {
 425             return asFixedArity().internalMemberName();
 426         }
 427         @Override
 428         Class<?> internalCallerClass() {
 429             return asFixedArity().internalCallerClass();
 430         }
 431 
 432         /*non-public*/
 433         @Override
 434         boolean isInvokeSpecial() {
 435             return asFixedArity().isInvokeSpecial();
 436         }
 437     }
 438 
 439     /** Factory method:  Spread selected argument. */
 440     static MethodHandle makeSpreadArguments(MethodHandle target,
 441                                             Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
 442         MethodType targetType = target.type();
 443 
 444         for (int i = 0; i < spreadArgCount; i++) {
 445             Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i);
 446             if (arg == null)  arg = Object.class;
 447             targetType = targetType.changeParameterType(spreadArgPos + i, arg);
 448         }
 449         target = target.asType(targetType);
 450 
 451         MethodType srcType = targetType
 452                 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType);
 453         // Now build a LambdaForm.
 454         MethodType lambdaType = srcType.invokerType();
 455         Name[] names = arguments(spreadArgCount + 2, lambdaType);
 456         int nameCursor = lambdaType.parameterCount();
 457         int[] indexes = new int[targetType.parameterCount()];
 458 
 459         for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) {
 460             Class<?> src = lambdaType.parameterType(i);
 461             if (i == spreadArgPos) {
 462                 // Spread the array.
 463                 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType);
 464                 Name array = names[argIndex];
 465                 names[nameCursor++] = new Name(Lazy.NF_checkSpreadArgument, array, spreadArgCount);
 466                 for (int j = 0; j < spreadArgCount; i++, j++) {
 467                     indexes[i] = nameCursor;
 468                     names[nameCursor++] = new Name(aload, array, j);
 469                 }
 470             } else if (i < indexes.length) {
 471                 indexes[i] = argIndex;
 472             }
 473         }
 474         assert(nameCursor == names.length-1);  // leave room for the final call
 475 
 476         // Build argument array for the call.
 477         Name[] targetArgs = new Name[targetType.parameterCount()];
 478         for (int i = 0; i < targetType.parameterCount(); i++) {
 479             int idx = indexes[i];
 480             targetArgs[i] = names[idx];
 481         }
 482         names[names.length - 1] = new Name(target, (Object[]) targetArgs);
 483 
 484         LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names);
 485         return SimpleMethodHandle.make(srcType, form);
 486     }
 487 
 488     static void checkSpreadArgument(Object av, int n) {
 489         if (av == null) {
 490             if (n == 0)  return;
 491         } else if (av instanceof Object[]) {
 492             int len = ((Object[])av).length;
 493             if (len == n)  return;
 494         } else {
 495             int len = java.lang.reflect.Array.getLength(av);
 496             if (len == n)  return;
 497         }
 498         // fall through to error:
 499         throw newIllegalArgumentException("array is not of length "+n);
 500     }
 501 
 502     /**
 503      * Pre-initialized NamedFunctions for bootstrapping purposes.
 504      * Factored in an inner class to delay initialization until first usage.
 505      */
 506     private static class Lazy {
 507         private static final Class<?> MHI = MethodHandleImpl.class;
 508 
 509         static final NamedFunction NF_checkSpreadArgument;
 510         static final NamedFunction NF_guardWithCatch;
 511         static final NamedFunction NF_selectAlternative;
 512         static final NamedFunction NF_throwException;
 513 
 514         static final MethodHandle MH_castReference;
 515         static final MethodHandle MH_copyAsPrimitiveArray;
 516         static final MethodHandle MH_fillNewTypedArray;
 517         static final MethodHandle MH_fillNewArray;
 518         static final MethodHandle MH_arrayIdentity;
 519 
 520         static {
 521             try {
 522                 NF_checkSpreadArgument = new NamedFunction(MHI.getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
 523                 NF_guardWithCatch      = new NamedFunction(MHI.getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
 524                                                                                  MethodHandle.class, Object[].class));
 525                 NF_selectAlternative   = new NamedFunction(MHI.getDeclaredMethod("selectAlternative", boolean.class, MethodHandle.class,
 526                                                                                  MethodHandle.class));
 527                 NF_throwException      = new NamedFunction(MHI.getDeclaredMethod("throwException", Throwable.class));
 528 
 529                 NF_checkSpreadArgument.resolve();
 530                 NF_guardWithCatch.resolve();
 531                 NF_selectAlternative.resolve();
 532                 NF_throwException.resolve();
 533 
 534                 MH_castReference        = IMPL_LOOKUP.findStatic(MHI, "castReference",
 535                                             MethodType.methodType(Object.class, Class.class, Object.class));
 536                 MH_copyAsPrimitiveArray = IMPL_LOOKUP.findStatic(MHI, "copyAsPrimitiveArray",
 537                                             MethodType.methodType(Object.class, Wrapper.class, Object[].class));
 538                 MH_arrayIdentity        = IMPL_LOOKUP.findStatic(MHI, "identity",
 539                                             MethodType.methodType(Object[].class, Object[].class));
 540                 MH_fillNewArray         = IMPL_LOOKUP.findStatic(MHI, "fillNewArray",
 541                                             MethodType.methodType(Object[].class, Integer.class, Object[].class));
 542                 MH_fillNewTypedArray    = IMPL_LOOKUP.findStatic(MHI, "fillNewTypedArray",
 543                                             MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class));
 544             } catch (ReflectiveOperationException ex) {
 545                 throw newInternalError(ex);
 546             }
 547         }
 548     }
 549 
 550     /** Factory method:  Collect or filter selected argument(s). */
 551     static MethodHandle makeCollectArguments(MethodHandle target,
 552                 MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) {
 553         MethodType targetType = target.type();          // (a..., c, [b...])=>r
 554         MethodType collectorType = collector.type();    // (b...)=>c
 555         int collectArgCount = collectorType.parameterCount();
 556         Class<?> collectValType = collectorType.returnType();
 557         int collectValCount = (collectValType == void.class ? 0 : 1);
 558         MethodType srcType = targetType                 // (a..., [b...])=>r
 559                 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
 560         if (!retainOriginalArgs) {                      // (a..., b...)=>r
 561             srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList());
 562         }
 563         // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
 564         // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
 565         // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ]
 566 
 567         // Now build a LambdaForm.
 568         MethodType lambdaType = srcType.invokerType();
 569         Name[] names = arguments(2, lambdaType);
 570         final int collectNamePos = names.length - 2;
 571         final int targetNamePos  = names.length - 1;
 572 
 573         Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount);
 574         names[collectNamePos] = new Name(collector, (Object[]) collectorArgs);
 575 
 576         // Build argument array for the target.
 577         // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ].
 578         // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ].
 579         Name[] targetArgs = new Name[targetType.parameterCount()];
 580         int inputArgPos  = 1;  // incoming LF args to copy to target
 581         int targetArgPos = 0;  // fill pointer for targetArgs
 582         int chunk = collectArgPos;  // |headArgs|
 583         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 584         inputArgPos  += chunk;
 585         targetArgPos += chunk;
 586         if (collectValType != void.class) {
 587             targetArgs[targetArgPos++] = names[collectNamePos];
 588         }
 589         chunk = collectArgCount;
 590         if (retainOriginalArgs) {
 591             System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 592             targetArgPos += chunk;   // optionally pass on the collected chunk
 593         }
 594         inputArgPos += chunk;
 595         chunk = targetArgs.length - targetArgPos;  // all the rest
 596         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 597         assert(inputArgPos + chunk == collectNamePos);  // use of rest of input args also
 598         names[targetNamePos] = new Name(target, (Object[]) targetArgs);
 599 
 600         LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names);
 601         return SimpleMethodHandle.make(srcType, form);
 602     }
 603 
 604     @LambdaForm.Hidden
 605     static
 606     MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 607         return testResult ? target : fallback;
 608     }
 609 
 610     static
 611     MethodHandle makeGuardWithTest(MethodHandle test,
 612                                    MethodHandle target,
 613                                    MethodHandle fallback) {
 614         MethodType basicType = target.type().basicType();
 615         MethodHandle invokeBasic = MethodHandles.basicInvoker(basicType);
 616         int arity = basicType.parameterCount();
 617         int extraNames = 3;
 618         MethodType lambdaType = basicType.invokerType();
 619         Name[] names = arguments(extraNames, lambdaType);
 620 
 621         Object[] testArgs   = Arrays.copyOfRange(names, 1, 1 + arity, Object[].class);
 622         Object[] targetArgs = Arrays.copyOfRange(names, 0, 1 + arity, Object[].class);
 623 
 624         // call test
 625         names[arity + 1] = new Name(test, testArgs);
 626 
 627         // call selectAlternative
 628         Object[] selectArgs = { names[arity + 1], target, fallback };
 629         names[arity + 2] = new Name(Lazy.NF_selectAlternative, selectArgs);
 630         targetArgs[0] = names[arity + 2];
 631 
 632         // call target or fallback
 633         names[arity + 3] = new Name(new NamedFunction(invokeBasic), targetArgs);
 634 
 635         LambdaForm form = new LambdaForm("guard", lambdaType.parameterCount(), names);
 636         return SimpleMethodHandle.make(target.type(), form);
 637     }
 638 
 639     /**
 640      * The LambdaForm shape for catchException combinator is the following:
 641      * <blockquote><pre>{@code
 642      *  guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{
 643      *    t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L);
 644      *    t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L);
 645      *    t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L);
 646      *    t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L);
 647      *    t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L);
 648      *    t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L);
 649      *    t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L);
 650      *   t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I}
 651      * }</pre></blockquote>
 652      *
 653      * argL0 and argL2 are target and catcher method handles. argL1 is exception class.
 654      * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[]
 655      * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()).
 656      *
 657      * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms
 658      * among catchException combinators with the same basic type.
 659      */
 660     private static LambdaForm makeGuardWithCatchForm(MethodType basicType) {
 661         MethodType lambdaType = basicType.invokerType();
 662 
 663         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC);
 664         if (lform != null) {
 665             return lform;
 666         }
 667         final int THIS_MH      = 0;  // the BMH_LLLLL
 668         final int ARG_BASE     = 1;  // start of incoming arguments
 669         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 670 
 671         int nameCursor = ARG_LIMIT;
 672         final int GET_TARGET       = nameCursor++;
 673         final int GET_CLASS        = nameCursor++;
 674         final int GET_CATCHER      = nameCursor++;
 675         final int GET_COLLECT_ARGS = nameCursor++;
 676         final int GET_UNBOX_RESULT = nameCursor++;
 677         final int BOXED_ARGS       = nameCursor++;
 678         final int TRY_CATCH        = nameCursor++;
 679         final int UNBOX_RESULT     = nameCursor++;
 680 
 681         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 682 
 683         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 684         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
 685         names[GET_CLASS]        = new Name(data.getterFunction(1), names[THIS_MH]);
 686         names[GET_CATCHER]      = new Name(data.getterFunction(2), names[THIS_MH]);
 687         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]);
 688         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]);
 689 
 690         // FIXME: rework argument boxing/result unboxing logic for LF interpretation
 691 
 692         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
 693         MethodType collectArgsType = basicType.changeReturnType(Object.class);
 694         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
 695         Object[] args = new Object[invokeBasic.type().parameterCount()];
 696         args[0] = names[GET_COLLECT_ARGS];
 697         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
 698         names[BOXED_ARGS] = new Name(new NamedFunction(invokeBasic), args);
 699 
 700         // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L);
 701         Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]};
 702         names[TRY_CATCH] = new Name(Lazy.NF_guardWithCatch, gwcArgs);
 703 
 704         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
 705         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
 706         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
 707         names[UNBOX_RESULT] = new Name(new NamedFunction(invokeBasicUnbox), unboxArgs);
 708 
 709         lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names);
 710 
 711         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
 712     }
 713 
 714     static
 715     MethodHandle makeGuardWithCatch(MethodHandle target,
 716                                     Class<? extends Throwable> exType,
 717                                     MethodHandle catcher) {
 718         MethodType type = target.type();
 719         LambdaForm form = makeGuardWithCatchForm(type.basicType());
 720 
 721         // Prepare auxiliary method handles used during LambdaForm interpretation.
 722         // Box arguments and wrap them into Object[]: ValueConversions.array().
 723         MethodType varargsType = type.changeReturnType(Object[].class);
 724         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
 725         // Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore().
 726         MethodHandle unboxResult;
 727         if (type.returnType().isPrimitive()) {
 728             unboxResult = ValueConversions.unbox(type.returnType());
 729         } else {
 730             unboxResult = ValueConversions.identity();
 731         }
 732 
 733         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 734         BoundMethodHandle mh;
 735         try {
 736             mh = (BoundMethodHandle)
 737                     data.constructor().invokeBasic(type, form, (Object) target, (Object) exType, (Object) catcher,
 738                                                    (Object) collectArgs, (Object) unboxResult);
 739         } catch (Throwable ex) {
 740             throw uncaughtException(ex);
 741         }
 742         assert(mh.type() == type);
 743         return mh;
 744     }
 745 
 746     /**
 747      * Intrinsified during LambdaForm compilation
 748      * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}).
 749      */
 750     @LambdaForm.Hidden
 751     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
 752                                  Object... av) throws Throwable {
 753         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
 754         try {
 755             return target.asFixedArity().invokeWithArguments(av);
 756         } catch (Throwable t) {
 757             if (!exType.isInstance(t)) throw t;
 758             return catcher.asFixedArity().invokeWithArguments(prepend(t, av));
 759         }
 760     }
 761 
 762     /** Prepend an element {@code elem} to an {@code array}. */
 763     @LambdaForm.Hidden
 764     private static Object[] prepend(Object elem, Object[] array) {
 765         Object[] newArray = new Object[array.length+1];
 766         newArray[0] = elem;
 767         System.arraycopy(array, 0, newArray, 1, array.length);
 768         return newArray;
 769     }
 770 
 771     static
 772     MethodHandle throwException(MethodType type) {
 773         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 774         int arity = type.parameterCount();
 775         if (arity > 1) {
 776             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
 777             mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity));
 778             return mh;
 779         }
 780         return makePairwiseConvert(Lazy.NF_throwException.resolvedHandle(), type, 2);
 781     }
 782 
 783     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 784 
 785     static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2];
 786     static MethodHandle fakeMethodHandleInvoke(MemberName method) {
 787         int idx;
 788         assert(method.isMethodHandleInvoke());
 789         switch (method.getName()) {
 790         case "invoke":       idx = 0; break;
 791         case "invokeExact":  idx = 1; break;
 792         default:             throw new InternalError(method.getName());
 793         }
 794         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx];
 795         if (mh != null)  return mh;
 796         MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class,
 797                                                 MethodHandle.class, Object[].class);
 798         mh = throwException(type);
 799         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 800         if (!method.getInvocationType().equals(mh.type()))
 801             throw new InternalError(method.toString());
 802         mh = mh.withInternalMemberName(method);
 803         mh = mh.asVarargsCollector(Object[].class);
 804         assert(method.isVarargs());
 805         FAKE_METHOD_HANDLE_INVOKE[idx] = mh;
 806         return mh;
 807     }
 808 
 809     /**
 810      * Create an alias for the method handle which, when called,
 811      * appears to be called from the same class loader and protection domain
 812      * as hostClass.
 813      * This is an expensive no-op unless the method which is called
 814      * is sensitive to its caller.  A small number of system methods
 815      * are in this category, including Class.forName and Method.invoke.
 816      */
 817     static
 818     MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 819         return BindCaller.bindCaller(mh, hostClass);
 820     }
 821 
 822     // Put the whole mess into its own nested class.
 823     // That way we can lazily load the code and set up the constants.
 824     private static class BindCaller {
 825         static
 826         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 827             // Do not use this function to inject calls into system classes.
 828             if (hostClass == null
 829                 ||    (hostClass.isArray() ||
 830                        hostClass.isPrimitive() ||
 831                        hostClass.getName().startsWith("java.") ||
 832                        hostClass.getName().startsWith("sun."))) {
 833                 throw new InternalError();  // does not happen, and should not anyway
 834             }
 835             // For simplicity, convert mh to a varargs-like method.
 836             MethodHandle vamh = prepareForInvoker(mh);
 837             // Cache the result of makeInjectedInvoker once per argument class.
 838             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
 839             return restoreToType(bccInvoker.bindTo(vamh), mh.type(), mh.internalMemberName(), hostClass);
 840         }
 841 
 842         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
 843             Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
 844             if (hostClass.getClassLoader() != bcc.getClassLoader())
 845                 throw new InternalError(hostClass.getName()+" (CL)");
 846             try {
 847                 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
 848                     throw new InternalError(hostClass.getName()+" (PD)");
 849             } catch (SecurityException ex) {
 850                 // Self-check was blocked by security manager.  This is OK.
 851                 // In fact the whole try body could be turned into an assertion.
 852             }
 853             try {
 854                 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
 855                 init.invokeExact();  // force initialization of the class
 856             } catch (Throwable ex) {
 857                 throw uncaughtException(ex);
 858             }
 859             MethodHandle bccInvoker;
 860             try {
 861                 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
 862                 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
 863             } catch (ReflectiveOperationException ex) {
 864                 throw uncaughtException(ex);
 865             }
 866             // Test the invoker, to ensure that it really injects into the right place.
 867             try {
 868                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
 869                 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
 870             } catch (Throwable ex) {
 871                 throw new InternalError(ex);
 872             }
 873             return bccInvoker;
 874         }
 875         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
 876             @Override protected MethodHandle computeValue(Class<?> hostClass) {
 877                 return makeInjectedInvoker(hostClass);
 878             }
 879         };
 880 
 881         // Adapt mh so that it can be called directly from an injected invoker:
 882         private static MethodHandle prepareForInvoker(MethodHandle mh) {
 883             mh = mh.asFixedArity();
 884             MethodType mt = mh.type();
 885             int arity = mt.parameterCount();
 886             MethodHandle vamh = mh.asType(mt.generic());
 887             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 888             vamh = vamh.asSpreader(Object[].class, arity);
 889             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 890             return vamh;
 891         }
 892 
 893         // Undo the adapter effect of prepareForInvoker:
 894         private static MethodHandle restoreToType(MethodHandle vamh, MethodType type,
 895                                                   MemberName member,
 896                                                   Class<?> hostClass) {
 897             MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount());
 898             mh = mh.asType(type);
 899             mh = new WrappedMember(mh, type, member, hostClass);
 900             return mh;
 901         }
 902 
 903         private static final MethodHandle MH_checkCallerClass;
 904         static {
 905             final Class<?> THIS_CLASS = BindCaller.class;
 906             assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
 907             try {
 908                 MH_checkCallerClass = IMPL_LOOKUP
 909                     .findStatic(THIS_CLASS, "checkCallerClass",
 910                                 MethodType.methodType(boolean.class, Class.class, Class.class));
 911                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
 912             } catch (Throwable ex) {
 913                 throw new InternalError(ex);
 914             }
 915         }
 916 
 917         @CallerSensitive
 918         private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
 919             // This method is called via MH_checkCallerClass and so it's
 920             // correct to ask for the immediate caller here.
 921             Class<?> actual = Reflection.getCallerClass();
 922             if (actual != expected && actual != expected2)
 923                 throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
 924                                         +(expected == expected2 ? "" : ", or else "+expected2.getName()));
 925             return true;
 926         }
 927 
 928         private static final byte[] T_BYTES;
 929         static {
 930             final Object[] values = {null};
 931             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 932                     public Void run() {
 933                         try {
 934                             Class<T> tClass = T.class;
 935                             String tName = tClass.getName();
 936                             String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
 937                             java.net.URLConnection uconn = tClass.getResource(tResource).openConnection();
 938                             int len = uconn.getContentLength();
 939                             byte[] bytes = new byte[len];
 940                             try (java.io.InputStream str = uconn.getInputStream()) {
 941                                 int nr = str.read(bytes);
 942                                 if (nr != len)  throw new java.io.IOException(tResource);
 943                             }
 944                             values[0] = bytes;
 945                         } catch (java.io.IOException ex) {
 946                             throw new InternalError(ex);
 947                         }
 948                         return null;
 949                     }
 950                 });
 951             T_BYTES = (byte[]) values[0];
 952         }
 953 
 954         // The following class is used as a template for Unsafe.defineAnonymousClass:
 955         private static class T {
 956             static void init() { }  // side effect: initializes this class
 957             static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
 958                 return vamh.invokeExact(args);
 959             }
 960         }
 961     }
 962 
 963 
 964     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
 965     static class WrappedMember extends MethodHandle {
 966         private final MethodHandle target;
 967         private final MemberName member;
 968         private final Class<?> callerClass;
 969 
 970         private WrappedMember(MethodHandle target, MethodType type, MemberName member, Class<?> callerClass) {
 971             super(type, reinvokerForm(target));
 972             this.target = target;
 973             this.member = member;
 974             this.callerClass = callerClass;
 975         }
 976 
 977         @Override
 978         MethodHandle reinvokerTarget() {
 979             return target;
 980         }
 981         @Override
 982         public MethodHandle asTypeUncached(MethodType newType) {
 983             // This MH is an alias for target, except for the MemberName
 984             // Drop the MemberName if there is any conversion.
 985             return asTypeCache = target.asType(newType);
 986         }
 987         @Override
 988         MemberName internalMemberName() {
 989             return member;
 990         }
 991         @Override
 992         Class<?> internalCallerClass() {
 993             return callerClass;
 994         }
 995         @Override
 996         boolean isInvokeSpecial() {
 997             return target.isInvokeSpecial();
 998         }
 999         @Override
1000         MethodHandle viewAsType(MethodType newType) {
1001             return new WrappedMember(target, newType, member, callerClass);
1002         }
1003     }
1004 
1005     static MethodHandle makeWrappedMember(MethodHandle target, MemberName member) {
1006         if (member.equals(target.internalMemberName()))
1007             return target;
1008         return new WrappedMember(target, target.type(), member, null);
1009     }
1010 
1011     /// Collection of multiple arguments.
1012 
1013     private static MethodHandle findCollector(String name, int nargs, Class<?> rtype, Class<?>... ptypes) {
1014         MethodType type = MethodType.genericMethodType(nargs)
1015                 .changeReturnType(rtype)
1016                 .insertParameterTypes(0, ptypes);
1017         try {
1018             return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, name, type);
1019         } catch (ReflectiveOperationException ex) {
1020             return null;
1021         }
1022     }
1023 
1024     private static final Object[] NO_ARGS_ARRAY = {};
1025     private static Object[] makeArray(Object... args) { return args; }
1026     private static Object[] array() { return NO_ARGS_ARRAY; }
1027     private static Object[] array(Object a0)
1028                 { return makeArray(a0); }
1029     private static Object[] array(Object a0, Object a1)
1030                 { return makeArray(a0, a1); }
1031     private static Object[] array(Object a0, Object a1, Object a2)
1032                 { return makeArray(a0, a1, a2); }
1033     private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1034                 { return makeArray(a0, a1, a2, a3); }
1035     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1036                                   Object a4)
1037                 { return makeArray(a0, a1, a2, a3, a4); }
1038     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1039                                   Object a4, Object a5)
1040                 { return makeArray(a0, a1, a2, a3, a4, a5); }
1041     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1042                                   Object a4, Object a5, Object a6)
1043                 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1044     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1045                                   Object a4, Object a5, Object a6, Object a7)
1046                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1047     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1048                                   Object a4, Object a5, Object a6, Object a7,
1049                                   Object a8)
1050                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1051     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1052                                   Object a4, Object a5, Object a6, Object a7,
1053                                   Object a8, Object a9)
1054                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1055     private static MethodHandle[] makeArrays() {
1056         ArrayList<MethodHandle> mhs = new ArrayList<>();
1057         for (;;) {
1058             MethodHandle mh = findCollector("array", mhs.size(), Object[].class);
1059             if (mh == null)  break;
1060             mhs.add(mh);
1061         }
1062         assert(mhs.size() == 11);  // current number of methods
1063         return mhs.toArray(new MethodHandle[MAX_ARITY+1]);
1064     }
1065     private static final MethodHandle[] ARRAYS = makeArrays();
1066 
1067     // filling versions of the above:
1068     // using Integer len instead of int len and no varargs to avoid bootstrapping problems
1069     private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) {
1070         Object[] a = new Object[len];
1071         fillWithArguments(a, 0, args);
1072         return a;
1073     }
1074     private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) {
1075         Object[] a = Arrays.copyOf(example, len);
1076         assert(a.getClass() != Object[].class);
1077         fillWithArguments(a, 0, args);
1078         return a;
1079     }
1080     private static void fillWithArguments(Object[] a, int pos, Object... args) {
1081         System.arraycopy(args, 0, a, pos, args.length);
1082     }
1083     // using Integer pos instead of int pos to avoid bootstrapping problems
1084     private static Object[] fillArray(Integer pos, Object[] a, Object a0)
1085                 { fillWithArguments(a, pos, a0); return a; }
1086     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1)
1087                 { fillWithArguments(a, pos, a0, a1); return a; }
1088     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2)
1089                 { fillWithArguments(a, pos, a0, a1, a2); return a; }
1090     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3)
1091                 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; }
1092     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1093                                   Object a4)
1094                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; }
1095     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1096                                   Object a4, Object a5)
1097                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); 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)
1100                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; }
1101     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1102                                   Object a4, Object a5, Object a6, Object a7)
1103                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; }
1104     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1105                                   Object a4, Object a5, Object a6, Object a7,
1106                                   Object a8)
1107                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; }
1108     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1109                                   Object a4, Object a5, Object a6, Object a7,
1110                                   Object a8, Object a9)
1111                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; }
1112     private static MethodHandle[] makeFillArrays() {
1113         ArrayList<MethodHandle> mhs = new ArrayList<>();
1114         mhs.add(null);  // there is no empty fill; at least a0 is required
1115         for (;;) {
1116             MethodHandle mh = findCollector("fillArray", mhs.size(), Object[].class, Integer.class, Object[].class);
1117             if (mh == null)  break;
1118             mhs.add(mh);
1119         }
1120         assert(mhs.size() == 11);  // current number of methods
1121         return mhs.toArray(new MethodHandle[0]);
1122     }
1123     private static final MethodHandle[] FILL_ARRAYS = makeFillArrays();
1124 
1125     private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) {
1126         Object a = w.makeArray(boxes.length);
1127         w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length);
1128         return a;
1129     }
1130 
1131     /** Return a method handle that takes the indicated number of Object
1132      *  arguments and returns an Object array of them, as if for varargs.
1133      */
1134     static MethodHandle varargsArray(int nargs) {
1135         MethodHandle mh = ARRAYS[nargs];
1136         if (mh != null)  return mh;
1137         mh = findCollector("array", nargs, Object[].class);
1138         if (mh != null)  return ARRAYS[nargs] = mh;
1139         mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs);
1140         assert(assertCorrectArity(mh, nargs));
1141         return ARRAYS[nargs] = mh;
1142     }
1143 
1144     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1145         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1146         return true;
1147     }
1148 
1149     // Array identity function (used as Lazy.MH_arrayIdentity).
1150     static <T> T[] identity(T[] x) {
1151         return x;
1152     }
1153 
1154     private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) {
1155         // Build up the result mh as a sequence of fills like this:
1156         //   finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23))
1157         // The various fill(_,10*I,___*[J]) are reusable.
1158         int leftLen = Math.min(nargs, LEFT_ARGS);  // absorb some arguments immediately
1159         int rightLen = nargs - leftLen;
1160         MethodHandle leftCollector = newArray.bindTo(nargs);
1161         leftCollector = leftCollector.asCollector(Object[].class, leftLen);
1162         MethodHandle mh = finisher;
1163         if (rightLen > 0) {
1164             MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen);
1165             if (mh == Lazy.MH_arrayIdentity)
1166                 mh = rightFiller;
1167             else
1168                 mh = MethodHandles.collectArguments(mh, 0, rightFiller);
1169         }
1170         if (mh == Lazy.MH_arrayIdentity)
1171             mh = leftCollector;
1172         else
1173             mh = MethodHandles.collectArguments(mh, 0, leftCollector);
1174         return mh;
1175     }
1176 
1177     private static final int LEFT_ARGS = (FILL_ARRAYS.length - 1);
1178     private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1];
1179     /** fill_array_to_right(N).invoke(a, argL..arg[N-1])
1180      *  fills a[L]..a[N-1] with corresponding arguments,
1181      *  and then returns a.  The value L is a global constant (LEFT_ARGS).
1182      */
1183     private static MethodHandle fillToRight(int nargs) {
1184         MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs];
1185         if (filler != null)  return filler;
1186         filler = buildFiller(nargs);
1187         assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1));
1188         return FILL_ARRAY_TO_RIGHT[nargs] = filler;
1189     }
1190     private static MethodHandle buildFiller(int nargs) {
1191         if (nargs <= LEFT_ARGS)
1192             return Lazy.MH_arrayIdentity;  // no args to fill; return the array unchanged
1193         // we need room for both mh and a in mh.invoke(a, arg*[nargs])
1194         final int CHUNK = LEFT_ARGS;
1195         int rightLen = nargs % CHUNK;
1196         int midLen = nargs - rightLen;
1197         if (rightLen == 0) {
1198             midLen = nargs - (rightLen = CHUNK);
1199             if (FILL_ARRAY_TO_RIGHT[midLen] == null) {
1200                 // build some precursors from left to right
1201                 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK)
1202                     if (j > LEFT_ARGS)  fillToRight(j);
1203             }
1204         }
1205         if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS);
1206         assert(rightLen > 0);
1207         MethodHandle midFill = fillToRight(midLen);  // recursive fill
1208         MethodHandle rightFill = FILL_ARRAYS[rightLen].bindTo(midLen);  // [midLen..nargs-1]
1209         assert(midFill.type().parameterCount()   == 1 + midLen - LEFT_ARGS);
1210         assert(rightFill.type().parameterCount() == 1 + rightLen);
1211 
1212         // Combine the two fills:
1213         //   right(mid(a, x10..x19), x20..x23)
1214         // The final product will look like this:
1215         //   right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23)
1216         if (midLen == LEFT_ARGS)
1217             return rightFill;
1218         else
1219             return MethodHandles.collectArguments(rightFill, 0, midFill);
1220     }
1221 
1222     // Type-polymorphic version of varargs maker.
1223     private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS
1224         = new ClassValue<MethodHandle[]>() {
1225             @Override
1226             protected MethodHandle[] computeValue(Class<?> type) {
1227                 return new MethodHandle[256];
1228             }
1229     };
1230 
1231     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1232 
1233     /** Return a method handle that takes the indicated number of
1234      *  typed arguments and returns an array of them.
1235      *  The type argument is the array type.
1236      */
1237     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1238         Class<?> elemType = arrayType.getComponentType();
1239         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1240         // FIXME: Need more special casing and caching here.
1241         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1242             int slots = nargs;
1243             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1244             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1245                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1246             if (slots > MAX_ARRAY_SLOTS)
1247                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1248         }
1249         if (elemType == Object.class)
1250             return varargsArray(nargs);
1251         // other cases:  primitive arrays, subtypes of Object[]
1252         MethodHandle cache[] = TYPED_COLLECTORS.get(elemType);
1253         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1254         if (mh != null)  return mh;
1255         if (nargs == 0) {
1256             Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0);
1257             mh = MethodHandles.constant(arrayType, example);
1258         } else if (elemType.isPrimitive()) {
1259             MethodHandle builder = Lazy.MH_fillNewArray;
1260             MethodHandle producer = buildArrayProducer(arrayType);
1261             mh = buildVarargsArray(builder, producer, nargs);
1262         } else {
1263             Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class);
1264             Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType);
1265             MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example);
1266             MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed
1267             mh = buildVarargsArray(builder, producer, nargs);
1268         }
1269         mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)));
1270         assert(assertCorrectArity(mh, nargs));
1271         if (nargs < cache.length)
1272             cache[nargs] = mh;
1273         return mh;
1274     }
1275 
1276     private static MethodHandle buildArrayProducer(Class<?> arrayType) {
1277         Class<?> elemType = arrayType.getComponentType();
1278         assert(elemType.isPrimitive());
1279         return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType));
1280     }
1281 }