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