rev 10755 : 8058892: FILL_ARRAYS and ARRAYS are eagely initialized in MethodHandleImpl
Reviewed-by: ?

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

1274 
1275     // filling versions of the above:
1276     // using Integer len instead of int len and no varargs to avoid bootstrapping problems
1277     private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) {
1278         Object[] a = new Object[len];
1279         fillWithArguments(a, 0, args);
1280         return a;
1281     }
1282     private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) {
1283         Object[] a = Arrays.copyOf(example, len);
1284         assert(a.getClass() != Object[].class);
1285         fillWithArguments(a, 0, args);
1286         return a;
1287     }
1288     private static void fillWithArguments(Object[] a, int pos, Object... args) {
1289         System.arraycopy(args, 0, a, pos, args.length);
1290     }
1291     // using Integer pos instead of int pos to avoid bootstrapping problems
1292     private static Object[] fillArray(Integer pos, Object[] a, Object a0)
1293                 { fillWithArguments(a, pos, a0); return a; }
1294     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1)
1295                 { fillWithArguments(a, pos, a0, a1); return a; }
1296     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2)
1297                 { fillWithArguments(a, pos, a0, a1, a2); return a; }
1298     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3)
1299                 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; }
1300     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1301                                   Object a4)
1302                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; }
1303     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1304                                   Object a4, Object a5)
1305                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); return a; }
1306     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1307                                   Object a4, Object a5, Object a6)
1308                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; }
1309     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1310                                   Object a4, Object a5, Object a6, Object a7)
1311                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; }
1312     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1313                                   Object a4, Object a5, Object a6, Object a7,
1314                                   Object a8)
1315                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; }
1316     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1317                                   Object a4, Object a5, Object a6, Object a7,
1318                                   Object a8, Object a9)
1319                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; }
1320 
1321     private static final int FILL_ARRAYS_COUNT = 11; // current number of fillArray methods
1322 
1323     private static MethodHandle[] makeFillArrays() {
1324         ArrayList<MethodHandle> mhs = new ArrayList<>();
1325         mhs.add(null);  // there is no empty fill; at least a0 is required
1326         for (;;) {
1327             MethodHandle mh = findCollector("fillArray", mhs.size(), Object[].class, Integer.class, Object[].class);
1328             if (mh == null)  break;
1329             mhs.add(mh);
1330         }
1331         assert(mhs.size() == FILL_ARRAYS_COUNT);
1332         return mhs.toArray(new MethodHandle[0]);
1333     }

1334 
1335     private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) {
1336         Object a = w.makeArray(boxes.length);
1337         w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length);
1338         return a;
1339     }
1340 
1341     /** Return a method handle that takes the indicated number of Object
1342      *  arguments and returns an Object array of them, as if for varargs.
1343      */
1344     static MethodHandle varargsArray(int nargs) {
1345         MethodHandle mh = Lazy.ARRAYS[nargs];
1346         if (mh != null)  return mh;
1347         mh = findCollector("array", nargs, Object[].class);
1348         if (mh != null)  mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1349         if (mh != null)  return Lazy.ARRAYS[nargs] = mh;
1350         mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs);
1351         assert(assertCorrectArity(mh, nargs));
1352         mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1353         return Lazy.ARRAYS[nargs] = mh;
1354     }
1355 
1356     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1357         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1358         return true;
1359     }
1360 
1361     // Array identity function (used as Lazy.MH_arrayIdentity).
1362     static <T> T[] identity(T[] x) {
1363         return x;
1364     }
1365 
1366     private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) {
1367         // Build up the result mh as a sequence of fills like this:
1368         //   finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23))
1369         // The various fill(_,10*I,___*[J]) are reusable.
1370         int leftLen = Math.min(nargs, LEFT_ARGS);  // absorb some arguments immediately
1371         int rightLen = nargs - leftLen;
1372         MethodHandle leftCollector = newArray.bindTo(nargs);
1373         leftCollector = leftCollector.asCollector(Object[].class, leftLen);
1374         MethodHandle mh = finisher;
1375         if (rightLen > 0) {
1376             MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen);
1377             if (mh == Lazy.MH_arrayIdentity)
1378                 mh = rightFiller;
1379             else
1380                 mh = MethodHandles.collectArguments(mh, 0, rightFiller);
1381         }
1382         if (mh == Lazy.MH_arrayIdentity)
1383             mh = leftCollector;
1384         else
1385             mh = MethodHandles.collectArguments(mh, 0, leftCollector);
1386         return mh;
1387     }
1388 
1389     private static final int LEFT_ARGS = FILL_ARRAYS_COUNT - 1;
1390     private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1];
1391     /** fill_array_to_right(N).invoke(a, argL..arg[N-1])
1392      *  fills a[L]..a[N-1] with corresponding arguments,
1393      *  and then returns a.  The value L is a global constant (LEFT_ARGS).
1394      */
1395     private static MethodHandle fillToRight(int nargs) {
1396         MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs];
1397         if (filler != null)  return filler;
1398         filler = buildFiller(nargs);
1399         assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1));
1400         return FILL_ARRAY_TO_RIGHT[nargs] = filler;
1401     }
1402     private static MethodHandle buildFiller(int nargs) {
1403         if (nargs <= LEFT_ARGS)
1404             return Lazy.MH_arrayIdentity;  // no args to fill; return the array unchanged
1405         // we need room for both mh and a in mh.invoke(a, arg*[nargs])
1406         final int CHUNK = LEFT_ARGS;
1407         int rightLen = nargs % CHUNK;
1408         int midLen = nargs - rightLen;
1409         if (rightLen == 0) {
1410             midLen = nargs - (rightLen = CHUNK);
1411             if (FILL_ARRAY_TO_RIGHT[midLen] == null) {
1412                 // build some precursors from left to right
1413                 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK)
1414                     if (j > LEFT_ARGS)  fillToRight(j);
1415             }
1416         }
1417         if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS);
1418         assert(rightLen > 0);
1419         MethodHandle midFill = fillToRight(midLen);  // recursive fill
1420         MethodHandle rightFill = Lazy.FILL_ARRAYS[rightLen].bindTo(midLen);  // [midLen..nargs-1]
1421         assert(midFill.type().parameterCount()   == 1 + midLen - LEFT_ARGS);
1422         assert(rightFill.type().parameterCount() == 1 + rightLen);
1423 
1424         // Combine the two fills:
1425         //   right(mid(a, x10..x19), x20..x23)
1426         // The final product will look like this:
1427         //   right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23)
1428         if (midLen == LEFT_ARGS)
1429             return rightFill;
1430         else
1431             return MethodHandles.collectArguments(rightFill, 0, midFill);
1432     }
1433 
1434     // Type-polymorphic version of varargs maker.
1435     private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS
1436         = new ClassValue<MethodHandle[]>() {
1437             @Override
1438             protected MethodHandle[] computeValue(Class<?> type) {
1439                 return new MethodHandle[256];
1440             }
1441     };
1442 
1443     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1444 
1445     /** Return a method handle that takes the indicated number of
1446      *  typed arguments and returns an array of them.
1447      *  The type argument is the array type.
1448      */
1449     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1450         Class<?> elemType = arrayType.getComponentType();
1451         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1452         // FIXME: Need more special casing and caching here.
1453         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1454             int slots = nargs;
1455             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1456             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1457                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1458             if (slots > MAX_ARRAY_SLOTS)
1459                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1460         }
1461         if (elemType == Object.class)
1462             return varargsArray(nargs);
1463         // other cases:  primitive arrays, subtypes of Object[]
1464         MethodHandle cache[] = TYPED_COLLECTORS.get(elemType);
1465         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1466         if (mh != null)  return mh;
1467         if (nargs == 0) {
1468             Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0);
1469             mh = MethodHandles.constant(arrayType, example);
1470         } else if (elemType.isPrimitive()) {
1471             MethodHandle builder = Lazy.MH_fillNewArray;
1472             MethodHandle producer = buildArrayProducer(arrayType);
1473             mh = buildVarargsArray(builder, producer, nargs);
1474         } else {
1475             Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class);
1476             Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType);
1477             MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example);
1478             MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed
1479             mh = buildVarargsArray(builder, producer, nargs);
1480         }
1481         mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)));
1482         mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1483         assert(assertCorrectArity(mh, nargs));
1484         if (nargs < cache.length)
1485             cache[nargs] = mh;
1486         return mh;
1487     }
1488 
1489     private static MethodHandle buildArrayProducer(Class<?> arrayType) {
1490         Class<?> elemType = arrayType.getComponentType();
1491         assert(elemType.isPrimitive());
1492         return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType));
1493     }
1494 }
--- EOF ---