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