1 /* 2 * Copyright (c) 2008, 2023, 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 jdk.internal.access.JavaLangInvokeAccess; 29 import jdk.internal.access.SharedSecrets; 30 import jdk.internal.constant.MethodTypeDescImpl; 31 import jdk.internal.constant.ReferenceClassDescImpl; 32 import jdk.internal.foreign.abi.NativeEntryPoint; 33 import jdk.internal.reflect.CallerSensitive; 34 import jdk.internal.reflect.Reflection; 35 import jdk.internal.vm.annotation.ForceInline; 36 import jdk.internal.vm.annotation.Hidden; 37 import jdk.internal.vm.annotation.Stable; 38 import sun.invoke.empty.Empty; 39 import sun.invoke.util.ValueConversions; 40 import sun.invoke.util.VerifyType; 41 import sun.invoke.util.Wrapper; 42 43 import java.lang.classfile.ClassFile; 44 import java.lang.constant.ClassDesc; 45 import java.lang.invoke.MethodHandles.Lookup; 46 import java.lang.reflect.Array; 47 import java.lang.reflect.Constructor; 48 import java.lang.reflect.Field; 49 import java.nio.ByteOrder; 50 import java.util.Arrays; 51 import java.util.Collections; 52 import java.util.HashMap; 53 import java.util.Iterator; 54 import java.util.List; 55 import java.util.Map; 56 import java.util.Objects; 57 import java.util.Set; 58 import java.util.concurrent.ConcurrentHashMap; 59 import java.util.function.Function; 60 import java.util.stream.Stream; 61 62 import static java.lang.classfile.ClassFile.*; 63 import static java.lang.constant.ConstantDescs.*; 64 import static java.lang.invoke.LambdaForm.*; 65 import static java.lang.invoke.MethodHandleNatives.Constants.MN_CALLER_SENSITIVE; 66 import static java.lang.invoke.MethodHandleNatives.Constants.MN_HIDDEN_MEMBER; 67 import static java.lang.invoke.MethodHandleStatics.*; 68 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 69 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.NESTMATE; 70 71 /** 72 * Trusted implementation code for MethodHandle. 73 * @author jrose 74 */ 75 /*non-public*/ 76 abstract class MethodHandleImpl { 77 78 /// Factory methods to create method handles: 79 80 static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, ArrayAccess access) { 81 if (arrayClass == Object[].class) { 82 return ArrayAccess.objectAccessor(access); 83 } 84 if (!arrayClass.isArray()) 85 throw newIllegalArgumentException("not an array: "+arrayClass); 86 MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass); 87 int cacheIndex = ArrayAccess.cacheIndex(access); 88 MethodHandle mh = cache[cacheIndex]; 89 if (mh != null) return mh; 90 mh = ArrayAccessor.getAccessor(arrayClass, access); 91 MethodType correctType = ArrayAccessor.correctType(arrayClass, access); 92 if (mh.type() != correctType) { 93 assert(mh.type().parameterType(0) == Object[].class); 94 /* if access == SET */ assert(access != ArrayAccess.SET || mh.type().parameterType(2) == Object.class); 95 /* if access == GET */ assert(access != ArrayAccess.GET || 96 (mh.type().returnType() == Object.class && 97 correctType.parameterType(0).getComponentType() == correctType.returnType())); 98 // safe to view non-strictly, because element type follows from array type 99 mh = mh.viewAsType(correctType, false); 100 } 101 mh = makeIntrinsic(mh, ArrayAccess.intrinsic(access)); 102 // Atomically update accessor cache. 103 synchronized(cache) { 104 if (cache[cacheIndex] == null) { 105 cache[cacheIndex] = mh; 106 } else { 107 // Throw away newly constructed accessor and use cached version. 108 mh = cache[cacheIndex]; 109 } 110 } 111 return mh; 112 } 113 114 enum ArrayAccess { 115 GET, SET, LENGTH; 116 117 // As ArrayAccess and ArrayAccessor have a circular dependency, the ArrayAccess properties cannot be stored in 118 // final fields. 119 120 static String opName(ArrayAccess a) { 121 return switch (a) { 122 case GET -> "getElement"; 123 case SET -> "setElement"; 124 case LENGTH -> "length"; 125 default -> throw unmatchedArrayAccess(a); 126 }; 127 } 128 129 static MethodHandle objectAccessor(ArrayAccess a) { 130 return switch (a) { 131 case GET -> ArrayAccessor.OBJECT_ARRAY_GETTER; 132 case SET -> ArrayAccessor.OBJECT_ARRAY_SETTER; 133 case LENGTH -> ArrayAccessor.OBJECT_ARRAY_LENGTH; 134 default -> throw unmatchedArrayAccess(a); 135 }; 136 } 137 138 static int cacheIndex(ArrayAccess a) { 139 return switch (a) { 140 case GET -> ArrayAccessor.GETTER_INDEX; 141 case SET -> ArrayAccessor.SETTER_INDEX; 142 case LENGTH -> ArrayAccessor.LENGTH_INDEX; 143 default -> throw unmatchedArrayAccess(a); 144 }; 145 } 146 147 static Intrinsic intrinsic(ArrayAccess a) { 148 return switch (a) { 149 case GET -> Intrinsic.ARRAY_LOAD; 150 case SET -> Intrinsic.ARRAY_STORE; 151 case LENGTH -> Intrinsic.ARRAY_LENGTH; 152 default -> throw unmatchedArrayAccess(a); 153 }; 154 } 155 } 156 157 static InternalError unmatchedArrayAccess(ArrayAccess a) { 158 return newInternalError("should not reach here (unmatched ArrayAccess: " + a + ")"); 159 } 160 161 static final class ArrayAccessor { 162 /// Support for array element and length access 163 static final int GETTER_INDEX = 0, SETTER_INDEX = 1, LENGTH_INDEX = 2, INDEX_LIMIT = 3; 164 static final ClassValue<MethodHandle[]> TYPED_ACCESSORS 165 = new ClassValue<MethodHandle[]>() { 166 @Override 167 protected MethodHandle[] computeValue(Class<?> type) { 168 return new MethodHandle[INDEX_LIMIT]; 169 } 170 }; 171 static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER, OBJECT_ARRAY_LENGTH; 172 static { 173 MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class); 174 cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.GET), Intrinsic.ARRAY_LOAD); 175 cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.SET), Intrinsic.ARRAY_STORE); 176 cache[LENGTH_INDEX] = OBJECT_ARRAY_LENGTH = makeIntrinsic(getAccessor(Object[].class, ArrayAccess.LENGTH), Intrinsic.ARRAY_LENGTH); 177 178 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName())); 179 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName())); 180 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_LENGTH.internalMemberName())); 181 } 182 183 static int getElementI(int[] a, int i) { return a[i]; } 184 static long getElementJ(long[] a, int i) { return a[i]; } 185 static float getElementF(float[] a, int i) { return a[i]; } 186 static double getElementD(double[] a, int i) { return a[i]; } 187 static boolean getElementZ(boolean[] a, int i) { return a[i]; } 188 static byte getElementB(byte[] a, int i) { return a[i]; } 189 static short getElementS(short[] a, int i) { return a[i]; } 190 static char getElementC(char[] a, int i) { return a[i]; } 191 static Object getElementL(Object[] a, int i) { return a[i]; } 192 193 static void setElementI(int[] a, int i, int x) { a[i] = x; } 194 static void setElementJ(long[] a, int i, long x) { a[i] = x; } 195 static void setElementF(float[] a, int i, float x) { a[i] = x; } 196 static void setElementD(double[] a, int i, double x) { a[i] = x; } 197 static void setElementZ(boolean[] a, int i, boolean x) { a[i] = x; } 198 static void setElementB(byte[] a, int i, byte x) { a[i] = x; } 199 static void setElementS(short[] a, int i, short x) { a[i] = x; } 200 static void setElementC(char[] a, int i, char x) { a[i] = x; } 201 static void setElementL(Object[] a, int i, Object x) { a[i] = x; } 202 203 static int lengthI(int[] a) { return a.length; } 204 static int lengthJ(long[] a) { return a.length; } 205 static int lengthF(float[] a) { return a.length; } 206 static int lengthD(double[] a) { return a.length; } 207 static int lengthZ(boolean[] a) { return a.length; } 208 static int lengthB(byte[] a) { return a.length; } 209 static int lengthS(short[] a) { return a.length; } 210 static int lengthC(char[] a) { return a.length; } 211 static int lengthL(Object[] a) { return a.length; } 212 213 static String name(Class<?> arrayClass, ArrayAccess access) { 214 Class<?> elemClass = arrayClass.getComponentType(); 215 if (elemClass == null) throw newIllegalArgumentException("not an array", arrayClass); 216 return ArrayAccess.opName(access) + Wrapper.basicTypeChar(elemClass); 217 } 218 static MethodType type(Class<?> arrayClass, ArrayAccess access) { 219 Class<?> elemClass = arrayClass.getComponentType(); 220 Class<?> arrayArgClass = arrayClass; 221 if (!elemClass.isPrimitive()) { 222 arrayArgClass = Object[].class; 223 elemClass = Object.class; 224 } 225 return switch (access) { 226 case GET -> MethodType.methodType(elemClass, arrayArgClass, int.class); 227 case SET -> MethodType.methodType(void.class, arrayArgClass, int.class, elemClass); 228 case LENGTH -> MethodType.methodType(int.class, arrayArgClass); 229 default -> throw unmatchedArrayAccess(access); 230 }; 231 } 232 static MethodType correctType(Class<?> arrayClass, ArrayAccess access) { 233 Class<?> elemClass = arrayClass.getComponentType(); 234 return switch (access) { 235 case GET -> MethodType.methodType(elemClass, arrayClass, int.class); 236 case SET -> MethodType.methodType(void.class, arrayClass, int.class, elemClass); 237 case LENGTH -> MethodType.methodType(int.class, arrayClass); 238 default -> throw unmatchedArrayAccess(access); 239 }; 240 } 241 static MethodHandle getAccessor(Class<?> arrayClass, ArrayAccess access) { 242 String name = name(arrayClass, access); 243 MethodType type = type(arrayClass, access); 244 try { 245 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type); 246 } catch (ReflectiveOperationException ex) { 247 throw uncaughtException(ex); 248 } 249 } 250 } 251 252 /** 253 * Create a JVM-level adapter method handle to conform the given method 254 * handle to the similar newType, using only pairwise argument conversions. 255 * For each argument, convert incoming argument to the exact type needed. 256 * The argument conversions allowed are casting, boxing and unboxing, 257 * integral widening or narrowing, and floating point widening or narrowing. 258 * @param srcType required call type 259 * @param target original method handle 260 * @param strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed 261 * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double) 262 * @return an adapter to the original handle with the desired new type, 263 * or the original target if the types are already identical 264 * or null if the adaptation cannot be made 265 */ 266 static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, 267 boolean strict, boolean monobox) { 268 MethodType dstType = target.type(); 269 if (srcType == dstType) 270 return target; 271 return makePairwiseConvertByEditor(target, srcType, strict, monobox); 272 } 273 274 private static int countNonNull(Object[] array) { 275 int count = 0; 276 if (array != null) { 277 for (Object x : array) { 278 if (x != null) ++count; 279 } 280 } 281 return count; 282 } 283 284 static MethodHandle makePairwiseConvertByEditor(MethodHandle target, MethodType srcType, 285 boolean strict, boolean monobox) { 286 // In method types arguments start at index 0, while the LF 287 // editor have the MH receiver at position 0 - adjust appropriately. 288 final int MH_RECEIVER_OFFSET = 1; 289 Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox); 290 int convCount = countNonNull(convSpecs); 291 if (convCount == 0) 292 return target.viewAsType(srcType, strict); 293 MethodType basicSrcType = srcType.basicType(); 294 MethodType midType = target.type().basicType(); 295 BoundMethodHandle mh = target.rebind(); 296 297 // Match each unique conversion to the positions at which it is to be applied 298 HashMap<Object, int[]> convSpecMap = HashMap.newHashMap(convCount); 299 for (int i = 0; i < convSpecs.length - MH_RECEIVER_OFFSET; i++) { 300 Object convSpec = convSpecs[i]; 301 if (convSpec == null) continue; 302 int[] positions = convSpecMap.get(convSpec); 303 if (positions == null) { 304 positions = new int[] { i + MH_RECEIVER_OFFSET }; 305 } else { 306 positions = Arrays.copyOf(positions, positions.length + 1); 307 positions[positions.length - 1] = i + MH_RECEIVER_OFFSET; 308 } 309 convSpecMap.put(convSpec, positions); 310 } 311 for (var entry : convSpecMap.entrySet()) { 312 Object convSpec = entry.getKey(); 313 314 MethodHandle fn; 315 if (convSpec instanceof Class) { 316 fn = getConstantHandle(MH_cast).bindTo(convSpec); 317 } else { 318 fn = (MethodHandle) convSpec; 319 } 320 int[] positions = entry.getValue(); 321 Class<?> newType = basicSrcType.parameterType(positions[0] - MH_RECEIVER_OFFSET); 322 BasicType newBasicType = BasicType.basicType(newType); 323 convCount -= positions.length; 324 if (convCount == 0) { 325 midType = srcType; 326 } else { 327 Class<?>[] ptypes = midType.ptypes().clone(); 328 for (int pos : positions) { 329 ptypes[pos - 1] = newType; 330 } 331 midType = MethodType.methodType(midType.rtype(), ptypes, true); 332 } 333 LambdaForm form2; 334 if (positions.length > 1) { 335 form2 = mh.editor().filterRepeatedArgumentForm(newBasicType, positions); 336 } else { 337 form2 = mh.editor().filterArgumentForm(positions[0], newBasicType); 338 } 339 mh = mh.copyWithExtendL(midType, form2, fn); 340 } 341 Object convSpec = convSpecs[convSpecs.length - 1]; 342 if (convSpec != null) { 343 MethodHandle fn; 344 if (convSpec instanceof Class) { 345 if (convSpec == void.class) 346 fn = null; 347 else 348 fn = getConstantHandle(MH_cast).bindTo(convSpec); 349 } else { 350 fn = (MethodHandle) convSpec; 351 } 352 Class<?> newType = basicSrcType.returnType(); 353 assert(--convCount == 0); 354 midType = srcType; 355 if (fn != null) { 356 mh = mh.rebind(); // rebind if too complex 357 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), false); 358 mh = mh.copyWithExtendL(midType, form2, fn); 359 } else { 360 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), true); 361 mh = mh.copyWith(midType, form2); 362 } 363 } 364 assert(convCount == 0); 365 assert(mh.type().equals(srcType)); 366 return mh; 367 } 368 369 static Object[] computeValueConversions(MethodType srcType, MethodType dstType, 370 boolean strict, boolean monobox) { 371 final int INARG_COUNT = srcType.parameterCount(); 372 Object[] convSpecs = null; 373 for (int i = 0; i <= INARG_COUNT; i++) { 374 boolean isRet = (i == INARG_COUNT); 375 Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i); 376 Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i); 377 if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) { 378 if (convSpecs == null) { 379 convSpecs = new Object[INARG_COUNT + 1]; 380 } 381 convSpecs[i] = valueConversion(src, dst, strict, monobox); 382 } 383 } 384 return convSpecs; 385 } 386 static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, 387 boolean strict) { 388 return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false); 389 } 390 391 /** 392 * Find a conversion function from the given source to the given destination. 393 * This conversion function will be used as a LF NamedFunction. 394 * Return a Class object if a simple cast is needed. 395 * Return void.class if void is involved. 396 */ 397 static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) { 398 assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)); // caller responsibility 399 if (dst == void.class) 400 return dst; 401 MethodHandle fn; 402 if (src.isPrimitive()) { 403 if (src == void.class) { 404 return void.class; // caller must recognize this specially 405 } else if (dst.isPrimitive()) { 406 // Examples: int->byte, byte->int, boolean->int (!strict) 407 fn = ValueConversions.convertPrimitive(src, dst); 408 } else { 409 // Examples: int->Integer, boolean->Object, float->Number 410 Wrapper wsrc = Wrapper.forPrimitiveType(src); 411 fn = ValueConversions.boxExact(wsrc); 412 assert(fn.type().parameterType(0) == wsrc.primitiveType()); 413 assert(fn.type().returnType() == wsrc.wrapperType()); 414 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) { 415 // Corner case, such as int->Long, which will probably fail. 416 MethodType mt = MethodType.methodType(dst, src); 417 if (strict) 418 fn = fn.asType(mt); 419 else 420 fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false); 421 } 422 } 423 } else if (dst.isPrimitive()) { 424 Wrapper wdst = Wrapper.forPrimitiveType(dst); 425 if (monobox || src == wdst.wrapperType()) { 426 // Use a strongly-typed unboxer, if possible. 427 fn = ValueConversions.unboxExact(wdst, strict); 428 } else { 429 // Examples: Object->int, Number->int, Comparable->int, Byte->int 430 // must include additional conversions 431 // src must be examined at runtime, to detect Byte, Character, etc. 432 fn = (strict 433 ? ValueConversions.unboxWiden(wdst) 434 : ValueConversions.unboxCast(wdst)); 435 } 436 } else { 437 // Simple reference conversion. 438 // Note: Do not check for a class hierarchy relation 439 // between src and dst. In all cases a 'null' argument 440 // will pass the cast conversion. 441 return dst; 442 } 443 assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn); 444 return fn; 445 } 446 447 static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) { 448 MethodType type = target.type(); 449 int last = type.parameterCount() - 1; 450 if (type.parameterType(last) != arrayType) 451 target = target.asType(type.changeParameterType(last, arrayType)); 452 target = target.asFixedArity(); // make sure this attribute is turned off 453 return new AsVarargsCollector(target, arrayType); 454 } 455 456 static final class AsVarargsCollector extends DelegatingMethodHandle { 457 private final MethodHandle target; 458 private final Class<?> arrayType; 459 private MethodHandle asCollectorCache; 460 461 AsVarargsCollector(MethodHandle target, Class<?> arrayType) { 462 this(target.type(), target, arrayType); 463 } 464 AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) { 465 super(type, target); 466 this.target = target; 467 this.arrayType = arrayType; 468 } 469 470 @Override 471 public boolean isVarargsCollector() { 472 return true; 473 } 474 475 @Override 476 protected MethodHandle getTarget() { 477 return target; 478 } 479 480 @Override 481 public MethodHandle asFixedArity() { 482 return target; 483 } 484 485 @Override 486 MethodHandle setVarargs(MemberName member) { 487 if (member.isVarargs()) return this; 488 return asFixedArity(); 489 } 490 491 @Override 492 public MethodHandle withVarargs(boolean makeVarargs) { 493 if (makeVarargs) return this; 494 return asFixedArity(); 495 } 496 497 @Override 498 public MethodHandle asTypeUncached(MethodType newType) { 499 MethodType type = this.type(); 500 int collectArg = type.parameterCount() - 1; 501 int newArity = newType.parameterCount(); 502 if (newArity == collectArg+1 && 503 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) { 504 // if arity and trailing parameter are compatible, do normal thing 505 return asFixedArity().asType(newType); 506 } 507 // check cache 508 MethodHandle acc = asCollectorCache; 509 if (acc != null && acc.type().parameterCount() == newArity) 510 return acc.asType(newType); 511 // build and cache a collector 512 int arrayLength = newArity - collectArg; 513 MethodHandle collector; 514 try { 515 collector = asFixedArity().asCollector(arrayType, arrayLength); 516 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector; 517 } catch (IllegalArgumentException ex) { 518 throw new WrongMethodTypeException("cannot build collector", ex); 519 } 520 asCollectorCache = collector; 521 return collector.asType(newType); 522 } 523 524 @Override 525 boolean viewAsTypeChecks(MethodType newType, boolean strict) { 526 super.viewAsTypeChecks(newType, true); 527 if (strict) return true; 528 // extra assertion for non-strict checks: 529 assert (type().lastParameterType().getComponentType() 530 .isAssignableFrom( 531 newType.lastParameterType().getComponentType())) 532 : Arrays.asList(this, newType); 533 return true; 534 } 535 536 @Override 537 public Object invokeWithArguments(Object... arguments) throws Throwable { 538 MethodType type = this.type(); 539 int argc; 540 final int MAX_SAFE = 127; // 127 longs require 254 slots, which is safe to spread 541 if (arguments == null 542 || (argc = arguments.length) <= MAX_SAFE 543 || argc < type.parameterCount()) { 544 return super.invokeWithArguments(arguments); 545 } 546 547 // a jumbo invocation requires more explicit reboxing of the trailing arguments 548 int uncollected = type.parameterCount() - 1; 549 Class<?> elemType = arrayType.getComponentType(); 550 int collected = argc - uncollected; 551 Object collArgs = (elemType == Object.class) 552 ? new Object[collected] : Array.newInstance(elemType, collected); 553 if (!elemType.isPrimitive()) { 554 // simple cast: just do some casting 555 try { 556 System.arraycopy(arguments, uncollected, collArgs, 0, collected); 557 } catch (ArrayStoreException ex) { 558 return super.invokeWithArguments(arguments); 559 } 560 } else { 561 // corner case of flat array requires reflection (or specialized copy loop) 562 MethodHandle arraySetter = MethodHandles.arrayElementSetter(arrayType); 563 try { 564 for (int i = 0; i < collected; i++) { 565 arraySetter.invoke(collArgs, i, arguments[uncollected + i]); 566 } 567 } catch (WrongMethodTypeException|ClassCastException ex) { 568 return super.invokeWithArguments(arguments); 569 } 570 } 571 572 // chop the jumbo list down to size and call in non-varargs mode 573 Object[] newArgs = new Object[uncollected + 1]; 574 System.arraycopy(arguments, 0, newArgs, 0, uncollected); 575 newArgs[uncollected] = collArgs; 576 return asFixedArity().invokeWithArguments(newArgs); 577 } 578 } 579 580 static void checkSpreadArgument(Object av, int n) { 581 if (av == null && n == 0) { 582 return; 583 } else if (av == null) { 584 throw new NullPointerException("null array reference"); 585 } else if (av instanceof Object[] array) { 586 int len = array.length; 587 if (len == n) return; 588 } else { 589 int len = java.lang.reflect.Array.getLength(av); 590 if (len == n) return; 591 } 592 // fall through to error: 593 throw newIllegalArgumentException("array is not of length "+n); 594 } 595 596 @Hidden 597 static MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) { 598 if (testResult) { 599 return target; 600 } else { 601 return fallback; 602 } 603 } 604 605 // Intrinsified by C2. Counters are used during parsing to calculate branch frequencies. 606 @Hidden 607 @jdk.internal.vm.annotation.IntrinsicCandidate 608 static boolean profileBoolean(boolean result, int[] counters) { 609 // Profile is int[2] where [0] and [1] correspond to false and true occurrences respectively. 610 int idx = result ? 1 : 0; 611 try { 612 counters[idx] = Math.addExact(counters[idx], 1); 613 } catch (ArithmeticException e) { 614 // Avoid continuous overflow by halving the problematic count. 615 counters[idx] = counters[idx] / 2; 616 } 617 return result; 618 } 619 620 // Intrinsified by C2. Returns true if obj is a compile-time constant. 621 @Hidden 622 @jdk.internal.vm.annotation.IntrinsicCandidate 623 static boolean isCompileConstant(Object obj) { 624 return false; 625 } 626 627 static MethodHandle makeGuardWithTest(MethodHandle test, 628 MethodHandle target, 629 MethodHandle fallback) { 630 MethodType type = target.type(); 631 assert(test.type().equals(type.changeReturnType(boolean.class)) && fallback.type().equals(type)); 632 MethodType basicType = type.basicType(); 633 LambdaForm form = makeGuardWithTestForm(basicType); 634 BoundMethodHandle mh; 635 try { 636 if (PROFILE_GWT) { 637 int[] counts = new int[2]; 638 mh = (BoundMethodHandle) 639 BoundMethodHandle.speciesData_LLLL().factory().invokeBasic(type, form, 640 (Object) test, (Object) profile(target), (Object) profile(fallback), counts); 641 } else { 642 mh = (BoundMethodHandle) 643 BoundMethodHandle.speciesData_LLL().factory().invokeBasic(type, form, 644 (Object) test, (Object) profile(target), (Object) profile(fallback)); 645 } 646 } catch (Throwable ex) { 647 throw uncaughtException(ex); 648 } 649 assert(mh.type() == type); 650 return mh; 651 } 652 653 654 static MethodHandle profile(MethodHandle target) { 655 if (DONT_INLINE_THRESHOLD >= 0) { 656 return makeBlockInliningWrapper(target); 657 } else { 658 return target; 659 } 660 } 661 662 /** 663 * Block inlining during JIT-compilation of a target method handle if it hasn't been invoked enough times. 664 * Corresponding LambdaForm has @DontInline when compiled into bytecode. 665 */ 666 static MethodHandle makeBlockInliningWrapper(MethodHandle target) { 667 LambdaForm lform; 668 if (DONT_INLINE_THRESHOLD > 0) { 669 lform = Makers.PRODUCE_BLOCK_INLINING_FORM.apply(target); 670 } else { 671 lform = Makers.PRODUCE_REINVOKER_FORM.apply(target); 672 } 673 return new CountingWrapper(target, lform, 674 Makers.PRODUCE_BLOCK_INLINING_FORM, Makers.PRODUCE_REINVOKER_FORM, 675 DONT_INLINE_THRESHOLD); 676 } 677 678 private static final class Makers { 679 /** Constructs reinvoker lambda form which block inlining during JIT-compilation for a particular method handle */ 680 static final Function<MethodHandle, LambdaForm> PRODUCE_BLOCK_INLINING_FORM = new Function<MethodHandle, LambdaForm>() { 681 @Override 682 public LambdaForm apply(MethodHandle target) { 683 return DelegatingMethodHandle.makeReinvokerForm(target, 684 MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, false, 685 DelegatingMethodHandle.NF_getTarget, CountingWrapper.NF_maybeStopCounting); 686 } 687 }; 688 689 /** Constructs simple reinvoker lambda form for a particular method handle */ 690 static final Function<MethodHandle, LambdaForm> PRODUCE_REINVOKER_FORM = new Function<MethodHandle, LambdaForm>() { 691 @Override 692 public LambdaForm apply(MethodHandle target) { 693 return DelegatingMethodHandle.makeReinvokerForm(target, 694 MethodTypeForm.LF_DELEGATE, DelegatingMethodHandle.class, DelegatingMethodHandle.NF_getTarget); 695 } 696 }; 697 698 /** Maker of type-polymorphic varargs */ 699 static final ClassValue<MethodHandle[]> TYPED_COLLECTORS = new ClassValue<MethodHandle[]>() { 700 @Override 701 protected MethodHandle[] computeValue(Class<?> type) { 702 return new MethodHandle[MAX_JVM_ARITY + 1]; 703 } 704 }; 705 } 706 707 /** 708 * Counting method handle. It has 2 states: counting and non-counting. 709 * It is in counting state for the first n invocations and then transitions to non-counting state. 710 * Behavior in counting and non-counting states is determined by lambda forms produced by 711 * countingFormProducer & nonCountingFormProducer respectively. 712 */ 713 static final class CountingWrapper extends DelegatingMethodHandle { 714 private final MethodHandle target; 715 private int count; 716 private Function<MethodHandle, LambdaForm> countingFormProducer; 717 private Function<MethodHandle, LambdaForm> nonCountingFormProducer; 718 private volatile boolean isCounting; 719 720 private CountingWrapper(MethodHandle target, LambdaForm lform, 721 Function<MethodHandle, LambdaForm> countingFromProducer, 722 Function<MethodHandle, LambdaForm> nonCountingFormProducer, 723 int count) { 724 super(target.type(), lform); 725 this.target = target; 726 this.count = count; 727 this.countingFormProducer = countingFromProducer; 728 this.nonCountingFormProducer = nonCountingFormProducer; 729 this.isCounting = (count > 0); 730 } 731 732 @Hidden 733 @Override 734 protected MethodHandle getTarget() { 735 return target; 736 } 737 738 @Override 739 public MethodHandle asTypeUncached(MethodType newType) { 740 MethodHandle newTarget = target.asType(newType); 741 MethodHandle wrapper; 742 if (isCounting) { 743 LambdaForm lform; 744 lform = countingFormProducer.apply(newTarget); 745 wrapper = new CountingWrapper(newTarget, lform, countingFormProducer, nonCountingFormProducer, DONT_INLINE_THRESHOLD); 746 } else { 747 wrapper = newTarget; // no need for a counting wrapper anymore 748 } 749 return wrapper; 750 } 751 752 boolean countDown() { 753 int c = count; 754 target.maybeCustomize(); // customize if counting happens for too long 755 if (c <= 1) { 756 // Try to limit number of updates. MethodHandle.updateForm() doesn't guarantee LF update visibility. 757 if (isCounting) { 758 isCounting = false; 759 return true; 760 } else { 761 return false; 762 } 763 } else { 764 count = c - 1; 765 return false; 766 } 767 } 768 769 @Hidden 770 static void maybeStopCounting(Object o1) { 771 final CountingWrapper wrapper = (CountingWrapper) o1; 772 if (wrapper.countDown()) { 773 // Reached invocation threshold. Replace counting behavior with a non-counting one. 774 wrapper.updateForm(new Function<>() { 775 public LambdaForm apply(LambdaForm oldForm) { 776 LambdaForm lform = wrapper.nonCountingFormProducer.apply(wrapper.target); 777 lform.compileToBytecode(); // speed up warmup by avoiding LF interpretation again after transition 778 return lform; 779 }}); 780 } 781 } 782 783 static final NamedFunction NF_maybeStopCounting; 784 static { 785 Class<?> THIS_CLASS = CountingWrapper.class; 786 try { 787 NF_maybeStopCounting = new NamedFunction(THIS_CLASS.getDeclaredMethod("maybeStopCounting", Object.class)); 788 } catch (ReflectiveOperationException ex) { 789 throw newInternalError(ex); 790 } 791 } 792 } 793 794 static LambdaForm makeGuardWithTestForm(MethodType basicType) { 795 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWT); 796 if (lform != null) return lform; 797 final int THIS_MH = 0; // the BMH_LLL 798 final int ARG_BASE = 1; // start of incoming arguments 799 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 800 int nameCursor = ARG_LIMIT; 801 final int GET_TEST = nameCursor++; 802 final int GET_TARGET = nameCursor++; 803 final int GET_FALLBACK = nameCursor++; 804 final int GET_COUNTERS = PROFILE_GWT ? nameCursor++ : -1; 805 final int CALL_TEST = nameCursor++; 806 final int PROFILE = (GET_COUNTERS != -1) ? nameCursor++ : -1; 807 final int TEST = nameCursor-1; // previous statement: either PROFILE or CALL_TEST 808 final int SELECT_ALT = nameCursor++; 809 final int CALL_TARGET = nameCursor++; 810 assert(CALL_TARGET == SELECT_ALT+1); // must be true to trigger IBG.emitSelectAlternative 811 812 MethodType lambdaType = basicType.invokerType(); 813 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 814 815 BoundMethodHandle.SpeciesData data = 816 (GET_COUNTERS != -1) ? BoundMethodHandle.speciesData_LLLL() 817 : BoundMethodHandle.speciesData_LLL(); 818 names[THIS_MH] = names[THIS_MH].withConstraint(data); 819 names[GET_TEST] = new Name(data.getterFunction(0), names[THIS_MH]); 820 names[GET_TARGET] = new Name(data.getterFunction(1), names[THIS_MH]); 821 names[GET_FALLBACK] = new Name(data.getterFunction(2), names[THIS_MH]); 822 if (GET_COUNTERS != -1) { 823 names[GET_COUNTERS] = new Name(data.getterFunction(3), names[THIS_MH]); 824 } 825 Object[] invokeArgs = Arrays.copyOfRange(names, 0, ARG_LIMIT, Object[].class); 826 827 // call test 828 MethodType testType = basicType.changeReturnType(boolean.class).basicType(); 829 invokeArgs[0] = names[GET_TEST]; 830 names[CALL_TEST] = new Name(testType, invokeArgs); 831 832 // profile branch 833 if (PROFILE != -1) { 834 names[PROFILE] = new Name(getFunction(NF_profileBoolean), names[CALL_TEST], names[GET_COUNTERS]); 835 } 836 // call selectAlternative 837 names[SELECT_ALT] = new Name(new NamedFunction( 838 makeIntrinsic(getConstantHandle(MH_selectAlternative), Intrinsic.SELECT_ALTERNATIVE)), 839 names[TEST], names[GET_TARGET], names[GET_FALLBACK]); 840 841 // call target or fallback 842 invokeArgs[0] = names[SELECT_ALT]; 843 names[CALL_TARGET] = new Name(basicType, invokeArgs); 844 845 lform = LambdaForm.create(lambdaType.parameterCount(), names, /*forceInline=*/true, Kind.GUARD); 846 847 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform); 848 } 849 850 /** 851 * The LambdaForm shape for catchException combinator is the following: 852 * <blockquote><pre>{@code 853 * guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{ 854 * t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L); 855 * t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L); 856 * t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L); 857 * t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L); 858 * t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L); 859 * t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L); 860 * t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L); 861 * t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I} 862 * }</pre></blockquote> 863 * 864 * argL0 and argL2 are target and catcher method handles. argL1 is exception class. 865 * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[] 866 * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()). 867 * 868 * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms 869 * among catchException combinators with the same basic type. 870 */ 871 private static LambdaForm makeGuardWithCatchForm(MethodType basicType) { 872 MethodType lambdaType = basicType.invokerType(); 873 874 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC); 875 if (lform != null) { 876 return lform; 877 } 878 final int THIS_MH = 0; // the BMH_LLLLL 879 final int ARG_BASE = 1; // start of incoming arguments 880 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 881 882 int nameCursor = ARG_LIMIT; 883 final int GET_TARGET = nameCursor++; 884 final int GET_CLASS = nameCursor++; 885 final int GET_CATCHER = nameCursor++; 886 final int GET_COLLECT_ARGS = nameCursor++; 887 final int GET_UNBOX_RESULT = nameCursor++; 888 final int BOXED_ARGS = nameCursor++; 889 final int TRY_CATCH = nameCursor++; 890 final int UNBOX_RESULT = nameCursor++; 891 892 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 893 894 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL(); 895 names[THIS_MH] = names[THIS_MH].withConstraint(data); 896 names[GET_TARGET] = new Name(data.getterFunction(0), names[THIS_MH]); 897 names[GET_CLASS] = new Name(data.getterFunction(1), names[THIS_MH]); 898 names[GET_CATCHER] = new Name(data.getterFunction(2), names[THIS_MH]); 899 names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]); 900 names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]); 901 902 // FIXME: rework argument boxing/result unboxing logic for LF interpretation 903 904 // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...); 905 MethodType collectArgsType = basicType.changeReturnType(Object.class); 906 MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType); 907 Object[] args = new Object[invokeBasic.type().parameterCount()]; 908 args[0] = names[GET_COLLECT_ARGS]; 909 System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE); 910 names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH)), args); 911 912 // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L); 913 Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]}; 914 names[TRY_CATCH] = new Name(getFunction(NF_guardWithCatch), gwcArgs); 915 916 // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L); 917 MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class)); 918 Object[] unboxArgs = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]}; 919 names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs); 920 921 lform = LambdaForm.create(lambdaType.parameterCount(), names, Kind.GUARD_WITH_CATCH); 922 923 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform); 924 } 925 926 static MethodHandle makeGuardWithCatch(MethodHandle target, 927 Class<? extends Throwable> exType, 928 MethodHandle catcher) { 929 MethodType type = target.type(); 930 LambdaForm form = makeGuardWithCatchForm(type.basicType()); 931 932 // Prepare auxiliary method handles used during LambdaForm interpretation. 933 // Box arguments and wrap them into Object[]: ValueConversions.array(). 934 MethodType varargsType = type.changeReturnType(Object[].class); 935 MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType); 936 MethodHandle unboxResult = unboxResultHandle(type.returnType()); 937 938 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL(); 939 BoundMethodHandle mh; 940 try { 941 mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) target, (Object) exType, 942 (Object) catcher, (Object) collectArgs, (Object) unboxResult); 943 } catch (Throwable ex) { 944 throw uncaughtException(ex); 945 } 946 assert(mh.type() == type); 947 return mh; 948 } 949 950 /** 951 * Intrinsified during LambdaForm compilation 952 * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}). 953 */ 954 @Hidden 955 static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher, 956 Object... av) throws Throwable { 957 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 958 try { 959 return target.asFixedArity().invokeWithArguments(av); 960 } catch (Throwable t) { 961 if (!exType.isInstance(t)) throw t; 962 return catcher.asFixedArity().invokeWithArguments(prepend(av, t)); 963 } 964 } 965 966 /** Prepend elements to an array. */ 967 @Hidden 968 private static Object[] prepend(Object[] array, Object... elems) { 969 int nArray = array.length; 970 int nElems = elems.length; 971 Object[] newArray = new Object[nArray + nElems]; 972 System.arraycopy(elems, 0, newArray, 0, nElems); 973 System.arraycopy(array, 0, newArray, nElems, nArray); 974 return newArray; 975 } 976 977 static MethodHandle throwException(MethodType type) { 978 assert(Throwable.class.isAssignableFrom(type.parameterType(0))); 979 int arity = type.parameterCount(); 980 if (arity > 1) { 981 MethodHandle mh = throwException(type.dropParameterTypes(1, arity)); 982 mh = MethodHandles.dropArgumentsTrusted(mh, 1, Arrays.copyOfRange(type.ptypes(), 1, arity)); 983 return mh; 984 } 985 return makePairwiseConvert(getFunction(NF_throwException).resolvedHandle(), type, false, true); 986 } 987 988 static <T extends Throwable> Empty throwException(T t) throws T { throw t; } 989 990 static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2]; 991 static MethodHandle fakeMethodHandleInvoke(MemberName method) { 992 assert(method.isMethodHandleInvoke()); 993 int idx = switch (method.getName()) { 994 case "invoke" -> 0; 995 case "invokeExact" -> 1; 996 default -> throw new InternalError(method.getName()); 997 }; 998 MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx]; 999 if (mh != null) return mh; 1000 MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class, 1001 MethodHandle.class, Object[].class); 1002 mh = throwException(type); 1003 mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle")); 1004 if (!method.getInvocationType().equals(mh.type())) 1005 throw new InternalError(method.toString()); 1006 mh = mh.withInternalMemberName(method, false); 1007 mh = mh.withVarargs(true); 1008 assert(method.isVarargs()); 1009 FAKE_METHOD_HANDLE_INVOKE[idx] = mh; 1010 return mh; 1011 } 1012 static MethodHandle fakeVarHandleInvoke(MemberName method) { 1013 // TODO caching, is it necessary? 1014 MethodType type = MethodType.methodType(method.getMethodType().returnType(), 1015 UnsupportedOperationException.class, 1016 VarHandle.class, Object[].class); 1017 MethodHandle mh = throwException(type); 1018 mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke VarHandle")); 1019 if (!method.getInvocationType().equals(mh.type())) 1020 throw new InternalError(method.toString()); 1021 mh = mh.withInternalMemberName(method, false); 1022 mh = mh.asVarargsCollector(Object[].class); 1023 assert(method.isVarargs()); 1024 return mh; 1025 } 1026 1027 /** 1028 * Create an alias for the method handle which, when called, 1029 * appears to be called from the same class loader and protection domain 1030 * as hostClass. 1031 * This is an expensive no-op unless the method which is called 1032 * is sensitive to its caller. A small number of system methods 1033 * are in this category, including Class.forName and Method.invoke. 1034 */ 1035 static MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) { 1036 return BindCaller.bindCaller(mh, hostClass); 1037 } 1038 1039 // Put the whole mess into its own nested class. 1040 // That way we can lazily load the code and set up the constants. 1041 private static class BindCaller { 1042 1043 private static final ClassDesc CD_Object_array = ReferenceClassDescImpl.ofValidated("[Ljava/lang/Object;"); 1044 private static final MethodType INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1045 private static final MethodType REFLECT_INVOKER_MT = MethodType.methodType(Object.class, MethodHandle.class, Object.class, Object[].class); 1046 1047 static MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) { 1048 // Code in the boot layer should now be careful while creating method handles or 1049 // functional interface instances created from method references to @CallerSensitive methods, 1050 // it needs to be ensured the handles or interface instances are kept safe and are not passed 1051 // from the boot layer to untrusted code. 1052 if (hostClass == null 1053 || (hostClass.isArray() || 1054 hostClass.isPrimitive() || 1055 hostClass.getName().startsWith("java.lang.invoke."))) { 1056 throw new InternalError(); // does not happen, and should not anyway 1057 } 1058 1059 MemberName member = mh.internalMemberName(); 1060 if (member != null) { 1061 // Look up the CSM adapter method with the same method name 1062 // but with an additional caller class parameter. If present, 1063 // bind the adapter's method handle with the lookup class as 1064 // the caller class argument 1065 MemberName csmAdapter = IMPL_LOOKUP.resolveOrNull(member.getReferenceKind(), 1066 new MemberName(member.getDeclaringClass(), 1067 member.getName(), 1068 member.getMethodType().appendParameterTypes(Class.class), 1069 member.getReferenceKind())); 1070 if (csmAdapter != null) { 1071 assert !csmAdapter.isCallerSensitive(); 1072 MethodHandle dmh = DirectMethodHandle.make(csmAdapter); 1073 dmh = MethodHandles.insertArguments(dmh, dmh.type().parameterCount() - 1, hostClass); 1074 dmh = new WrappedMember(dmh, mh.type(), member, mh.isInvokeSpecial(), hostClass); 1075 return dmh; 1076 } 1077 } 1078 1079 // If no adapter method for CSM with an additional Class parameter 1080 // is present, then inject an invoker class that is the caller 1081 // invoking the method handle of the CSM 1082 try { 1083 return bindCallerWithInjectedInvoker(mh, hostClass); 1084 } catch (ReflectiveOperationException ex) { 1085 throw uncaughtException(ex); 1086 } 1087 } 1088 1089 private static MethodHandle bindCallerWithInjectedInvoker(MethodHandle mh, Class<?> hostClass) 1090 throws ReflectiveOperationException 1091 { 1092 // For simplicity, convert mh to a varargs-like method. 1093 MethodHandle vamh = prepareForInvoker(mh); 1094 // Cache the result of makeInjectedInvoker once per argument class. 1095 MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass).invoker(); 1096 return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass); 1097 } 1098 1099 private static Class<?> makeInjectedInvoker(Class<?> targetClass) { 1100 /* 1101 * The invoker class defined to the same class loader as the lookup class 1102 * but in an unnamed package so that the class bytes can be cached and 1103 * reused for any @CSM. 1104 * 1105 * @CSM must be public and exported if called by any module. 1106 */ 1107 String name = targetClass.getName() + "$$InjectedInvoker"; 1108 if (targetClass.isHidden()) { 1109 // use the original class name 1110 name = name.replace('/', '_'); 1111 } 1112 name = name.replace('.', '/'); 1113 Class<?> invokerClass = new Lookup(targetClass) 1114 .makeHiddenClassDefiner(name, INJECTED_INVOKER_TEMPLATE, Set.of(NESTMATE), dumper()) 1115 .defineClass(true, targetClass); 1116 assert checkInjectedInvoker(targetClass, invokerClass); 1117 return invokerClass; 1118 } 1119 1120 private static ClassValue<InjectedInvokerHolder> CV_makeInjectedInvoker = new ClassValue<>() { 1121 @Override 1122 protected InjectedInvokerHolder computeValue(Class<?> hostClass) { 1123 return new InjectedInvokerHolder(makeInjectedInvoker(hostClass)); 1124 } 1125 }; 1126 1127 /* 1128 * Returns a method handle of an invoker class injected for reflection 1129 * implementation use with the following signature: 1130 * reflect_invoke_V(MethodHandle mh, Object target, Object[] args) 1131 * 1132 * Method::invoke on a caller-sensitive method will call 1133 * MethodAccessorImpl::invoke(Object, Object[]) through reflect_invoke_V 1134 * target.csm(args) 1135 * NativeMethodAccessorImpl::invoke(target, args) 1136 * MethodAccessImpl::invoke(target, args) 1137 * InjectedInvoker::reflect_invoke_V(vamh, target, args); 1138 * method::invoke(target, args) 1139 * p.Foo::m 1140 * 1141 * An injected invoker class is a hidden class which has the same 1142 * defining class loader, runtime package, and protection domain 1143 * as the given caller class. 1144 */ 1145 static MethodHandle reflectiveInvoker(Class<?> caller) { 1146 return BindCaller.CV_makeInjectedInvoker.get(caller).reflectInvoker(); 1147 } 1148 1149 private static final class InjectedInvokerHolder { 1150 private final Class<?> invokerClass; 1151 // lazily resolved and cached DMH(s) of invoke_V methods 1152 private MethodHandle invoker; 1153 private MethodHandle reflectInvoker; 1154 1155 private InjectedInvokerHolder(Class<?> invokerClass) { 1156 this.invokerClass = invokerClass; 1157 } 1158 1159 private MethodHandle invoker() { 1160 var mh = invoker; 1161 if (mh == null) { 1162 try { 1163 invoker = mh = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT); 1164 } catch (Error | RuntimeException ex) { 1165 throw ex; 1166 } catch (Throwable ex) { 1167 throw new InternalError(ex); 1168 } 1169 } 1170 return mh; 1171 } 1172 1173 private MethodHandle reflectInvoker() { 1174 var mh = reflectInvoker; 1175 if (mh == null) { 1176 try { 1177 reflectInvoker = mh = IMPL_LOOKUP.findStatic(invokerClass, "reflect_invoke_V", REFLECT_INVOKER_MT); 1178 } catch (Error | RuntimeException ex) { 1179 throw ex; 1180 } catch (Throwable ex) { 1181 throw new InternalError(ex); 1182 } 1183 } 1184 return mh; 1185 } 1186 } 1187 1188 // Adapt mh so that it can be called directly from an injected invoker: 1189 private static MethodHandle prepareForInvoker(MethodHandle mh) { 1190 mh = mh.asFixedArity(); 1191 MethodType mt = mh.type(); 1192 int arity = mt.parameterCount(); 1193 MethodHandle vamh = mh.asType(mt.generic()); 1194 vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames 1195 vamh = vamh.asSpreader(Object[].class, arity); 1196 vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames 1197 return vamh; 1198 } 1199 1200 // Undo the adapter effect of prepareForInvoker: 1201 private static MethodHandle restoreToType(MethodHandle vamh, 1202 MethodHandle original, 1203 Class<?> hostClass) { 1204 MethodType type = original.type(); 1205 MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount()); 1206 MemberName member = original.internalMemberName(); 1207 mh = mh.asType(type); 1208 mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass); 1209 return mh; 1210 } 1211 1212 private static boolean checkInjectedInvoker(Class<?> hostClass, Class<?> invokerClass) { 1213 assert (hostClass.getClassLoader() == invokerClass.getClassLoader()) : hostClass.getName()+" (CL)"; 1214 try { 1215 assert (hostClass.getProtectionDomain() == invokerClass.getProtectionDomain()) : hostClass.getName()+" (PD)"; 1216 } catch (SecurityException ex) { 1217 // Self-check was blocked by security manager. This is OK. 1218 } 1219 try { 1220 // Test the invoker to ensure that it really injects into the right place. 1221 MethodHandle invoker = IMPL_LOOKUP.findStatic(invokerClass, "invoke_V", INVOKER_MT); 1222 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass); 1223 return (boolean)invoker.invoke(vamh, new Object[]{ invokerClass }); 1224 } catch (Error|RuntimeException ex) { 1225 throw ex; 1226 } catch (Throwable ex) { 1227 throw new InternalError(ex); 1228 } 1229 } 1230 1231 private static final MethodHandle MH_checkCallerClass; 1232 static { 1233 final Class<?> THIS_CLASS = BindCaller.class; 1234 assert(checkCallerClass(THIS_CLASS)); 1235 try { 1236 MH_checkCallerClass = IMPL_LOOKUP 1237 .findStatic(THIS_CLASS, "checkCallerClass", 1238 MethodType.methodType(boolean.class, Class.class)); 1239 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS)); 1240 } catch (Throwable ex) { 1241 throw new InternalError(ex); 1242 } 1243 } 1244 1245 @CallerSensitive 1246 @ForceInline // to ensure Reflection.getCallerClass optimization 1247 private static boolean checkCallerClass(Class<?> expected) { 1248 // This method is called via MH_checkCallerClass and so it's correct to ask for the immediate caller here. 1249 Class<?> actual = Reflection.getCallerClass(); 1250 if (actual != expected) 1251 throw new InternalError("found " + actual.getName() + ", expected " + expected.getName()); 1252 return true; 1253 } 1254 1255 private static final byte[] INJECTED_INVOKER_TEMPLATE = generateInvokerTemplate(); 1256 1257 /** Produces byte code for a class that is used as an injected invoker. */ 1258 private static byte[] generateInvokerTemplate() { 1259 // private static class InjectedInvoker { 1260 // /* this is used to wrap DMH(s) of caller-sensitive methods */ 1261 // @Hidden 1262 // static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable { 1263 // return vamh.invokeExact(args); 1264 // } 1265 // /* this is used in caller-sensitive reflective method accessor */ 1266 // @Hidden 1267 // static Object reflect_invoke_V(MethodHandle vamh, Object target, Object[] args) throws Throwable { 1268 // return vamh.invokeExact(target, args); 1269 // } 1270 // } 1271 // } 1272 return ClassFile.of().build(ReferenceClassDescImpl.ofValidated("LInjectedInvoker;"), clb -> clb 1273 .withFlags(ACC_PRIVATE | ACC_SUPER) 1274 .withMethodBody( 1275 "invoke_V", 1276 MethodTypeDescImpl.ofValidated(CD_Object, CD_MethodHandle, CD_Object_array), 1277 ACC_STATIC, 1278 cob -> cob.aload(0) 1279 .aload(1) 1280 .invokevirtual(CD_MethodHandle, "invokeExact", MethodTypeDescImpl.ofValidated(CD_Object, CD_Object_array)) 1281 .areturn()) 1282 .withMethodBody( 1283 "reflect_invoke_V", 1284 MethodTypeDescImpl.ofValidated(CD_Object, CD_MethodHandle, CD_Object, CD_Object_array), 1285 ACC_STATIC, 1286 cob -> cob.aload(0) 1287 .aload(1) 1288 .aload(2) 1289 .invokevirtual(CD_MethodHandle, "invokeExact", MethodTypeDescImpl.ofValidated(CD_Object, CD_Object, CD_Object_array)) 1290 .areturn())); 1291 } 1292 } 1293 1294 /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */ 1295 static final class WrappedMember extends DelegatingMethodHandle { 1296 private final MethodHandle target; 1297 private final MemberName member; 1298 private final Class<?> callerClass; 1299 private final boolean isInvokeSpecial; 1300 1301 private WrappedMember(MethodHandle target, MethodType type, 1302 MemberName member, boolean isInvokeSpecial, 1303 Class<?> callerClass) { 1304 super(type, target); 1305 this.target = target; 1306 this.member = member; 1307 this.callerClass = callerClass; 1308 this.isInvokeSpecial = isInvokeSpecial; 1309 } 1310 1311 @Override 1312 MemberName internalMemberName() { 1313 return member; 1314 } 1315 @Override 1316 Class<?> internalCallerClass() { 1317 return callerClass; 1318 } 1319 @Override 1320 boolean isInvokeSpecial() { 1321 return isInvokeSpecial; 1322 } 1323 @Override 1324 protected MethodHandle getTarget() { 1325 return target; 1326 } 1327 @Override 1328 public MethodHandle asTypeUncached(MethodType newType) { 1329 // This MH is an alias for target, except for the MemberName 1330 // Drop the MemberName if there is any conversion. 1331 return target.asType(newType); 1332 } 1333 } 1334 1335 static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) { 1336 if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial()) 1337 return target; 1338 return new WrappedMember(target, target.type(), member, isInvokeSpecial, null); 1339 } 1340 1341 /** Intrinsic IDs */ 1342 /*non-public*/ 1343 enum Intrinsic { 1344 SELECT_ALTERNATIVE, 1345 GUARD_WITH_CATCH, 1346 TRY_FINALLY, 1347 TABLE_SWITCH, 1348 LOOP, 1349 ARRAY_LOAD, 1350 ARRAY_STORE, 1351 ARRAY_LENGTH, 1352 IDENTITY, 1353 ZERO, 1354 NONE // no intrinsic associated 1355 } 1356 1357 /** Mark arbitrary method handle as intrinsic. 1358 * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */ 1359 static final class IntrinsicMethodHandle extends DelegatingMethodHandle { 1360 private final MethodHandle target; 1361 private final Intrinsic intrinsicName; 1362 private final Object intrinsicData; 1363 1364 IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) { 1365 this(target, intrinsicName, null); 1366 } 1367 1368 IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName, Object intrinsicData) { 1369 super(target.type(), target); 1370 this.target = target; 1371 this.intrinsicName = intrinsicName; 1372 this.intrinsicData = intrinsicData; 1373 } 1374 1375 @Override 1376 protected MethodHandle getTarget() { 1377 return target; 1378 } 1379 1380 @Override 1381 Intrinsic intrinsicName() { 1382 return intrinsicName; 1383 } 1384 1385 @Override 1386 Object intrinsicData() { 1387 return intrinsicData; 1388 } 1389 1390 @Override 1391 public MethodHandle asTypeUncached(MethodType newType) { 1392 // This MH is an alias for target, except for the intrinsic name 1393 // Drop the name if there is any conversion. 1394 return target.asType(newType); 1395 } 1396 1397 @Override 1398 String internalProperties() { 1399 return super.internalProperties() + 1400 "\n& Intrinsic="+intrinsicName; 1401 } 1402 1403 @Override 1404 public MethodHandle asCollector(Class<?> arrayType, int arrayLength) { 1405 if (intrinsicName == Intrinsic.IDENTITY) { 1406 MethodType resultType = type().asCollectorType(arrayType, type().parameterCount() - 1, arrayLength); 1407 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength); 1408 return newArray.asType(resultType); 1409 } 1410 return super.asCollector(arrayType, arrayLength); 1411 } 1412 } 1413 1414 static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) { 1415 return makeIntrinsic(target, intrinsicName, null); 1416 } 1417 1418 static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName, Object intrinsicData) { 1419 if (intrinsicName == target.intrinsicName()) 1420 return target; 1421 return new IntrinsicMethodHandle(target, intrinsicName, intrinsicData); 1422 } 1423 1424 static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) { 1425 return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName); 1426 } 1427 1428 private static final @Stable MethodHandle[] ARRAYS = new MethodHandle[MAX_ARITY + 1]; 1429 1430 /** Return a method handle that takes the indicated number of Object 1431 * arguments and returns an Object array of them, as if for varargs. 1432 */ 1433 static MethodHandle varargsArray(int nargs) { 1434 MethodHandle mh = ARRAYS[nargs]; 1435 if (mh != null) { 1436 return mh; 1437 } 1438 mh = makeCollector(Object[].class, nargs); 1439 assert(assertCorrectArity(mh, nargs)); 1440 return ARRAYS[nargs] = mh; 1441 } 1442 1443 /** Return a method handle that takes the indicated number of 1444 * typed arguments and returns an array of them. 1445 * The type argument is the array type. 1446 */ 1447 static MethodHandle varargsArray(Class<?> arrayType, int nargs) { 1448 Class<?> elemType = arrayType.getComponentType(); 1449 if (elemType == null) throw new IllegalArgumentException("not an array: "+arrayType); 1450 if (nargs >= MAX_JVM_ARITY/2 - 1) { 1451 int slots = nargs; 1452 final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1; // 1 for receiver MH 1453 if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive()) 1454 slots *= Wrapper.forPrimitiveType(elemType).stackSlots(); 1455 if (slots > MAX_ARRAY_SLOTS) 1456 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs); 1457 } 1458 if (elemType == Object.class) 1459 return varargsArray(nargs); 1460 // other cases: primitive arrays, subtypes of Object[] 1461 MethodHandle cache[] = Makers.TYPED_COLLECTORS.get(elemType); 1462 MethodHandle mh = nargs < cache.length ? cache[nargs] : null; 1463 if (mh != null) return mh; 1464 mh = makeCollector(arrayType, nargs); 1465 assert(assertCorrectArity(mh, nargs)); 1466 if (nargs < cache.length) 1467 cache[nargs] = mh; 1468 return mh; 1469 } 1470 1471 private static boolean assertCorrectArity(MethodHandle mh, int arity) { 1472 assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh; 1473 return true; 1474 } 1475 1476 static final int MAX_JVM_ARITY = 255; // limit imposed by the JVM 1477 1478 /*non-public*/ 1479 static void assertSame(Object mh1, Object mh2) { 1480 if (mh1 != mh2) { 1481 String msg = String.format("mh1 != mh2: mh1 = %s (form: %s); mh2 = %s (form: %s)", 1482 mh1, ((MethodHandle)mh1).form, 1483 mh2, ((MethodHandle)mh2).form); 1484 throw newInternalError(msg); 1485 } 1486 } 1487 1488 // Local constant functions: 1489 1490 /* non-public */ 1491 static final byte NF_checkSpreadArgument = 0, 1492 NF_guardWithCatch = 1, 1493 NF_throwException = 2, 1494 NF_tryFinally = 3, 1495 NF_loop = 4, 1496 NF_profileBoolean = 5, 1497 NF_tableSwitch = 6, 1498 NF_LIMIT = 7; 1499 1500 private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT]; 1501 1502 static NamedFunction getFunction(byte func) { 1503 NamedFunction nf = NFS[func]; 1504 if (nf != null) { 1505 return nf; 1506 } 1507 return NFS[func] = createFunction(func); 1508 } 1509 1510 private static NamedFunction createFunction(byte func) { 1511 try { 1512 return switch (func) { 1513 case NF_checkSpreadArgument -> new NamedFunction(MethodHandleImpl.class 1514 .getDeclaredMethod("checkSpreadArgument", Object.class, int.class)); 1515 case NF_guardWithCatch -> new NamedFunction(MethodHandleImpl.class 1516 .getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class, 1517 MethodHandle.class, Object[].class)); 1518 case NF_tryFinally -> new NamedFunction(MethodHandleImpl.class 1519 .getDeclaredMethod("tryFinally", MethodHandle.class, MethodHandle.class, Object[].class)); 1520 case NF_loop -> new NamedFunction(MethodHandleImpl.class 1521 .getDeclaredMethod("loop", BasicType[].class, LoopClauses.class, Object[].class)); 1522 case NF_throwException -> new NamedFunction(MethodHandleImpl.class 1523 .getDeclaredMethod("throwException", Throwable.class)); 1524 case NF_profileBoolean -> new NamedFunction(MethodHandleImpl.class 1525 .getDeclaredMethod("profileBoolean", boolean.class, int[].class)); 1526 case NF_tableSwitch -> new NamedFunction(MethodHandleImpl.class 1527 .getDeclaredMethod("tableSwitch", int.class, MethodHandle.class, CasesHolder.class, Object[].class)); 1528 default -> throw new InternalError("Undefined function: " + func); 1529 }; 1530 } catch (ReflectiveOperationException ex) { 1531 throw newInternalError(ex); 1532 } 1533 } 1534 1535 static { 1536 SharedSecrets.setJavaLangInvokeAccess(new JavaLangInvokeAccess() { 1537 @Override 1538 public Class<?> getDeclaringClass(Object rmname) { 1539 ResolvedMethodName method = (ResolvedMethodName)rmname; 1540 return method.declaringClass(); 1541 } 1542 1543 @Override 1544 public MethodType getMethodType(String descriptor, ClassLoader loader) { 1545 return MethodType.fromDescriptor(descriptor, loader); 1546 } 1547 1548 public boolean isCallerSensitive(int flags) { 1549 return (flags & MN_CALLER_SENSITIVE) == MN_CALLER_SENSITIVE; 1550 } 1551 1552 public boolean isHiddenMember(int flags) { 1553 return (flags & MN_HIDDEN_MEMBER) == MN_HIDDEN_MEMBER; 1554 } 1555 1556 @Override 1557 public Map<String, byte[]> generateHolderClasses(Stream<String> traces) { 1558 return GenerateJLIClassesHelper.generateHolderClasses(traces); 1559 } 1560 1561 @Override 1562 public VarHandle memorySegmentViewHandle(Class<?> carrier, long alignmentMask, ByteOrder order) { 1563 return VarHandles.memorySegmentViewHandle(carrier, alignmentMask, order); 1564 } 1565 1566 @Override 1567 public MethodHandle nativeMethodHandle(NativeEntryPoint nep) { 1568 return NativeMethodHandle.make(nep); 1569 } 1570 1571 @Override 1572 public VarHandle filterValue(VarHandle target, MethodHandle filterToTarget, MethodHandle filterFromTarget) { 1573 return VarHandles.filterValue(target, filterToTarget, filterFromTarget); 1574 } 1575 1576 @Override 1577 public VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 1578 return VarHandles.filterCoordinates(target, pos, filters); 1579 } 1580 1581 @Override 1582 public VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 1583 return VarHandles.dropCoordinates(target, pos, valueTypes); 1584 } 1585 1586 @Override 1587 public VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 1588 return VarHandles.permuteCoordinates(target, newCoordinates, reorder); 1589 } 1590 1591 @Override 1592 public VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle filter) { 1593 return VarHandles.collectCoordinates(target, pos, filter); 1594 } 1595 1596 @Override 1597 public VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 1598 return VarHandles.insertCoordinates(target, pos, values); 1599 } 1600 1601 1602 @Override 1603 public MethodHandle unreflectConstructor(Constructor<?> ctor) throws IllegalAccessException { 1604 return IMPL_LOOKUP.unreflectConstructor(ctor); 1605 } 1606 1607 @Override 1608 public MethodHandle unreflectField(Field field, boolean isSetter) throws IllegalAccessException { 1609 return isSetter ? IMPL_LOOKUP.unreflectSetter(field) : IMPL_LOOKUP.unreflectGetter(field); 1610 } 1611 1612 @Override 1613 public MethodHandle findVirtual(Class<?> defc, String name, MethodType type) throws IllegalAccessException { 1614 try { 1615 return IMPL_LOOKUP.findVirtual(defc, name, type); 1616 } catch (NoSuchMethodException e) { 1617 return null; 1618 } 1619 } 1620 1621 @Override 1622 public MethodHandle findStatic(Class<?> defc, String name, MethodType type) throws IllegalAccessException { 1623 try { 1624 return IMPL_LOOKUP.findStatic(defc, name, type); 1625 } catch (NoSuchMethodException e) { 1626 return null; 1627 } 1628 } 1629 1630 @Override 1631 public MethodHandle reflectiveInvoker(Class<?> caller) { 1632 Objects.requireNonNull(caller); 1633 return BindCaller.reflectiveInvoker(caller); 1634 } 1635 1636 @Override 1637 public Class<?>[] exceptionTypes(MethodHandle handle) { 1638 return VarHandles.exceptionTypes(handle); 1639 } 1640 1641 @Override 1642 public MethodHandle serializableConstructor(Class<?> decl, Constructor<?> ctorToCall) throws IllegalAccessException { 1643 return IMPL_LOOKUP.serializableConstructor(decl, ctorToCall); 1644 } 1645 1646 }); 1647 } 1648 1649 /** Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore(). */ 1650 private static MethodHandle unboxResultHandle(Class<?> returnType) { 1651 if (returnType.isPrimitive()) { 1652 if (returnType == void.class) { 1653 return ValueConversions.ignore(); 1654 } else { 1655 Wrapper w = Wrapper.forPrimitiveType(returnType); 1656 return ValueConversions.unboxExact(w); 1657 } 1658 } else { 1659 return MethodHandles.identity(Object.class); 1660 } 1661 } 1662 1663 /** 1664 * Assembles a loop method handle from the given handles and type information. 1665 * 1666 * @param tloop the return type of the loop. 1667 * @param targs types of the arguments to be passed to the loop. 1668 * @param init sanitized array of initializers for loop-local variables. 1669 * @param step sanitized array of loop bodies. 1670 * @param pred sanitized array of predicates. 1671 * @param fini sanitized array of loop finalizers. 1672 * 1673 * @return a handle that, when invoked, will execute the loop. 1674 */ 1675 static MethodHandle makeLoop(Class<?> tloop, List<Class<?>> targs, List<MethodHandle> init, List<MethodHandle> step, 1676 List<MethodHandle> pred, List<MethodHandle> fini) { 1677 MethodType type = MethodType.methodType(tloop, targs); 1678 BasicType[] initClauseTypes = 1679 init.stream().map(h -> h.type().returnType()).map(BasicType::basicType).toArray(BasicType[]::new); 1680 LambdaForm form = makeLoopForm(type.basicType(), initClauseTypes); 1681 1682 // Prepare auxiliary method handles used during LambdaForm interpretation. 1683 // Box arguments and wrap them into Object[]: ValueConversions.array(). 1684 MethodType varargsType = type.changeReturnType(Object[].class); 1685 MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType); 1686 MethodHandle unboxResult = unboxResultHandle(tloop); 1687 1688 LoopClauses clauseData = 1689 new LoopClauses(new MethodHandle[][]{toArray(init), toArray(step), toArray(pred), toArray(fini)}); 1690 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL(); 1691 BoundMethodHandle mh; 1692 try { 1693 mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) clauseData, 1694 (Object) collectArgs, (Object) unboxResult); 1695 } catch (Throwable ex) { 1696 throw uncaughtException(ex); 1697 } 1698 assert(mh.type() == type); 1699 return mh; 1700 } 1701 1702 private static MethodHandle[] toArray(List<MethodHandle> l) { 1703 return l.toArray(new MethodHandle[0]); 1704 } 1705 1706 /** 1707 * Loops introduce some complexity as they can have additional local state. Hence, LambdaForms for loops are 1708 * generated from a template. The LambdaForm template shape for the loop combinator is as follows (assuming one 1709 * reference parameter passed in {@code a1}, and a reference return type, with the return value represented by 1710 * {@code t12}): 1711 * <blockquote><pre>{@code 1712 * loop=Lambda(a0:L,a1:L)=>{ 1713 * t2:L=BoundMethodHandle$Species_L3.argL0(a0:L); // LoopClauses holding init, step, pred, fini handles 1714 * t3:L=BoundMethodHandle$Species_L3.argL1(a0:L); // helper handle to box the arguments into an Object[] 1715 * t4:L=BoundMethodHandle$Species_L3.argL2(a0:L); // helper handle to unbox the result 1716 * t5:L=MethodHandle.invokeBasic(t3:L,a1:L); // box the arguments into an Object[] 1717 * t6:L=MethodHandleImpl.loop(null,t2:L,t3:L); // call the loop executor 1718 * t7:L=MethodHandle.invokeBasic(t4:L,t6:L);t7:L} // unbox the result; return the result 1719 * }</pre></blockquote> 1720 * <p> 1721 * {@code argL0} is a LoopClauses instance holding, in a 2-dimensional array, the init, step, pred, and fini method 1722 * handles. {@code argL1} and {@code argL2} are auxiliary method handles: {@code argL1} boxes arguments and wraps 1723 * them into {@code Object[]} ({@code ValueConversions.array()}), and {@code argL2} unboxes the result if necessary 1724 * ({@code ValueConversions.unbox()}). 1725 * <p> 1726 * Having {@code t3} and {@code t4} passed in via a BMH and not hardcoded in the lambda form allows to share lambda 1727 * forms among loop combinators with the same basic type. 1728 * <p> 1729 * The above template is instantiated by using the {@link LambdaFormEditor} to replace the {@code null} argument to 1730 * the {@code loop} invocation with the {@code BasicType} array describing the loop clause types. This argument is 1731 * ignored in the loop invoker, but will be extracted and used in {@linkplain InvokerBytecodeGenerator#emitLoop(int) 1732 * bytecode generation}. 1733 */ 1734 private static LambdaForm makeLoopForm(MethodType basicType, BasicType[] localVarTypes) { 1735 MethodType lambdaType = basicType.invokerType(); 1736 1737 final int THIS_MH = 0; // the BMH_LLL 1738 final int ARG_BASE = 1; // start of incoming arguments 1739 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 1740 1741 int nameCursor = ARG_LIMIT; 1742 final int GET_CLAUSE_DATA = nameCursor++; 1743 final int GET_COLLECT_ARGS = nameCursor++; 1744 final int GET_UNBOX_RESULT = nameCursor++; 1745 final int BOXED_ARGS = nameCursor++; 1746 final int LOOP = nameCursor++; 1747 final int UNBOX_RESULT = nameCursor++; 1748 1749 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_LOOP); 1750 if (lform == null) { 1751 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 1752 1753 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLL(); 1754 names[THIS_MH] = names[THIS_MH].withConstraint(data); 1755 names[GET_CLAUSE_DATA] = new Name(data.getterFunction(0), names[THIS_MH]); 1756 names[GET_COLLECT_ARGS] = new Name(data.getterFunction(1), names[THIS_MH]); 1757 names[GET_UNBOX_RESULT] = new Name(data.getterFunction(2), names[THIS_MH]); 1758 1759 // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...); 1760 MethodType collectArgsType = basicType.changeReturnType(Object.class); 1761 MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType); 1762 Object[] args = new Object[invokeBasic.type().parameterCount()]; 1763 args[0] = names[GET_COLLECT_ARGS]; 1764 System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT - ARG_BASE); 1765 names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.LOOP)), args); 1766 1767 // t_{i+1}:L=MethodHandleImpl.loop(localTypes:L,clauses:L,t_{i}:L); 1768 Object[] lArgs = 1769 new Object[]{null, // placeholder for BasicType[] localTypes - will be added by LambdaFormEditor 1770 names[GET_CLAUSE_DATA], names[BOXED_ARGS]}; 1771 names[LOOP] = new Name(getFunction(NF_loop), lArgs); 1772 1773 // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L); 1774 MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class)); 1775 Object[] unboxArgs = new Object[]{names[GET_UNBOX_RESULT], names[LOOP]}; 1776 names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs); 1777 1778 lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_LOOP, 1779 LambdaForm.create(lambdaType.parameterCount(), names, Kind.LOOP)); 1780 } 1781 1782 // BOXED_ARGS is the index into the names array where the loop idiom starts 1783 return lform.editor().noteLoopLocalTypesForm(BOXED_ARGS, localVarTypes); 1784 } 1785 1786 static class LoopClauses { 1787 @Stable final MethodHandle[][] clauses; 1788 LoopClauses(MethodHandle[][] clauses) { 1789 assert clauses.length == 4; 1790 this.clauses = clauses; 1791 } 1792 @Override 1793 public String toString() { 1794 StringBuilder sb = new StringBuilder("LoopClauses -- "); 1795 for (int i = 0; i < 4; ++i) { 1796 if (i > 0) { 1797 sb.append(" "); 1798 } 1799 sb.append('<').append(i).append(">: "); 1800 MethodHandle[] hs = clauses[i]; 1801 for (int j = 0; j < hs.length; ++j) { 1802 if (j > 0) { 1803 sb.append(" "); 1804 } 1805 sb.append('*').append(j).append(": ").append(hs[j]).append('\n'); 1806 } 1807 } 1808 sb.append(" --\n"); 1809 return sb.toString(); 1810 } 1811 } 1812 1813 /** 1814 * Intrinsified during LambdaForm compilation 1815 * (see {@link InvokerBytecodeGenerator#emitLoop(int)}). 1816 */ 1817 @Hidden 1818 static Object loop(BasicType[] localTypes, LoopClauses clauseData, Object... av) throws Throwable { 1819 final MethodHandle[] init = clauseData.clauses[0]; 1820 final MethodHandle[] step = clauseData.clauses[1]; 1821 final MethodHandle[] pred = clauseData.clauses[2]; 1822 final MethodHandle[] fini = clauseData.clauses[3]; 1823 int varSize = (int) Stream.of(init).filter(h -> h.type().returnType() != void.class).count(); 1824 int nArgs = init[0].type().parameterCount(); 1825 Object[] varsAndArgs = new Object[varSize + nArgs]; 1826 for (int i = 0, v = 0; i < init.length; ++i) { 1827 MethodHandle ih = init[i]; 1828 if (ih.type().returnType() == void.class) { 1829 ih.invokeWithArguments(av); 1830 } else { 1831 varsAndArgs[v++] = ih.invokeWithArguments(av); 1832 } 1833 } 1834 System.arraycopy(av, 0, varsAndArgs, varSize, nArgs); 1835 final int nSteps = step.length; 1836 for (; ; ) { 1837 for (int i = 0, v = 0; i < nSteps; ++i) { 1838 MethodHandle p = pred[i]; 1839 MethodHandle s = step[i]; 1840 MethodHandle f = fini[i]; 1841 if (s.type().returnType() == void.class) { 1842 s.invokeWithArguments(varsAndArgs); 1843 } else { 1844 varsAndArgs[v++] = s.invokeWithArguments(varsAndArgs); 1845 } 1846 if (!(boolean) p.invokeWithArguments(varsAndArgs)) { 1847 return f.invokeWithArguments(varsAndArgs); 1848 } 1849 } 1850 } 1851 } 1852 1853 /** 1854 * This method is bound as the predicate in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle, 1855 * MethodHandle) counting loops}. 1856 * 1857 * @param limit the upper bound of the parameter, statically bound at loop creation time. 1858 * @param counter the counter parameter, passed in during loop execution. 1859 * 1860 * @return whether the counter has reached the limit. 1861 */ 1862 static boolean countedLoopPredicate(int limit, int counter) { 1863 return counter < limit; 1864 } 1865 1866 /** 1867 * This method is bound as the step function in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle, 1868 * MethodHandle) counting loops} to increment the counter. 1869 * 1870 * @param limit the upper bound of the loop counter (ignored). 1871 * @param counter the loop counter. 1872 * 1873 * @return the loop counter incremented by 1. 1874 */ 1875 static int countedLoopStep(int limit, int counter) { 1876 return counter + 1; 1877 } 1878 1879 /** 1880 * This is bound to initialize the loop-local iterator in {@linkplain MethodHandles#iteratedLoop iterating loops}. 1881 * 1882 * @param it the {@link Iterable} over which the loop iterates. 1883 * 1884 * @return an {@link Iterator} over the argument's elements. 1885 */ 1886 static Iterator<?> initIterator(Iterable<?> it) { 1887 return it.iterator(); 1888 } 1889 1890 /** 1891 * This method is bound as the predicate in {@linkplain MethodHandles#iteratedLoop iterating loops}. 1892 * 1893 * @param it the iterator to be checked. 1894 * 1895 * @return {@code true} iff there are more elements to iterate over. 1896 */ 1897 static boolean iteratePredicate(Iterator<?> it) { 1898 return it.hasNext(); 1899 } 1900 1901 /** 1902 * This method is bound as the step for retrieving the current value from the iterator in {@linkplain 1903 * MethodHandles#iteratedLoop iterating loops}. 1904 * 1905 * @param it the iterator. 1906 * 1907 * @return the next element from the iterator. 1908 */ 1909 static Object iterateNext(Iterator<?> it) { 1910 return it.next(); 1911 } 1912 1913 /** 1914 * Makes a {@code try-finally} handle that conforms to the type constraints. 1915 * 1916 * @param target the target to execute in a {@code try-finally} block. 1917 * @param cleanup the cleanup to execute in the {@code finally} block. 1918 * @param rtype the result type of the entire construct. 1919 * @param argTypes the types of the arguments. 1920 * 1921 * @return a handle on the constructed {@code try-finally} block. 1922 */ 1923 static MethodHandle makeTryFinally(MethodHandle target, MethodHandle cleanup, Class<?> rtype, Class<?>[] argTypes) { 1924 MethodType type = MethodType.methodType(rtype, argTypes); 1925 LambdaForm form = makeTryFinallyForm(type.basicType()); 1926 1927 // Prepare auxiliary method handles used during LambdaForm interpretation. 1928 // Box arguments and wrap them into Object[]: ValueConversions.array(). 1929 MethodType varargsType = type.changeReturnType(Object[].class); 1930 MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType); 1931 MethodHandle unboxResult = unboxResultHandle(rtype); 1932 1933 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL(); 1934 BoundMethodHandle mh; 1935 try { 1936 mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) target, (Object) cleanup, 1937 (Object) collectArgs, (Object) unboxResult); 1938 } catch (Throwable ex) { 1939 throw uncaughtException(ex); 1940 } 1941 assert(mh.type() == type); 1942 return mh; 1943 } 1944 1945 /** 1946 * The LambdaForm shape for the tryFinally combinator is as follows (assuming one reference parameter passed in 1947 * {@code a1}, and a reference return type, with the return value represented by {@code t8}): 1948 * <blockquote><pre>{@code 1949 * tryFinally=Lambda(a0:L,a1:L)=>{ 1950 * t2:L=BoundMethodHandle$Species_LLLL.argL0(a0:L); // target method handle 1951 * t3:L=BoundMethodHandle$Species_LLLL.argL1(a0:L); // cleanup method handle 1952 * t4:L=BoundMethodHandle$Species_LLLL.argL2(a0:L); // helper handle to box the arguments into an Object[] 1953 * t5:L=BoundMethodHandle$Species_LLLL.argL3(a0:L); // helper handle to unbox the result 1954 * t6:L=MethodHandle.invokeBasic(t4:L,a1:L); // box the arguments into an Object[] 1955 * t7:L=MethodHandleImpl.tryFinally(t2:L,t3:L,t6:L); // call the tryFinally executor 1956 * t8:L=MethodHandle.invokeBasic(t5:L,t7:L);t8:L} // unbox the result; return the result 1957 * }</pre></blockquote> 1958 * <p> 1959 * {@code argL0} and {@code argL1} are the target and cleanup method handles. 1960 * {@code argL2} and {@code argL3} are auxiliary method handles: {@code argL2} boxes arguments and wraps them into 1961 * {@code Object[]} ({@code ValueConversions.array()}), and {@code argL3} unboxes the result if necessary 1962 * ({@code ValueConversions.unbox()}). 1963 * <p> 1964 * Having {@code t4} and {@code t5} passed in via a BMH and not hardcoded in the lambda form allows to share lambda 1965 * forms among tryFinally combinators with the same basic type. 1966 */ 1967 private static LambdaForm makeTryFinallyForm(MethodType basicType) { 1968 MethodType lambdaType = basicType.invokerType(); 1969 1970 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_TF); 1971 if (lform != null) { 1972 return lform; 1973 } 1974 final int THIS_MH = 0; // the BMH_LLLL 1975 final int ARG_BASE = 1; // start of incoming arguments 1976 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 1977 1978 int nameCursor = ARG_LIMIT; 1979 final int GET_TARGET = nameCursor++; 1980 final int GET_CLEANUP = nameCursor++; 1981 final int GET_COLLECT_ARGS = nameCursor++; 1982 final int GET_UNBOX_RESULT = nameCursor++; 1983 final int BOXED_ARGS = nameCursor++; 1984 final int TRY_FINALLY = nameCursor++; 1985 final int UNBOX_RESULT = nameCursor++; 1986 1987 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 1988 1989 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL(); 1990 names[THIS_MH] = names[THIS_MH].withConstraint(data); 1991 names[GET_TARGET] = new Name(data.getterFunction(0), names[THIS_MH]); 1992 names[GET_CLEANUP] = new Name(data.getterFunction(1), names[THIS_MH]); 1993 names[GET_COLLECT_ARGS] = new Name(data.getterFunction(2), names[THIS_MH]); 1994 names[GET_UNBOX_RESULT] = new Name(data.getterFunction(3), names[THIS_MH]); 1995 1996 // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...); 1997 MethodType collectArgsType = basicType.changeReturnType(Object.class); 1998 MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType); 1999 Object[] args = new Object[invokeBasic.type().parameterCount()]; 2000 args[0] = names[GET_COLLECT_ARGS]; 2001 System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE); 2002 names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.TRY_FINALLY)), args); 2003 2004 // t_{i+1}:L=MethodHandleImpl.tryFinally(target:L,exType:L,catcher:L,t_{i}:L); 2005 Object[] tfArgs = new Object[] {names[GET_TARGET], names[GET_CLEANUP], names[BOXED_ARGS]}; 2006 names[TRY_FINALLY] = new Name(getFunction(NF_tryFinally), tfArgs); 2007 2008 // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L); 2009 MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class)); 2010 Object[] unboxArgs = new Object[] {names[GET_UNBOX_RESULT], names[TRY_FINALLY]}; 2011 names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs); 2012 2013 lform = LambdaForm.create(lambdaType.parameterCount(), names, Kind.TRY_FINALLY); 2014 2015 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_TF, lform); 2016 } 2017 2018 /** 2019 * Intrinsified during LambdaForm compilation 2020 * (see {@link InvokerBytecodeGenerator#emitTryFinally emitTryFinally}). 2021 */ 2022 @Hidden 2023 static Object tryFinally(MethodHandle target, MethodHandle cleanup, Object... av) throws Throwable { 2024 Throwable t = null; 2025 Object r = null; 2026 try { 2027 r = target.invokeWithArguments(av); 2028 } catch (Throwable thrown) { 2029 t = thrown; 2030 throw t; 2031 } finally { 2032 Object[] args = target.type().returnType() == void.class ? prepend(av, t) : prepend(av, t, r); 2033 r = cleanup.invokeWithArguments(args); 2034 } 2035 return r; 2036 } 2037 2038 // see varargsArray method for chaching/package-private version of this 2039 private static MethodHandle makeCollector(Class<?> arrayType, int parameterCount) { 2040 MethodType type = MethodType.methodType(arrayType, Collections.nCopies(parameterCount, arrayType.componentType())); 2041 MethodHandle newArray = MethodHandles.arrayConstructor(arrayType); 2042 2043 LambdaForm form = makeCollectorForm(type.basicType(), arrayType); 2044 2045 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_L(); 2046 BoundMethodHandle mh; 2047 try { 2048 mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) newArray); 2049 } catch (Throwable ex) { 2050 throw uncaughtException(ex); 2051 } 2052 assert(mh.type() == type); 2053 return mh; 2054 } 2055 2056 private static LambdaForm makeCollectorForm(MethodType basicType, Class<?> arrayType) { 2057 MethodType lambdaType = basicType.invokerType(); 2058 int parameterCount = basicType.parameterCount(); 2059 2060 // Only share the lambda form for empty arrays and reference types. 2061 // Sharing based on the basic type alone doesn't work because 2062 // we need a separate lambda form for byte/short/char/int which 2063 // are all erased to int otherwise. 2064 // Other caching for primitive types happens at the MethodHandle level (see varargsArray). 2065 boolean isReferenceType = !arrayType.componentType().isPrimitive(); 2066 boolean isSharedLambdaForm = parameterCount == 0 || isReferenceType; 2067 if (isSharedLambdaForm) { 2068 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_COLLECTOR); 2069 if (lform != null) { 2070 return lform; 2071 } 2072 } 2073 2074 // use erased accessor for reference types 2075 MethodHandle storeFunc = isReferenceType 2076 ? ArrayAccessor.OBJECT_ARRAY_SETTER 2077 : makeArrayElementAccessor(arrayType, ArrayAccess.SET); 2078 2079 final int THIS_MH = 0; // the BMH_L 2080 final int ARG_BASE = 1; // start of incoming arguments 2081 final int ARG_LIMIT = ARG_BASE + parameterCount; 2082 2083 int nameCursor = ARG_LIMIT; 2084 final int GET_NEW_ARRAY = nameCursor++; 2085 final int CALL_NEW_ARRAY = nameCursor++; 2086 final int STORE_ELEMENT_BASE = nameCursor; 2087 final int STORE_ELEMENT_LIMIT = STORE_ELEMENT_BASE + parameterCount; 2088 nameCursor = STORE_ELEMENT_LIMIT; 2089 2090 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 2091 2092 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_L(); 2093 names[THIS_MH] = names[THIS_MH].withConstraint(data); 2094 names[GET_NEW_ARRAY] = new Name(data.getterFunction(0), names[THIS_MH]); 2095 2096 MethodHandle invokeBasic = MethodHandles.basicInvoker(MethodType.methodType(Object.class, int.class)); 2097 names[CALL_NEW_ARRAY] = new Name(new NamedFunction(invokeBasic), names[GET_NEW_ARRAY], parameterCount); 2098 for (int storeIndex = 0, 2099 storeNameCursor = STORE_ELEMENT_BASE, 2100 argCursor = ARG_BASE; 2101 storeNameCursor < STORE_ELEMENT_LIMIT; 2102 storeIndex++, storeNameCursor++, argCursor++){ 2103 2104 names[storeNameCursor] = new Name(new NamedFunction(makeIntrinsic(storeFunc, Intrinsic.ARRAY_STORE)), 2105 names[CALL_NEW_ARRAY], storeIndex, names[argCursor]); 2106 } 2107 2108 LambdaForm lform = LambdaForm.create(lambdaType.parameterCount(), names, CALL_NEW_ARRAY, Kind.COLLECTOR); 2109 if (isSharedLambdaForm) { 2110 lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_COLLECTOR, lform); 2111 } 2112 return lform; 2113 } 2114 2115 // use a wrapper because we need this array to be @Stable 2116 static class CasesHolder { 2117 @Stable 2118 final MethodHandle[] cases; 2119 2120 public CasesHolder(MethodHandle[] cases) { 2121 this.cases = cases; 2122 } 2123 } 2124 2125 static MethodHandle makeTableSwitch(MethodType type, MethodHandle defaultCase, MethodHandle[] caseActions) { 2126 MethodType varargsType = type.changeReturnType(Object[].class); 2127 MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType); 2128 2129 MethodHandle unboxResult = unboxResultHandle(type.returnType()); 2130 2131 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLL(); 2132 LambdaForm form = makeTableSwitchForm(type.basicType(), data, caseActions.length); 2133 BoundMethodHandle mh; 2134 CasesHolder caseHolder = new CasesHolder(caseActions); 2135 try { 2136 mh = (BoundMethodHandle) data.factory().invokeBasic(type, form, (Object) defaultCase, (Object) collectArgs, 2137 (Object) unboxResult, (Object) caseHolder); 2138 } catch (Throwable ex) { 2139 throw uncaughtException(ex); 2140 } 2141 assert(mh.type() == type); 2142 return mh; 2143 } 2144 2145 private static class TableSwitchCacheKey { 2146 private static final Map<TableSwitchCacheKey, LambdaForm> CACHE = new ConcurrentHashMap<>(); 2147 2148 private final MethodType basicType; 2149 private final int numberOfCases; 2150 2151 public TableSwitchCacheKey(MethodType basicType, int numberOfCases) { 2152 this.basicType = basicType; 2153 this.numberOfCases = numberOfCases; 2154 } 2155 2156 @Override 2157 public boolean equals(Object o) { 2158 if (this == o) return true; 2159 if (o == null || getClass() != o.getClass()) return false; 2160 TableSwitchCacheKey that = (TableSwitchCacheKey) o; 2161 return numberOfCases == that.numberOfCases && Objects.equals(basicType, that.basicType); 2162 } 2163 @Override 2164 public int hashCode() { 2165 return Objects.hash(basicType, numberOfCases); 2166 } 2167 } 2168 2169 private static LambdaForm makeTableSwitchForm(MethodType basicType, BoundMethodHandle.SpeciesData data, 2170 int numCases) { 2171 MethodType lambdaType = basicType.invokerType(); 2172 2173 // We need to cache based on the basic type X number of cases, 2174 // since the number of cases is used when generating bytecode. 2175 // This also means that we can't use the cache in MethodTypeForm, 2176 // which only uses the basic type as a key. 2177 TableSwitchCacheKey key = new TableSwitchCacheKey(basicType, numCases); 2178 LambdaForm lform = TableSwitchCacheKey.CACHE.get(key); 2179 if (lform != null) { 2180 return lform; 2181 } 2182 2183 final int THIS_MH = 0; 2184 final int ARG_BASE = 1; // start of incoming arguments 2185 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 2186 final int ARG_SWITCH_ON = ARG_BASE; 2187 assert ARG_SWITCH_ON < ARG_LIMIT; 2188 2189 int nameCursor = ARG_LIMIT; 2190 final int GET_COLLECT_ARGS = nameCursor++; 2191 final int GET_DEFAULT_CASE = nameCursor++; 2192 final int GET_UNBOX_RESULT = nameCursor++; 2193 final int GET_CASES = nameCursor++; 2194 final int BOXED_ARGS = nameCursor++; 2195 final int TABLE_SWITCH = nameCursor++; 2196 final int UNBOXED_RESULT = nameCursor++; 2197 2198 int fieldCursor = 0; 2199 final int FIELD_DEFAULT_CASE = fieldCursor++; 2200 final int FIELD_COLLECT_ARGS = fieldCursor++; 2201 final int FIELD_UNBOX_RESULT = fieldCursor++; 2202 final int FIELD_CASES = fieldCursor++; 2203 2204 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 2205 2206 names[THIS_MH] = names[THIS_MH].withConstraint(data); 2207 names[GET_DEFAULT_CASE] = new Name(data.getterFunction(FIELD_DEFAULT_CASE), names[THIS_MH]); 2208 names[GET_COLLECT_ARGS] = new Name(data.getterFunction(FIELD_COLLECT_ARGS), names[THIS_MH]); 2209 names[GET_UNBOX_RESULT] = new Name(data.getterFunction(FIELD_UNBOX_RESULT), names[THIS_MH]); 2210 names[GET_CASES] = new Name(data.getterFunction(FIELD_CASES), names[THIS_MH]); 2211 2212 { 2213 MethodType collectArgsType = basicType.changeReturnType(Object.class); 2214 MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType); 2215 Object[] args = new Object[invokeBasic.type().parameterCount()]; 2216 args[0] = names[GET_COLLECT_ARGS]; 2217 System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT - ARG_BASE); 2218 names[BOXED_ARGS] = new Name(new NamedFunction(makeIntrinsic(invokeBasic, Intrinsic.TABLE_SWITCH, numCases)), args); 2219 } 2220 2221 { 2222 Object[] tfArgs = new Object[]{ 2223 names[ARG_SWITCH_ON], names[GET_DEFAULT_CASE], names[GET_CASES], names[BOXED_ARGS]}; 2224 names[TABLE_SWITCH] = new Name(getFunction(NF_tableSwitch), tfArgs); 2225 } 2226 2227 { 2228 MethodHandle invokeBasic = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class)); 2229 Object[] unboxArgs = new Object[]{names[GET_UNBOX_RESULT], names[TABLE_SWITCH]}; 2230 names[UNBOXED_RESULT] = new Name(invokeBasic, unboxArgs); 2231 } 2232 2233 lform = LambdaForm.create(lambdaType.parameterCount(), names, Kind.TABLE_SWITCH); 2234 LambdaForm prev = TableSwitchCacheKey.CACHE.putIfAbsent(key, lform); 2235 return prev != null ? prev : lform; 2236 } 2237 2238 @Hidden 2239 static Object tableSwitch(int input, MethodHandle defaultCase, CasesHolder holder, Object[] args) throws Throwable { 2240 MethodHandle[] caseActions = holder.cases; 2241 MethodHandle selectedCase; 2242 if (input < 0 || input >= caseActions.length) { 2243 selectedCase = defaultCase; 2244 } else { 2245 selectedCase = caseActions[input]; 2246 } 2247 return selectedCase.invokeWithArguments(args); 2248 } 2249 2250 // Indexes into constant method handles: 2251 static final int 2252 MH_cast = 0, 2253 MH_selectAlternative = 1, 2254 MH_countedLoopPred = 2, 2255 MH_countedLoopStep = 3, 2256 MH_initIterator = 4, 2257 MH_iteratePred = 5, 2258 MH_iterateNext = 6, 2259 MH_Array_newInstance = 7, 2260 MH_VarHandles_handleCheckedExceptions = 8, 2261 MH_LIMIT = 9; 2262 2263 static MethodHandle getConstantHandle(int idx) { 2264 MethodHandle handle = HANDLES[idx]; 2265 if (handle != null) { 2266 return handle; 2267 } 2268 return setCachedHandle(idx, makeConstantHandle(idx)); 2269 } 2270 2271 private static synchronized MethodHandle setCachedHandle(int idx, final MethodHandle method) { 2272 // Simulate a CAS, to avoid racy duplication of results. 2273 MethodHandle prev = HANDLES[idx]; 2274 if (prev != null) { 2275 return prev; 2276 } 2277 HANDLES[idx] = method; 2278 return method; 2279 } 2280 2281 // Local constant method handles: 2282 private static final @Stable MethodHandle[] HANDLES = new MethodHandle[MH_LIMIT]; 2283 2284 private static MethodHandle makeConstantHandle(int idx) { 2285 try { 2286 switch (idx) { 2287 case MH_cast: 2288 return IMPL_LOOKUP.findVirtual(Class.class, "cast", 2289 MethodType.methodType(Object.class, Object.class)); 2290 case MH_selectAlternative: 2291 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative", 2292 MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class)); 2293 case MH_countedLoopPred: 2294 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopPredicate", 2295 MethodType.methodType(boolean.class, int.class, int.class)); 2296 case MH_countedLoopStep: 2297 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopStep", 2298 MethodType.methodType(int.class, int.class, int.class)); 2299 case MH_initIterator: 2300 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "initIterator", 2301 MethodType.methodType(Iterator.class, Iterable.class)); 2302 case MH_iteratePred: 2303 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iteratePredicate", 2304 MethodType.methodType(boolean.class, Iterator.class)); 2305 case MH_iterateNext: 2306 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iterateNext", 2307 MethodType.methodType(Object.class, Iterator.class)); 2308 case MH_Array_newInstance: 2309 return IMPL_LOOKUP.findStatic(Array.class, "newInstance", 2310 MethodType.methodType(Object.class, Class.class, int.class)); 2311 case MH_VarHandles_handleCheckedExceptions: 2312 return IMPL_LOOKUP.findStatic(VarHandles.class, "handleCheckedExceptions", 2313 MethodType.methodType(void.class, Throwable.class)); 2314 } 2315 } catch (ReflectiveOperationException ex) { 2316 throw newInternalError(ex); 2317 } 2318 throw newInternalError("Unknown function index: " + idx); 2319 } 2320 } --- EOF ---