1 /* 2 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import java.security.AccessController; 29 import java.security.PrivilegedAction; 30 import java.util.ArrayList; 31 import java.util.Arrays; 32 import java.util.Collections; 33 import java.util.function.Function; 34 35 import sun.invoke.empty.Empty; 36 import sun.invoke.util.ValueConversions; 37 import sun.invoke.util.VerifyType; 38 import sun.invoke.util.Wrapper; 39 import sun.reflect.CallerSensitive; 40 import sun.reflect.Reflection; 41 import static java.lang.invoke.LambdaForm.*; 42 import static java.lang.invoke.MethodHandleStatics.*; 43 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 44 45 /** 46 * Trusted implementation code for MethodHandle. 47 * @author jrose 48 */ 49 /*non-public*/ abstract class MethodHandleImpl { 50 // Do not adjust this except for special platforms: 51 private static final int MAX_ARITY; 52 static { 53 final Object[] values = { 255 }; 54 AccessController.doPrivileged(new PrivilegedAction<Void>() { 55 @Override 56 public Void run() { 57 values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255); 58 return null; 59 } 60 }); 61 MAX_ARITY = (Integer) values[0]; 62 } 63 64 /// Factory methods to create method handles: 65 66 static void initStatics() { 67 // Trigger selected static initializations. 68 MemberName.Factory.INSTANCE.getClass(); 69 } 70 71 static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) { 72 if (arrayClass == Object[].class) 73 return (isSetter ? ArrayAccessor.OBJECT_ARRAY_SETTER : ArrayAccessor.OBJECT_ARRAY_GETTER); 74 if (!arrayClass.isArray()) 75 throw newIllegalArgumentException("not an array: "+arrayClass); 76 MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass); 77 int cacheIndex = (isSetter ? ArrayAccessor.SETTER_INDEX : ArrayAccessor.GETTER_INDEX); 78 MethodHandle mh = cache[cacheIndex]; 79 if (mh != null) return mh; 80 mh = ArrayAccessor.getAccessor(arrayClass, isSetter); 81 MethodType correctType = ArrayAccessor.correctType(arrayClass, isSetter); 82 if (mh.type() != correctType) { 83 assert(mh.type().parameterType(0) == Object[].class); 84 assert((isSetter ? mh.type().parameterType(2) : mh.type().returnType()) == Object.class); 85 assert(isSetter || correctType.parameterType(0).getComponentType() == correctType.returnType()); 86 // safe to view non-strictly, because element type follows from array type 87 mh = mh.viewAsType(correctType, false); 88 } 89 mh = makeIntrinsic(mh, (isSetter ? Intrinsic.ARRAY_STORE : Intrinsic.ARRAY_LOAD)); 90 // Atomically update accessor cache. 91 synchronized(cache) { 92 if (cache[cacheIndex] == null) { 93 cache[cacheIndex] = mh; 94 } else { 95 // Throw away newly constructed accessor and use cached version. 96 mh = cache[cacheIndex]; 97 } 98 } 99 return mh; 100 } 101 102 static final class ArrayAccessor { 103 /// Support for array element access 104 static final int GETTER_INDEX = 0, SETTER_INDEX = 1, INDEX_LIMIT = 2; 105 static final ClassValue<MethodHandle[]> TYPED_ACCESSORS 106 = new ClassValue<MethodHandle[]>() { 107 @Override 108 protected MethodHandle[] computeValue(Class<?> type) { 109 return new MethodHandle[INDEX_LIMIT]; 110 } 111 }; 112 static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER; 113 static { 114 MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class); 115 cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, false), Intrinsic.ARRAY_LOAD); 116 cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, true), Intrinsic.ARRAY_STORE); 117 118 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName())); 119 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName())); 120 } 121 122 static int getElementI(int[] a, int i) { return a[i]; } 123 static long getElementJ(long[] a, int i) { return a[i]; } 124 static float getElementF(float[] a, int i) { return a[i]; } 125 static double getElementD(double[] a, int i) { return a[i]; } 126 static boolean getElementZ(boolean[] a, int i) { return a[i]; } 127 static byte getElementB(byte[] a, int i) { return a[i]; } 128 static short getElementS(short[] a, int i) { return a[i]; } 129 static char getElementC(char[] a, int i) { return a[i]; } 130 static Object getElementL(Object[] a, int i) { return a[i]; } 131 132 static void setElementI(int[] a, int i, int x) { a[i] = x; } 133 static void setElementJ(long[] a, int i, long x) { a[i] = x; } 134 static void setElementF(float[] a, int i, float x) { a[i] = x; } 135 static void setElementD(double[] a, int i, double x) { a[i] = x; } 136 static void setElementZ(boolean[] a, int i, boolean x) { a[i] = x; } 137 static void setElementB(byte[] a, int i, byte x) { a[i] = x; } 138 static void setElementS(short[] a, int i, short x) { a[i] = x; } 139 static void setElementC(char[] a, int i, char x) { a[i] = x; } 140 static void setElementL(Object[] a, int i, Object x) { a[i] = x; } 141 142 static String name(Class<?> arrayClass, boolean isSetter) { 143 Class<?> elemClass = arrayClass.getComponentType(); 144 if (elemClass == null) throw newIllegalArgumentException("not an array", arrayClass); 145 return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(elemClass); 146 } 147 static MethodType type(Class<?> arrayClass, boolean isSetter) { 148 Class<?> elemClass = arrayClass.getComponentType(); 149 Class<?> arrayArgClass = arrayClass; 150 if (!elemClass.isPrimitive()) { 151 arrayArgClass = Object[].class; 152 elemClass = Object.class; 153 } 154 return !isSetter ? 155 MethodType.methodType(elemClass, arrayArgClass, int.class) : 156 MethodType.methodType(void.class, arrayArgClass, int.class, elemClass); 157 } 158 static MethodType correctType(Class<?> arrayClass, boolean isSetter) { 159 Class<?> elemClass = arrayClass.getComponentType(); 160 return !isSetter ? 161 MethodType.methodType(elemClass, arrayClass, int.class) : 162 MethodType.methodType(void.class, arrayClass, int.class, elemClass); 163 } 164 static MethodHandle getAccessor(Class<?> arrayClass, boolean isSetter) { 165 String name = name(arrayClass, isSetter); 166 MethodType type = type(arrayClass, isSetter); 167 try { 168 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type); 169 } catch (ReflectiveOperationException ex) { 170 throw uncaughtException(ex); 171 } 172 } 173 } 174 175 /** 176 * Create a JVM-level adapter method handle to conform the given method 177 * handle to the similar newType, using only pairwise argument conversions. 178 * For each argument, convert incoming argument to the exact type needed. 179 * The argument conversions allowed are casting, boxing and unboxing, 180 * integral widening or narrowing, and floating point widening or narrowing. 181 * @param srcType required call type 182 * @param target original method handle 183 * @param strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed 184 * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double) 185 * @return an adapter to the original handle with the desired new type, 186 * or the original target if the types are already identical 187 * or null if the adaptation cannot be made 188 */ 189 static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, 190 boolean strict, boolean monobox) { 191 MethodType dstType = target.type(); 192 if (srcType == dstType) 193 return target; 194 return makePairwiseConvertByEditor(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 makePairwiseConvertByEditor(MethodHandle target, MethodType srcType, 206 boolean strict, boolean monobox) { 207 Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox); 208 int convCount = countNonNull(convSpecs); 209 if (convCount == 0) 210 return target.viewAsType(srcType, strict); 211 MethodType basicSrcType = srcType.basicType(); 212 MethodType midType = target.type().basicType(); 213 BoundMethodHandle mh = target.rebind(); 214 // FIXME: Reduce number of bindings when there is more than one Class conversion. 215 // FIXME: Reduce number of bindings when there are repeated conversions. 216 for (int i = 0; i < convSpecs.length-1; i++) { 217 Object convSpec = convSpecs[i]; 218 if (convSpec == null) continue; 219 MethodHandle fn; 220 if (convSpec instanceof Class) { 221 fn = Lazy.MH_castReference.bindTo(convSpec); 222 } else { 223 fn = (MethodHandle) convSpec; 224 } 225 Class<?> newType = basicSrcType.parameterType(i); 226 if (--convCount == 0) 227 midType = srcType; 228 else 229 midType = midType.changeParameterType(i, newType); 230 LambdaForm form2 = mh.editor().filterArgumentForm(1+i, BasicType.basicType(newType)); 231 mh = mh.copyWithExtendL(midType, form2, fn); 232 mh = mh.rebind(); 233 } 234 Object convSpec = convSpecs[convSpecs.length-1]; 235 if (convSpec != null) { 236 MethodHandle fn; 237 if (convSpec instanceof Class) { 238 if (convSpec == void.class) 239 fn = null; 240 else 241 fn = Lazy.MH_castReference.bindTo(convSpec); 242 } else { 243 fn = (MethodHandle) convSpec; 244 } 245 Class<?> newType = basicSrcType.returnType(); 246 assert(--convCount == 0); 247 midType = srcType; 248 if (fn != null) { 249 mh = mh.rebind(); // rebind if too complex 250 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), false); 251 mh = mh.copyWithExtendL(midType, form2, fn); 252 } else { 253 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), true); 254 mh = mh.copyWith(midType, form2); 255 } 256 } 257 assert(convCount == 0); 258 assert(mh.type().equals(srcType)); 259 return mh; 260 } 261 262 static MethodHandle makePairwiseConvertIndirect(MethodHandle target, MethodType srcType, 263 boolean strict, boolean monobox) { 264 assert(target.type().parameterCount() == srcType.parameterCount()); 265 // Calculate extra arguments (temporaries) required in the names array. 266 Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox); 267 final int INARG_COUNT = srcType.parameterCount(); 268 int convCount = countNonNull(convSpecs); 269 boolean retConv = (convSpecs[INARG_COUNT] != null); 270 boolean retVoid = srcType.returnType() == void.class; 271 if (retConv && retVoid) { 272 convCount -= 1; 273 retConv = false; 274 } 275 276 final int IN_MH = 0; 277 final int INARG_BASE = 1; 278 final int INARG_LIMIT = INARG_BASE + INARG_COUNT; 279 final int NAME_LIMIT = INARG_LIMIT + convCount + 1; 280 final int RETURN_CONV = (!retConv ? -1 : NAME_LIMIT - 1); 281 final int OUT_CALL = (!retConv ? NAME_LIMIT : RETURN_CONV) - 1; 282 final int RESULT = (retVoid ? -1 : NAME_LIMIT - 1); 283 284 // Now build a LambdaForm. 285 MethodType lambdaType = srcType.basicType().invokerType(); 286 Name[] names = arguments(NAME_LIMIT - INARG_LIMIT, lambdaType); 287 288 // Collect the arguments to the outgoing call, maybe with conversions: 289 final int OUTARG_BASE = 0; // target MH is Name.function, name Name.arguments[0] 290 Object[] outArgs = new Object[OUTARG_BASE + INARG_COUNT]; 291 292 int nameCursor = INARG_LIMIT; 293 for (int i = 0; i < INARG_COUNT; i++) { 294 Object convSpec = convSpecs[i]; 295 if (convSpec == null) { 296 // do nothing: difference is trivial 297 outArgs[OUTARG_BASE + i] = names[INARG_BASE + i]; 298 continue; 299 } 300 301 Name conv; 302 if (convSpec instanceof Class) { 303 Class<?> convClass = (Class<?>) convSpec; 304 conv = new Name(Lazy.MH_castReference, convClass, names[INARG_BASE + i]); 305 } else { 306 MethodHandle fn = (MethodHandle) convSpec; 307 conv = new Name(fn, names[INARG_BASE + i]); 308 } 309 assert(names[nameCursor] == null); 310 names[nameCursor++] = conv; 311 assert(outArgs[OUTARG_BASE + i] == null); 312 outArgs[OUTARG_BASE + i] = conv; 313 } 314 315 // Build argument array for the call. 316 assert(nameCursor == OUT_CALL); 317 names[OUT_CALL] = new Name(target, outArgs); 318 319 Object convSpec = convSpecs[INARG_COUNT]; 320 if (!retConv) { 321 assert(OUT_CALL == names.length-1); 322 } else { 323 Name conv; 324 if (convSpec == void.class) { 325 conv = new Name(LambdaForm.constantZero(BasicType.basicType(srcType.returnType()))); 326 } else if (convSpec instanceof Class) { 327 Class<?> convClass = (Class<?>) convSpec; 328 conv = new Name(Lazy.MH_castReference, convClass, names[OUT_CALL]); 329 } else { 330 MethodHandle fn = (MethodHandle) convSpec; 331 if (fn.type().parameterCount() == 0) 332 conv = new Name(fn); // don't pass retval to void conversion 333 else 334 conv = new Name(fn, names[OUT_CALL]); 335 } 336 assert(names[RETURN_CONV] == null); 337 names[RETURN_CONV] = conv; 338 assert(RETURN_CONV == names.length-1); 339 } 340 341 LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names, RESULT); 342 return SimpleMethodHandle.make(srcType, form); 343 } 344 345 /** 346 * Identity function, with reference cast. 347 * @param t an arbitrary reference type 348 * @param x an arbitrary reference value 349 * @return the same value x 350 */ 351 @ForceInline 352 @SuppressWarnings("unchecked") 353 static <T,U> T castReference(Class<? extends T> t, U x) { 354 // inlined Class.cast because we can't ForceInline it 355 if (x != null && !t.isInstance(x)) 356 throw newClassCastException(t, x); 357 return (T) x; 358 } 359 360 private static ClassCastException newClassCastException(Class<?> t, Object obj) { 361 return new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + t.getName()); 362 } 363 364 static Object[] computeValueConversions(MethodType srcType, MethodType dstType, 365 boolean strict, boolean monobox) { 366 final int INARG_COUNT = srcType.parameterCount(); 367 Object[] convSpecs = new Object[INARG_COUNT+1]; 368 for (int i = 0; i <= INARG_COUNT; i++) { 369 boolean isRet = (i == INARG_COUNT); 370 Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i); 371 Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i); 372 if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) { 373 convSpecs[i] = valueConversion(src, dst, strict, monobox); 374 } 375 } 376 return convSpecs; 377 } 378 static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, 379 boolean strict) { 380 return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false); 381 } 382 383 /** 384 * Find a conversion function from the given source to the given destination. 385 * This conversion function will be used as a LF NamedFunction. 386 * Return a Class object if a simple cast is needed. 387 * Return void.class if void is involved. 388 */ 389 static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) { 390 assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)); // caller responsibility 391 if (dst == void.class) 392 return dst; 393 MethodHandle fn; 394 if (src.isPrimitive()) { 395 if (src == void.class) { 396 return void.class; // caller must recognize this specially 397 } else if (dst.isPrimitive()) { 398 // Examples: int->byte, byte->int, boolean->int (!strict) 399 fn = ValueConversions.convertPrimitive(src, dst); 400 } else { 401 // Examples: int->Integer, boolean->Object, float->Number 402 Wrapper wsrc = Wrapper.forPrimitiveType(src); 403 fn = ValueConversions.boxExact(wsrc); 404 assert(fn.type().parameterType(0) == wsrc.primitiveType()); 405 assert(fn.type().returnType() == wsrc.wrapperType()); 406 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) { 407 // Corner case, such as int->Long, which will probably fail. 408 MethodType mt = MethodType.methodType(dst, src); 409 if (strict) 410 fn = fn.asType(mt); 411 else 412 fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false); 413 } 414 } 415 } else if (dst.isPrimitive()) { 416 Wrapper wdst = Wrapper.forPrimitiveType(dst); 417 if (monobox || src == wdst.wrapperType()) { 418 // Use a strongly-typed unboxer, if possible. 419 fn = ValueConversions.unboxExact(wdst, strict); 420 } else { 421 // Examples: Object->int, Number->int, Comparable->int, Byte->int 422 // must include additional conversions 423 // src must be examined at runtime, to detect Byte, Character, etc. 424 fn = (strict 425 ? ValueConversions.unboxWiden(wdst) 426 : ValueConversions.unboxCast(wdst)); 427 } 428 } else { 429 // Simple reference conversion. 430 // Note: Do not check for a class hierarchy relation 431 // between src and dst. In all cases a 'null' argument 432 // will pass the cast conversion. 433 return dst; 434 } 435 assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn); 436 return fn; 437 } 438 439 static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) { 440 MethodType type = target.type(); 441 int last = type.parameterCount() - 1; 442 if (type.parameterType(last) != arrayType) 443 target = target.asType(type.changeParameterType(last, arrayType)); 444 target = target.asFixedArity(); // make sure this attribute is turned off 445 return new AsVarargsCollector(target, arrayType); 446 } 447 448 private static final class AsVarargsCollector extends DelegatingMethodHandle { 449 private final MethodHandle target; 450 private final Class<?> arrayType; 451 private @Stable MethodHandle asCollectorCache; 452 453 AsVarargsCollector(MethodHandle target, Class<?> arrayType) { 454 this(target.type(), target, arrayType); 455 } 456 AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) { 457 super(type, target); 458 this.target = target; 459 this.arrayType = arrayType; 460 this.asCollectorCache = target.asCollector(arrayType, 0); 461 } 462 463 @Override 464 public boolean isVarargsCollector() { 465 return true; 466 } 467 468 @Override 469 protected MethodHandle getTarget() { 470 return target; 471 } 472 473 @Override 474 public MethodHandle asFixedArity() { 475 return target; 476 } 477 478 @Override 479 MethodHandle setVarargs(MemberName member) { 480 if (member.isVarargs()) return this; 481 return asFixedArity(); 482 } 483 484 @Override 485 public MethodHandle asTypeUncached(MethodType newType) { 486 MethodType type = this.type(); 487 int collectArg = type.parameterCount() - 1; 488 int newArity = newType.parameterCount(); 489 if (newArity == collectArg+1 && 490 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) { 491 // if arity and trailing parameter are compatible, do normal thing 492 return asTypeCache = asFixedArity().asType(newType); 493 } 494 // check cache 495 MethodHandle acc = asCollectorCache; 496 if (acc != null && acc.type().parameterCount() == newArity) 497 return asTypeCache = acc.asType(newType); 498 // build and cache a collector 499 int arrayLength = newArity - collectArg; 500 MethodHandle collector; 501 try { 502 collector = asFixedArity().asCollector(arrayType, arrayLength); 503 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector; 504 } catch (IllegalArgumentException ex) { 505 throw new WrongMethodTypeException("cannot build collector", ex); 506 } 507 asCollectorCache = collector; 508 return asTypeCache = collector.asType(newType); 509 } 510 511 @Override 512 boolean viewAsTypeChecks(MethodType newType, boolean strict) { 513 super.viewAsTypeChecks(newType, true); 514 if (strict) return true; 515 // extra assertion for non-strict checks: 516 assert (type().lastParameterType().getComponentType() 517 .isAssignableFrom( 518 newType.lastParameterType().getComponentType())) 519 : Arrays.asList(this, newType); 520 return true; 521 } 522 } 523 524 /** Factory method: Spread selected argument. */ 525 static MethodHandle makeSpreadArguments(MethodHandle target, 526 Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) { 527 MethodType targetType = target.type(); 528 529 for (int i = 0; i < spreadArgCount; i++) { 530 Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i); 531 if (arg == null) arg = Object.class; 532 targetType = targetType.changeParameterType(spreadArgPos + i, arg); 533 } 534 target = target.asType(targetType); 535 536 MethodType srcType = targetType 537 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType); 538 // Now build a LambdaForm. 539 MethodType lambdaType = srcType.invokerType(); 540 Name[] names = arguments(spreadArgCount + 2, lambdaType); 541 int nameCursor = lambdaType.parameterCount(); 542 int[] indexes = new int[targetType.parameterCount()]; 543 544 for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) { 545 Class<?> src = lambdaType.parameterType(i); 546 if (i == spreadArgPos) { 547 // Spread the array. 548 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType); 549 Name array = names[argIndex]; 550 names[nameCursor++] = new Name(Lazy.NF_checkSpreadArgument, array, spreadArgCount); 551 for (int j = 0; j < spreadArgCount; i++, j++) { 552 indexes[i] = nameCursor; 553 names[nameCursor++] = new Name(aload, array, j); 554 } 555 } else if (i < indexes.length) { 556 indexes[i] = argIndex; 557 } 558 } 559 assert(nameCursor == names.length-1); // leave room for the final call 560 561 // Build argument array for the call. 562 Name[] targetArgs = new Name[targetType.parameterCount()]; 563 for (int i = 0; i < targetType.parameterCount(); i++) { 564 int idx = indexes[i]; 565 targetArgs[i] = names[idx]; 566 } 567 names[names.length - 1] = new Name(target, (Object[]) targetArgs); 568 569 LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names); 570 return SimpleMethodHandle.make(srcType, form); 571 } 572 573 static void checkSpreadArgument(Object av, int n) { 574 if (av == null) { 575 if (n == 0) return; 576 } else if (av instanceof Object[]) { 577 int len = ((Object[])av).length; 578 if (len == n) return; 579 } else { 580 int len = java.lang.reflect.Array.getLength(av); 581 if (len == n) return; 582 } 583 // fall through to error: 584 throw newIllegalArgumentException("array is not of length "+n); 585 } 586 587 /** 588 * Pre-initialized NamedFunctions for bootstrapping purposes. 589 * Factored in an inner class to delay initialization until first usage. 590 */ 591 static class Lazy { 592 private static final Class<?> MHI = MethodHandleImpl.class; 593 594 private static final MethodHandle[] ARRAYS; 595 private static final MethodHandle[] FILL_ARRAYS; 596 597 static final NamedFunction NF_checkSpreadArgument; 598 static final NamedFunction NF_guardWithCatch; 599 static final NamedFunction NF_throwException; 600 601 static final MethodHandle MH_castReference; 602 static final MethodHandle MH_selectAlternative; 603 static final MethodHandle MH_copyAsPrimitiveArray; 604 static final MethodHandle MH_fillNewTypedArray; 605 static final MethodHandle MH_fillNewArray; 606 static final MethodHandle MH_arrayIdentity; 607 608 static { 609 ARRAYS = makeArrays(); 610 FILL_ARRAYS = makeFillArrays(); 611 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, int[].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, int[] counters) { 700 if (counters != null) { 701 updateCounters(counters, testResult); 702 } 703 if (testResult) { 704 return target; 705 } else { 706 return fallback; 707 } 708 } 709 710 // Intrinsified by C2. Counters are used during parsing to calculate branch frequencies. 711 @LambdaForm.Hidden 712 static 713 boolean profileBranch(boolean result, int[] counters) { 714 updateCounters(counters, result); 715 return result; 716 } 717 718 @LambdaForm.Hidden 719 @ForceInline 720 static 721 void updateCounters(int[] counters, boolean result) { 722 int idx = result ? 0 : 1; 723 try { 724 counters[idx] = Math.addExact(counters[idx], 1); 725 } catch (ArithmeticException e) { 726 // Avoid continuous overflow by halving the problematic count. 727 counters[idx] = counters[idx] / 2; 728 } 729 } 730 731 static 732 MethodHandle makeGuardWithTest(MethodHandle test, 733 MethodHandle target, 734 MethodHandle fallback) { 735 MethodType type = target.type(); 736 assert(test.type().equals(type.changeReturnType(boolean.class)) && fallback.type().equals(type)); 737 MethodType basicType = type.basicType(); 738 int[] counters = PROFILE_GWT ? new int[2] : null; 739 LambdaForm form = makeGuardWithTestForm(basicType); 740 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL(); 741 BoundMethodHandle mh; 742 743 try { 744 mh = (BoundMethodHandle) 745 data.constructor().invokeBasic(type, form, 746 (Object) test, (Object) profile(target), (Object) profile(fallback), counters); 747 } catch (Throwable ex) { 748 throw uncaughtException(ex); 749 } 750 assert(mh.type() == type); 751 return mh; 752 } 753 754 755 static 756 MethodHandle profile(MethodHandle target) { 757 if (DONT_INLINE_THRESHOLD >= 0) { 758 return makeBlockInlningWrapper(target); 759 } else { 760 return target; 761 } 762 } 763 764 /** 765 * Block inlining during JIT-compilation of a target method handle if it hasn't been invoked enough times. 766 * Corresponding LambdaForm has @DontInline when compiled into bytecode. 767 */ 768 static 769 MethodHandle makeBlockInlningWrapper(MethodHandle target) { 770 LambdaForm lform = PRODUCE_BLOCK_INLINING_FORM.apply(target); 771 return new CountingWrapper(target, lform, 772 PRODUCE_BLOCK_INLINING_FORM, PRODUCE_REINVOKER_FORM, 773 DONT_INLINE_THRESHOLD); 774 } 775 776 /** Constructs reinvoker lambda form which block inlining during JIT-compilation for a particular method handle */ 777 private static final Function<MethodHandle, LambdaForm> PRODUCE_BLOCK_INLINING_FORM = new Function<MethodHandle, LambdaForm>() { 778 @Override 779 public LambdaForm apply(MethodHandle target) { 780 return DelegatingMethodHandle.makeReinvokerForm(target, 781 MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, "reinvoker.dontInline", false, 782 DelegatingMethodHandle.NF_getTarget, CountingWrapper.NF_maybeStopCounting); 783 } 784 }; 785 786 /** Constructs simple reinvoker lambda form for a particular method handle */ 787 private static final Function<MethodHandle, LambdaForm> PRODUCE_REINVOKER_FORM = new Function<MethodHandle, LambdaForm>() { 788 @Override 789 public LambdaForm apply(MethodHandle target) { 790 return DelegatingMethodHandle.makeReinvokerForm(target, 791 MethodTypeForm.LF_DELEGATE, DelegatingMethodHandle.class, DelegatingMethodHandle.NF_getTarget); 792 } 793 }; 794 795 /** 796 * Counting method handle. It has 2 states: counting and non-counting. 797 * It is in counting state for the first n invocations and then transitions to non-counting state. 798 * Behavior in counting and non-counting states is determined by lambda forms produced by 799 * countingFormProducer & nonCountingFormProducer respectively. 800 */ 801 static class CountingWrapper extends DelegatingMethodHandle { 802 private final MethodHandle target; 803 private int count; 804 private Function<MethodHandle, LambdaForm> countingFormProducer; 805 private Function<MethodHandle, LambdaForm> nonCountingFormProducer; 806 private volatile boolean isCounting; 807 808 private CountingWrapper(MethodHandle target, LambdaForm lform, 809 Function<MethodHandle, LambdaForm> countingFromProducer, 810 Function<MethodHandle, LambdaForm> nonCountingFormProducer, 811 int count) { 812 super(target.type(), lform); 813 this.target = target; 814 this.count = count; 815 this.countingFormProducer = countingFromProducer; 816 this.nonCountingFormProducer = nonCountingFormProducer; 817 this.isCounting = (count > 0); 818 } 819 820 @Hidden 821 @Override 822 protected MethodHandle getTarget() { 823 return target; 824 } 825 826 @Override 827 public MethodHandle asTypeUncached(MethodType newType) { 828 MethodHandle newTarget = target.asType(newType); 829 MethodHandle wrapper; 830 if (isCounting) { 831 LambdaForm lform; 832 lform = countingFormProducer.apply(target); 833 wrapper = new CountingWrapper(newTarget, lform, countingFormProducer, nonCountingFormProducer, DONT_INLINE_THRESHOLD); 834 } else { 835 wrapper = newTarget; // no need for a counting wrapper anymore 836 } 837 return (asTypeCache = wrapper); 838 } 839 840 boolean countDown() { 841 if (count <= 0) { 842 // Try to limit number of updates. MethodHandle.updateForm() doesn't guarantee LF update visibility. 843 if (isCounting) { 844 isCounting = false; 845 return true; 846 } else { 847 return false; 848 } 849 } else { 850 --count; 851 return false; 852 } 853 } 854 855 @Hidden 856 static void maybeStopCounting(Object o1) { 857 CountingWrapper wrapper = (CountingWrapper) o1; 858 if (wrapper.countDown()) { 859 // Reached invocation threshold. Replace counting behavior with a non-counting one. 860 LambdaForm lform = wrapper.nonCountingFormProducer.apply(wrapper.target); 861 lform.compileToBytecode(); // speed up warmup by avoiding LF interpretation again after transition 862 wrapper.updateForm(lform); 863 } 864 } 865 866 static final NamedFunction NF_maybeStopCounting; 867 static { 868 Class<?> THIS_CLASS = CountingWrapper.class; 869 try { 870 NF_maybeStopCounting = new NamedFunction(THIS_CLASS.getDeclaredMethod("maybeStopCounting", Object.class)); 871 } catch (ReflectiveOperationException ex) { 872 throw newInternalError(ex); 873 } 874 } 875 } 876 877 static 878 LambdaForm makeGuardWithTestForm(MethodType basicType) { 879 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWT); 880 if (lform != null) return lform; 881 final int THIS_MH = 0; // the BMH_LLL 882 final int ARG_BASE = 1; // start of incoming arguments 883 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 884 int nameCursor = ARG_LIMIT; 885 final int GET_TEST = nameCursor++; 886 final int GET_TARGET = nameCursor++; 887 final int GET_FALLBACK = nameCursor++; 888 final int GET_COUNTERS = nameCursor++; 889 final int CALL_TEST = nameCursor++; 890 final int SELECT_ALT = nameCursor++; 891 final int CALL_TARGET = nameCursor++; 892 assert(CALL_TARGET == SELECT_ALT+1); // must be true to trigger IBG.emitSelectAlternative 893 894 MethodType lambdaType = basicType.invokerType(); 895 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 896 897 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL(); 898 names[THIS_MH] = names[THIS_MH].withConstraint(data); 899 names[GET_TEST] = new Name(data.getterFunction(0), names[THIS_MH]); 900 names[GET_TARGET] = new Name(data.getterFunction(1), names[THIS_MH]); 901 names[GET_FALLBACK] = new Name(data.getterFunction(2), names[THIS_MH]); 902 names[GET_COUNTERS] = new Name(data.getterFunction(3), names[THIS_MH]); 903 Object[] invokeArgs = Arrays.copyOfRange(names, 0, ARG_LIMIT, Object[].class); 904 905 // call test 906 MethodType testType = basicType.changeReturnType(boolean.class).basicType(); 907 invokeArgs[0] = names[GET_TEST]; 908 names[CALL_TEST] = new Name(testType, invokeArgs); 909 910 // call selectAlternative 911 names[SELECT_ALT] = new Name(Lazy.MH_selectAlternative, names[CALL_TEST], 912 names[GET_TARGET], names[GET_FALLBACK], names[GET_COUNTERS]); 913 914 // call target or fallback 915 invokeArgs[0] = names[SELECT_ALT]; 916 names[CALL_TARGET] = new Name(basicType, invokeArgs); 917 918 lform = new LambdaForm("guard", lambdaType.parameterCount(), names, /*forceInline=*/true); 919 920 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform); 921 } 922 923 /** 924 * The LambdaForm shape for catchException combinator is the following: 925 * <blockquote><pre>{@code 926 * guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{ 927 * t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L); 928 * t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L); 929 * t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L); 930 * t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L); 931 * t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L); 932 * t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L); 933 * t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L); 934 * t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I} 935 * }</pre></blockquote> 936 * 937 * argL0 and argL2 are target and catcher method handles. argL1 is exception class. 938 * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[] 939 * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()). 940 * 941 * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms 942 * among catchException combinators with the same basic type. 943 */ 944 private static LambdaForm makeGuardWithCatchForm(MethodType basicType) { 945 MethodType lambdaType = basicType.invokerType(); 946 947 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC); 948 if (lform != null) { 949 return lform; 950 } 951 final int THIS_MH = 0; // the BMH_LLLLL 952 final int ARG_BASE = 1; // start of incoming arguments 953 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 954 955 int nameCursor = ARG_LIMIT; 956 final int GET_TARGET = nameCursor++; 957 final int GET_CLASS = nameCursor++; 958 final int GET_CATCHER = nameCursor++; 959 final int GET_COLLECT_ARGS = nameCursor++; 960 final int GET_UNBOX_RESULT = nameCursor++; 961 final int BOXED_ARGS = nameCursor++; 962 final int TRY_CATCH = nameCursor++; 963 final int UNBOX_RESULT = nameCursor++; 964 965 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 966 967 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL(); 968 names[THIS_MH] = names[THIS_MH].withConstraint(data); 969 names[GET_TARGET] = new Name(data.getterFunction(0), names[THIS_MH]); 970 names[GET_CLASS] = new Name(data.getterFunction(1), names[THIS_MH]); 971 names[GET_CATCHER] = new Name(data.getterFunction(2), names[THIS_MH]); 972 names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]); 973 names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]); 974 975 // FIXME: rework argument boxing/result unboxing logic for LF interpretation 976 977 // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...); 978 MethodType collectArgsType = basicType.changeReturnType(Object.class); 979 MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType); 980 Object[] args = new Object[invokeBasic.type().parameterCount()]; 981 args[0] = names[GET_COLLECT_ARGS]; 982 System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE); 983 names[BOXED_ARGS] = new Name(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH), args); 984 985 // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L); 986 Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]}; 987 names[TRY_CATCH] = new Name(Lazy.NF_guardWithCatch, gwcArgs); 988 989 // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L); 990 MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class)); 991 Object[] unboxArgs = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]}; 992 names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs); 993 994 lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names); 995 996 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform); 997 } 998 999 static 1000 MethodHandle makeGuardWithCatch(MethodHandle target, 1001 Class<? extends Throwable> exType, 1002 MethodHandle catcher) { 1003 MethodType type = target.type(); 1004 LambdaForm form = makeGuardWithCatchForm(type.basicType()); 1005 1006 // Prepare auxiliary method handles used during LambdaForm interpretation. 1007 // Box arguments and wrap them into Object[]: ValueConversions.array(). 1008 MethodType varargsType = type.changeReturnType(Object[].class); 1009 MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType); 1010 // Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore(). 1011 MethodHandle unboxResult; 1012 Class<?> rtype = type.returnType(); 1013 if (rtype.isPrimitive()) { 1014 if (rtype == void.class) { 1015 unboxResult = ValueConversions.ignore(); 1016 } else { 1017 Wrapper w = Wrapper.forPrimitiveType(type.returnType()); 1018 unboxResult = ValueConversions.unboxExact(w); 1019 } 1020 } else { 1021 unboxResult = MethodHandles.identity(Object.class); 1022 } 1023 1024 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL(); 1025 BoundMethodHandle mh; 1026 try { 1027 mh = (BoundMethodHandle) 1028 data.constructor().invokeBasic(type, form, (Object) target, (Object) exType, (Object) catcher, 1029 (Object) collectArgs, (Object) unboxResult); 1030 } catch (Throwable ex) { 1031 throw uncaughtException(ex); 1032 } 1033 assert(mh.type() == type); 1034 return mh; 1035 } 1036 1037 /** 1038 * Intrinsified during LambdaForm compilation 1039 * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}). 1040 */ 1041 @LambdaForm.Hidden 1042 static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher, 1043 Object... av) throws Throwable { 1044 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 1045 try { 1046 return target.asFixedArity().invokeWithArguments(av); 1047 } catch (Throwable t) { 1048 if (!exType.isInstance(t)) throw t; 1049 return catcher.asFixedArity().invokeWithArguments(prepend(t, av)); 1050 } 1051 } 1052 1053 /** Prepend an element {@code elem} to an {@code array}. */ 1054 @LambdaForm.Hidden 1055 private static Object[] prepend(Object elem, Object[] array) { 1056 Object[] newArray = new Object[array.length+1]; 1057 newArray[0] = elem; 1058 System.arraycopy(array, 0, newArray, 1, array.length); 1059 return newArray; 1060 } 1061 1062 static 1063 MethodHandle throwException(MethodType type) { 1064 assert(Throwable.class.isAssignableFrom(type.parameterType(0))); 1065 int arity = type.parameterCount(); 1066 if (arity > 1) { 1067 MethodHandle mh = throwException(type.dropParameterTypes(1, arity)); 1068 mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity)); 1069 return mh; 1070 } 1071 return makePairwiseConvert(Lazy.NF_throwException.resolvedHandle(), type, false, true); 1072 } 1073 1074 static <T extends Throwable> Empty throwException(T t) throws T { throw t; } 1075 1076 static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2]; 1077 static MethodHandle fakeMethodHandleInvoke(MemberName method) { 1078 int idx; 1079 assert(method.isMethodHandleInvoke()); 1080 switch (method.getName()) { 1081 case "invoke": idx = 0; break; 1082 case "invokeExact": idx = 1; break; 1083 default: throw new InternalError(method.getName()); 1084 } 1085 MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx]; 1086 if (mh != null) return mh; 1087 MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class, 1088 MethodHandle.class, Object[].class); 1089 mh = throwException(type); 1090 mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle")); 1091 if (!method.getInvocationType().equals(mh.type())) 1092 throw new InternalError(method.toString()); 1093 mh = mh.withInternalMemberName(method, false); 1094 mh = mh.asVarargsCollector(Object[].class); 1095 assert(method.isVarargs()); 1096 FAKE_METHOD_HANDLE_INVOKE[idx] = mh; 1097 return mh; 1098 } 1099 1100 /** 1101 * Create an alias for the method handle which, when called, 1102 * appears to be called from the same class loader and protection domain 1103 * as hostClass. 1104 * This is an expensive no-op unless the method which is called 1105 * is sensitive to its caller. A small number of system methods 1106 * are in this category, including Class.forName and Method.invoke. 1107 */ 1108 static 1109 MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) { 1110 return BindCaller.bindCaller(mh, hostClass); 1111 } 1112 1113 // Put the whole mess into its own nested class. 1114 // That way we can lazily load the code and set up the constants. 1115 private static class BindCaller { 1116 static 1117 MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) { 1118 // Do not use this function to inject calls into system classes. 1119 if (hostClass == null 1120 || (hostClass.isArray() || 1121 hostClass.isPrimitive() || 1122 hostClass.getName().startsWith("java.") || 1123 hostClass.getName().startsWith("sun."))) { 1124 throw new InternalError(); // does not happen, and should not anyway 1125 } 1126 // For simplicity, convert mh to a varargs-like method. 1127 MethodHandle vamh = prepareForInvoker(mh); 1128 // Cache the result of makeInjectedInvoker once per argument class. 1129 MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass); 1130 return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass); 1131 } 1132 1133 private static MethodHandle makeInjectedInvoker(Class<?> hostClass) { 1134 Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null); 1135 if (hostClass.getClassLoader() != bcc.getClassLoader()) 1136 throw new InternalError(hostClass.getName()+" (CL)"); 1137 try { 1138 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain()) 1139 throw new InternalError(hostClass.getName()+" (PD)"); 1140 } catch (SecurityException ex) { 1141 // Self-check was blocked by security manager. This is OK. 1142 // In fact the whole try body could be turned into an assertion. 1143 } 1144 try { 1145 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class)); 1146 init.invokeExact(); // force initialization of the class 1147 } catch (Throwable ex) { 1148 throw uncaughtException(ex); 1149 } 1150 MethodHandle bccInvoker; 1151 try { 1152 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1153 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT); 1154 } catch (ReflectiveOperationException ex) { 1155 throw uncaughtException(ex); 1156 } 1157 // Test the invoker, to ensure that it really injects into the right place. 1158 try { 1159 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass); 1160 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc}); 1161 } catch (Throwable ex) { 1162 throw new InternalError(ex); 1163 } 1164 return bccInvoker; 1165 } 1166 private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() { 1167 @Override protected MethodHandle computeValue(Class<?> hostClass) { 1168 return makeInjectedInvoker(hostClass); 1169 } 1170 }; 1171 1172 // Adapt mh so that it can be called directly from an injected invoker: 1173 private static MethodHandle prepareForInvoker(MethodHandle mh) { 1174 mh = mh.asFixedArity(); 1175 MethodType mt = mh.type(); 1176 int arity = mt.parameterCount(); 1177 MethodHandle vamh = mh.asType(mt.generic()); 1178 vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames 1179 vamh = vamh.asSpreader(Object[].class, arity); 1180 vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames 1181 return vamh; 1182 } 1183 1184 // Undo the adapter effect of prepareForInvoker: 1185 private static MethodHandle restoreToType(MethodHandle vamh, 1186 MethodHandle original, 1187 Class<?> hostClass) { 1188 MethodType type = original.type(); 1189 MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount()); 1190 MemberName member = original.internalMemberName(); 1191 mh = mh.asType(type); 1192 mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass); 1193 return mh; 1194 } 1195 1196 private static final MethodHandle MH_checkCallerClass; 1197 static { 1198 final Class<?> THIS_CLASS = BindCaller.class; 1199 assert(checkCallerClass(THIS_CLASS, THIS_CLASS)); 1200 try { 1201 MH_checkCallerClass = IMPL_LOOKUP 1202 .findStatic(THIS_CLASS, "checkCallerClass", 1203 MethodType.methodType(boolean.class, Class.class, Class.class)); 1204 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS)); 1205 } catch (Throwable ex) { 1206 throw new InternalError(ex); 1207 } 1208 } 1209 1210 @CallerSensitive 1211 private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) { 1212 // This method is called via MH_checkCallerClass and so it's 1213 // correct to ask for the immediate caller here. 1214 Class<?> actual = Reflection.getCallerClass(); 1215 if (actual != expected && actual != expected2) 1216 throw new InternalError("found "+actual.getName()+", expected "+expected.getName() 1217 +(expected == expected2 ? "" : ", or else "+expected2.getName())); 1218 return true; 1219 } 1220 1221 private static final byte[] T_BYTES; 1222 static { 1223 final Object[] values = {null}; 1224 AccessController.doPrivileged(new PrivilegedAction<Void>() { 1225 public Void run() { 1226 try { 1227 Class<T> tClass = T.class; 1228 String tName = tClass.getName(); 1229 String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class"; 1230 java.net.URLConnection uconn = tClass.getResource(tResource).openConnection(); 1231 int len = uconn.getContentLength(); 1232 byte[] bytes = new byte[len]; 1233 try (java.io.InputStream str = uconn.getInputStream()) { 1234 int nr = str.read(bytes); 1235 if (nr != len) throw new java.io.IOException(tResource); 1236 } 1237 values[0] = bytes; 1238 } catch (java.io.IOException ex) { 1239 throw new InternalError(ex); 1240 } 1241 return null; 1242 } 1243 }); 1244 T_BYTES = (byte[]) values[0]; 1245 } 1246 1247 // The following class is used as a template for Unsafe.defineAnonymousClass: 1248 private static class T { 1249 static void init() { } // side effect: initializes this class 1250 static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable { 1251 return vamh.invokeExact(args); 1252 } 1253 } 1254 } 1255 1256 1257 /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */ 1258 private static final class WrappedMember extends DelegatingMethodHandle { 1259 private final MethodHandle target; 1260 private final MemberName member; 1261 private final Class<?> callerClass; 1262 private final boolean isInvokeSpecial; 1263 1264 private WrappedMember(MethodHandle target, MethodType type, 1265 MemberName member, boolean isInvokeSpecial, 1266 Class<?> callerClass) { 1267 super(type, target); 1268 this.target = target; 1269 this.member = member; 1270 this.callerClass = callerClass; 1271 this.isInvokeSpecial = isInvokeSpecial; 1272 } 1273 1274 @Override 1275 MemberName internalMemberName() { 1276 return member; 1277 } 1278 @Override 1279 Class<?> internalCallerClass() { 1280 return callerClass; 1281 } 1282 @Override 1283 boolean isInvokeSpecial() { 1284 return isInvokeSpecial; 1285 } 1286 @Override 1287 protected MethodHandle getTarget() { 1288 return target; 1289 } 1290 @Override 1291 public MethodHandle asTypeUncached(MethodType newType) { 1292 // This MH is an alias for target, except for the MemberName 1293 // Drop the MemberName if there is any conversion. 1294 return asTypeCache = target.asType(newType); 1295 } 1296 } 1297 1298 static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) { 1299 if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial()) 1300 return target; 1301 return new WrappedMember(target, target.type(), member, isInvokeSpecial, null); 1302 } 1303 1304 /** Intrinsic IDs */ 1305 /*non-public*/ 1306 enum Intrinsic { 1307 SELECT_ALTERNATIVE, 1308 GUARD_WITH_CATCH, 1309 NEW_ARRAY, 1310 ARRAY_LOAD, 1311 ARRAY_STORE, 1312 IDENTITY, 1313 ZERO, 1314 NONE // no intrinsic associated 1315 } 1316 1317 /** Mark arbitrary method handle as intrinsic. 1318 * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */ 1319 private static final class IntrinsicMethodHandle extends DelegatingMethodHandle { 1320 private final MethodHandle target; 1321 private final Intrinsic intrinsicName; 1322 1323 IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) { 1324 super(target.type(), target); 1325 this.target = target; 1326 this.intrinsicName = intrinsicName; 1327 } 1328 1329 @Override 1330 protected MethodHandle getTarget() { 1331 return target; 1332 } 1333 1334 @Override 1335 Intrinsic intrinsicName() { 1336 return intrinsicName; 1337 } 1338 1339 @Override 1340 public MethodHandle asTypeUncached(MethodType newType) { 1341 // This MH is an alias for target, except for the intrinsic name 1342 // Drop the name if there is any conversion. 1343 return asTypeCache = target.asType(newType); 1344 } 1345 1346 @Override 1347 String internalProperties() { 1348 return super.internalProperties() + 1349 "\n& Intrinsic="+intrinsicName; 1350 } 1351 1352 @Override 1353 public MethodHandle asCollector(Class<?> arrayType, int arrayLength) { 1354 if (intrinsicName == Intrinsic.IDENTITY) { 1355 MethodType resultType = type().asCollectorType(arrayType, arrayLength); 1356 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength); 1357 return newArray.asType(resultType); 1358 } 1359 return super.asCollector(arrayType, arrayLength); 1360 } 1361 } 1362 1363 static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) { 1364 if (intrinsicName == target.intrinsicName()) 1365 return target; 1366 return new IntrinsicMethodHandle(target, intrinsicName); 1367 } 1368 1369 static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) { 1370 return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName); 1371 } 1372 1373 /// Collection of multiple arguments. 1374 1375 private static MethodHandle findCollector(String name, int nargs, Class<?> rtype, Class<?>... ptypes) { 1376 MethodType type = MethodType.genericMethodType(nargs) 1377 .changeReturnType(rtype) 1378 .insertParameterTypes(0, ptypes); 1379 try { 1380 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, name, type); 1381 } catch (ReflectiveOperationException ex) { 1382 return null; 1383 } 1384 } 1385 1386 private static final Object[] NO_ARGS_ARRAY = {}; 1387 private static Object[] makeArray(Object... args) { return args; } 1388 private static Object[] array() { return NO_ARGS_ARRAY; } 1389 private static Object[] array(Object a0) 1390 { return makeArray(a0); } 1391 private static Object[] array(Object a0, Object a1) 1392 { return makeArray(a0, a1); } 1393 private static Object[] array(Object a0, Object a1, Object a2) 1394 { return makeArray(a0, a1, a2); } 1395 private static Object[] array(Object a0, Object a1, Object a2, Object a3) 1396 { return makeArray(a0, a1, a2, a3); } 1397 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1398 Object a4) 1399 { return makeArray(a0, a1, a2, a3, a4); } 1400 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1401 Object a4, Object a5) 1402 { return makeArray(a0, a1, a2, a3, a4, a5); } 1403 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1404 Object a4, Object a5, Object a6) 1405 { return makeArray(a0, a1, a2, a3, a4, a5, a6); } 1406 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1407 Object a4, Object a5, Object a6, Object a7) 1408 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); } 1409 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1410 Object a4, Object a5, Object a6, Object a7, 1411 Object a8) 1412 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); } 1413 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1414 Object a4, Object a5, Object a6, Object a7, 1415 Object a8, Object a9) 1416 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); } 1417 1418 private static final int ARRAYS_COUNT = 11; 1419 1420 private static MethodHandle[] makeArrays() { 1421 MethodHandle[] mhs = new MethodHandle[MAX_ARITY + 1]; 1422 for (int i = 0; i < ARRAYS_COUNT; i++) { 1423 MethodHandle mh = findCollector("array", i, Object[].class); 1424 mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY); 1425 mhs[i] = mh; 1426 } 1427 assert(assertArrayMethodCount(mhs)); 1428 return mhs; 1429 } 1430 1431 private static boolean assertArrayMethodCount(MethodHandle[] mhs) { 1432 assert(findCollector("array", ARRAYS_COUNT, Object[].class) == null); 1433 for (int i = 0; i < ARRAYS_COUNT; i++) { 1434 assert(mhs[i] != null); 1435 } 1436 return true; 1437 } 1438 1439 // filling versions of the above: 1440 // using Integer len instead of int len and no varargs to avoid bootstrapping problems 1441 private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) { 1442 Object[] a = new Object[len]; 1443 fillWithArguments(a, 0, args); 1444 return a; 1445 } 1446 private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) { 1447 Object[] a = Arrays.copyOf(example, len); 1448 assert(a.getClass() != Object[].class); 1449 fillWithArguments(a, 0, args); 1450 return a; 1451 } 1452 private static void fillWithArguments(Object[] a, int pos, Object... args) { 1453 System.arraycopy(args, 0, a, pos, args.length); 1454 } 1455 // using Integer pos instead of int pos to avoid bootstrapping problems 1456 private static Object[] fillArray(Integer pos, Object[] a, Object a0) 1457 { fillWithArguments(a, pos, a0); return a; } 1458 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1) 1459 { fillWithArguments(a, pos, a0, a1); return a; } 1460 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2) 1461 { fillWithArguments(a, pos, a0, a1, a2); return a; } 1462 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3) 1463 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; } 1464 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1465 Object a4) 1466 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; } 1467 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1468 Object a4, Object a5) 1469 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); return a; } 1470 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1471 Object a4, Object a5, Object a6) 1472 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; } 1473 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1474 Object a4, Object a5, Object a6, Object a7) 1475 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; } 1476 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1477 Object a4, Object a5, Object a6, Object a7, 1478 Object a8) 1479 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; } 1480 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1481 Object a4, Object a5, Object a6, Object a7, 1482 Object a8, Object a9) 1483 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; } 1484 1485 private static final int FILL_ARRAYS_COUNT = 11; // current number of fillArray methods 1486 1487 private static MethodHandle[] makeFillArrays() { 1488 MethodHandle[] mhs = new MethodHandle[FILL_ARRAYS_COUNT]; 1489 mhs[0] = null; // there is no empty fill; at least a0 is required 1490 for (int i = 1; i < FILL_ARRAYS_COUNT; i++) { 1491 MethodHandle mh = findCollector("fillArray", i, Object[].class, Integer.class, Object[].class); 1492 mhs[i] = mh; 1493 } 1494 assert(assertFillArrayMethodCount(mhs)); 1495 return mhs; 1496 } 1497 1498 private static boolean assertFillArrayMethodCount(MethodHandle[] mhs) { 1499 assert(findCollector("fillArray", FILL_ARRAYS_COUNT, Object[].class, Integer.class, Object[].class) == null); 1500 for (int i = 1; i < FILL_ARRAYS_COUNT; i++) { 1501 assert(mhs[i] != null); 1502 } 1503 return true; 1504 } 1505 1506 private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) { 1507 Object a = w.makeArray(boxes.length); 1508 w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length); 1509 return a; 1510 } 1511 1512 /** Return a method handle that takes the indicated number of Object 1513 * arguments and returns an Object array of them, as if for varargs. 1514 */ 1515 static MethodHandle varargsArray(int nargs) { 1516 MethodHandle mh = Lazy.ARRAYS[nargs]; 1517 if (mh != null) return mh; 1518 mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs); 1519 assert(assertCorrectArity(mh, nargs)); 1520 mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY); 1521 return Lazy.ARRAYS[nargs] = mh; 1522 } 1523 1524 private static boolean assertCorrectArity(MethodHandle mh, int arity) { 1525 assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh; 1526 return true; 1527 } 1528 1529 // Array identity function (used as Lazy.MH_arrayIdentity). 1530 static <T> T[] identity(T[] x) { 1531 return x; 1532 } 1533 1534 private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) { 1535 // Build up the result mh as a sequence of fills like this: 1536 // finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23)) 1537 // The various fill(_,10*I,___*[J]) are reusable. 1538 int leftLen = Math.min(nargs, LEFT_ARGS); // absorb some arguments immediately 1539 int rightLen = nargs - leftLen; 1540 MethodHandle leftCollector = newArray.bindTo(nargs); 1541 leftCollector = leftCollector.asCollector(Object[].class, leftLen); 1542 MethodHandle mh = finisher; 1543 if (rightLen > 0) { 1544 MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen); 1545 if (mh == Lazy.MH_arrayIdentity) 1546 mh = rightFiller; 1547 else 1548 mh = MethodHandles.collectArguments(mh, 0, rightFiller); 1549 } 1550 if (mh == Lazy.MH_arrayIdentity) 1551 mh = leftCollector; 1552 else 1553 mh = MethodHandles.collectArguments(mh, 0, leftCollector); 1554 return mh; 1555 } 1556 1557 private static final int LEFT_ARGS = FILL_ARRAYS_COUNT - 1; 1558 private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1]; 1559 /** fill_array_to_right(N).invoke(a, argL..arg[N-1]) 1560 * fills a[L]..a[N-1] with corresponding arguments, 1561 * and then returns a. The value L is a global constant (LEFT_ARGS). 1562 */ 1563 private static MethodHandle fillToRight(int nargs) { 1564 MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs]; 1565 if (filler != null) return filler; 1566 filler = buildFiller(nargs); 1567 assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1)); 1568 return FILL_ARRAY_TO_RIGHT[nargs] = filler; 1569 } 1570 private static MethodHandle buildFiller(int nargs) { 1571 if (nargs <= LEFT_ARGS) 1572 return Lazy.MH_arrayIdentity; // no args to fill; return the array unchanged 1573 // we need room for both mh and a in mh.invoke(a, arg*[nargs]) 1574 final int CHUNK = LEFT_ARGS; 1575 int rightLen = nargs % CHUNK; 1576 int midLen = nargs - rightLen; 1577 if (rightLen == 0) { 1578 midLen = nargs - (rightLen = CHUNK); 1579 if (FILL_ARRAY_TO_RIGHT[midLen] == null) { 1580 // build some precursors from left to right 1581 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK) 1582 if (j > LEFT_ARGS) fillToRight(j); 1583 } 1584 } 1585 if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS); 1586 assert(rightLen > 0); 1587 MethodHandle midFill = fillToRight(midLen); // recursive fill 1588 MethodHandle rightFill = Lazy.FILL_ARRAYS[rightLen].bindTo(midLen); // [midLen..nargs-1] 1589 assert(midFill.type().parameterCount() == 1 + midLen - LEFT_ARGS); 1590 assert(rightFill.type().parameterCount() == 1 + rightLen); 1591 1592 // Combine the two fills: 1593 // right(mid(a, x10..x19), x20..x23) 1594 // The final product will look like this: 1595 // right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23) 1596 if (midLen == LEFT_ARGS) 1597 return rightFill; 1598 else 1599 return MethodHandles.collectArguments(rightFill, 0, midFill); 1600 } 1601 1602 // Type-polymorphic version of varargs maker. 1603 private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS 1604 = new ClassValue<MethodHandle[]>() { 1605 @Override 1606 protected MethodHandle[] computeValue(Class<?> type) { 1607 return new MethodHandle[256]; 1608 } 1609 }; 1610 1611 static final int MAX_JVM_ARITY = 255; // limit imposed by the JVM 1612 1613 /** Return a method handle that takes the indicated number of 1614 * typed arguments and returns an array of them. 1615 * The type argument is the array type. 1616 */ 1617 static MethodHandle varargsArray(Class<?> arrayType, int nargs) { 1618 Class<?> elemType = arrayType.getComponentType(); 1619 if (elemType == null) throw new IllegalArgumentException("not an array: "+arrayType); 1620 // FIXME: Need more special casing and caching here. 1621 if (nargs >= MAX_JVM_ARITY/2 - 1) { 1622 int slots = nargs; 1623 final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1; // 1 for receiver MH 1624 if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive()) 1625 slots *= Wrapper.forPrimitiveType(elemType).stackSlots(); 1626 if (slots > MAX_ARRAY_SLOTS) 1627 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs); 1628 } 1629 if (elemType == Object.class) 1630 return varargsArray(nargs); 1631 // other cases: primitive arrays, subtypes of Object[] 1632 MethodHandle cache[] = TYPED_COLLECTORS.get(elemType); 1633 MethodHandle mh = nargs < cache.length ? cache[nargs] : null; 1634 if (mh != null) return mh; 1635 if (nargs == 0) { 1636 Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0); 1637 mh = MethodHandles.constant(arrayType, example); 1638 } else if (elemType.isPrimitive()) { 1639 MethodHandle builder = Lazy.MH_fillNewArray; 1640 MethodHandle producer = buildArrayProducer(arrayType); 1641 mh = buildVarargsArray(builder, producer, nargs); 1642 } else { 1643 Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class); 1644 Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType); 1645 MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example); 1646 MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed 1647 mh = buildVarargsArray(builder, producer, nargs); 1648 } 1649 mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType))); 1650 mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY); 1651 assert(assertCorrectArity(mh, nargs)); 1652 if (nargs < cache.length) 1653 cache[nargs] = mh; 1654 return mh; 1655 } 1656 1657 private static MethodHandle buildArrayProducer(Class<?> arrayType) { 1658 Class<?> elemType = arrayType.getComponentType(); 1659 assert(elemType.isPrimitive()); 1660 return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType)); 1661 } 1662 }