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