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