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 
  34 import sun.invoke.empty.Empty;
  35 import sun.invoke.util.ValueConversions;
  36 import sun.invoke.util.VerifyType;
  37 import sun.invoke.util.Wrapper;
  38 import sun.reflect.CallerSensitive;
  39 import sun.reflect.Reflection;
  40 import static java.lang.invoke.LambdaForm.*;
  41 import static java.lang.invoke.MethodHandleStatics.*;
  42 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  43 
  44 /**
  45  * Trusted implementation code for MethodHandle.
  46  * @author jrose
  47  */
  48 /*non-public*/ abstract class MethodHandleImpl {
  49     // Do not adjust this except for special platforms:
  50     private static final int MAX_ARITY;
  51     static {
  52         final Object[] values = { 255 };
  53         AccessController.doPrivileged(new PrivilegedAction<Void>() {
  54             @Override
  55             public Void run() {
  56                 values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255);
  57                 return null;
  58             }
  59         });
  60         MAX_ARITY = (Integer) values[0];
  61     }
  62 
  63     /// Factory methods to create method handles:
  64 
  65     static void initStatics() {
  66         // Trigger selected static initializations.
  67         MemberName.Factory.INSTANCE.getClass();
  68     }
  69 
  70     static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) {
  71         if (arrayClass == Object[].class)
  72             return (isSetter ? ArrayAccessor.OBJECT_ARRAY_SETTER : ArrayAccessor.OBJECT_ARRAY_GETTER);
  73         if (!arrayClass.isArray())
  74             throw newIllegalArgumentException("not an array: "+arrayClass);
  75         MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass);
  76         int cacheIndex = (isSetter ? ArrayAccessor.SETTER_INDEX : ArrayAccessor.GETTER_INDEX);
  77         MethodHandle mh = cache[cacheIndex];
  78         if (mh != null)  return mh;
  79         mh = ArrayAccessor.getAccessor(arrayClass, isSetter);
  80         MethodType correctType = ArrayAccessor.correctType(arrayClass, isSetter);
  81         if (mh.type() != correctType) {
  82             assert(mh.type().parameterType(0) == Object[].class);
  83             assert((isSetter ? mh.type().parameterType(2) : mh.type().returnType()) == Object.class);
  84             assert(isSetter || correctType.parameterType(0).getComponentType() == correctType.returnType());
  85             // safe to view non-strictly, because element type follows from array type
  86             mh = mh.viewAsType(correctType, false);
  87         }
  88         mh = makeIntrinsic(mh, (isSetter ? Intrinsic.ARRAY_STORE : Intrinsic.ARRAY_LOAD));
  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 = makeIntrinsic(getAccessor(Object[].class, false), Intrinsic.ARRAY_LOAD);
 115             cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, true),  Intrinsic.ARRAY_STORE);
 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 strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed
 183      * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double)
 184      * @return an adapter to the original handle with the desired new type,
 185      *          or the original target if the types are already identical
 186      *          or null if the adaptation cannot be made
 187      */
 188     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 189                                             boolean strict, boolean monobox) {
 190         MethodType dstType = target.type();
 191         assert(dstType.parameterCount() == target.type().parameterCount());
 192         if (srcType == dstType)
 193             return target;
 194         return makePairwiseConvertIndirect(target, srcType, strict, monobox);
 195     }
 196 
 197     private static int countNonNull(Object[] array) {
 198         int count = 0;
 199         for (Object x : array) {
 200             if (x != null)  ++count;
 201         }
 202         return count;
 203     }
 204 
 205     static MethodHandle makePairwiseConvertIndirect(MethodHandle target, MethodType srcType,
 206                                                     boolean strict, boolean monobox) {
 207         // Calculate extra arguments (temporaries) required in the names array.
 208         Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox);
 209         final int INARG_COUNT = srcType.parameterCount();
 210         int convCount = countNonNull(convSpecs);
 211         boolean retConv = (convSpecs[INARG_COUNT] != null);
 212         boolean retVoid = srcType.returnType() == void.class;
 213         if (retConv && retVoid) {
 214             convCount -= 1;
 215             retConv = false;
 216         }
 217 
 218         final int IN_MH         = 0;
 219         final int INARG_BASE    = 1;
 220         final int INARG_LIMIT   = INARG_BASE + INARG_COUNT;
 221         final int NAME_LIMIT    = INARG_LIMIT + convCount + 1;
 222         final int RETURN_CONV   = (!retConv ? -1         : NAME_LIMIT - 1);
 223         final int OUT_CALL      = (!retConv ? NAME_LIMIT : RETURN_CONV) - 1;
 224         final int RESULT        = (retVoid ? -1 : NAME_LIMIT - 1);
 225 
 226         // Now build a LambdaForm.
 227         MethodType lambdaType = srcType.basicType().invokerType();
 228         Name[] names = arguments(NAME_LIMIT - INARG_LIMIT, lambdaType);
 229 
 230         // Collect the arguments to the outgoing call, maybe with conversions:
 231         final int OUTARG_BASE = 0;  // target MH is Name.function, name Name.arguments[0]
 232         Object[] outArgs = new Object[OUTARG_BASE + INARG_COUNT];
 233 
 234         int nameCursor = INARG_LIMIT;
 235         for (int i = 0; i < INARG_COUNT; i++) {
 236             Object convSpec = convSpecs[i];
 237             if (convSpec == null) {
 238                 // do nothing: difference is trivial
 239                 outArgs[OUTARG_BASE + i] = names[INARG_BASE + i];
 240                 continue;
 241             }
 242 
 243             Name conv;
 244             if (convSpec instanceof Class) {
 245                 Class<?> convClass = (Class<?>) convSpec;
 246                 conv = new Name(Lazy.MH_castReference, convClass, names[INARG_BASE + i]);
 247             } else {
 248                 MethodHandle fn = (MethodHandle) convSpec;
 249                 conv = new Name(fn, names[INARG_BASE + i]);
 250             }
 251             assert(names[nameCursor] == null);
 252             names[nameCursor++] = conv;
 253             assert(outArgs[OUTARG_BASE + i] == null);
 254             outArgs[OUTARG_BASE + i] = conv;
 255         }
 256 
 257         // Build argument array for the call.
 258         assert(nameCursor == OUT_CALL);
 259         names[OUT_CALL] = new Name(target, outArgs);
 260 
 261         Object convSpec = convSpecs[INARG_COUNT];
 262         if (!retConv) {
 263             assert(OUT_CALL == names.length-1);
 264         } else {
 265             Name conv;
 266             if (convSpec == void.class) {
 267                 conv = new Name(LambdaForm.constantZero(BasicType.basicType(srcType.returnType())));
 268             } else if (convSpec instanceof Class) {
 269                 Class<?> convClass = (Class<?>) convSpec;
 270                 conv = new Name(Lazy.MH_castReference, convClass, names[OUT_CALL]);
 271             } else {
 272                 MethodHandle fn = (MethodHandle) convSpec;
 273                 if (fn.type().parameterCount() == 0)
 274                     conv = new Name(fn);  // don't pass retval to void conversion
 275                 else
 276                     conv = new Name(fn, names[OUT_CALL]);
 277             }
 278             assert(names[RETURN_CONV] == null);
 279             names[RETURN_CONV] = conv;
 280             assert(RETURN_CONV == names.length-1);
 281         }
 282 
 283         LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names, RESULT);
 284         return SimpleMethodHandle.make(srcType, form);
 285     }
 286 
 287     /**
 288      * Identity function, with reference cast.
 289      * @param t an arbitrary reference type
 290      * @param x an arbitrary reference value
 291      * @return the same value x
 292      */
 293     @ForceInline
 294     @SuppressWarnings("unchecked")
 295     static <T,U> T castReference(Class<? extends T> t, U x) {
 296         // inlined Class.cast because we can't ForceInline it
 297         if (x != null && !t.isInstance(x))
 298             throw newClassCastException(t, x);
 299         return (T) x;
 300     }
 301 
 302     private static ClassCastException newClassCastException(Class<?> t, Object obj) {
 303         return new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + t.getName());
 304     }
 305 
 306     static Object[] computeValueConversions(MethodType srcType, MethodType dstType,
 307                                             boolean strict, boolean monobox) {
 308         final int INARG_COUNT = srcType.parameterCount();
 309         Object[] convSpecs = new Object[INARG_COUNT+1];
 310         for (int i = 0; i <= INARG_COUNT; i++) {
 311             boolean isRet = (i == INARG_COUNT);
 312             Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i);
 313             Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i);
 314             if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) {
 315                 convSpecs[i] = valueConversion(src, dst, strict, monobox);
 316             }
 317         }
 318         return convSpecs;
 319     }
 320     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 321                                             boolean strict) {
 322         return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false);
 323     }
 324 
 325     /**
 326      * Find a conversion function from the given source to the given destination.
 327      * This conversion function will be used as a LF NamedFunction.
 328      * Return a Class object if a simple cast is needed.
 329      * Return void.class if void is involved.
 330      */
 331     static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) {
 332         assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict));  // caller responsibility
 333         if (dst == void.class)
 334             return dst;
 335         MethodHandle fn;
 336         if (src.isPrimitive()) {
 337             if (src == void.class) {
 338                 return void.class;  // caller must recognize this specially
 339             } else if (dst.isPrimitive()) {
 340                 // Examples: int->byte, byte->int, boolean->int (!strict)
 341                 fn = ValueConversions.convertPrimitive(src, dst);
 342             } else {
 343                 // Examples: int->Integer, boolean->Object, float->Number
 344                 Wrapper wsrc = Wrapper.forPrimitiveType(src);
 345                 fn = ValueConversions.boxExact(wsrc);
 346                 assert(fn.type().parameterType(0) == wsrc.primitiveType());
 347                 assert(fn.type().returnType() == wsrc.wrapperType());
 348                 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) {
 349                     // Corner case, such as int->Long, which will probably fail.
 350                     MethodType mt = MethodType.methodType(dst, src);
 351                     if (strict)
 352                         fn = fn.asType(mt);
 353                     else
 354                         fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false);
 355                 }
 356             }
 357         } else if (dst.isPrimitive()) {
 358             Wrapper wdst = Wrapper.forPrimitiveType(dst);
 359             if (monobox || src == wdst.wrapperType()) {
 360                 // Use a strongly-typed unboxer, if possible.
 361                 fn = ValueConversions.unboxExact(wdst, strict);
 362             } else {
 363                 // Examples:  Object->int, Number->int, Comparable->int, Byte->int
 364                 // must include additional conversions
 365                 // src must be examined at runtime, to detect Byte, Character, etc.
 366                 fn = (strict
 367                         ? ValueConversions.unboxWiden(wdst)
 368                         : ValueConversions.unboxCast(wdst));
 369             }
 370         } else {
 371             // Simple reference conversion.
 372             // Note:  Do not check for a class hierarchy relation
 373             // between src and dst.  In all cases a 'null' argument
 374             // will pass the cast conversion.
 375             return dst;
 376         }
 377         assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn);
 378         return fn;
 379     }
 380 
 381     static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
 382         MethodType type = target.type();
 383         int last = type.parameterCount() - 1;
 384         if (type.parameterType(last) != arrayType)
 385             target = target.asType(type.changeParameterType(last, arrayType));
 386         target = target.asFixedArity();  // make sure this attribute is turned off
 387         return new AsVarargsCollector(target, arrayType);
 388     }
 389 
 390     private static final class AsVarargsCollector extends DelegatingMethodHandle {
 391         private final MethodHandle target;
 392         private final Class<?> arrayType;
 393         private @Stable MethodHandle asCollectorCache;
 394 
 395         AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
 396             this(target.type(), target, arrayType);
 397         }
 398         AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) {
 399             super(type, target);
 400             this.target = target;
 401             this.arrayType = arrayType;
 402             this.asCollectorCache = target.asCollector(arrayType, 0);
 403         }
 404 
 405         @Override
 406         public boolean isVarargsCollector() {
 407             return true;
 408         }
 409 
 410         @Override
 411         protected MethodHandle getTarget() {
 412             return target;
 413         }
 414 
 415         @Override
 416         public MethodHandle asFixedArity() {
 417             return target;
 418         }
 419 
 420         @Override
 421         MethodHandle setVarargs(MemberName member) {
 422             if (member.isVarargs())  return this;
 423             return asFixedArity();
 424         }
 425 
 426         @Override
 427         public MethodHandle asTypeUncached(MethodType newType) {
 428             MethodType type = this.type();
 429             int collectArg = type.parameterCount() - 1;
 430             int newArity = newType.parameterCount();
 431             if (newArity == collectArg+1 &&
 432                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 433                 // if arity and trailing parameter are compatible, do normal thing
 434                 return asTypeCache = asFixedArity().asType(newType);
 435             }
 436             // check cache
 437             MethodHandle acc = asCollectorCache;
 438             if (acc != null && acc.type().parameterCount() == newArity)
 439                 return asTypeCache = acc.asType(newType);
 440             // build and cache a collector
 441             int arrayLength = newArity - collectArg;
 442             MethodHandle collector;
 443             try {
 444                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 445                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 446             } catch (IllegalArgumentException ex) {
 447                 throw new WrongMethodTypeException("cannot build collector", ex);
 448             }
 449             asCollectorCache = collector;
 450             return asTypeCache = collector.asType(newType);
 451         }
 452 
 453         @Override
 454         boolean viewAsTypeChecks(MethodType newType, boolean strict) {
 455             super.viewAsTypeChecks(newType, true);
 456             if (strict) return true;
 457             // extra assertion for non-strict checks:
 458             assert (type().lastParameterType().getComponentType()
 459                     .isAssignableFrom(
 460                             newType.lastParameterType().getComponentType()))
 461                     : Arrays.asList(this, newType);
 462             return true;
 463         }
 464     }
 465 
 466     /** Factory method:  Spread selected argument. */
 467     static MethodHandle makeSpreadArguments(MethodHandle target,
 468                                             Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
 469         MethodType targetType = target.type();
 470 
 471         for (int i = 0; i < spreadArgCount; i++) {
 472             Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i);
 473             if (arg == null)  arg = Object.class;
 474             targetType = targetType.changeParameterType(spreadArgPos + i, arg);
 475         }
 476         target = target.asType(targetType);
 477 
 478         MethodType srcType = targetType
 479                 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType);
 480         // Now build a LambdaForm.
 481         MethodType lambdaType = srcType.invokerType();
 482         Name[] names = arguments(spreadArgCount + 2, lambdaType);
 483         int nameCursor = lambdaType.parameterCount();
 484         int[] indexes = new int[targetType.parameterCount()];
 485 
 486         for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) {
 487             Class<?> src = lambdaType.parameterType(i);
 488             if (i == spreadArgPos) {
 489                 // Spread the array.
 490                 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType);
 491                 Name array = names[argIndex];
 492                 names[nameCursor++] = new Name(Lazy.NF_checkSpreadArgument, array, spreadArgCount);
 493                 for (int j = 0; j < spreadArgCount; i++, j++) {
 494                     indexes[i] = nameCursor;
 495                     names[nameCursor++] = new Name(aload, array, j);
 496                 }
 497             } else if (i < indexes.length) {
 498                 indexes[i] = argIndex;
 499             }
 500         }
 501         assert(nameCursor == names.length-1);  // leave room for the final call
 502 
 503         // Build argument array for the call.
 504         Name[] targetArgs = new Name[targetType.parameterCount()];
 505         for (int i = 0; i < targetType.parameterCount(); i++) {
 506             int idx = indexes[i];
 507             targetArgs[i] = names[idx];
 508         }
 509         names[names.length - 1] = new Name(target, (Object[]) targetArgs);
 510 
 511         LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names);
 512         return SimpleMethodHandle.make(srcType, form);
 513     }
 514 
 515     static void checkSpreadArgument(Object av, int n) {
 516         if (av == null) {
 517             if (n == 0)  return;
 518         } else if (av instanceof Object[]) {
 519             int len = ((Object[])av).length;
 520             if (len == n)  return;
 521         } else {
 522             int len = java.lang.reflect.Array.getLength(av);
 523             if (len == n)  return;
 524         }
 525         // fall through to error:
 526         throw newIllegalArgumentException("array is not of length "+n);
 527     }
 528 
 529     /**
 530      * Pre-initialized NamedFunctions for bootstrapping purposes.
 531      * Factored in an inner class to delay initialization until first usage.
 532      */
 533     private static class Lazy {
 534         private static final Class<?> MHI = MethodHandleImpl.class;
 535 
 536         static final NamedFunction NF_checkSpreadArgument;
 537         static final NamedFunction NF_guardWithCatch;
 538         static final NamedFunction NF_throwException;
 539 
 540         static final MethodHandle MH_castReference;
 541         static final MethodHandle MH_selectAlternative;
 542         static final MethodHandle MH_copyAsPrimitiveArray;
 543         static final MethodHandle MH_fillNewTypedArray;
 544         static final MethodHandle MH_fillNewArray;
 545         static final MethodHandle MH_arrayIdentity;
 546 
 547         static {
 548             try {
 549                 NF_checkSpreadArgument = new NamedFunction(MHI.getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
 550                 NF_guardWithCatch      = new NamedFunction(MHI.getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
 551                                                                                  MethodHandle.class, Object[].class));
 552                 NF_throwException      = new NamedFunction(MHI.getDeclaredMethod("throwException", Throwable.class));
 553 
 554                 NF_checkSpreadArgument.resolve();
 555                 NF_guardWithCatch.resolve();
 556                 NF_throwException.resolve();
 557 
 558                 MH_castReference        = IMPL_LOOKUP.findStatic(MHI, "castReference",
 559                                             MethodType.methodType(Object.class, Class.class, Object.class));
 560                 MH_copyAsPrimitiveArray = IMPL_LOOKUP.findStatic(MHI, "copyAsPrimitiveArray",
 561                                             MethodType.methodType(Object.class, Wrapper.class, Object[].class));
 562                 MH_arrayIdentity        = IMPL_LOOKUP.findStatic(MHI, "identity",
 563                                             MethodType.methodType(Object[].class, Object[].class));
 564                 MH_fillNewArray         = IMPL_LOOKUP.findStatic(MHI, "fillNewArray",
 565                                             MethodType.methodType(Object[].class, Integer.class, Object[].class));
 566                 MH_fillNewTypedArray    = IMPL_LOOKUP.findStatic(MHI, "fillNewTypedArray",
 567                                             MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class));
 568 
 569                 MH_selectAlternative    = makeIntrinsic(
 570                         IMPL_LOOKUP.findStatic(MHI, "selectAlternative",
 571                                 MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class)),
 572                         Intrinsic.SELECT_ALTERNATIVE);
 573             } catch (ReflectiveOperationException ex) {
 574                 throw newInternalError(ex);
 575             }
 576         }
 577     }
 578 
 579     /** Factory method:  Collect or filter selected argument(s). */
 580     static MethodHandle makeCollectArguments(MethodHandle target,
 581                 MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) {
 582         MethodType targetType = target.type();          // (a..., c, [b...])=>r
 583         MethodType collectorType = collector.type();    // (b...)=>c
 584         int collectArgCount = collectorType.parameterCount();
 585         Class<?> collectValType = collectorType.returnType();
 586         int collectValCount = (collectValType == void.class ? 0 : 1);
 587         MethodType srcType = targetType                 // (a..., [b...])=>r
 588                 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
 589         if (!retainOriginalArgs) {                      // (a..., b...)=>r
 590             srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList());
 591         }
 592         // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
 593         // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
 594         // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ]
 595 
 596         // Now build a LambdaForm.
 597         MethodType lambdaType = srcType.invokerType();
 598         Name[] names = arguments(2, lambdaType);
 599         final int collectNamePos = names.length - 2;
 600         final int targetNamePos  = names.length - 1;
 601 
 602         Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount);
 603         names[collectNamePos] = new Name(collector, (Object[]) collectorArgs);
 604 
 605         // Build argument array for the target.
 606         // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ].
 607         // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ].
 608         Name[] targetArgs = new Name[targetType.parameterCount()];
 609         int inputArgPos  = 1;  // incoming LF args to copy to target
 610         int targetArgPos = 0;  // fill pointer for targetArgs
 611         int chunk = collectArgPos;  // |headArgs|
 612         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 613         inputArgPos  += chunk;
 614         targetArgPos += chunk;
 615         if (collectValType != void.class) {
 616             targetArgs[targetArgPos++] = names[collectNamePos];
 617         }
 618         chunk = collectArgCount;
 619         if (retainOriginalArgs) {
 620             System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 621             targetArgPos += chunk;   // optionally pass on the collected chunk
 622         }
 623         inputArgPos += chunk;
 624         chunk = targetArgs.length - targetArgPos;  // all the rest
 625         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 626         assert(inputArgPos + chunk == collectNamePos);  // use of rest of input args also
 627         names[targetNamePos] = new Name(target, (Object[]) targetArgs);
 628 
 629         LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names);
 630         return SimpleMethodHandle.make(srcType, form);
 631     }
 632 
 633     @LambdaForm.Hidden
 634     static
 635     MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 636         return testResult ? target : fallback;
 637     }
 638 
 639     static
 640     MethodHandle makeGuardWithTest(MethodHandle test,
 641                                    MethodHandle target,
 642                                    MethodHandle fallback) {
 643         MethodType type = target.type();
 644         assert(test.type().equals(type.changeReturnType(boolean.class)) && fallback.type().equals(type));
 645         MethodType basicType = type.basicType();
 646         LambdaForm form = makeGuardWithTestForm(basicType);
 647         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL();
 648         BoundMethodHandle mh;
 649         try {
 650             mh = (BoundMethodHandle)
 651                     data.constructor().invokeBasic(type, form,
 652                         (Object) test, (Object) target, (Object) fallback);
 653         } catch (Throwable ex) {
 654             throw uncaughtException(ex);
 655         }
 656         assert(mh.type() == type);
 657         return mh;
 658     }
 659 
 660     static
 661     LambdaForm makeGuardWithTestForm(MethodType basicType) {
 662         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWT);
 663         if (lform != null)  return lform;
 664         final int THIS_MH      = 0;  // the BMH_LLL
 665         final int ARG_BASE     = 1;  // start of incoming arguments
 666         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 667         int nameCursor = ARG_LIMIT;
 668         final int GET_TEST     = nameCursor++;
 669         final int GET_TARGET   = nameCursor++;
 670         final int GET_FALLBACK = nameCursor++;
 671         final int CALL_TEST    = nameCursor++;
 672         final int SELECT_ALT   = nameCursor++;
 673         final int CALL_TARGET  = nameCursor++;
 674         assert(CALL_TARGET == SELECT_ALT+1);  // must be true to trigger IBG.emitSelectAlternative
 675 
 676         MethodType lambdaType = basicType.invokerType();
 677         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 678 
 679         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL();
 680         names[THIS_MH] = names[THIS_MH].withConstraint(data);
 681         names[GET_TEST]     = new Name(data.getterFunction(0), names[THIS_MH]);
 682         names[GET_TARGET]   = new Name(data.getterFunction(1), names[THIS_MH]);
 683         names[GET_FALLBACK] = new Name(data.getterFunction(2), names[THIS_MH]);
 684 
 685         Object[] invokeArgs = Arrays.copyOfRange(names, 0, ARG_LIMIT, Object[].class);
 686 
 687         // call test
 688         MethodType testType = basicType.changeReturnType(boolean.class).basicType();
 689         invokeArgs[0] = names[GET_TEST];
 690         names[CALL_TEST] = new Name(testType, invokeArgs);
 691 
 692         // call selectAlternative
 693         names[SELECT_ALT] = new Name(Lazy.MH_selectAlternative, names[CALL_TEST],
 694                                      names[GET_TARGET], names[GET_FALLBACK]);
 695 
 696         // call target or fallback
 697         invokeArgs[0] = names[SELECT_ALT];
 698         names[CALL_TARGET] = new Name(basicType, invokeArgs);
 699 
 700         lform = new LambdaForm("guard", lambdaType.parameterCount(), names);
 701 
 702         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform);
 703     }
 704 
 705     /**
 706      * The LambdaForm shape for catchException combinator is the following:
 707      * <blockquote><pre>{@code
 708      *  guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{
 709      *    t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L);
 710      *    t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L);
 711      *    t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L);
 712      *    t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L);
 713      *    t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L);
 714      *    t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L);
 715      *    t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L);
 716      *   t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I}
 717      * }</pre></blockquote>
 718      *
 719      * argL0 and argL2 are target and catcher method handles. argL1 is exception class.
 720      * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[]
 721      * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()).
 722      *
 723      * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms
 724      * among catchException combinators with the same basic type.
 725      */
 726     private static LambdaForm makeGuardWithCatchForm(MethodType basicType) {
 727         MethodType lambdaType = basicType.invokerType();
 728 
 729         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC);
 730         if (lform != null) {
 731             return lform;
 732         }
 733         final int THIS_MH      = 0;  // the BMH_LLLLL
 734         final int ARG_BASE     = 1;  // start of incoming arguments
 735         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 736 
 737         int nameCursor = ARG_LIMIT;
 738         final int GET_TARGET       = nameCursor++;
 739         final int GET_CLASS        = nameCursor++;
 740         final int GET_CATCHER      = nameCursor++;
 741         final int GET_COLLECT_ARGS = nameCursor++;
 742         final int GET_UNBOX_RESULT = nameCursor++;
 743         final int BOXED_ARGS       = nameCursor++;
 744         final int TRY_CATCH        = nameCursor++;
 745         final int UNBOX_RESULT     = nameCursor++;
 746 
 747         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 748 
 749         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 750         names[THIS_MH]          = names[THIS_MH].withConstraint(data);
 751         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
 752         names[GET_CLASS]        = new Name(data.getterFunction(1), names[THIS_MH]);
 753         names[GET_CATCHER]      = new Name(data.getterFunction(2), names[THIS_MH]);
 754         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]);
 755         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]);
 756 
 757         // FIXME: rework argument boxing/result unboxing logic for LF interpretation
 758 
 759         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
 760         MethodType collectArgsType = basicType.changeReturnType(Object.class);
 761         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
 762         Object[] args = new Object[invokeBasic.type().parameterCount()];
 763         args[0] = names[GET_COLLECT_ARGS];
 764         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
 765         names[BOXED_ARGS] = new Name(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH), args);
 766 
 767         // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L);
 768         Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]};
 769         names[TRY_CATCH] = new Name(Lazy.NF_guardWithCatch, gwcArgs);
 770 
 771         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
 772         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
 773         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
 774         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 775 
 776         lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names);
 777 
 778         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
 779     }
 780 
 781     static
 782     MethodHandle makeGuardWithCatch(MethodHandle target,
 783                                     Class<? extends Throwable> exType,
 784                                     MethodHandle catcher) {
 785         MethodType type = target.type();
 786         LambdaForm form = makeGuardWithCatchForm(type.basicType());
 787 
 788         // Prepare auxiliary method handles used during LambdaForm interpretation.
 789         // Box arguments and wrap them into Object[]: ValueConversions.array().
 790         MethodType varargsType = type.changeReturnType(Object[].class);
 791         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
 792         // Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore().
 793         MethodHandle unboxResult;
 794         Class<?> rtype = type.returnType();
 795         if (rtype.isPrimitive()) {
 796             if (rtype == void.class) {
 797                 unboxResult = ValueConversions.ignore();
 798             } else {
 799                 Wrapper w = Wrapper.forPrimitiveType(type.returnType());
 800                 unboxResult = ValueConversions.unboxExact(w);
 801             }
 802         } else {
 803             unboxResult = MethodHandles.identity(Object.class);
 804         }
 805 
 806         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 807         BoundMethodHandle mh;
 808         try {
 809             mh = (BoundMethodHandle)
 810                     data.constructor().invokeBasic(type, form, (Object) target, (Object) exType, (Object) catcher,
 811                                                    (Object) collectArgs, (Object) unboxResult);
 812         } catch (Throwable ex) {
 813             throw uncaughtException(ex);
 814         }
 815         assert(mh.type() == type);
 816         return mh;
 817     }
 818 
 819     /**
 820      * Intrinsified during LambdaForm compilation
 821      * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}).
 822      */
 823     @LambdaForm.Hidden
 824     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
 825                                  Object... av) throws Throwable {
 826         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
 827         try {
 828             return target.asFixedArity().invokeWithArguments(av);
 829         } catch (Throwable t) {
 830             if (!exType.isInstance(t)) throw t;
 831             return catcher.asFixedArity().invokeWithArguments(prepend(t, av));
 832         }
 833     }
 834 
 835     /** Prepend an element {@code elem} to an {@code array}. */
 836     @LambdaForm.Hidden
 837     private static Object[] prepend(Object elem, Object[] array) {
 838         Object[] newArray = new Object[array.length+1];
 839         newArray[0] = elem;
 840         System.arraycopy(array, 0, newArray, 1, array.length);
 841         return newArray;
 842     }
 843 
 844     static
 845     MethodHandle throwException(MethodType type) {
 846         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 847         int arity = type.parameterCount();
 848         if (arity > 1) {
 849             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
 850             mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity));
 851             return mh;
 852         }
 853         return makePairwiseConvert(Lazy.NF_throwException.resolvedHandle(), type, false, true);
 854     }
 855 
 856     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 857 
 858     static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2];
 859     static MethodHandle fakeMethodHandleInvoke(MemberName method) {
 860         int idx;
 861         assert(method.isMethodHandleInvoke());
 862         switch (method.getName()) {
 863         case "invoke":       idx = 0; break;
 864         case "invokeExact":  idx = 1; break;
 865         default:             throw new InternalError(method.getName());
 866         }
 867         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx];
 868         if (mh != null)  return mh;
 869         MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class,
 870                                                 MethodHandle.class, Object[].class);
 871         mh = throwException(type);
 872         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 873         if (!method.getInvocationType().equals(mh.type()))
 874             throw new InternalError(method.toString());
 875         mh = mh.withInternalMemberName(method, false);
 876         mh = mh.asVarargsCollector(Object[].class);
 877         assert(method.isVarargs());
 878         FAKE_METHOD_HANDLE_INVOKE[idx] = mh;
 879         return mh;
 880     }
 881 
 882     /**
 883      * Create an alias for the method handle which, when called,
 884      * appears to be called from the same class loader and protection domain
 885      * as hostClass.
 886      * This is an expensive no-op unless the method which is called
 887      * is sensitive to its caller.  A small number of system methods
 888      * are in this category, including Class.forName and Method.invoke.
 889      */
 890     static
 891     MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 892         return BindCaller.bindCaller(mh, hostClass);
 893     }
 894 
 895     // Put the whole mess into its own nested class.
 896     // That way we can lazily load the code and set up the constants.
 897     private static class BindCaller {
 898         static
 899         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 900             // Do not use this function to inject calls into system classes.
 901             if (hostClass == null
 902                 ||    (hostClass.isArray() ||
 903                        hostClass.isPrimitive() ||
 904                        hostClass.getName().startsWith("java.") ||
 905                        hostClass.getName().startsWith("sun."))) {
 906                 throw new InternalError();  // does not happen, and should not anyway
 907             }
 908             // For simplicity, convert mh to a varargs-like method.
 909             MethodHandle vamh = prepareForInvoker(mh);
 910             // Cache the result of makeInjectedInvoker once per argument class.
 911             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
 912             return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass);
 913         }
 914 
 915         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
 916             Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
 917             if (hostClass.getClassLoader() != bcc.getClassLoader())
 918                 throw new InternalError(hostClass.getName()+" (CL)");
 919             try {
 920                 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
 921                     throw new InternalError(hostClass.getName()+" (PD)");
 922             } catch (SecurityException ex) {
 923                 // Self-check was blocked by security manager.  This is OK.
 924                 // In fact the whole try body could be turned into an assertion.
 925             }
 926             try {
 927                 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
 928                 init.invokeExact();  // force initialization of the class
 929             } catch (Throwable ex) {
 930                 throw uncaughtException(ex);
 931             }
 932             MethodHandle bccInvoker;
 933             try {
 934                 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
 935                 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
 936             } catch (ReflectiveOperationException ex) {
 937                 throw uncaughtException(ex);
 938             }
 939             // Test the invoker, to ensure that it really injects into the right place.
 940             try {
 941                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
 942                 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
 943             } catch (Throwable ex) {
 944                 throw new InternalError(ex);
 945             }
 946             return bccInvoker;
 947         }
 948         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
 949             @Override protected MethodHandle computeValue(Class<?> hostClass) {
 950                 return makeInjectedInvoker(hostClass);
 951             }
 952         };
 953 
 954         // Adapt mh so that it can be called directly from an injected invoker:
 955         private static MethodHandle prepareForInvoker(MethodHandle mh) {
 956             mh = mh.asFixedArity();
 957             MethodType mt = mh.type();
 958             int arity = mt.parameterCount();
 959             MethodHandle vamh = mh.asType(mt.generic());
 960             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 961             vamh = vamh.asSpreader(Object[].class, arity);
 962             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 963             return vamh;
 964         }
 965 
 966         // Undo the adapter effect of prepareForInvoker:
 967         private static MethodHandle restoreToType(MethodHandle vamh,
 968                                                   MethodHandle original,
 969                                                   Class<?> hostClass) {
 970             MethodType type = original.type();
 971             MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount());
 972             MemberName member = original.internalMemberName();
 973             mh = mh.asType(type);
 974             mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass);
 975             return mh;
 976         }
 977 
 978         private static final MethodHandle MH_checkCallerClass;
 979         static {
 980             final Class<?> THIS_CLASS = BindCaller.class;
 981             assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
 982             try {
 983                 MH_checkCallerClass = IMPL_LOOKUP
 984                     .findStatic(THIS_CLASS, "checkCallerClass",
 985                                 MethodType.methodType(boolean.class, Class.class, Class.class));
 986                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
 987             } catch (Throwable ex) {
 988                 throw new InternalError(ex);
 989             }
 990         }
 991 
 992         @CallerSensitive
 993         private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
 994             // This method is called via MH_checkCallerClass and so it's
 995             // correct to ask for the immediate caller here.
 996             Class<?> actual = Reflection.getCallerClass();
 997             if (actual != expected && actual != expected2)
 998                 throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
 999                                         +(expected == expected2 ? "" : ", or else "+expected2.getName()));
1000             return true;
1001         }
1002 
1003         private static final byte[] T_BYTES;
1004         static {
1005             final Object[] values = {null};
1006             AccessController.doPrivileged(new PrivilegedAction<Void>() {
1007                     public Void run() {
1008                         try {
1009                             Class<T> tClass = T.class;
1010                             String tName = tClass.getName();
1011                             String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
1012                             java.net.URLConnection uconn = tClass.getResource(tResource).openConnection();
1013                             int len = uconn.getContentLength();
1014                             byte[] bytes = new byte[len];
1015                             try (java.io.InputStream str = uconn.getInputStream()) {
1016                                 int nr = str.read(bytes);
1017                                 if (nr != len)  throw new java.io.IOException(tResource);
1018                             }
1019                             values[0] = bytes;
1020                         } catch (java.io.IOException ex) {
1021                             throw new InternalError(ex);
1022                         }
1023                         return null;
1024                     }
1025                 });
1026             T_BYTES = (byte[]) values[0];
1027         }
1028 
1029         // The following class is used as a template for Unsafe.defineAnonymousClass:
1030         private static class T {
1031             static void init() { }  // side effect: initializes this class
1032             static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
1033                 return vamh.invokeExact(args);
1034             }
1035         }
1036     }
1037 
1038 
1039     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
1040     private static final class WrappedMember extends DelegatingMethodHandle {
1041         private final MethodHandle target;
1042         private final MemberName member;
1043         private final Class<?> callerClass;
1044         private final boolean isInvokeSpecial;
1045 
1046         private WrappedMember(MethodHandle target, MethodType type,
1047                               MemberName member, boolean isInvokeSpecial,
1048                               Class<?> callerClass) {
1049             super(type, target);
1050             this.target = target;
1051             this.member = member;
1052             this.callerClass = callerClass;
1053             this.isInvokeSpecial = isInvokeSpecial;
1054         }
1055 
1056         @Override
1057         MemberName internalMemberName() {
1058             return member;
1059         }
1060         @Override
1061         Class<?> internalCallerClass() {
1062             return callerClass;
1063         }
1064         @Override
1065         boolean isInvokeSpecial() {
1066             return isInvokeSpecial;
1067         }
1068         @Override
1069         protected MethodHandle getTarget() {
1070             return target;
1071         }
1072         @Override
1073         public MethodHandle asTypeUncached(MethodType newType) {
1074             // This MH is an alias for target, except for the MemberName
1075             // Drop the MemberName if there is any conversion.
1076             return asTypeCache = target.asType(newType);
1077         }
1078     }
1079 
1080     static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) {
1081         if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial())
1082             return target;
1083         return new WrappedMember(target, target.type(), member, isInvokeSpecial, null);
1084     }
1085 
1086     /** Intrinsic IDs */
1087     /*non-public*/
1088     enum Intrinsic {
1089         SELECT_ALTERNATIVE,
1090         GUARD_WITH_CATCH,
1091         NEW_ARRAY,
1092         ARRAY_LOAD,
1093         ARRAY_STORE,
1094         IDENTITY,
1095         ZERO,
1096         NONE // no intrinsic associated
1097     }
1098 
1099     /** Mark arbitrary method handle as intrinsic.
1100      * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */
1101     private static final class IntrinsicMethodHandle extends DelegatingMethodHandle {
1102         private final MethodHandle target;
1103         private final Intrinsic intrinsicName;
1104 
1105         IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) {
1106             super(target.type(), target);
1107             this.target = target;
1108             this.intrinsicName = intrinsicName;
1109         }
1110 
1111         @Override
1112         protected MethodHandle getTarget() {
1113             return target;
1114         }
1115 
1116         @Override
1117         Intrinsic intrinsicName() {
1118             return intrinsicName;
1119         }
1120 
1121         @Override
1122         public MethodHandle asTypeUncached(MethodType newType) {
1123             // This MH is an alias for target, except for the intrinsic name
1124             // Drop the name if there is any conversion.
1125             return asTypeCache = target.asType(newType);
1126         }
1127 
1128         @Override
1129         String internalProperties() {
1130             return super.internalProperties() +
1131                     "\n& Intrinsic="+intrinsicName;
1132         }
1133 
1134         @Override
1135         public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
1136             if (intrinsicName == Intrinsic.IDENTITY) {
1137                 MethodType resultType = type().asCollectorType(arrayType, arrayLength);
1138                 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength);
1139                 return newArray.asType(resultType);
1140             }
1141             return super.asCollector(arrayType, arrayLength);
1142         }
1143     }
1144 
1145     static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) {
1146         if (intrinsicName == target.intrinsicName())
1147             return target;
1148         return new IntrinsicMethodHandle(target, intrinsicName);
1149     }
1150 
1151     static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) {
1152         return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName);
1153     }
1154 
1155     /// Collection of multiple arguments.
1156 
1157     private static MethodHandle findCollector(String name, int nargs, Class<?> rtype, Class<?>... ptypes) {
1158         MethodType type = MethodType.genericMethodType(nargs)
1159                 .changeReturnType(rtype)
1160                 .insertParameterTypes(0, ptypes);
1161         try {
1162             return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, name, type);
1163         } catch (ReflectiveOperationException ex) {
1164             return null;
1165         }
1166     }
1167 
1168     private static final Object[] NO_ARGS_ARRAY = {};
1169     private static Object[] makeArray(Object... args) { return args; }
1170     private static Object[] array() { return NO_ARGS_ARRAY; }
1171     private static Object[] array(Object a0)
1172                 { return makeArray(a0); }
1173     private static Object[] array(Object a0, Object a1)
1174                 { return makeArray(a0, a1); }
1175     private static Object[] array(Object a0, Object a1, Object a2)
1176                 { return makeArray(a0, a1, a2); }
1177     private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1178                 { return makeArray(a0, a1, a2, a3); }
1179     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1180                                   Object a4)
1181                 { return makeArray(a0, a1, a2, a3, a4); }
1182     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1183                                   Object a4, Object a5)
1184                 { return makeArray(a0, a1, a2, a3, a4, a5); }
1185     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1186                                   Object a4, Object a5, Object a6)
1187                 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1188     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1189                                   Object a4, Object a5, Object a6, Object a7)
1190                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1191     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1192                                   Object a4, Object a5, Object a6, Object a7,
1193                                   Object a8)
1194                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1195     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1196                                   Object a4, Object a5, Object a6, Object a7,
1197                                   Object a8, Object a9)
1198                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1199     private static MethodHandle[] makeArrays() {
1200         ArrayList<MethodHandle> mhs = new ArrayList<>();
1201         for (;;) {
1202             MethodHandle mh = findCollector("array", mhs.size(), Object[].class);
1203             if (mh == null)  break;
1204             mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1205             mhs.add(mh);
1206         }
1207         assert(mhs.size() == 11);  // current number of methods
1208         return mhs.toArray(new MethodHandle[MAX_ARITY+1]);
1209     }
1210     private static final MethodHandle[] ARRAYS = makeArrays();
1211 
1212     // filling versions of the above:
1213     // using Integer len instead of int len and no varargs to avoid bootstrapping problems
1214     private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) {
1215         Object[] a = new Object[len];
1216         fillWithArguments(a, 0, args);
1217         return a;
1218     }
1219     private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) {
1220         Object[] a = Arrays.copyOf(example, len);
1221         assert(a.getClass() != Object[].class);
1222         fillWithArguments(a, 0, args);
1223         return a;
1224     }
1225     private static void fillWithArguments(Object[] a, int pos, Object... args) {
1226         System.arraycopy(args, 0, a, pos, args.length);
1227     }
1228     // using Integer pos instead of int pos to avoid bootstrapping problems
1229     private static Object[] fillArray(Integer pos, Object[] a, Object a0)
1230                 { fillWithArguments(a, pos, a0); return a; }
1231     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1)
1232                 { fillWithArguments(a, pos, a0, a1); return a; }
1233     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2)
1234                 { fillWithArguments(a, pos, a0, a1, a2); return a; }
1235     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3)
1236                 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; }
1237     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1238                                   Object a4)
1239                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; }
1240     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1241                                   Object a4, Object a5)
1242                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); return a; }
1243     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1244                                   Object a4, Object a5, Object a6)
1245                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; }
1246     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1247                                   Object a4, Object a5, Object a6, Object a7)
1248                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; }
1249     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1250                                   Object a4, Object a5, Object a6, Object a7,
1251                                   Object a8)
1252                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; }
1253     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1254                                   Object a4, Object a5, Object a6, Object a7,
1255                                   Object a8, Object a9)
1256                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; }
1257     private static MethodHandle[] makeFillArrays() {
1258         ArrayList<MethodHandle> mhs = new ArrayList<>();
1259         mhs.add(null);  // there is no empty fill; at least a0 is required
1260         for (;;) {
1261             MethodHandle mh = findCollector("fillArray", mhs.size(), Object[].class, Integer.class, Object[].class);
1262             if (mh == null)  break;
1263             mhs.add(mh);
1264         }
1265         assert(mhs.size() == 11);  // current number of methods
1266         return mhs.toArray(new MethodHandle[0]);
1267     }
1268     private static final MethodHandle[] FILL_ARRAYS = makeFillArrays();
1269 
1270     private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) {
1271         Object a = w.makeArray(boxes.length);
1272         w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length);
1273         return a;
1274     }
1275 
1276     /** Return a method handle that takes the indicated number of Object
1277      *  arguments and returns an Object array of them, as if for varargs.
1278      */
1279     static MethodHandle varargsArray(int nargs) {
1280         MethodHandle mh = ARRAYS[nargs];
1281         if (mh != null)  return mh;
1282         mh = findCollector("array", nargs, Object[].class);
1283         if (mh != null)  mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1284         if (mh != null)  return ARRAYS[nargs] = mh;
1285         mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs);
1286         assert(assertCorrectArity(mh, nargs));
1287         mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1288         return ARRAYS[nargs] = mh;
1289     }
1290 
1291     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1292         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1293         return true;
1294     }
1295 
1296     // Array identity function (used as Lazy.MH_arrayIdentity).
1297     static <T> T[] identity(T[] x) {
1298         return x;
1299     }
1300 
1301     private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) {
1302         // Build up the result mh as a sequence of fills like this:
1303         //   finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23))
1304         // The various fill(_,10*I,___*[J]) are reusable.
1305         int leftLen = Math.min(nargs, LEFT_ARGS);  // absorb some arguments immediately
1306         int rightLen = nargs - leftLen;
1307         MethodHandle leftCollector = newArray.bindTo(nargs);
1308         leftCollector = leftCollector.asCollector(Object[].class, leftLen);
1309         MethodHandle mh = finisher;
1310         if (rightLen > 0) {
1311             MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen);
1312             if (mh == Lazy.MH_arrayIdentity)
1313                 mh = rightFiller;
1314             else
1315                 mh = MethodHandles.collectArguments(mh, 0, rightFiller);
1316         }
1317         if (mh == Lazy.MH_arrayIdentity)
1318             mh = leftCollector;
1319         else
1320             mh = MethodHandles.collectArguments(mh, 0, leftCollector);
1321         return mh;
1322     }
1323 
1324     private static final int LEFT_ARGS = (FILL_ARRAYS.length - 1);
1325     private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1];
1326     /** fill_array_to_right(N).invoke(a, argL..arg[N-1])
1327      *  fills a[L]..a[N-1] with corresponding arguments,
1328      *  and then returns a.  The value L is a global constant (LEFT_ARGS).
1329      */
1330     private static MethodHandle fillToRight(int nargs) {
1331         MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs];
1332         if (filler != null)  return filler;
1333         filler = buildFiller(nargs);
1334         assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1));
1335         return FILL_ARRAY_TO_RIGHT[nargs] = filler;
1336     }
1337     private static MethodHandle buildFiller(int nargs) {
1338         if (nargs <= LEFT_ARGS)
1339             return Lazy.MH_arrayIdentity;  // no args to fill; return the array unchanged
1340         // we need room for both mh and a in mh.invoke(a, arg*[nargs])
1341         final int CHUNK = LEFT_ARGS;
1342         int rightLen = nargs % CHUNK;
1343         int midLen = nargs - rightLen;
1344         if (rightLen == 0) {
1345             midLen = nargs - (rightLen = CHUNK);
1346             if (FILL_ARRAY_TO_RIGHT[midLen] == null) {
1347                 // build some precursors from left to right
1348                 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK)
1349                     if (j > LEFT_ARGS)  fillToRight(j);
1350             }
1351         }
1352         if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS);
1353         assert(rightLen > 0);
1354         MethodHandle midFill = fillToRight(midLen);  // recursive fill
1355         MethodHandle rightFill = FILL_ARRAYS[rightLen].bindTo(midLen);  // [midLen..nargs-1]
1356         assert(midFill.type().parameterCount()   == 1 + midLen - LEFT_ARGS);
1357         assert(rightFill.type().parameterCount() == 1 + rightLen);
1358 
1359         // Combine the two fills:
1360         //   right(mid(a, x10..x19), x20..x23)
1361         // The final product will look like this:
1362         //   right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23)
1363         if (midLen == LEFT_ARGS)
1364             return rightFill;
1365         else
1366             return MethodHandles.collectArguments(rightFill, 0, midFill);
1367     }
1368 
1369     // Type-polymorphic version of varargs maker.
1370     private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS
1371         = new ClassValue<MethodHandle[]>() {
1372             @Override
1373             protected MethodHandle[] computeValue(Class<?> type) {
1374                 return new MethodHandle[256];
1375             }
1376     };
1377 
1378     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1379 
1380     /** Return a method handle that takes the indicated number of
1381      *  typed arguments and returns an array of them.
1382      *  The type argument is the array type.
1383      */
1384     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1385         Class<?> elemType = arrayType.getComponentType();
1386         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1387         // FIXME: Need more special casing and caching here.
1388         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1389             int slots = nargs;
1390             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1391             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1392                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1393             if (slots > MAX_ARRAY_SLOTS)
1394                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1395         }
1396         if (elemType == Object.class)
1397             return varargsArray(nargs);
1398         // other cases:  primitive arrays, subtypes of Object[]
1399         MethodHandle cache[] = TYPED_COLLECTORS.get(elemType);
1400         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1401         if (mh != null)  return mh;
1402         if (nargs == 0) {
1403             Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0);
1404             mh = MethodHandles.constant(arrayType, example);
1405         } else if (elemType.isPrimitive()) {
1406             MethodHandle builder = Lazy.MH_fillNewArray;
1407             MethodHandle producer = buildArrayProducer(arrayType);
1408             mh = buildVarargsArray(builder, producer, nargs);
1409         } else {
1410             Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class);
1411             Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType);
1412             MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example);
1413             MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed
1414             mh = buildVarargsArray(builder, producer, nargs);
1415         }
1416         mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)));
1417         mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1418         assert(assertCorrectArity(mh, nargs));
1419         if (nargs < cache.length)
1420             cache[nargs] = mh;
1421         return mh;
1422     }
1423 
1424     private static MethodHandle buildArrayProducer(Class<?> arrayType) {
1425         Class<?> elemType = arrayType.getComponentType();
1426         assert(elemType.isPrimitive());
1427         return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType));
1428     }
1429 }