1 /* 2 * Copyright (c) 2011, 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 java.lang.classfile.TypeKind; 29 import jdk.internal.perf.PerfCounter; 30 import jdk.internal.vm.annotation.DontInline; 31 import jdk.internal.vm.annotation.Hidden; 32 import jdk.internal.vm.annotation.Stable; 33 import sun.invoke.util.Wrapper; 34 35 import java.lang.annotation.ElementType; 36 import java.lang.annotation.Retention; 37 import java.lang.annotation.RetentionPolicy; 38 import java.lang.annotation.Target; 39 import java.lang.reflect.Method; 40 import java.util.Arrays; 41 import java.util.HashMap; 42 43 import static java.lang.invoke.LambdaForm.BasicType.*; 44 import static java.lang.invoke.MethodHandleNatives.Constants.*; 45 import static java.lang.invoke.MethodHandleStatics.*; 46 47 /** 48 * The symbolic, non-executable form of a method handle's invocation semantics. 49 * It consists of a series of names. 50 * The first N (N=arity) names are parameters, 51 * while any remaining names are temporary values. 52 * Each temporary specifies the application of a function to some arguments. 53 * The functions are method handles, while the arguments are mixes of 54 * constant values and local names. 55 * The result of the lambda is defined as one of the names, often the last one. 56 * <p> 57 * Here is an approximate grammar: 58 * <blockquote><pre>{@code 59 * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}" 60 * ArgName = "a" N ":" T 61 * TempName = "t" N ":" T "=" Function "(" Argument* ");" 62 * Function = ConstantValue 63 * Argument = NameRef | ConstantValue 64 * Result = NameRef | "void" 65 * NameRef = "a" N | "t" N 66 * N = (any whole number) 67 * T = "L" | "I" | "J" | "F" | "D" | "V" 68 * }</pre></blockquote> 69 * Names are numbered consecutively from left to right starting at zero. 70 * (The letters are merely a taste of syntax sugar.) 71 * Thus, the first temporary (if any) is always numbered N (where N=arity). 72 * Every occurrence of a name reference in an argument list must refer to 73 * a name previously defined within the same lambda. 74 * A lambda has a void result if and only if its result index is -1. 75 * If a temporary has the type "V", it cannot be the subject of a NameRef, 76 * even though possesses a number. 77 * Note that all reference types are erased to "L", which stands for {@code Object}. 78 * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}. 79 * The other types stand for the usual primitive types. 80 * <p> 81 * Function invocation closely follows the static rules of the Java verifier. 82 * Arguments and return values must exactly match when their "Name" types are 83 * considered. 84 * Conversions are allowed only if they do not change the erased type. 85 * <ul> 86 * <li>L = Object: casts are used freely to convert into and out of reference types 87 * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments}) 88 * <li>J = long: no implicit conversions 89 * <li>F = float: no implicit conversions 90 * <li>D = double: no implicit conversions 91 * <li>V = void: a function result may be void if and only if its Name is of type "V" 92 * </ul> 93 * Although implicit conversions are not allowed, explicit ones can easily be 94 * encoded by using temporary expressions which call type-transformed identity functions. 95 * <p> 96 * Examples: 97 * <blockquote><pre>{@code 98 * (a0:J)=>{ a0 } 99 * == identity(long) 100 * (a0:I)=>{ t1:V = System.out#println(a0); void } 101 * == System.out#println(int) 102 * (a0:L)=>{ t1:V = System.out#println(a0); a0 } 103 * == identity, with printing side-effect 104 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 105 * t3:L = BoundMethodHandle#target(a0); 106 * t4:L = MethodHandle#invoke(t3, t2, a1); t4 } 107 * == general invoker for unary insertArgument combination 108 * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0); 109 * t3:L = MethodHandle#invoke(t2, a1); 110 * t4:L = FilterMethodHandle#target(a0); 111 * t5:L = MethodHandle#invoke(t4, t3); t5 } 112 * == general invoker for unary filterArgument combination 113 * (a0:L, a1:L)=>{ ...(same as previous example)... 114 * t5:L = MethodHandle#invoke(t4, t3, a1); t5 } 115 * == general invoker for unary/unary foldArgument combination 116 * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 } 117 * == invoker for identity method handle which performs i2l 118 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 119 * t3:L = Class#cast(t2,a1); t3 } 120 * == invoker for identity method handle which performs cast 121 * }</pre></blockquote> 122 * <p> 123 * @author John Rose, JSR 292 EG 124 */ 125 class LambdaForm { 126 final int arity; 127 final int result; 128 final boolean forceInline; 129 final MethodHandle customized; 130 @Stable final Name[] names; 131 final Kind kind; 132 MemberName vmentry; // low-level behavior, or null if not yet prepared 133 private boolean isCompiled; 134 135 // Either a LambdaForm cache (managed by LambdaFormEditor) or a link to uncustomized version (for customized LF) 136 volatile Object transformCache; 137 138 public static final int VOID_RESULT = -1, LAST_RESULT = -2; 139 140 enum BasicType { 141 L_TYPE('L', Object.class, Wrapper.OBJECT, TypeKind.REFERENCE), // all reference types 142 I_TYPE('I', int.class, Wrapper.INT, TypeKind.INT), 143 J_TYPE('J', long.class, Wrapper.LONG, TypeKind.LONG), 144 F_TYPE('F', float.class, Wrapper.FLOAT, TypeKind.FLOAT), 145 D_TYPE('D', double.class, Wrapper.DOUBLE, TypeKind.DOUBLE), // all primitive types 146 V_TYPE('V', void.class, Wrapper.VOID, TypeKind.VOID); // not valid in all contexts 147 148 static final @Stable BasicType[] ALL_TYPES = BasicType.values(); 149 static final @Stable BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1); 150 151 static final int ARG_TYPE_LIMIT = ARG_TYPES.length; 152 static final int TYPE_LIMIT = ALL_TYPES.length; 153 154 final char btChar; 155 final Class<?> btClass; 156 final Wrapper btWrapper; 157 final TypeKind btKind; 158 159 private BasicType(char btChar, Class<?> btClass, Wrapper wrapper, TypeKind typeKind) { 160 this.btChar = btChar; 161 this.btClass = btClass; 162 this.btWrapper = wrapper; 163 this.btKind = typeKind; 164 } 165 166 char basicTypeChar() { 167 return btChar; 168 } 169 Class<?> basicTypeClass() { 170 return btClass; 171 } 172 Wrapper basicTypeWrapper() { 173 return btWrapper; 174 } 175 TypeKind basicTypeKind() { 176 return btKind; 177 } 178 int basicTypeSlots() { 179 return btWrapper.stackSlots(); 180 } 181 182 static BasicType basicType(byte type) { 183 return ALL_TYPES[type]; 184 } 185 static BasicType basicType(char type) { 186 return switch (type) { 187 case 'L' -> L_TYPE; 188 case 'I' -> I_TYPE; 189 case 'J' -> J_TYPE; 190 case 'F' -> F_TYPE; 191 case 'D' -> D_TYPE; 192 case 'V' -> V_TYPE; 193 // all subword types are represented as ints 194 case 'Z', 'B', 'S', 'C' -> I_TYPE; 195 default -> throw newInternalError("Unknown type char: '" + type + "'"); 196 }; 197 } 198 static BasicType basicType(Class<?> type) { 199 return basicType(Wrapper.basicTypeChar(type)); 200 } 201 static int[] basicTypeOrds(BasicType[] types) { 202 if (types == null) { 203 return null; 204 } 205 int[] a = new int[types.length]; 206 for(int i = 0; i < types.length; ++i) { 207 a[i] = types[i].ordinal(); 208 } 209 return a; 210 } 211 212 static char basicTypeChar(Class<?> type) { 213 return basicType(type).btChar; 214 } 215 216 static int[] basicTypesOrd(Class<?>[] types) { 217 int[] ords = new int[types.length]; 218 for (int i = 0; i < ords.length; i++) { 219 ords[i] = basicType(types[i]).ordinal(); 220 } 221 return ords; 222 } 223 224 static boolean isBasicTypeChar(char c) { 225 return "LIJFDV".indexOf(c) >= 0; 226 } 227 static boolean isArgBasicTypeChar(char c) { 228 return "LIJFD".indexOf(c) >= 0; 229 } 230 231 static { assert(checkBasicType()); } 232 private static boolean checkBasicType() { 233 for (int i = 0; i < ARG_TYPE_LIMIT; i++) { 234 assert ARG_TYPES[i].ordinal() == i; 235 assert ARG_TYPES[i] == ALL_TYPES[i]; 236 } 237 for (int i = 0; i < TYPE_LIMIT; i++) { 238 assert ALL_TYPES[i].ordinal() == i; 239 } 240 assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE; 241 assert !Arrays.asList(ARG_TYPES).contains(V_TYPE); 242 return true; 243 } 244 } 245 246 enum Kind { 247 GENERIC("invoke"), 248 IDENTITY("identity"), 249 CONSTANT("constant"), 250 BOUND_REINVOKER("BMH.reinvoke", "reinvoke"), 251 REINVOKER("MH.reinvoke", "reinvoke"), 252 DELEGATE("MH.delegate", "delegate"), 253 EXACT_LINKER("MH.invokeExact_MT", "invokeExact_MT"), 254 EXACT_INVOKER("MH.exactInvoker", "exactInvoker"), 255 GENERIC_LINKER("MH.invoke_MT", "invoke_MT"), 256 GENERIC_INVOKER("MH.invoker", "invoker"), 257 LINK_TO_TARGET_METHOD("linkToTargetMethod"), 258 LINK_TO_CALL_SITE("linkToCallSite"), 259 DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual", "invokeVirtual"), 260 DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial", "invokeSpecial"), 261 DIRECT_INVOKE_SPECIAL_IFC("DMH.invokeSpecialIFC", "invokeSpecialIFC"), 262 DIRECT_INVOKE_STATIC("DMH.invokeStatic", "invokeStatic"), 263 DIRECT_NEW_INVOKE_SPECIAL("DMH.newInvokeSpecial", "newInvokeSpecial"), 264 DIRECT_INVOKE_INTERFACE("DMH.invokeInterface", "invokeInterface"), 265 DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit", "invokeStaticInit"), 266 GET_REFERENCE("getReference"), 267 PUT_REFERENCE("putReference"), 268 GET_REFERENCE_VOLATILE("getReferenceVolatile"), 269 PUT_REFERENCE_VOLATILE("putReferenceVolatile"), 270 GET_FLAT_VALUE("getFlatValue"), 271 PUT_FLAT_VALUE("putFlatValue"), 272 GET_FLAT_VALUE_VOLATILE("getFlatValueVolatile"), 273 PUT_FLAT_VALUE_VOLATILE("putFlatValueVolatile"), 274 GET_INT("getInt"), 275 PUT_INT("putInt"), 276 GET_INT_VOLATILE("getIntVolatile"), 277 PUT_INT_VOLATILE("putIntVolatile"), 278 GET_BOOLEAN("getBoolean"), 279 PUT_BOOLEAN("putBoolean"), 280 GET_BOOLEAN_VOLATILE("getBooleanVolatile"), 281 PUT_BOOLEAN_VOLATILE("putBooleanVolatile"), 282 GET_BYTE("getByte"), 283 PUT_BYTE("putByte"), 284 GET_BYTE_VOLATILE("getByteVolatile"), 285 PUT_BYTE_VOLATILE("putByteVolatile"), 286 GET_CHAR("getChar"), 287 PUT_CHAR("putChar"), 288 GET_CHAR_VOLATILE("getCharVolatile"), 289 PUT_CHAR_VOLATILE("putCharVolatile"), 290 GET_SHORT("getShort"), 291 PUT_SHORT("putShort"), 292 GET_SHORT_VOLATILE("getShortVolatile"), 293 PUT_SHORT_VOLATILE("putShortVolatile"), 294 GET_LONG("getLong"), 295 PUT_LONG("putLong"), 296 GET_LONG_VOLATILE("getLongVolatile"), 297 PUT_LONG_VOLATILE("putLongVolatile"), 298 GET_FLOAT("getFloat"), 299 PUT_FLOAT("putFloat"), 300 GET_FLOAT_VOLATILE("getFloatVolatile"), 301 PUT_FLOAT_VOLATILE("putFloatVolatile"), 302 GET_DOUBLE("getDouble"), 303 PUT_DOUBLE("putDouble"), 304 GET_DOUBLE_VOLATILE("getDoubleVolatile"), 305 PUT_DOUBLE_VOLATILE("putDoubleVolatile"), 306 TRY_FINALLY("tryFinally"), 307 TABLE_SWITCH("tableSwitch"), 308 COLLECTOR("collector"), 309 LOOP("loop"), 310 GUARD("guard"), 311 GUARD_WITH_CATCH("guardWithCatch"), 312 VARHANDLE_EXACT_INVOKER("VH.exactInvoker"), 313 VARHANDLE_INVOKER("VH.invoker", "invoker"), 314 VARHANDLE_LINKER("VH.invoke_MT", "invoke_MT"); 315 316 final String defaultLambdaName; 317 final String methodName; 318 319 private Kind(String defaultLambdaName) { 320 this(defaultLambdaName, defaultLambdaName); 321 } 322 323 private Kind(String defaultLambdaName, String methodName) { 324 this.defaultLambdaName = defaultLambdaName; 325 this.methodName = methodName; 326 } 327 } 328 329 // private version that doesn't do checks or defensive copies 330 private LambdaForm(int arity, int result, boolean forceInline, MethodHandle customized, Name[] names, Kind kind) { 331 this.arity = arity; 332 this.result = result; 333 this.forceInline = forceInline; 334 this.customized = customized; 335 this.names = names; 336 this.kind = kind; 337 this.vmentry = null; 338 this.isCompiled = false; 339 } 340 341 // root factory pre/post processing and calls simple constructor 342 private static LambdaForm create(int arity, Name[] names, int result, boolean forceInline, MethodHandle customized, Kind kind) { 343 names = names.clone(); 344 assert(namesOK(arity, names)); 345 result = fixResult(result, names); 346 347 boolean canInterpret = normalizeNames(arity, names); 348 LambdaForm form = new LambdaForm(arity, result, forceInline, customized, names, kind); 349 assert(form.nameRefsAreLegal()); 350 if (!canInterpret) { 351 form.compileToBytecode(); 352 } 353 return form; 354 } 355 356 // derived factories with defaults 357 private static final int DEFAULT_RESULT = LAST_RESULT; 358 private static final boolean DEFAULT_FORCE_INLINE = true; 359 private static final MethodHandle DEFAULT_CUSTOMIZED = null; 360 private static final Kind DEFAULT_KIND = Kind.GENERIC; 361 362 static LambdaForm create(int arity, Name[] names, int result) { 363 return create(arity, names, result, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, DEFAULT_KIND); 364 } 365 static LambdaForm create(int arity, Name[] names, int result, Kind kind) { 366 return create(arity, names, result, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, kind); 367 } 368 static LambdaForm create(int arity, Name[] names) { 369 return create(arity, names, DEFAULT_RESULT, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, DEFAULT_KIND); 370 } 371 static LambdaForm create(int arity, Name[] names, Kind kind) { 372 return create(arity, names, DEFAULT_RESULT, DEFAULT_FORCE_INLINE, DEFAULT_CUSTOMIZED, kind); 373 } 374 static LambdaForm create(int arity, Name[] names, boolean forceInline, Kind kind) { 375 return create(arity, names, DEFAULT_RESULT, forceInline, DEFAULT_CUSTOMIZED, kind); 376 } 377 378 private static int fixResult(int result, Name[] names) { 379 if (result == LAST_RESULT) 380 result = names.length - 1; // might still be void 381 if (result >= 0 && names[result].type == V_TYPE) 382 result = VOID_RESULT; 383 return result; 384 } 385 386 static boolean debugNames() { 387 return DEBUG_NAME_COUNTERS != null; 388 } 389 390 static void associateWithDebugName(LambdaForm form, String name) { 391 assert (debugNames()); 392 synchronized (DEBUG_NAMES) { 393 DEBUG_NAMES.put(form, name); 394 } 395 } 396 397 String lambdaName() { 398 if (DEBUG_NAMES != null) { 399 synchronized (DEBUG_NAMES) { 400 String name = DEBUG_NAMES.get(this); 401 if (name == null) { 402 name = generateDebugName(); 403 } 404 return name; 405 } 406 } 407 return kind.defaultLambdaName; 408 } 409 410 private String generateDebugName() { 411 assert (debugNames()); 412 String debugNameStem = kind.defaultLambdaName; 413 Integer ctr = DEBUG_NAME_COUNTERS.getOrDefault(debugNameStem, 0); 414 DEBUG_NAME_COUNTERS.put(debugNameStem, ctr + 1); 415 StringBuilder buf = new StringBuilder(debugNameStem); 416 int leadingZero = buf.length(); 417 buf.append((int) ctr); 418 for (int i = buf.length() - leadingZero; i < 3; i++) { 419 buf.insert(leadingZero, '0'); 420 } 421 buf.append('_'); 422 buf.append(basicTypeSignature()); 423 String name = buf.toString(); 424 associateWithDebugName(this, name); 425 return name; 426 } 427 428 private static boolean namesOK(int arity, Name[] names) { 429 for (int i = 0; i < names.length; i++) { 430 Name n = names[i]; 431 assert(n != null) : "n is null"; 432 if (i < arity) 433 assert( n.isParam()) : n + " is not param at " + i; 434 else 435 assert(!n.isParam()) : n + " is param at " + i; 436 } 437 return true; 438 } 439 440 /** Customize LambdaForm for a particular MethodHandle */ 441 LambdaForm customize(MethodHandle mh) { 442 if (customized == mh) { 443 return this; 444 } 445 LambdaForm customForm = LambdaForm.create(arity, names, result, forceInline, mh, kind); 446 if (COMPILE_THRESHOLD >= 0 && isCompiled) { 447 // If shared LambdaForm has been compiled, compile customized version as well. 448 customForm.compileToBytecode(); 449 } 450 customForm.transformCache = this; // LambdaFormEditor should always use uncustomized form. 451 return customForm; 452 } 453 454 /** Get uncustomized flavor of the LambdaForm */ 455 LambdaForm uncustomize() { 456 if (customized == null) { 457 return this; 458 } 459 assert(transformCache != null); // Customized LambdaForm should always has a link to uncustomized version. 460 LambdaForm uncustomizedForm = (LambdaForm)transformCache; 461 if (COMPILE_THRESHOLD >= 0 && isCompiled) { 462 // If customized LambdaForm has been compiled, compile uncustomized version as well. 463 uncustomizedForm.compileToBytecode(); 464 } 465 return uncustomizedForm; 466 } 467 468 /** Renumber and/or replace params so that they are interned and canonically numbered. 469 * @return true if we can interpret 470 */ 471 private static boolean normalizeNames(int arity, Name[] names) { 472 Name[] oldNames = names.clone(); 473 int maxOutArity = 0; 474 for (int i = 0; i < names.length; i++) { 475 Name n = names[i]; 476 names[i] = n.withIndex(i); 477 if (n.arguments != null && maxOutArity < n.arguments.length) 478 maxOutArity = n.arguments.length; 479 } 480 if (oldNames != null) { 481 for (int i = Math.max(1, arity); i < names.length; i++) { 482 Name fixed = names[i].replaceNames(oldNames, names, 0, i); 483 names[i] = fixed.withIndex(i); 484 } 485 } 486 int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT); 487 boolean needIntern = false; 488 for (int i = 0; i < maxInterned; i++) { 489 Name n = names[i], n2 = internArgument(n); 490 if (n != n2) { 491 names[i] = n2; 492 needIntern = true; 493 } 494 } 495 if (needIntern) { 496 for (int i = arity; i < names.length; i++) { 497 names[i].internArguments(); 498 } 499 } 500 501 // return true if we can interpret 502 if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) { 503 // Cannot use LF interpreter on very high arity expressions. 504 assert(maxOutArity <= MethodType.MAX_JVM_ARITY); 505 return false; 506 } 507 return true; 508 } 509 510 /** 511 * Check that all embedded Name references are localizable to this lambda, 512 * and are properly ordered after their corresponding definitions. 513 * <p> 514 * Note that a Name can be local to multiple lambdas, as long as 515 * it possesses the same index in each use site. 516 * This allows Name references to be freely reused to construct 517 * fresh lambdas, without confusion. 518 */ 519 boolean nameRefsAreLegal() { 520 assert(arity >= 0 && arity <= names.length); 521 assert(result >= -1 && result < names.length); 522 // Do all names possess an index consistent with their local definition order? 523 for (int i = 0; i < arity; i++) { 524 Name n = names[i]; 525 assert(n.index() == i) : Arrays.asList(n.index(), i); 526 assert(n.isParam()); 527 } 528 // Also, do all local name references 529 for (int i = arity; i < names.length; i++) { 530 Name n = names[i]; 531 assert(n.index() == i); 532 for (Object arg : n.arguments) { 533 if (arg instanceof Name n2) { 534 int i2 = n2.index; 535 assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length; 536 assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this); 537 assert(i2 < i); // ref must come after def! 538 } 539 } 540 } 541 return true; 542 } 543 544 // /** Invoke this form on the given arguments. */ 545 // final Object invoke(Object... args) throws Throwable { 546 // // NYI: fit this into the fast path? 547 // return interpretWithArguments(args); 548 // } 549 550 /** Report the return type. */ 551 BasicType returnType() { 552 if (result < 0) return V_TYPE; 553 Name n = names[result]; 554 return n.type; 555 } 556 557 /** Report the N-th argument type. */ 558 BasicType parameterType(int n) { 559 return parameter(n).type; 560 } 561 562 /** Report the N-th argument name. */ 563 Name parameter(int n) { 564 Name param = names[n]; 565 assert(n < arity && param.isParam()); 566 return param; 567 } 568 569 /** Report the N-th argument type constraint. */ 570 Object parameterConstraint(int n) { 571 return parameter(n).constraint; 572 } 573 574 /** Report the arity. */ 575 int arity() { 576 return arity; 577 } 578 579 /** Report the number of expressions (non-parameter names). */ 580 int expressionCount() { 581 return names.length - arity; 582 } 583 584 /** Return the method type corresponding to my basic type signature. */ 585 MethodType methodType() { 586 Class<?>[] ptypes = new Class<?>[arity]; 587 for (int i = 0; i < arity; ++i) { 588 ptypes[i] = parameterType(i).btClass; 589 } 590 return MethodType.methodType(returnType().btClass, ptypes, true); 591 } 592 593 /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */ 594 final String basicTypeSignature() { 595 StringBuilder buf = new StringBuilder(arity() + 3); 596 for (int i = 0, a = arity(); i < a; i++) 597 buf.append(parameterType(i).basicTypeChar()); 598 return buf.append('_').append(returnType().basicTypeChar()).toString(); 599 } 600 static int signatureArity(String sig) { 601 assert(isValidSignature(sig)); 602 return sig.indexOf('_'); 603 } 604 static boolean isValidSignature(String sig) { 605 int arity = sig.indexOf('_'); 606 if (arity < 0) return false; // must be of the form *_* 607 int siglen = sig.length(); 608 if (siglen != arity + 2) return false; // *_X 609 for (int i = 0; i < siglen; i++) { 610 if (i == arity) continue; // skip '_' 611 char c = sig.charAt(i); 612 if (c == 'V') 613 return (i == siglen - 1 && arity == siglen - 2); 614 if (!isArgBasicTypeChar(c)) return false; // must be [LIJFD] 615 } 616 return true; // [LIJFD]*_[LIJFDV] 617 } 618 619 /** 620 * Check if i-th name is a call to MethodHandleImpl.selectAlternative. 621 */ 622 boolean isSelectAlternative(int pos) { 623 // selectAlternative idiom: 624 // t_{n}:L=MethodHandleImpl.selectAlternative(...) 625 // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 626 if (pos+1 >= names.length) return false; 627 Name name0 = names[pos]; 628 Name name1 = names[pos+1]; 629 return name0.refersTo(MethodHandleImpl.class, "selectAlternative") && 630 name1.isInvokeBasic() && 631 name1.lastUseIndex(name0) == 0 && // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 632 lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1} 633 } 634 635 private boolean isMatchingIdiom(int pos, String idiomName, int nArgs) { 636 if (pos+2 >= names.length) return false; 637 Name name0 = names[pos]; 638 Name name1 = names[pos+1]; 639 Name name2 = names[pos+2]; 640 return name1.refersTo(MethodHandleImpl.class, idiomName) && 641 name0.isInvokeBasic() && 642 name2.isInvokeBasic() && 643 name1.lastUseIndex(name0) == nArgs && // t_{n+1}:L=MethodHandleImpl.<invoker>(<args>, t_{n}); 644 lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1} 645 name2.lastUseIndex(name1) == 1 && // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 646 lastUseIndex(name1) == pos+2; // t_{n+1} is local: used only in t_{n+2} 647 } 648 649 /** 650 * Check if i-th name is a start of GuardWithCatch idiom. 651 */ 652 boolean isGuardWithCatch(int pos) { 653 // GuardWithCatch idiom: 654 // t_{n}:L=MethodHandle.invokeBasic(...) 655 // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n}); 656 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 657 return isMatchingIdiom(pos, "guardWithCatch", 3); 658 } 659 660 /** 661 * Check if i-th name is a start of the tryFinally idiom. 662 */ 663 boolean isTryFinally(int pos) { 664 // tryFinally idiom: 665 // t_{n}:L=MethodHandle.invokeBasic(...) 666 // t_{n+1}:L=MethodHandleImpl.tryFinally(*, *, t_{n}) 667 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 668 return isMatchingIdiom(pos, "tryFinally", 2); 669 } 670 671 /** 672 * Check if i-th name is a start of the tableSwitch idiom. 673 */ 674 boolean isTableSwitch(int pos) { 675 // tableSwitch idiom: 676 // t_{n}:L=MethodHandle.invokeBasic(...) // args 677 // t_{n+1}:L=MethodHandleImpl.tableSwitch(*, *, *, t_{n}) 678 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 679 if (pos + 2 >= names.length) return false; 680 681 final int POS_COLLECT_ARGS = pos; 682 final int POS_TABLE_SWITCH = pos + 1; 683 final int POS_UNBOX_RESULT = pos + 2; 684 685 Name collectArgs = names[POS_COLLECT_ARGS]; 686 Name tableSwitch = names[POS_TABLE_SWITCH]; 687 Name unboxResult = names[POS_UNBOX_RESULT]; 688 return tableSwitch.refersTo(MethodHandleImpl.class, "tableSwitch") && 689 collectArgs.isInvokeBasic() && 690 unboxResult.isInvokeBasic() && 691 tableSwitch.lastUseIndex(collectArgs) == 3 && // t_{n+1}:L=MethodHandleImpl.<invoker>(*, *, *, t_{n}); 692 lastUseIndex(collectArgs) == POS_TABLE_SWITCH && // t_{n} is local: used only in t_{n+1} 693 unboxResult.lastUseIndex(tableSwitch) == 1 && // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 694 lastUseIndex(tableSwitch) == POS_UNBOX_RESULT; // t_{n+1} is local: used only in t_{n+2} 695 } 696 697 /** 698 * Check if i-th name is a start of the loop idiom. 699 */ 700 boolean isLoop(int pos) { 701 // loop idiom: 702 // t_{n}:L=MethodHandle.invokeBasic(...) 703 // t_{n+1}:L=MethodHandleImpl.loop(types, *, t_{n}) 704 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 705 return isMatchingIdiom(pos, "loop", 2); 706 } 707 708 /* 709 * Code generation issues: 710 * 711 * Compiled LFs should be reusable in general. 712 * The biggest issue is how to decide when to pull a name into 713 * the bytecode, versus loading a reified form from the MH data. 714 * 715 * For example, an asType wrapper may require execution of a cast 716 * after a call to a MH. The target type of the cast can be placed 717 * as a constant in the LF itself. This will force the cast type 718 * to be compiled into the bytecodes and native code for the MH. 719 * Or, the target type of the cast can be erased in the LF, and 720 * loaded from the MH data. (Later on, if the MH as a whole is 721 * inlined, the data will flow into the inlined instance of the LF, 722 * as a constant, and the end result will be an optimal cast.) 723 * 724 * This erasure of cast types can be done with any use of 725 * reference types. It can also be done with whole method 726 * handles. Erasing a method handle might leave behind 727 * LF code that executes correctly for any MH of a given 728 * type, and load the required MH from the enclosing MH's data. 729 * Or, the erasure might even erase the expected MT. 730 * 731 * Also, for direct MHs, the MemberName of the target 732 * could be erased, and loaded from the containing direct MH. 733 * As a simple case, a LF for all int-valued non-static 734 * field getters would perform a cast on its input argument 735 * (to non-constant base type derived from the MemberName) 736 * and load an integer value from the input object 737 * (at a non-constant offset also derived from the MemberName). 738 * Such MN-erased LFs would be inlinable back to optimized 739 * code, whenever a constant enclosing DMH is available 740 * to supply a constant MN from its data. 741 * 742 * The main problem here is to keep LFs reasonably generic, 743 * while ensuring that hot spots will inline good instances. 744 * "Reasonably generic" means that we don't end up with 745 * repeated versions of bytecode or machine code that do 746 * not differ in their optimized form. Repeated versions 747 * of machine would have the undesirable overheads of 748 * (a) redundant compilation work and (b) extra I$ pressure. 749 * To control repeated versions, we need to be ready to 750 * erase details from LFs and move them into MH data, 751 * whenever those details are not relevant to significant 752 * optimization. "Significant" means optimization of 753 * code that is actually hot. 754 * 755 * Achieving this may require dynamic splitting of MHs, by replacing 756 * a generic LF with a more specialized one, on the same MH, 757 * if (a) the MH is frequently executed and (b) the MH cannot 758 * be inlined into a containing caller, such as an invokedynamic. 759 * 760 * Compiled LFs that are no longer used should be GC-able. 761 * If they contain non-BCP references, they should be properly 762 * interlinked with the class loader(s) that their embedded types 763 * depend on. This probably means that reusable compiled LFs 764 * will be tabulated (indexed) on relevant class loaders, 765 * or else that the tables that cache them will have weak links. 766 */ 767 768 /** 769 * Make this LF directly executable, as part of a MethodHandle. 770 * Invariant: Every MH which is invoked must prepare its LF 771 * before invocation. 772 * (In principle, the JVM could do this very lazily, 773 * as a sort of pre-invocation linkage step.) 774 */ 775 public void prepare() { 776 if (COMPILE_THRESHOLD == 0 && !forceInterpretation() && !isCompiled) { 777 compileToBytecode(); 778 } 779 if (this.vmentry != null) { 780 // already prepared (e.g., a primitive DMH invoker form) 781 return; 782 } 783 MethodType mtype = methodType(); 784 MethodTypeForm form = mtype.form(); 785 786 MemberName entry = form.cachedInterpretEntry(); 787 if (entry == null) { 788 assert (isValidSignature(basicTypeSignature())); 789 entry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(mtype); 790 entry = form.setCachedInterpretEntry(entry); 791 } 792 this.vmentry = entry; 793 // TO DO: Maybe add invokeGeneric, invokeWithArguments 794 } 795 796 private static @Stable PerfCounter LF_FAILED; 797 798 private static PerfCounter failedCompilationCounter() { 799 if (LF_FAILED == null) { 800 LF_FAILED = PerfCounter.newPerfCounter("java.lang.invoke.failedLambdaFormCompilations"); 801 } 802 return LF_FAILED; 803 } 804 805 /** Generate optimizable bytecode for this form. */ 806 void compileToBytecode() { 807 if (forceInterpretation()) { 808 return; // this should not be compiled 809 } 810 if (vmentry != null && isCompiled) { 811 return; // already compiled somehow 812 } 813 814 // Obtain the invoker MethodType outside of the following try block. 815 // This ensures that an IllegalArgumentException is directly thrown if the 816 // type would have 256 or more parameters 817 MethodType invokerType = methodType(); 818 assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType)); 819 try { 820 vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType); 821 if (TRACE_INTERPRETER) 822 traceInterpreter("compileToBytecode", this); 823 isCompiled = true; 824 } catch (InvokerBytecodeGenerator.BytecodeGenerationException bge) { 825 // bytecode generation failed - mark this LambdaForm as to be run in interpretation mode only 826 invocationCounter = -1; 827 failedCompilationCounter().increment(); 828 if (LOG_LF_COMPILATION_FAILURE) { 829 System.out.println("LambdaForm compilation failed: " + this); 830 bge.printStackTrace(System.out); 831 } 832 } catch (Error e) { 833 // Pass through any error 834 throw e; 835 } catch (Exception e) { 836 // Wrap any exception 837 throw newInternalError(this.toString(), e); 838 } 839 } 840 841 // The next few routines are called only from assert expressions 842 // They verify that the built-in invokers process the correct raw data types. 843 private static boolean argumentTypesMatch(String sig, Object[] av) { 844 int arity = signatureArity(sig); 845 assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity; 846 assert(av[0] instanceof MethodHandle) : "av[0] not instance of MethodHandle: " + av[0]; 847 MethodHandle mh = (MethodHandle) av[0]; 848 MethodType mt = mh.type(); 849 assert(mt.parameterCount() == arity-1); 850 for (int i = 0; i < av.length; i++) { 851 Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1)); 852 assert(valueMatches(basicType(sig.charAt(i)), pt, av[i])); 853 } 854 return true; 855 } 856 private static boolean valueMatches(BasicType tc, Class<?> type, Object x) { 857 // The following line is needed because (...)void method handles can use non-void invokers 858 if (type == void.class) tc = V_TYPE; // can drop any kind of value 859 assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type); 860 switch (tc) { 861 case I_TYPE: assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break; 862 case J_TYPE: assert x instanceof Long : "instanceof Long: " + x; break; 863 case F_TYPE: assert x instanceof Float : "instanceof Float: " + x; break; 864 case D_TYPE: assert x instanceof Double : "instanceof Double: " + x; break; 865 case L_TYPE: assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break; 866 case V_TYPE: break; // allow anything here; will be dropped 867 default: assert(false); 868 } 869 return true; 870 } 871 private static boolean checkInt(Class<?> type, Object x) { 872 assert(x instanceof Integer); 873 if (type == int.class) return true; 874 Wrapper w = Wrapper.forBasicType(type); 875 assert(w.isSubwordOrInt()); 876 Object x1 = Wrapper.INT.wrap(w.wrap(x)); 877 return x.equals(x1); 878 } 879 private static boolean checkRef(Class<?> type, Object x) { 880 assert(!type.isPrimitive()); 881 if (x == null) return true; 882 if (type.isInterface()) return true; 883 return type.isInstance(x); 884 } 885 886 /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */ 887 private static final int COMPILE_THRESHOLD; 888 static { 889 COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD); 890 } 891 private int invocationCounter = 0; // a value of -1 indicates LambdaForm interpretation mode forever 892 893 private boolean forceInterpretation() { 894 return invocationCounter == -1; 895 } 896 897 /** Interpretively invoke this form on the given arguments. */ 898 @Hidden 899 @DontInline 900 Object interpretWithArguments(Object... argumentValues) throws Throwable { 901 if (TRACE_INTERPRETER) 902 return interpretWithArgumentsTracing(argumentValues); 903 checkInvocationCounter(); 904 assert(arityCheck(argumentValues)); 905 Object[] values = Arrays.copyOf(argumentValues, names.length); 906 for (int i = argumentValues.length; i < values.length; i++) { 907 values[i] = interpretName(names[i], values); 908 } 909 Object rv = (result < 0) ? null : values[result]; 910 assert(resultCheck(argumentValues, rv)); 911 return rv; 912 } 913 914 /** Evaluate a single Name within this form, applying its function to its arguments. */ 915 @Hidden 916 @DontInline 917 Object interpretName(Name name, Object[] values) throws Throwable { 918 if (TRACE_INTERPRETER) 919 traceInterpreter("| interpretName", name.debugString(), (Object[]) null); 920 Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class); 921 for (int i = 0; i < arguments.length; i++) { 922 Object a = arguments[i]; 923 if (a instanceof Name n) { 924 int i2 = n.index(); 925 assert(names[i2] == a); 926 a = values[i2]; 927 arguments[i] = a; 928 } 929 } 930 return name.function.invokeWithArguments(arguments); 931 } 932 933 private void checkInvocationCounter() { 934 if (COMPILE_THRESHOLD != 0 && 935 !forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) { 936 invocationCounter++; // benign race 937 if (invocationCounter >= COMPILE_THRESHOLD) { 938 // Replace vmentry with a bytecode version of this LF. 939 compileToBytecode(); 940 } 941 } 942 } 943 Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable { 944 traceInterpreter("[ interpretWithArguments", this, argumentValues); 945 if (!forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) { 946 int ctr = invocationCounter++; // benign race 947 traceInterpreter("| invocationCounter", ctr); 948 if (invocationCounter >= COMPILE_THRESHOLD) { 949 compileToBytecode(); 950 } 951 } 952 Object rval; 953 try { 954 assert(arityCheck(argumentValues)); 955 Object[] values = Arrays.copyOf(argumentValues, names.length); 956 for (int i = argumentValues.length; i < values.length; i++) { 957 values[i] = interpretName(names[i], values); 958 } 959 rval = (result < 0) ? null : values[result]; 960 } catch (Throwable ex) { 961 traceInterpreter("] throw =>", ex); 962 throw ex; 963 } 964 traceInterpreter("] return =>", rval); 965 return rval; 966 } 967 968 static void traceInterpreter(String event, Object obj, Object... args) { 969 if (TRACE_INTERPRETER) { 970 System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : "")); 971 } 972 } 973 static void traceInterpreter(String event, Object obj) { 974 traceInterpreter(event, obj, (Object[])null); 975 } 976 private boolean arityCheck(Object[] argumentValues) { 977 assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length"; 978 // also check that the leading (receiver) argument is somehow bound to this LF: 979 assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0]; 980 MethodHandle mh = (MethodHandle) argumentValues[0]; 981 assert(mh.internalForm() == this); 982 // note: argument #0 could also be an interface wrapper, in the future 983 argumentTypesMatch(basicTypeSignature(), argumentValues); 984 return true; 985 } 986 private boolean resultCheck(Object[] argumentValues, Object result) { 987 MethodHandle mh = (MethodHandle) argumentValues[0]; 988 MethodType mt = mh.type(); 989 assert(valueMatches(returnType(), mt.returnType(), result)); 990 return true; 991 } 992 993 public String toString() { 994 return debugString(-1); 995 } 996 997 String debugString(int indentLevel) { 998 String prefix = MethodHandle.debugPrefix(indentLevel); 999 String lambdaName = lambdaName(); 1000 StringBuilder buf = new StringBuilder(lambdaName); 1001 buf.append("=Lambda("); 1002 for (int i = 0; i < names.length; i++) { 1003 if (i == arity) buf.append(")=>{"); 1004 Name n = names[i]; 1005 if (i >= arity) buf.append("\n ").append(prefix); 1006 buf.append(n.paramString()); 1007 if (i < arity) { 1008 if (i+1 < arity) buf.append(","); 1009 continue; 1010 } 1011 buf.append("=").append(n.exprString()); 1012 buf.append(";"); 1013 } 1014 if (arity == names.length) buf.append(")=>{"); 1015 buf.append(result < 0 ? "void" : names[result]).append("}"); 1016 if (TRACE_INTERPRETER) { 1017 // Extra verbosity: 1018 buf.append(":").append(basicTypeSignature()); 1019 buf.append("/").append(vmentry); 1020 } 1021 return buf.toString(); 1022 } 1023 1024 @Override 1025 public boolean equals(Object obj) { 1026 return obj instanceof LambdaForm lf && equals(lf); 1027 } 1028 public boolean equals(LambdaForm that) { 1029 if (this.result != that.result) return false; 1030 return Arrays.equals(this.names, that.names); 1031 } 1032 public int hashCode() { 1033 return result + 31 * Arrays.hashCode(names); 1034 } 1035 LambdaFormEditor editor() { 1036 return LambdaFormEditor.lambdaFormEditor(this); 1037 } 1038 1039 boolean contains(Name name) { 1040 int pos = name.index(); 1041 if (pos >= 0) { 1042 return pos < names.length && name.equals(names[pos]); 1043 } 1044 for (int i = arity; i < names.length; i++) { 1045 if (name.equals(names[i])) 1046 return true; 1047 } 1048 return false; 1049 } 1050 1051 static class NamedFunction { 1052 final MemberName member; 1053 private @Stable MethodHandle resolvedHandle; 1054 private @Stable MethodType type; 1055 1056 NamedFunction(MethodHandle resolvedHandle) { 1057 this(resolvedHandle.internalMemberName(), resolvedHandle); 1058 } 1059 NamedFunction(MemberName member, MethodHandle resolvedHandle) { 1060 this.member = member; 1061 this.resolvedHandle = resolvedHandle; 1062 // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest. 1063 //assert(!isInvokeBasic(member)); 1064 } 1065 NamedFunction(MethodType basicInvokerType) { 1066 assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType; 1067 if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) { 1068 this.resolvedHandle = basicInvokerType.invokers().basicInvoker(); 1069 this.member = resolvedHandle.internalMemberName(); 1070 } else { 1071 // necessary to pass BigArityTest 1072 this.member = Invokers.invokeBasicMethod(basicInvokerType); 1073 } 1074 assert(isInvokeBasic(member)); 1075 } 1076 1077 private static boolean isInvokeBasic(MemberName member) { 1078 return member != null && 1079 member.getDeclaringClass() == MethodHandle.class && 1080 "invokeBasic".equals(member.getName()); 1081 } 1082 1083 // The next 2 constructors are used to break circular dependencies on MH.invokeStatic, etc. 1084 // Any LambdaForm containing such a member is not interpretable. 1085 // This is OK, since all such LFs are prepared with special primitive vmentry points. 1086 // And even without the resolvedHandle, the name can still be compiled and optimized. 1087 NamedFunction(Method method) { 1088 this(new MemberName(method)); 1089 } 1090 NamedFunction(MemberName member) { 1091 this(member, null); 1092 } 1093 1094 MethodHandle resolvedHandle() { 1095 if (resolvedHandle == null) resolve(); 1096 return resolvedHandle; 1097 } 1098 1099 synchronized void resolve() { 1100 if (resolvedHandle == null) { 1101 resolvedHandle = DirectMethodHandle.make(member); 1102 } 1103 } 1104 1105 @Override 1106 public boolean equals(Object other) { 1107 if (this == other) return true; 1108 if (other == null) return false; 1109 return (other instanceof NamedFunction that) 1110 && this.member != null 1111 && this.member.equals(that.member); 1112 } 1113 1114 @Override 1115 public int hashCode() { 1116 if (member != null) 1117 return member.hashCode(); 1118 return super.hashCode(); 1119 } 1120 1121 static final MethodType INVOKER_METHOD_TYPE = 1122 MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1123 1124 private static MethodHandle computeInvoker(MethodTypeForm typeForm) { 1125 typeForm = typeForm.basicType().form(); // normalize to basic type 1126 MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV); 1127 if (mh != null) return mh; 1128 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while 1129 mh = DirectMethodHandle.make(invoker); 1130 MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV); 1131 if (mh2 != null) return mh2; // benign race 1132 if (!mh.type().equals(INVOKER_METHOD_TYPE)) 1133 throw newInternalError(mh.debugString()); 1134 return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh); 1135 } 1136 1137 @Hidden 1138 Object invokeWithArguments(Object... arguments) throws Throwable { 1139 // If we have a cached invoker, call it right away. 1140 // NOTE: The invoker always returns a reference value. 1141 if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments); 1142 return invoker().invokeBasic(resolvedHandle(), arguments); 1143 } 1144 1145 @Hidden 1146 Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable { 1147 Object rval; 1148 try { 1149 traceInterpreter("[ call", this, arguments); 1150 // resolvedHandle might be uninitialized, ok for tracing 1151 if (resolvedHandle == null) { 1152 traceInterpreter("| resolve", this); 1153 resolvedHandle(); 1154 } 1155 rval = invoker().invokeBasic(resolvedHandle(), arguments); 1156 } catch (Throwable ex) { 1157 traceInterpreter("] throw =>", ex); 1158 throw ex; 1159 } 1160 traceInterpreter("] return =>", rval); 1161 return rval; 1162 } 1163 1164 private MethodHandle invoker() { 1165 return computeInvoker(methodType().form()); 1166 } 1167 1168 MethodType methodType() { 1169 MethodType type = this.type; 1170 if (type == null) { 1171 this.type = type = calculateMethodType(member, resolvedHandle); 1172 } 1173 return type; 1174 } 1175 1176 private static MethodType calculateMethodType(MemberName member, MethodHandle resolvedHandle) { 1177 if (resolvedHandle != null) { 1178 return resolvedHandle.type(); 1179 } else { 1180 // only for certain internal LFs during bootstrapping 1181 return member.getInvocationType(); 1182 } 1183 } 1184 1185 MemberName member() { 1186 assert(assertMemberIsConsistent()); 1187 return member; 1188 } 1189 1190 // Called only from assert. 1191 private boolean assertMemberIsConsistent() { 1192 if (resolvedHandle instanceof DirectMethodHandle) { 1193 MemberName m = resolvedHandle.internalMemberName(); 1194 assert(m.equals(member)); 1195 } 1196 return true; 1197 } 1198 1199 Class<?> memberDeclaringClassOrNull() { 1200 return (member == null) ? null : member.getDeclaringClass(); 1201 } 1202 1203 BasicType returnType() { 1204 return basicType(methodType().returnType()); 1205 } 1206 1207 BasicType parameterType(int n) { 1208 return basicType(methodType().parameterType(n)); 1209 } 1210 1211 int arity() { 1212 return methodType().parameterCount(); 1213 } 1214 1215 public String toString() { 1216 if (member == null) return String.valueOf(resolvedHandle); 1217 return member.getDeclaringClass().getSimpleName()+"."+member.getName(); 1218 } 1219 1220 public boolean isIdentity() { 1221 return this.equals(identity(returnType())); 1222 } 1223 1224 public MethodHandleImpl.Intrinsic intrinsicName() { 1225 return resolvedHandle != null 1226 ? resolvedHandle.intrinsicName() 1227 : MethodHandleImpl.Intrinsic.NONE; 1228 } 1229 1230 public Object intrinsicData() { 1231 return resolvedHandle != null 1232 ? resolvedHandle.intrinsicData() 1233 : null; 1234 } 1235 } 1236 1237 public static String basicTypeSignature(MethodType type) { 1238 int params = type.parameterCount(); 1239 char[] sig = new char[params + 2]; 1240 int sigp = 0; 1241 while (sigp < params) { 1242 sig[sigp] = basicTypeChar(type.parameterType(sigp++)); 1243 } 1244 sig[sigp++] = '_'; 1245 sig[sigp++] = basicTypeChar(type.returnType()); 1246 assert(sigp == sig.length); 1247 return String.valueOf(sig); 1248 } 1249 1250 /** Hack to make signatures more readable when they show up in method names. 1251 * Signature should start with a sequence of uppercase ASCII letters. 1252 * Runs of three or more are replaced by a single letter plus a decimal repeat count. 1253 * A tail of anything other than uppercase ASCII is passed through unchanged. 1254 * @param signature sequence of uppercase ASCII letters with possible repetitions 1255 * @return same sequence, with repetitions counted by decimal numerals 1256 */ 1257 public static String shortenSignature(String signature) { 1258 final int NO_CHAR = -1, MIN_RUN = 3; 1259 int c0, c1 = NO_CHAR, c1reps = 0; 1260 StringBuilder buf = null; 1261 int len = signature.length(); 1262 if (len < MIN_RUN) return signature; 1263 for (int i = 0; i <= len; i++) { 1264 if (c1 != NO_CHAR && !('A' <= c1 && c1 <= 'Z')) { 1265 // wrong kind of char; bail out here 1266 if (buf != null) { 1267 buf.append(signature, i - c1reps, len); 1268 } 1269 break; 1270 } 1271 // shift in the next char: 1272 c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i)); 1273 if (c1 == c0) { ++c1reps; continue; } 1274 // shift in the next count: 1275 int c0reps = c1reps; c1reps = 1; 1276 // end of a character run 1277 if (c0reps < MIN_RUN) { 1278 if (buf != null) { 1279 while (--c0reps >= 0) 1280 buf.append((char)c0); 1281 } 1282 continue; 1283 } 1284 // found three or more in a row 1285 if (buf == null) 1286 buf = new StringBuilder().append(signature, 0, i - c0reps); 1287 buf.append((char)c0).append(c0reps); 1288 } 1289 return (buf == null) ? signature : buf.toString(); 1290 } 1291 1292 static final class Name { 1293 final BasicType type; 1294 final short index; 1295 final NamedFunction function; 1296 final Object constraint; // additional type information, if not null 1297 @Stable final Object[] arguments; 1298 1299 private static final Object[] EMPTY_ARGS = new Object[0]; 1300 1301 private Name(int index, BasicType type, NamedFunction function, Object[] arguments, Object constraint) { 1302 this.index = (short)index; 1303 this.type = type; 1304 this.function = function; 1305 this.arguments = arguments; 1306 this.constraint = constraint; 1307 assert(this.index == index && typesMatch(function, arguments)); 1308 assert(constraint == null || isParam()); // only params have constraints 1309 assert(constraint == null || constraint instanceof ClassSpecializer.SpeciesData || constraint instanceof Class); 1310 } 1311 1312 Name(MethodHandle function, Object... arguments) { 1313 this(new NamedFunction(function), arguments); 1314 } 1315 Name(MethodType functionType, Object... arguments) { 1316 this(new NamedFunction(functionType), arguments); 1317 assert(arguments[0] instanceof Name name && name.type == L_TYPE); 1318 } 1319 Name(MemberName function, Object... arguments) { 1320 this(new NamedFunction(function), arguments); 1321 } 1322 Name(NamedFunction function) { 1323 this(-1, function.returnType(), function, EMPTY_ARGS, null); 1324 } 1325 Name(NamedFunction function, Object arg) { 1326 this(-1, function.returnType(), function, new Object[] { arg }, null); 1327 } 1328 Name(NamedFunction function, Object arg0, Object arg1) { 1329 this(-1, function.returnType(), function, new Object[] { arg0, arg1 }, null); 1330 } 1331 Name(NamedFunction function, Object... arguments) { 1332 this(-1, function.returnType(), function, Arrays.copyOf(arguments, arguments.length, Object[].class), null); 1333 } 1334 /** Create a raw parameter of the given type, with an expected index. */ 1335 Name(int index, BasicType type) { 1336 this(index, type, null, null, null); 1337 } 1338 /** Create a raw parameter of the given type. */ 1339 Name(BasicType type) { this(-1, type); } 1340 1341 BasicType type() { return type; } 1342 int index() { return index; } 1343 1344 char typeChar() { 1345 return type.btChar; 1346 } 1347 1348 Name withIndex(int i) { 1349 if (i == this.index) return this; 1350 return new Name(i, type, function, arguments, constraint); 1351 } 1352 1353 Name withConstraint(Object constraint) { 1354 if (constraint == this.constraint) return this; 1355 return new Name(index, type, function, arguments, constraint); 1356 } 1357 1358 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly 1359 if (oldName == newName) return this; 1360 @SuppressWarnings("LocalVariableHidesMemberVariable") 1361 Object[] arguments = this.arguments; 1362 if (arguments == null) return this; 1363 boolean replaced = false; 1364 for (int j = 0; j < arguments.length; j++) { 1365 if (arguments[j] == oldName) { 1366 if (!replaced) { 1367 replaced = true; 1368 arguments = arguments.clone(); 1369 } 1370 arguments[j] = newName; 1371 } 1372 } 1373 if (!replaced) return this; 1374 return new Name(function, arguments); 1375 } 1376 /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i]. 1377 * Limit such replacements to {@code start<=i<end}. Return possibly changed self. 1378 */ 1379 Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) { 1380 if (start >= end) return this; 1381 @SuppressWarnings("LocalVariableHidesMemberVariable") 1382 Object[] arguments = this.arguments; 1383 boolean replaced = false; 1384 eachArg: 1385 for (int j = 0; j < arguments.length; j++) { 1386 if (arguments[j] instanceof Name n) { 1387 int check = n.index; 1388 // harmless check to see if the thing is already in newNames: 1389 if (check >= 0 && check < newNames.length && n == newNames[check]) 1390 continue eachArg; 1391 // n might not have the correct index: n != oldNames[n.index]. 1392 for (int i = start; i < end; i++) { 1393 if (n == oldNames[i]) { 1394 if (n == newNames[i]) 1395 continue eachArg; 1396 if (!replaced) { 1397 replaced = true; 1398 arguments = arguments.clone(); 1399 } 1400 arguments[j] = newNames[i]; 1401 continue eachArg; 1402 } 1403 } 1404 } 1405 } 1406 if (!replaced) return this; 1407 return new Name(function, arguments); 1408 } 1409 void internArguments() { 1410 @SuppressWarnings("LocalVariableHidesMemberVariable") 1411 Object[] arguments = this.arguments; 1412 for (int j = 0; j < arguments.length; j++) { 1413 if (arguments[j] instanceof Name n) { 1414 if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT) 1415 arguments[j] = internArgument(n); 1416 } 1417 } 1418 } 1419 boolean isParam() { 1420 return function == null; 1421 } 1422 1423 boolean refersTo(Class<?> declaringClass, String methodName) { 1424 return function != null && 1425 function.member() != null && function.member().refersTo(declaringClass, methodName); 1426 } 1427 1428 /** 1429 * Check if MemberName is a call to MethodHandle.invokeBasic. 1430 */ 1431 boolean isInvokeBasic() { 1432 if (function == null) 1433 return false; 1434 if (arguments.length < 1) 1435 return false; // must have MH argument 1436 MemberName member = function.member(); 1437 return member != null && member.refersTo(MethodHandle.class, "invokeBasic") && 1438 !member.isPublic() && !member.isStatic(); 1439 } 1440 1441 /** 1442 * Check if MemberName is a call to MethodHandle.linkToStatic, etc. 1443 */ 1444 boolean isLinkerMethodInvoke() { 1445 if (function == null) 1446 return false; 1447 if (arguments.length < 1) 1448 return false; // must have MH argument 1449 MemberName member = function.member(); 1450 return member != null && 1451 member.getDeclaringClass() == MethodHandle.class && 1452 !member.isPublic() && member.isStatic() && 1453 member.getName().startsWith("linkTo"); 1454 } 1455 1456 public String toString() { 1457 return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar(); 1458 } 1459 public String debugString() { 1460 String s = paramString(); 1461 return (function == null) ? s : s + "=" + exprString(); 1462 } 1463 public String paramString() { 1464 String s = toString(); 1465 Object c = constraint; 1466 if (c == null) 1467 return s; 1468 if (c instanceof Class<?> cl) c = cl.getSimpleName(); 1469 return s + "/" + c; 1470 } 1471 public String exprString() { 1472 if (function == null) return toString(); 1473 StringBuilder buf = new StringBuilder(function.toString()); 1474 buf.append("("); 1475 String cma = ""; 1476 for (Object a : arguments) { 1477 buf.append(cma); cma = ","; 1478 if (a instanceof Name || a instanceof Integer) 1479 buf.append(a); 1480 else 1481 buf.append("(").append(a).append(")"); 1482 } 1483 buf.append(")"); 1484 return buf.toString(); 1485 } 1486 1487 private boolean typesMatch(NamedFunction function, Object ... arguments) { 1488 if (arguments == null) { 1489 assert(function == null); 1490 return true; 1491 } 1492 assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString(); 1493 for (int i = 0; i < arguments.length; i++) { 1494 assert (typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString(); 1495 } 1496 return true; 1497 } 1498 1499 private static boolean typesMatch(BasicType parameterType, Object object) { 1500 if (object instanceof Name name) { 1501 return name.type == parameterType; 1502 } 1503 switch (parameterType) { 1504 case I_TYPE: return object instanceof Integer; 1505 case J_TYPE: return object instanceof Long; 1506 case F_TYPE: return object instanceof Float; 1507 case D_TYPE: return object instanceof Double; 1508 } 1509 assert(parameterType == L_TYPE); 1510 return true; 1511 } 1512 1513 /** Return the index of the last occurrence of n in the argument array. 1514 * Return -1 if the name is not used. 1515 */ 1516 int lastUseIndex(Name n) { 1517 Object[] arguments = this.arguments; 1518 if (arguments == null) return -1; 1519 for (int i = arguments.length; --i >= 0; ) { 1520 if (arguments[i] == n) return i; 1521 } 1522 return -1; 1523 } 1524 1525 public boolean equals(Name that) { 1526 if (this == that) return true; 1527 if (isParam()) 1528 // each parameter is a unique atom 1529 return false; // this != that 1530 return 1531 //this.index == that.index && 1532 this.type == that.type && 1533 this.function.equals(that.function) && 1534 Arrays.equals(this.arguments, that.arguments); 1535 } 1536 @Override 1537 public boolean equals(Object x) { 1538 return x instanceof Name n && equals(n); 1539 } 1540 @Override 1541 public int hashCode() { 1542 if (isParam()) 1543 return index | (type.ordinal() << 8); 1544 return function.hashCode() ^ Arrays.hashCode(arguments); 1545 } 1546 } 1547 1548 /** Return the index of the last name which contains n as an argument. 1549 * Return -1 if the name is not used. Return names.length if it is the return value. 1550 */ 1551 int lastUseIndex(Name n) { 1552 int ni = n.index, nmax = names.length; 1553 assert(names[ni] == n); 1554 if (result == ni) return nmax; // live all the way beyond the end 1555 for (int i = nmax; --i > ni; ) { 1556 if (names[i].lastUseIndex(n) >= 0) 1557 return i; 1558 } 1559 return -1; 1560 } 1561 1562 /** Return the number of times n is used as an argument or return value. */ 1563 int useCount(Name n) { 1564 int count = (result == n.index) ? 1 : 0; 1565 int i = Math.max(n.index + 1, arity); 1566 Name[] names = this.names; 1567 while (i < names.length) { 1568 Object[] arguments = names[i++].arguments; 1569 if (arguments != null) { 1570 for (Object argument : arguments) { 1571 if (argument == n) { 1572 count++; 1573 } 1574 } 1575 } 1576 } 1577 return count; 1578 } 1579 1580 static Name argument(int which, BasicType type) { 1581 if (which >= INTERNED_ARGUMENT_LIMIT) 1582 return new Name(which, type); 1583 return INTERNED_ARGUMENTS[type.ordinal()][which]; 1584 } 1585 static Name internArgument(Name n) { 1586 assert(n.isParam()) : "not param: " + n; 1587 assert(n.index < INTERNED_ARGUMENT_LIMIT); 1588 if (n.constraint != null) return n; 1589 return argument(n.index, n.type); 1590 } 1591 static Name[] arguments(int extra, MethodType types) { 1592 int length = types.parameterCount(); 1593 Name[] names = new Name[length + extra]; 1594 for (int i = 0; i < length; i++) 1595 names[i] = argument(i, basicType(types.parameterType(i))); 1596 return names; 1597 } 1598 1599 static Name[] invokeArguments(int extra, MethodType types) { 1600 int length = types.parameterCount(); 1601 Name[] names = new Name[length + extra + 1]; 1602 names[0] = argument(0, L_TYPE); 1603 for (int i = 0; i < length; i++) 1604 names[i + 1] = argument(i + 1, basicType(types.parameterType(i))); 1605 return names; 1606 } 1607 1608 static final int INTERNED_ARGUMENT_LIMIT = 10; 1609 private static final Name[][] INTERNED_ARGUMENTS 1610 = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT]; 1611 static { 1612 for (BasicType type : BasicType.ARG_TYPES) { 1613 int ord = type.ordinal(); 1614 for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) { 1615 INTERNED_ARGUMENTS[ord][i] = new Name(i, type); 1616 } 1617 } 1618 } 1619 1620 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 1621 1622 static LambdaForm identityForm(BasicType type) { 1623 int ord = type.ordinal(); 1624 LambdaForm form = LF_identity[ord]; 1625 if (form != null) { 1626 return form; 1627 } 1628 createIdentityForm(type); 1629 return LF_identity[ord]; 1630 } 1631 1632 static NamedFunction identity(BasicType type) { 1633 int ord = type.ordinal(); 1634 NamedFunction function = NF_identity[ord]; 1635 if (function != null) { 1636 return function; 1637 } 1638 createIdentityForm(type); 1639 return NF_identity[ord]; 1640 } 1641 1642 static LambdaForm constantForm(BasicType type) { 1643 assert type != null && type != V_TYPE : type; 1644 var cached = LF_constant[type.ordinal()]; 1645 if (cached != null) 1646 return cached; 1647 return createConstantForm(type); 1648 } 1649 1650 private static LambdaForm createConstantForm(BasicType type) { 1651 UNSAFE.ensureClassInitialized(BoundMethodHandle.class); // defend access to SimpleMethodHandle 1652 var species = SimpleMethodHandle.BMH_SPECIES.extendWith(type); 1653 var carrier = argument(0, L_TYPE).withConstraint(species); // BMH bound with data 1654 Name[] constNames = new Name[] { carrier, new Name(species.getterFunction(0), carrier) }; 1655 return LF_constant[type.ordinal()] = create(1, constNames, Kind.CONSTANT); 1656 } 1657 1658 private static final @Stable LambdaForm[] LF_identity = new LambdaForm[TYPE_LIMIT]; 1659 private static final @Stable NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT]; 1660 private static final @Stable LambdaForm[] LF_constant = new LambdaForm[ARG_TYPE_LIMIT]; // no void 1661 1662 private static final Object createIdentityFormLock = new Object(); 1663 private static void createIdentityForm(BasicType type) { 1664 // Avoid racy initialization during bootstrap 1665 UNSAFE.ensureClassInitialized(BoundMethodHandle.class); 1666 synchronized (createIdentityFormLock) { 1667 final int ord = type.ordinal(); 1668 LambdaForm idForm = LF_identity[ord]; 1669 if (idForm != null) { 1670 return; 1671 } 1672 char btChar = type.basicTypeChar(); 1673 boolean isVoid = (type == V_TYPE); 1674 Class<?> btClass = type.btClass; 1675 MethodType idType = (isVoid) ? MethodType.methodType(btClass) : MethodType.methodType(btClass, btClass); 1676 1677 // Look up symbolic names. It might not be necessary to have these, 1678 // but if we need to emit direct references to bytecodes, it helps. 1679 MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic); 1680 try { 1681 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, LM_TRUSTED, NoSuchMethodException.class); 1682 } catch (IllegalAccessException|NoSuchMethodException ex) { 1683 throw newInternalError(ex); 1684 } 1685 1686 NamedFunction idFun; 1687 1688 // Create the LFs and NamedFunctions. Precompiling LFs to byte code is needed to break circular 1689 // bootstrap dependency on this method in case we're interpreting LFs 1690 if (isVoid) { 1691 Name[] idNames = new Name[] { argument(0, L_TYPE) }; 1692 idForm = LambdaForm.create(1, idNames, VOID_RESULT, Kind.IDENTITY); 1693 idForm.compileToBytecode(); 1694 idFun = new NamedFunction(idMem, SimpleMethodHandle.make(idMem.getInvocationType(), idForm)); 1695 } else { 1696 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) }; 1697 idForm = LambdaForm.create(2, idNames, 1, Kind.IDENTITY); 1698 idForm.compileToBytecode(); 1699 idFun = new NamedFunction(idMem, MethodHandleImpl.makeIntrinsic(idMem.getInvocationType(), idForm, 1700 MethodHandleImpl.Intrinsic.IDENTITY)); 1701 } 1702 1703 LF_identity[ord] = idForm; 1704 NF_identity[ord] = idFun; 1705 1706 assert(idFun.isIdentity()); 1707 } 1708 } 1709 1710 // Avoid appealing to ValueConversions at bootstrap time: 1711 private static int identity_I(int x) { return x; } 1712 private static long identity_J(long x) { return x; } 1713 private static float identity_F(float x) { return x; } 1714 private static double identity_D(double x) { return x; } 1715 private static Object identity_L(Object x) { return x; } 1716 private static void identity_V() { return; } 1717 /** 1718 * Internal marker for byte-compiled LambdaForms. 1719 */ 1720 /*non-public*/ 1721 @Target(ElementType.METHOD) 1722 @Retention(RetentionPolicy.RUNTIME) 1723 @interface Compiled { 1724 } 1725 1726 private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS; 1727 private static final HashMap<LambdaForm,String> DEBUG_NAMES; 1728 static { 1729 if (debugEnabled()) { 1730 DEBUG_NAME_COUNTERS = new HashMap<>(); 1731 DEBUG_NAMES = new HashMap<>(); 1732 } else { 1733 DEBUG_NAME_COUNTERS = null; 1734 DEBUG_NAMES = null; 1735 } 1736 } 1737 1738 static { 1739 // The Holder class will contain pre-generated forms resolved 1740 // using MemberName.getFactory(). However, that doesn't initialize the 1741 // class, which subtly breaks inlining etc. By forcing 1742 // initialization of the Holder class we avoid these issues. 1743 UNSAFE.ensureClassInitialized(Holder.class); 1744 } 1745 1746 /* Placeholder class for identity and constant forms generated ahead of time */ 1747 final class Holder {} 1748 1749 // The following hack is necessary in order to suppress TRACE_INTERPRETER 1750 // during execution of the static initializes of this class. 1751 // Turning on TRACE_INTERPRETER too early will cause 1752 // stack overflows and other misbehavior during attempts to trace events 1753 // that occur during LambdaForm.<clinit>. 1754 // Therefore, do not move this line higher in this file, and do not remove. 1755 private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER; 1756 }