1 /* 2 * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import java.lang.annotation.*; 29 import java.lang.reflect.Method; 30 import java.util.Map; 31 import java.util.List; 32 import java.util.Arrays; 33 import java.util.ArrayList; 34 import java.util.HashMap; 35 import java.util.concurrent.ConcurrentHashMap; 36 import sun.invoke.util.Wrapper; 37 import sun.invoke.Stable; 38 import static java.lang.invoke.MethodHandleStatics.*; 39 import static java.lang.invoke.MethodHandleNatives.Constants.*; 40 import java.lang.reflect.Field; 41 import java.util.Objects; 42 43 /** 44 * The symbolic, non-executable form of a method handle's invocation semantics. 45 * It consists of a series of names. 46 * The first N (N=arity) names are parameters, 47 * while any remaining names are temporary values. 48 * Each temporary specifies the application of a function to some arguments. 49 * The functions are method handles, while the arguments are mixes of 50 * constant values and local names. 51 * The result of the lambda is defined as one of the names, often the last one. 52 * <p> 53 * Here is an approximate grammar: 54 * <pre> 55 * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}" 56 * ArgName = "a" N ":" T 57 * TempName = "t" N ":" T "=" Function "(" Argument* ");" 58 * Function = ConstantValue 59 * Argument = NameRef | ConstantValue 60 * Result = NameRef | "void" 61 * NameRef = "a" N | "t" N 62 * N = (any whole number) 63 * T = "L" | "I" | "J" | "F" | "D" | "V" 64 * </pre> 65 * Names are numbered consecutively from left to right starting at zero. 66 * (The letters are merely a taste of syntax sugar.) 67 * Thus, the first temporary (if any) is always numbered N (where N=arity). 68 * Every occurrence of a name reference in an argument list must refer to 69 * a name previously defined within the same lambda. 70 * A lambda has a void result if and only if its result index is -1. 71 * If a temporary has the type "V", it cannot be the subject of a NameRef, 72 * even though possesses a number. 73 * Note that all reference types are erased to "L", which stands for {@code Object). 74 * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}. 75 * The other types stand for the usual primitive types. 76 * <p> 77 * Function invocation closely follows the static rules of the Java verifier. 78 * Arguments and return values must exactly match when their "Name" types are 79 * considered. 80 * Conversions are allowed only if they do not change the erased type. 81 * <ul> 82 * <li>L = Object: casts are used freely to convert into and out of reference types 83 * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments}) 84 * <li>J = long: no implicit conversions 85 * <li>F = float: no implicit conversions 86 * <li>D = double: no implicit conversions 87 * <li>V = void: a function result may be void if and only if its Name is of type "V" 88 * </ul> 89 * Although implicit conversions are not allowed, explicit ones can easily be 90 * encoded by using temporary expressions which call type-transformed identity functions. 91 * <p> 92 * Examples: 93 * <pre> 94 * (a0:J)=>{ a0 } 95 * == identity(long) 96 * (a0:I)=>{ t1:V = System.out#println(a0); void } 97 * == System.out#println(int) 98 * (a0:L)=>{ t1:V = System.out#println(a0); a0 } 99 * == identity, with printing side-effect 100 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 101 * t3:L = BoundMethodHandle#target(a0); 102 * t4:L = MethodHandle#invoke(t3, t2, a1); t4 } 103 * == general invoker for unary insertArgument combination 104 * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0); 105 * t3:L = MethodHandle#invoke(t2, a1); 106 * t4:L = FilterMethodHandle#target(a0); 107 * t5:L = MethodHandle#invoke(t4, t3); t5 } 108 * == general invoker for unary filterArgument combination 109 * (a0:L, a1:L)=>{ ...(same as previous example)... 110 * t5:L = MethodHandle#invoke(t4, t3, a1); t5 } 111 * == general invoker for unary/unary foldArgument combination 112 * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 } 113 * == invoker for identity method handle which performs i2l 114 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 115 * t3:L = Class#cast(t2,a1); t3 } 116 * == invoker for identity method handle which performs cast 117 * </pre> 118 * <p> 119 * @author John Rose, JSR 292 EG 120 */ 121 class LambdaForm { 122 final int arity; 123 final int result; 124 @Stable final Name[] names; 125 final String debugName; 126 MemberName vmentry; // low-level behavior, or null if not yet prepared 127 private boolean isCompiled; 128 129 // Caches for common structural transforms: 130 LambdaForm[] bindCache; 131 132 public static final int VOID_RESULT = -1, LAST_RESULT = -2; 133 134 LambdaForm(String debugName, 135 int arity, Name[] names, int result) { 136 assert(namesOK(arity, names)); 137 this.arity = arity; 138 this.result = fixResult(result, names); 139 this.names = names.clone(); 140 this.debugName = debugName; 141 normalize(); 142 } 143 144 LambdaForm(String debugName, 145 int arity, Name[] names) { 146 this(debugName, 147 arity, names, LAST_RESULT); 148 } 149 150 LambdaForm(String debugName, 151 Name[] formals, Name[] temps, Name result) { 152 this(debugName, 153 formals.length, buildNames(formals, temps, result), LAST_RESULT); 154 } 155 156 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) { 157 int arity = formals.length; 158 int length = arity + temps.length + (result == null ? 0 : 1); 159 Name[] names = Arrays.copyOf(formals, length); 160 System.arraycopy(temps, 0, names, arity, temps.length); 161 if (result != null) 162 names[length - 1] = result; 163 return names; 164 } 165 166 private LambdaForm(String sig) { 167 // Make a blank lambda form, which returns a constant zero or null. 168 // It is used as a template for managing the invocation of similar forms that are non-empty. 169 // Called only from getPreparedForm. 170 assert(isValidSignature(sig)); 171 this.arity = signatureArity(sig); 172 this.result = (signatureReturn(sig) == 'V' ? -1 : arity); 173 this.names = buildEmptyNames(arity, sig); 174 this.debugName = "LF.zero"; 175 assert(nameRefsAreLegal()); 176 assert(isEmpty()); 177 assert(sig.equals(basicTypeSignature())); 178 } 179 180 private static Name[] buildEmptyNames(int arity, String basicTypeSignature) { 181 assert(isValidSignature(basicTypeSignature)); 182 int resultPos = arity + 1; // skip '_' 183 if (arity < 0 || basicTypeSignature.length() != resultPos+1) 184 throw new IllegalArgumentException("bad arity for "+basicTypeSignature); 185 int numRes = (basicTypeSignature.charAt(resultPos) == 'V' ? 0 : 1); 186 Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity)); 187 for (int i = 0; i < numRes; i++) { 188 names[arity + i] = constantZero(arity + i, basicTypeSignature.charAt(resultPos + i)); 189 } 190 return names; 191 } 192 193 private static int fixResult(int result, Name[] names) { 194 if (result >= 0) { 195 if (names[result].type == 'V') 196 return -1; 197 } else if (result == LAST_RESULT) { 198 return names.length - 1; 199 } 200 return result; 201 } 202 203 private static boolean namesOK(int arity, Name[] names) { 204 for (int i = 0; i < names.length; i++) { 205 Name n = names[i]; 206 assert(n != null) : "n is null"; 207 if (i < arity) 208 assert( n.isParam()) : n + " is not param at " + i; 209 else 210 assert(!n.isParam()) : n + " is param at " + i; 211 } 212 return true; 213 } 214 215 /** Renumber and/or replace params so that they are interned and canonically numbered. */ 216 private void normalize() { 217 Name[] oldNames = null; 218 int changesStart = 0; 219 for (int i = 0; i < names.length; i++) { 220 Name n = names[i]; 221 if (!n.initIndex(i)) { 222 if (oldNames == null) { 223 oldNames = names.clone(); 224 changesStart = i; 225 } 226 names[i] = n.cloneWithIndex(i); 227 } 228 } 229 if (oldNames != null) { 230 int startFixing = arity; 231 if (startFixing <= changesStart) 232 startFixing = changesStart+1; 233 for (int i = startFixing; i < names.length; i++) { 234 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i); 235 names[i] = fixed.newIndex(i); 236 } 237 } 238 assert(nameRefsAreLegal()); 239 int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT); 240 boolean needIntern = false; 241 for (int i = 0; i < maxInterned; i++) { 242 Name n = names[i], n2 = internArgument(n); 243 if (n != n2) { 244 names[i] = n2; 245 needIntern = true; 246 } 247 } 248 if (needIntern) { 249 for (int i = arity; i < names.length; i++) { 250 names[i].internArguments(); 251 } 252 assert(nameRefsAreLegal()); 253 } 254 } 255 256 /** 257 * Check that all embedded Name references are localizable to this lambda, 258 * and are properly ordered after their corresponding definitions. 259 * <p> 260 * Note that a Name can be local to multiple lambdas, as long as 261 * it possesses the same index in each use site. 262 * This allows Name references to be freely reused to construct 263 * fresh lambdas, without confusion. 264 */ 265 private boolean nameRefsAreLegal() { 266 assert(arity >= 0 && arity <= names.length); 267 assert(result >= -1 && result < names.length); 268 // Do all names possess an index consistent with their local definition order? 269 for (int i = 0; i < arity; i++) { 270 Name n = names[i]; 271 assert(n.index() == i) : Arrays.asList(n.index(), i); 272 assert(n.isParam()); 273 } 274 // Also, do all local name references 275 for (int i = arity; i < names.length; i++) { 276 Name n = names[i]; 277 assert(n.index() == i); 278 for (Object arg : n.arguments) { 279 if (arg instanceof Name) { 280 Name n2 = (Name) arg; 281 int i2 = n2.index; 282 assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length; 283 assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this); 284 assert(i2 < i); // ref must come after def! 285 } 286 } 287 } 288 return true; 289 } 290 291 /** Invoke this form on the given arguments. */ 292 // final Object invoke(Object... args) throws Throwable { 293 // // NYI: fit this into the fast path? 294 // return interpretWithArguments(args); 295 // } 296 297 /** Report the return type. */ 298 char returnType() { 299 if (result < 0) return 'V'; 300 Name n = names[result]; 301 return n.type; 302 } 303 304 /** Report the N-th argument type. */ 305 char parameterType(int n) { 306 assert(n < arity); 307 return names[n].type; 308 } 309 310 /** Report the arity. */ 311 int arity() { 312 return arity; 313 } 314 315 /** Return the method type corresponding to my basic type signature. */ 316 MethodType methodType() { 317 return signatureType(basicTypeSignature()); 318 } 319 /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */ 320 final String basicTypeSignature() { 321 StringBuilder buf = new StringBuilder(arity() + 3); 322 for (int i = 0, a = arity(); i < a; i++) 323 buf.append(parameterType(i)); 324 return buf.append('_').append(returnType()).toString(); 325 } 326 static int signatureArity(String sig) { 327 assert(isValidSignature(sig)); 328 return sig.indexOf('_'); 329 } 330 static char signatureReturn(String sig) { 331 return sig.charAt(signatureArity(sig)+1); 332 } 333 static boolean isValidSignature(String sig) { 334 int arity = sig.indexOf('_'); 335 if (arity < 0) return false; // must be of the form *_* 336 int siglen = sig.length(); 337 if (siglen != arity + 2) return false; // *_X 338 for (int i = 0; i < siglen; i++) { 339 if (i == arity) continue; // skip '_' 340 char c = sig.charAt(i); 341 if (c == 'V') 342 return (i == siglen - 1 && arity == siglen - 2); 343 if (ALL_TYPES.indexOf(c) < 0) return false; // must be [LIJFD] 344 } 345 return true; // [LIJFD]*_[LIJFDV] 346 } 347 static Class<?> typeClass(char t) { 348 switch (t) { 349 case 'I': return int.class; 350 case 'J': return long.class; 351 case 'F': return float.class; 352 case 'D': return double.class; 353 case 'L': return Object.class; 354 case 'V': return void.class; 355 default: assert false; 356 } 357 return null; 358 } 359 static MethodType signatureType(String sig) { 360 Class<?>[] ptypes = new Class<?>[signatureArity(sig)]; 361 for (int i = 0; i < ptypes.length; i++) 362 ptypes[i] = typeClass(sig.charAt(i)); 363 Class<?> rtype = typeClass(signatureReturn(sig)); 364 return MethodType.methodType(rtype, ptypes); 365 } 366 367 /* 368 * Code generation issues: 369 * 370 * Compiled LFs should be reusable in general. 371 * The biggest issue is how to decide when to pull a name into 372 * the bytecode, versus loading a reified form from the MH data. 373 * 374 * For example, an asType wrapper may require execution of a cast 375 * after a call to a MH. The target type of the cast can be placed 376 * as a constant in the LF itself. This will force the cast type 377 * to be compiled into the bytecodes and native code for the MH. 378 * Or, the target type of the cast can be erased in the LF, and 379 * loaded from the MH data. (Later on, if the MH as a whole is 380 * inlined, the data will flow into the inlined instance of the LF, 381 * as a constant, and the end result will be an optimal cast.) 382 * 383 * This erasure of cast types can be done with any use of 384 * reference types. It can also be done with whole method 385 * handles. Erasing a method handle might leave behind 386 * LF code that executes correctly for any MH of a given 387 * type, and load the required MH from the enclosing MH's data. 388 * Or, the erasure might even erase the expected MT. 389 * 390 * Also, for direct MHs, the MemberName of the target 391 * could be erased, and loaded from the containing direct MH. 392 * As a simple case, a LF for all int-valued non-static 393 * field getters would perform a cast on its input argument 394 * (to non-constant base type derived from the MemberName) 395 * and load an integer value from the input object 396 * (at a non-constant offset also derived from the MemberName). 397 * Such MN-erased LFs would be inlinable back to optimized 398 * code, whenever a constant enclosing DMH is available 399 * to supply a constant MN from its data. 400 * 401 * The main problem here is to keep LFs reasonably generic, 402 * while ensuring that hot spots will inline good instances. 403 * "Reasonably generic" means that we don't end up with 404 * repeated versions of bytecode or machine code that do 405 * not differ in their optimized form. Repeated versions 406 * of machine would have the undesirable overheads of 407 * (a) redundant compilation work and (b) extra I$ pressure. 408 * To control repeated versions, we need to be ready to 409 * erase details from LFs and move them into MH data, 410 * whevener those details are not relevant to significant 411 * optimization. "Significant" means optimization of 412 * code that is actually hot. 413 * 414 * Achieving this may require dynamic splitting of MHs, by replacing 415 * a generic LF with a more specialized one, on the same MH, 416 * if (a) the MH is frequently executed and (b) the MH cannot 417 * be inlined into a containing caller, such as an invokedynamic. 418 * 419 * Compiled LFs that are no longer used should be GC-able. 420 * If they contain non-BCP references, they should be properly 421 * interlinked with the class loader(s) that their embedded types 422 * depend on. This probably means that reusable compiled LFs 423 * will be tabulated (indexed) on relevant class loaders, 424 * or else that the tables that cache them will have weak links. 425 */ 426 427 /** 428 * Make this LF directly executable, as part of a MethodHandle. 429 * Invariant: Every MH which is invoked must prepare its LF 430 * before invocation. 431 * (In principle, the JVM could do this very lazily, 432 * as a sort of pre-invocation linkage step.) 433 */ 434 public void prepare() { 435 if (COMPILE_THRESHOLD == 0) { 436 compileToBytecode(); 437 } 438 if (this.vmentry != null) { 439 // already prepared (e.g., a primitive DMH invoker form) 440 return; 441 } 442 LambdaForm prep = getPreparedForm(basicTypeSignature()); 443 this.vmentry = prep.vmentry; 444 // TO DO: Maybe add invokeGeneric, invokeWithArguments 445 } 446 447 /** Generate optimizable bytecode for this form. */ 448 MemberName compileToBytecode() { 449 MethodType invokerType = methodType(); 450 assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType)); 451 if (vmentry != null && isCompiled) { 452 return vmentry; // already compiled somehow 453 } 454 try { 455 vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType); 456 if (TRACE_INTERPRETER) 457 traceInterpreter("compileToBytecode", this); 458 isCompiled = true; 459 return vmentry; 460 } catch (Error | Exception ex) { 461 throw newInternalError(this.toString(), ex); 462 } 463 } 464 465 private static final ConcurrentHashMap<String,LambdaForm> PREPARED_FORMS; 466 static { 467 int capacity = 512; // expect many distinct signatures over time 468 float loadFactor = 0.75f; // normal default 469 int writers = 1; 470 PREPARED_FORMS = new ConcurrentHashMap<>(capacity, loadFactor, writers); 471 } 472 473 private static Map<String,LambdaForm> computeInitialPreparedForms() { 474 // Find all predefined invokers and associate them with canonical empty lambda forms. 475 HashMap<String,LambdaForm> forms = new HashMap<>(); 476 for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) { 477 if (!m.isStatic() || !m.isPackage()) continue; 478 MethodType mt = m.getMethodType(); 479 if (mt.parameterCount() > 0 && 480 mt.parameterType(0) == MethodHandle.class && 481 m.getName().startsWith("interpret_")) { 482 String sig = basicTypeSignature(mt); 483 assert(m.getName().equals("interpret" + sig.substring(sig.indexOf('_')))); 484 LambdaForm form = new LambdaForm(sig); 485 form.vmentry = m; 486 mt.form().setCachedLambdaForm(MethodTypeForm.LF_COUNTER, form); 487 // FIXME: get rid of PREPARED_FORMS; use MethodTypeForm cache only 488 forms.put(sig, form); 489 } 490 } 491 //System.out.println("computeInitialPreparedForms => "+forms); 492 return forms; 493 } 494 495 // Set this false to disable use of the interpret_L methods defined in this file. 496 private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true; 497 498 // The following are predefined exact invokers. The system must build 499 // a separate invoker for each distinct signature. 500 static Object interpret_L(MethodHandle mh) throws Throwable { 501 Object[] av = {mh}; 502 String sig = null; 503 assert(argumentTypesMatch(sig = "L_L", av)); 504 Object res = mh.form.interpretWithArguments(av); 505 assert(returnTypesMatch(sig, av, res)); 506 return res; 507 } 508 static Object interpret_L(MethodHandle mh, Object x1) throws Throwable { 509 Object[] av = {mh, x1}; 510 String sig = null; 511 assert(argumentTypesMatch(sig = "LL_L", av)); 512 Object res = mh.form.interpretWithArguments(av); 513 assert(returnTypesMatch(sig, av, res)); 514 return res; 515 } 516 static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable { 517 Object[] av = {mh, x1, x2}; 518 String sig = null; 519 assert(argumentTypesMatch(sig = "LLL_L", av)); 520 Object res = mh.form.interpretWithArguments(av); 521 assert(returnTypesMatch(sig, av, res)); 522 return res; 523 } 524 private static LambdaForm getPreparedForm(String sig) { 525 MethodType mtype = signatureType(sig); 526 //LambdaForm prep = PREPARED_FORMS.get(sig); 527 LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET); 528 if (prep != null) return prep; 529 assert(isValidSignature(sig)); 530 prep = new LambdaForm(sig); 531 prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig); 532 //LambdaForm prep2 = PREPARED_FORMS.putIfAbsent(sig.intern(), prep); 533 return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep); 534 } 535 536 // The next few routines are called only from assert expressions 537 // They verify that the built-in invokers process the correct raw data types. 538 private static boolean argumentTypesMatch(String sig, Object[] av) { 539 int arity = signatureArity(sig); 540 assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity; 541 assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0]; 542 MethodHandle mh = (MethodHandle) av[0]; 543 MethodType mt = mh.type(); 544 assert(mt.parameterCount() == arity-1); 545 for (int i = 0; i < av.length; i++) { 546 Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1)); 547 assert(valueMatches(sig.charAt(i), pt, av[i])); 548 } 549 return true; 550 } 551 private static boolean valueMatches(char tc, Class<?> type, Object x) { 552 // The following line is needed because (...)void method handles can use non-void invokers 553 if (type == void.class) tc = 'V'; // can drop any kind of value 554 assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type); 555 switch (tc) { 556 case 'I': assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break; 557 case 'J': assert x instanceof Long : "instanceof Long: " + x; break; 558 case 'F': assert x instanceof Float : "instanceof Float: " + x; break; 559 case 'D': assert x instanceof Double : "instanceof Double: " + x; break; 560 case 'L': assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break; 561 case 'V': break; // allow anything here; will be dropped 562 default: assert(false); 563 } 564 return true; 565 } 566 private static boolean returnTypesMatch(String sig, Object[] av, Object res) { 567 MethodHandle mh = (MethodHandle) av[0]; 568 return valueMatches(signatureReturn(sig), mh.type().returnType(), res); 569 } 570 private static boolean checkInt(Class<?> type, Object x) { 571 assert(x instanceof Integer); 572 if (type == int.class) return true; 573 Wrapper w = Wrapper.forBasicType(type); 574 assert(w.isSubwordOrInt()); 575 Object x1 = Wrapper.INT.wrap(w.wrap(x)); 576 return x.equals(x1); 577 } 578 private static boolean checkRef(Class<?> type, Object x) { 579 assert(!type.isPrimitive()); 580 if (x == null) return true; 581 if (type.isInterface()) return true; 582 return type.isInstance(x); 583 } 584 585 /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */ 586 private static final int COMPILE_THRESHOLD; 587 static { 588 if (MethodHandleStatics.COMPILE_THRESHOLD != null) 589 COMPILE_THRESHOLD = MethodHandleStatics.COMPILE_THRESHOLD; 590 else 591 COMPILE_THRESHOLD = 30; // default value 592 } 593 private int invocationCounter = 0; 594 595 @Hidden 596 @DontInline 597 /** Interpretively invoke this form on the given arguments. */ 598 Object interpretWithArguments(Object... argumentValues) throws Throwable { 599 if (TRACE_INTERPRETER) 600 return interpretWithArgumentsTracing(argumentValues); 601 checkInvocationCounter(); 602 assert(arityCheck(argumentValues)); 603 Object[] values = Arrays.copyOf(argumentValues, names.length); 604 for (int i = argumentValues.length; i < values.length; i++) { 605 values[i] = interpretName(names[i], values); 606 } 607 return (result < 0) ? null : values[result]; 608 } 609 610 @Hidden 611 @DontInline 612 /** Evaluate a single Name within this form, applying its function to its arguments. */ 613 Object interpretName(Name name, Object[] values) throws Throwable { 614 if (TRACE_INTERPRETER) 615 traceInterpreter("| interpretName", name.debugString(), (Object[]) null); 616 Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class); 617 for (int i = 0; i < arguments.length; i++) { 618 Object a = arguments[i]; 619 if (a instanceof Name) { 620 int i2 = ((Name)a).index(); 621 assert(names[i2] == a); 622 a = values[i2]; 623 arguments[i] = a; 624 } 625 } 626 return name.function.invokeWithArguments(arguments); 627 } 628 629 private void checkInvocationCounter() { 630 if (COMPILE_THRESHOLD != 0 && 631 invocationCounter < COMPILE_THRESHOLD) { 632 invocationCounter++; // benign race 633 if (invocationCounter >= COMPILE_THRESHOLD) { 634 // Replace vmentry with a bytecode version of this LF. 635 compileToBytecode(); 636 } 637 } 638 } 639 Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable { 640 traceInterpreter("[ interpretWithArguments", this, argumentValues); 641 if (invocationCounter < COMPILE_THRESHOLD) { 642 int ctr = invocationCounter++; // benign race 643 traceInterpreter("| invocationCounter", ctr); 644 if (invocationCounter >= COMPILE_THRESHOLD) { 645 compileToBytecode(); 646 } 647 } 648 Object rval; 649 try { 650 assert(arityCheck(argumentValues)); 651 Object[] values = Arrays.copyOf(argumentValues, names.length); 652 for (int i = argumentValues.length; i < values.length; i++) { 653 values[i] = interpretName(names[i], values); 654 } 655 rval = (result < 0) ? null : values[result]; 656 } catch (Throwable ex) { 657 traceInterpreter("] throw =>", ex); 658 throw ex; 659 } 660 traceInterpreter("] return =>", rval); 661 return rval; 662 } 663 664 //** This transform is applied (statically) to every name.function. */ 665 /* 666 private static MethodHandle eraseSubwordTypes(MethodHandle mh) { 667 MethodType mt = mh.type(); 668 if (mt.hasPrimitives()) { 669 mt = mt.changeReturnType(eraseSubwordType(mt.returnType())); 670 for (int i = 0; i < mt.parameterCount(); i++) { 671 mt = mt.changeParameterType(i, eraseSubwordType(mt.parameterType(i))); 672 } 673 mh = MethodHandles.explicitCastArguments(mh, mt); 674 } 675 return mh; 676 } 677 private static Class<?> eraseSubwordType(Class<?> type) { 678 if (!type.isPrimitive()) return type; 679 if (type == int.class) return type; 680 Wrapper w = Wrapper.forPrimitiveType(type); 681 if (w.isSubwordOrInt()) return int.class; 682 return type; 683 } 684 */ 685 686 static void traceInterpreter(String event, Object obj, Object... args) { 687 if (!TRACE_INTERPRETER) return; 688 System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : "")); 689 } 690 static void traceInterpreter(String event, Object obj) { 691 traceInterpreter(event, obj, (Object[])null); 692 } 693 private boolean arityCheck(Object[] argumentValues) { 694 assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length"; 695 // also check that the leading (receiver) argument is somehow bound to this LF: 696 assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0]; 697 assert(((MethodHandle)argumentValues[0]).internalForm() == this); 698 // note: argument #0 could also be an interface wrapper, in the future 699 return true; 700 } 701 702 private boolean isEmpty() { 703 if (result < 0) 704 return (names.length == arity); 705 else if (result == arity && names.length == arity + 1) 706 return names[arity].isConstantZero(); 707 else 708 return false; 709 } 710 711 public String toString() { 712 StringBuilder buf = new StringBuilder(debugName+"=Lambda("); 713 for (int i = 0; i < names.length; i++) { 714 if (i == arity) buf.append(")=>{"); 715 Name n = names[i]; 716 if (i >= arity) buf.append("\n "); 717 buf.append(n); 718 if (i < arity) { 719 if (i+1 < arity) buf.append(","); 720 continue; 721 } 722 buf.append("=").append(n.exprString()); 723 buf.append(";"); 724 } 725 buf.append(result < 0 ? "void" : names[result]).append("}"); 726 if (TRACE_INTERPRETER) { 727 // Extra verbosity: 728 buf.append(":").append(basicTypeSignature()); 729 buf.append("/").append(vmentry); 730 } 731 return buf.toString(); 732 } 733 734 /** 735 * Apply immediate binding for a Name in this form indicated by its position relative to the form. 736 * The first parameter to a LambdaForm, a0:L, always represents the form's method handle, so 0 is not 737 * accepted as valid. 738 */ 739 LambdaForm bindImmediate(int pos, char basicType, Object value) { 740 // must be an argument, and the types must match 741 assert pos > 0 && pos < arity && names[pos].type == basicType && Name.typesMatch(basicType, value); 742 743 int arity2 = arity - 1; 744 Name[] names2 = new Name[names.length - 1]; 745 for (int r = 0, w = 0; r < names.length; ++r, ++w) { // (r)ead from names, (w)rite to names2 746 Name n = names[r]; 747 if (n.isParam()) { 748 if (n.index == pos) { 749 // do not copy over the argument that is to be replaced with a literal, 750 // but adjust the write index 751 --w; 752 } else { 753 names2[w] = new Name(w, n.type); 754 } 755 } else { 756 Object[] arguments2 = new Object[n.arguments.length]; 757 for (int i = 0; i < n.arguments.length; ++i) { 758 Object arg = n.arguments[i]; 759 if (arg instanceof Name) { 760 int ni = ((Name) arg).index; 761 if (ni == pos) { 762 arguments2[i] = value; 763 } else if (ni < pos) { 764 // replacement position not yet passed 765 arguments2[i] = names2[ni]; 766 } else { 767 // replacement position passed 768 arguments2[i] = names2[ni - 1]; 769 } 770 } else { 771 arguments2[i] = arg; 772 } 773 } 774 names2[w] = new Name(n.function, arguments2); 775 names2[w].initIndex(w); 776 } 777 } 778 779 int result2 = result == -1 ? -1 : result - 1; 780 return new LambdaForm(debugName, arity2, names2, result2); 781 } 782 783 LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) { 784 Name name = names[namePos]; 785 BoundMethodHandle.SpeciesData newData = oldData.extendWithType(name.type); 786 return bind(name, newData.getterName(names[0], oldData.fieldCount()), oldData, newData); 787 } 788 LambdaForm bind(Name name, Name binding, 789 BoundMethodHandle.SpeciesData oldData, 790 BoundMethodHandle.SpeciesData newData) { 791 int pos = name.index; 792 assert(name.isParam()); 793 assert(!binding.isParam()); 794 assert(name.type == binding.type); 795 assert(0 <= pos && pos < arity && names[pos] == name); 796 assert(binding.function.memberDeclaringClassOrNull() == newData.clazz); 797 assert(oldData.getters.length == newData.getters.length-1); 798 if (bindCache != null) { 799 LambdaForm form = bindCache[pos]; 800 if (form != null) { 801 assert(form.contains(binding)) : "form << " + form + " >> does not contain binding << " + binding + " >>"; 802 return form; 803 } 804 } else { 805 bindCache = new LambdaForm[arity]; 806 } 807 assert(nameRefsAreLegal()); 808 int arity2 = arity-1; 809 Name[] names2 = names.clone(); 810 names2[pos] = binding; // we might move this in a moment 811 812 // The newly created LF will run with a different BMH. 813 // Switch over any pre-existing BMH field references to the new BMH class. 814 int firstOldRef = -1; 815 for (int i = 0; i < names2.length; i++) { 816 Name n = names[i]; 817 if (n.function != null && 818 n.function.memberDeclaringClassOrNull() == oldData.clazz) { 819 MethodHandle oldGetter = n.function.resolvedHandle; 820 MethodHandle newGetter = null; 821 for (int j = 0; j < oldData.getters.length; j++) { 822 if (oldGetter == oldData.getters[j]) 823 newGetter = newData.getters[j]; 824 } 825 if (newGetter != null) { 826 if (firstOldRef < 0) firstOldRef = i; 827 Name n2 = new Name(newGetter, n.arguments); 828 names2[i] = n2; 829 } 830 } 831 } 832 833 // Walk over the new list of names once, in forward order. 834 // Replace references to 'name' with 'binding'. 835 // Replace data structure references to the old BMH species with the new. 836 // This might cause a ripple effect, but it will settle in one pass. 837 assert(firstOldRef < 0 || firstOldRef > pos); 838 for (int i = pos+1; i < names2.length; i++) { 839 if (i <= arity2) continue; 840 names2[i] = names2[i].replaceNames(names, names2, pos, i); 841 } 842 843 // (a0, a1, name=a2, a3, a4) => (a0, a1, a3, a4, binding) 844 int insPos = pos; 845 for (; insPos+1 < names2.length; insPos++) { 846 Name n = names2[insPos+1]; 847 if (n.isSiblingBindingBefore(binding)) { 848 names2[insPos] = n; 849 } else { 850 break; 851 } 852 } 853 names2[insPos] = binding; 854 855 // Since we moved some stuff, maybe update the result reference: 856 int result2 = result; 857 if (result2 == pos) 858 result2 = insPos; 859 else if (result2 > pos && result2 <= insPos) 860 result2 -= 1; 861 862 return bindCache[pos] = new LambdaForm(debugName, arity2, names2, result2); 863 } 864 865 boolean contains(Name name) { 866 int pos = name.index(); 867 if (pos >= 0) { 868 return pos < names.length && name.equals(names[pos]); 869 } 870 for (int i = arity; i < names.length; i++) { 871 if (name.equals(names[i])) 872 return true; 873 } 874 return false; 875 } 876 877 LambdaForm addArguments(int pos, char... types) { 878 assert(pos <= arity); 879 int length = names.length; 880 int inTypes = types.length; 881 Name[] names2 = Arrays.copyOf(names, length + inTypes); 882 int arity2 = arity + inTypes; 883 int result2 = result; 884 if (result2 >= arity) 885 result2 += inTypes; 886 // names array has MH in slot 0; skip it. 887 int argpos = pos + 1; 888 // Note: The LF constructor will rename names2[argpos...]. 889 // Make space for new arguments (shift temporaries). 890 System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos); 891 for (int i = 0; i < inTypes; i++) { 892 names2[argpos + i] = new Name(types[i]); 893 } 894 return new LambdaForm(debugName, arity2, names2, result2); 895 } 896 897 LambdaForm addArguments(int pos, List<Class<?>> types) { 898 char[] basicTypes = new char[types.size()]; 899 for (int i = 0; i < basicTypes.length; i++) 900 basicTypes[i] = basicType(types.get(i)); 901 return addArguments(pos, basicTypes); 902 } 903 904 LambdaForm permuteArguments(int skip, int[] reorder, char[] types) { 905 // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg. 906 // The types are the types of the new (incoming) arguments. 907 int length = names.length; 908 int inTypes = types.length; 909 int outArgs = reorder.length; 910 assert(skip+outArgs == arity); 911 assert(permutedTypesMatch(reorder, types, names, skip)); 912 int pos = 0; 913 // skip trivial first part of reordering: 914 while (pos < outArgs && reorder[pos] == pos) pos += 1; 915 Name[] names2 = new Name[length - outArgs + inTypes]; 916 System.arraycopy(names, 0, names2, 0, skip+pos); 917 // copy the body: 918 int bodyLength = length - arity; 919 System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength); 920 int arity2 = names2.length - bodyLength; 921 int result2 = result; 922 if (result2 >= 0) { 923 if (result2 < skip+outArgs) { 924 // return the corresponding inArg 925 result2 = reorder[result2-skip]; 926 } else { 927 result2 = result2 - outArgs + inTypes; 928 } 929 } 930 // rework names in the body: 931 for (int j = pos; j < outArgs; j++) { 932 Name n = names[skip+j]; 933 int i = reorder[j]; 934 // replace names[skip+j] by names2[skip+i] 935 Name n2 = names2[skip+i]; 936 if (n2 == null) 937 names2[skip+i] = n2 = new Name(types[i]); 938 else 939 assert(n2.type == types[i]); 940 for (int k = arity2; k < names2.length; k++) { 941 names2[k] = names2[k].replaceName(n, n2); 942 } 943 } 944 // some names are unused, but must be filled in 945 for (int i = skip+pos; i < arity2; i++) { 946 if (names2[i] == null) 947 names2[i] = argument(i, types[i - skip]); 948 } 949 for (int j = arity; j < names.length; j++) { 950 int i = j - arity + arity2; 951 // replace names2[i] by names[j] 952 Name n = names[j]; 953 Name n2 = names2[i]; 954 if (n != n2) { 955 for (int k = i+1; k < names2.length; k++) { 956 names2[k] = names2[k].replaceName(n, n2); 957 } 958 } 959 } 960 return new LambdaForm(debugName, arity2, names2, result2); 961 } 962 963 static boolean permutedTypesMatch(int[] reorder, char[] types, Name[] names, int skip) { 964 int inTypes = types.length; 965 int outArgs = reorder.length; 966 for (int i = 0; i < outArgs; i++) { 967 assert(names[skip+i].isParam()); 968 assert(names[skip+i].type == types[reorder[i]]); 969 } 970 return true; 971 } 972 973 static class NamedFunction { 974 final MemberName member; 975 @Stable MethodHandle resolvedHandle; 976 @Stable MethodHandle invoker; 977 978 NamedFunction(MethodHandle resolvedHandle) { 979 this(resolvedHandle.internalMemberName(), resolvedHandle); 980 } 981 NamedFunction(MemberName member, MethodHandle resolvedHandle) { 982 this.member = member; 983 //resolvedHandle = eraseSubwordTypes(resolvedHandle); 984 this.resolvedHandle = resolvedHandle; 985 } 986 987 // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc. 988 // Any LambdaForm containing such a member is not interpretable. 989 // This is OK, since all such LFs are prepared with special primitive vmentry points. 990 // And even without the resolvedHandle, the name can still be compiled and optimized. 991 NamedFunction(Method method) { 992 this(new MemberName(method)); 993 } 994 NamedFunction(Field field) { 995 this(new MemberName(field)); 996 } 997 NamedFunction(MemberName member) { 998 this.member = member; 999 this.resolvedHandle = null; 1000 } 1001 1002 MethodHandle resolvedHandle() { 1003 if (resolvedHandle == null) resolve(); 1004 return resolvedHandle; 1005 } 1006 1007 void resolve() { 1008 resolvedHandle = DirectMethodHandle.make(member); 1009 } 1010 1011 @Override 1012 public boolean equals(Object other) { 1013 if (this == other) return true; 1014 if (other == null) return false; 1015 if (!(other instanceof NamedFunction)) return false; 1016 NamedFunction that = (NamedFunction) other; 1017 return this.member != null && this.member.equals(that.member); 1018 } 1019 1020 @Override 1021 public int hashCode() { 1022 if (member != null) 1023 return member.hashCode(); 1024 return super.hashCode(); 1025 } 1026 1027 // Put the predefined NamedFunction invokers into the table. 1028 static void initializeInvokers() { 1029 for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) { 1030 if (!m.isStatic() || !m.isPackage()) continue; 1031 MethodType type = m.getMethodType(); 1032 if (type.equals(INVOKER_METHOD_TYPE) && 1033 m.getName().startsWith("invoke_")) { 1034 String sig = m.getName().substring("invoke_".length()); 1035 int arity = LambdaForm.signatureArity(sig); 1036 MethodType srcType = MethodType.genericMethodType(arity); 1037 if (LambdaForm.signatureReturn(sig) == 'V') 1038 srcType = srcType.changeReturnType(void.class); 1039 MethodTypeForm typeForm = srcType.form(); 1040 typeForm.namedFunctionInvoker = DirectMethodHandle.make(m); 1041 } 1042 } 1043 } 1044 1045 // The following are predefined NamedFunction invokers. The system must build 1046 // a separate invoker for each distinct signature. 1047 /** void return type invokers. */ 1048 @Hidden 1049 static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable { 1050 assert(a.length == 0); 1051 mh.invokeBasic(); 1052 return null; 1053 } 1054 @Hidden 1055 static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable { 1056 assert(a.length == 1); 1057 mh.invokeBasic(a[0]); 1058 return null; 1059 } 1060 @Hidden 1061 static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable { 1062 assert(a.length == 2); 1063 mh.invokeBasic(a[0], a[1]); 1064 return null; 1065 } 1066 @Hidden 1067 static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable { 1068 assert(a.length == 3); 1069 mh.invokeBasic(a[0], a[1], a[2]); 1070 return null; 1071 } 1072 @Hidden 1073 static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable { 1074 assert(a.length == 4); 1075 mh.invokeBasic(a[0], a[1], a[2], a[3]); 1076 return null; 1077 } 1078 @Hidden 1079 static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable { 1080 assert(a.length == 5); 1081 mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]); 1082 return null; 1083 } 1084 /** Object return type invokers. */ 1085 @Hidden 1086 static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable { 1087 assert(a.length == 0); 1088 return mh.invokeBasic(); 1089 } 1090 @Hidden 1091 static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable { 1092 assert(a.length == 1); 1093 return mh.invokeBasic(a[0]); 1094 } 1095 @Hidden 1096 static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable { 1097 assert(a.length == 2); 1098 return mh.invokeBasic(a[0], a[1]); 1099 } 1100 @Hidden 1101 static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable { 1102 assert(a.length == 3); 1103 return mh.invokeBasic(a[0], a[1], a[2]); 1104 } 1105 @Hidden 1106 static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable { 1107 assert(a.length == 4); 1108 return mh.invokeBasic(a[0], a[1], a[2], a[3]); 1109 } 1110 @Hidden 1111 static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable { 1112 assert(a.length == 5); 1113 return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]); 1114 } 1115 1116 static final MethodType INVOKER_METHOD_TYPE = 1117 MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1118 1119 private static MethodHandle computeInvoker(MethodTypeForm typeForm) { 1120 MethodHandle mh = typeForm.namedFunctionInvoker; 1121 if (mh != null) return mh; 1122 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while 1123 mh = DirectMethodHandle.make(invoker); 1124 MethodHandle mh2 = typeForm.namedFunctionInvoker; 1125 if (mh2 != null) return mh2; // benign race 1126 if (!mh.type().equals(INVOKER_METHOD_TYPE)) 1127 throw new InternalError(mh.debugString()); 1128 return typeForm.namedFunctionInvoker = mh; 1129 } 1130 1131 @Hidden 1132 Object invokeWithArguments(Object... arguments) throws Throwable { 1133 // If we have a cached invoker, call it right away. 1134 // NOTE: The invoker always returns a reference value. 1135 if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments); 1136 assert(checkArgumentTypes(arguments, methodType())); 1137 return invoker().invokeBasic(resolvedHandle(), arguments); 1138 } 1139 1140 @Hidden 1141 Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable { 1142 Object rval; 1143 try { 1144 traceInterpreter("[ call", this, arguments); 1145 if (invoker == null) { 1146 traceInterpreter("| getInvoker", this); 1147 invoker(); 1148 } 1149 if (resolvedHandle == null) { 1150 traceInterpreter("| resolve", this); 1151 resolvedHandle(); 1152 } 1153 assert(checkArgumentTypes(arguments, methodType())); 1154 rval = invoker().invokeBasic(resolvedHandle(), arguments); 1155 } catch (Throwable ex) { 1156 traceInterpreter("] throw =>", ex); 1157 throw ex; 1158 } 1159 traceInterpreter("] return =>", rval); 1160 return rval; 1161 } 1162 1163 private MethodHandle invoker() { 1164 if (invoker != null) return invoker; 1165 // Get an invoker and cache it. 1166 return invoker = computeInvoker(methodType().form()); 1167 } 1168 1169 private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) { 1170 if (true) return true; // FIXME 1171 MethodType dstType = methodType.form().erasedType(); 1172 MethodType srcType = dstType.basicType().wrap(); 1173 Class<?>[] ptypes = new Class<?>[arguments.length]; 1174 for (int i = 0; i < arguments.length; i++) { 1175 Object arg = arguments[i]; 1176 Class<?> ptype = arg == null ? Object.class : arg.getClass(); 1177 // If the dest. type is a primitive we keep the 1178 // argument type. 1179 ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class; 1180 } 1181 MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap(); 1182 assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType; 1183 return true; 1184 } 1185 1186 String basicTypeSignature() { 1187 //return LambdaForm.basicTypeSignature(resolvedHandle.type()); 1188 return LambdaForm.basicTypeSignature(methodType()); 1189 } 1190 1191 MethodType methodType() { 1192 if (resolvedHandle != null) 1193 return resolvedHandle.type(); 1194 else 1195 // only for certain internal LFs during bootstrapping 1196 return member.getInvocationType(); 1197 } 1198 1199 MemberName member() { 1200 assert(assertMemberIsConsistent()); 1201 return member; 1202 } 1203 1204 // Called only from assert. 1205 private boolean assertMemberIsConsistent() { 1206 if (resolvedHandle instanceof DirectMethodHandle) { 1207 MemberName m = resolvedHandle.internalMemberName(); 1208 assert(m.equals(member)); 1209 } 1210 return true; 1211 } 1212 1213 Class<?> memberDeclaringClassOrNull() { 1214 return (member == null) ? null : member.getDeclaringClass(); 1215 } 1216 1217 char returnType() { 1218 return basicType(methodType().returnType()); 1219 } 1220 1221 char parameterType(int n) { 1222 return basicType(methodType().parameterType(n)); 1223 } 1224 1225 int arity() { 1226 //int siglen = member.getMethodType().parameterCount(); 1227 //if (!member.isStatic()) siglen += 1; 1228 //return siglen; 1229 return methodType().parameterCount(); 1230 } 1231 1232 public String toString() { 1233 if (member == null) return resolvedHandle.toString(); 1234 return member.getDeclaringClass().getSimpleName()+"."+member.getName(); 1235 } 1236 } 1237 1238 void resolve() { 1239 for (Name n : names) n.resolve(); 1240 } 1241 1242 public static char basicType(Class<?> type) { 1243 char c = Wrapper.basicTypeChar(type); 1244 if ("ZBSC".indexOf(c) >= 0) c = 'I'; 1245 assert("LIJFDV".indexOf(c) >= 0); 1246 return c; 1247 } 1248 public static char[] basicTypes(List<Class<?>> types) { 1249 char[] btypes = new char[types.size()]; 1250 for (int i = 0; i < btypes.length; i++) { 1251 btypes[i] = basicType(types.get(i)); 1252 } 1253 return btypes; 1254 } 1255 public static String basicTypeSignature(MethodType type) { 1256 char[] sig = new char[type.parameterCount() + 2]; 1257 int sigp = 0; 1258 for (Class<?> pt : type.parameterList()) { 1259 sig[sigp++] = basicType(pt); 1260 } 1261 sig[sigp++] = '_'; 1262 sig[sigp++] = basicType(type.returnType()); 1263 assert(sigp == sig.length); 1264 return String.valueOf(sig); 1265 } 1266 1267 static final class Name { 1268 final char type; 1269 private short index; 1270 final NamedFunction function; 1271 @Stable final Object[] arguments; 1272 1273 private Name(int index, char type, NamedFunction function, Object[] arguments) { 1274 this.index = (short)index; 1275 this.type = type; 1276 this.function = function; 1277 this.arguments = arguments; 1278 assert(this.index == index); 1279 } 1280 Name(MethodHandle function, Object... arguments) { 1281 this(new NamedFunction(function), arguments); 1282 } 1283 Name(MemberName function, Object... arguments) { 1284 this(new NamedFunction(function), arguments); 1285 } 1286 Name(NamedFunction function, Object... arguments) { 1287 this(-1, function.returnType(), function, arguments = arguments.clone()); 1288 assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString(); 1289 for (int i = 0; i < arguments.length; i++) 1290 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString(); 1291 } 1292 Name(int index, char type) { 1293 this(index, type, null, null); 1294 } 1295 Name(char type) { 1296 this(-1, type); 1297 } 1298 1299 char type() { return type; } 1300 int index() { return index; } 1301 boolean initIndex(int i) { 1302 if (index != i) { 1303 if (index != -1) return false; 1304 index = (short)i; 1305 } 1306 return true; 1307 } 1308 1309 1310 void resolve() { 1311 if (function != null) 1312 function.resolve(); 1313 } 1314 1315 Name newIndex(int i) { 1316 if (initIndex(i)) return this; 1317 return cloneWithIndex(i); 1318 } 1319 Name cloneWithIndex(int i) { 1320 Object[] newArguments = (arguments == null) ? null : arguments.clone(); 1321 return new Name(i, type, function, newArguments); 1322 } 1323 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly 1324 if (oldName == newName) return this; 1325 @SuppressWarnings("LocalVariableHidesMemberVariable") 1326 Object[] arguments = this.arguments; 1327 if (arguments == null) return this; 1328 boolean replaced = false; 1329 for (int j = 0; j < arguments.length; j++) { 1330 if (arguments[j] == oldName) { 1331 if (!replaced) { 1332 replaced = true; 1333 arguments = arguments.clone(); 1334 } 1335 arguments[j] = newName; 1336 } 1337 } 1338 if (!replaced) return this; 1339 return new Name(function, arguments); 1340 } 1341 Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) { 1342 @SuppressWarnings("LocalVariableHidesMemberVariable") 1343 Object[] arguments = this.arguments; 1344 boolean replaced = false; 1345 eachArg: 1346 for (int j = 0; j < arguments.length; j++) { 1347 if (arguments[j] instanceof Name) { 1348 Name n = (Name) arguments[j]; 1349 int check = n.index; 1350 // harmless check to see if the thing is already in newNames: 1351 if (check >= 0 && check < newNames.length && n == newNames[check]) 1352 continue eachArg; 1353 // n might not have the correct index: n != oldNames[n.index]. 1354 for (int i = start; i < end; i++) { 1355 if (n == oldNames[i]) { 1356 if (n == newNames[i]) 1357 continue eachArg; 1358 if (!replaced) { 1359 replaced = true; 1360 arguments = arguments.clone(); 1361 } 1362 arguments[j] = newNames[i]; 1363 continue eachArg; 1364 } 1365 } 1366 } 1367 } 1368 if (!replaced) return this; 1369 return new Name(function, arguments); 1370 } 1371 void internArguments() { 1372 @SuppressWarnings("LocalVariableHidesMemberVariable") 1373 Object[] arguments = this.arguments; 1374 for (int j = 0; j < arguments.length; j++) { 1375 if (arguments[j] instanceof Name) { 1376 Name n = (Name) arguments[j]; 1377 if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT) 1378 arguments[j] = internArgument(n); 1379 } 1380 } 1381 } 1382 boolean isParam() { 1383 return function == null; 1384 } 1385 boolean isConstantZero() { 1386 return !isParam() && arguments.length == 0 && function.equals(constantZero(0, type).function); 1387 } 1388 1389 public String toString() { 1390 return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+type; 1391 } 1392 public String debugString() { 1393 String s = toString(); 1394 return (function == null) ? s : s + "=" + exprString(); 1395 } 1396 public String exprString() { 1397 if (function == null) return "null"; 1398 StringBuilder buf = new StringBuilder(function.toString()); 1399 buf.append("("); 1400 String cma = ""; 1401 for (Object a : arguments) { 1402 buf.append(cma); cma = ","; 1403 if (a instanceof Name || a instanceof Integer) 1404 buf.append(a); 1405 else 1406 buf.append("(").append(a).append(")"); 1407 } 1408 buf.append(")"); 1409 return buf.toString(); 1410 } 1411 1412 private static boolean typesMatch(char parameterType, Object object) { 1413 if (object instanceof Name) { 1414 return ((Name)object).type == parameterType; 1415 } 1416 switch (parameterType) { 1417 case 'I': return object instanceof Integer; 1418 case 'J': return object instanceof Long; 1419 case 'F': return object instanceof Float; 1420 case 'D': return object instanceof Double; 1421 } 1422 assert(parameterType == 'L'); 1423 return true; 1424 } 1425 1426 /** 1427 * Does this Name precede the given binding node in some canonical order? 1428 * This predicate is used to order data bindings (via insertion sort) 1429 * with some stability. 1430 * @param binding 1431 * @return 1432 */ 1433 boolean isSiblingBindingBefore(Name binding) { 1434 assert(!binding.isParam()); 1435 if (isParam()) return true; 1436 if (function.equals(binding.function) && 1437 arguments.length == binding.arguments.length) { 1438 boolean sawInt = false; 1439 for (int i = 0; i < arguments.length; i++) { 1440 Object a1 = arguments[i]; 1441 Object a2 = binding.arguments[i]; 1442 if (!a1.equals(a2)) { 1443 if (a1 instanceof Integer && a2 instanceof Integer) { 1444 if (sawInt) continue; 1445 sawInt = true; 1446 if ((int)a1 < (int)a2) continue; // still might be true 1447 } 1448 return false; 1449 } 1450 } 1451 return sawInt; 1452 } 1453 return false; 1454 } 1455 1456 public boolean equals(Name that) { 1457 if (this == that) return true; 1458 if (isParam()) 1459 // each parameter is a unique atom 1460 return false; // this != that 1461 return 1462 //this.index == that.index && 1463 this.type == that.type && 1464 this.function.equals(that.function) && 1465 Arrays.equals(this.arguments, that.arguments); 1466 } 1467 @Override 1468 public boolean equals(Object x) { 1469 return x instanceof Name && equals((Name)x); 1470 } 1471 @Override 1472 public int hashCode() { 1473 if (isParam()) 1474 return index | (type << 8); 1475 return function.hashCode() ^ Arrays.hashCode(arguments); 1476 } 1477 } 1478 1479 static Name argument(int which, char type) { 1480 int tn = ALL_TYPES.indexOf(type); 1481 if (tn < 0 || which >= INTERNED_ARGUMENT_LIMIT) 1482 return new Name(which, type); 1483 return INTERNED_ARGUMENTS[tn][which]; 1484 } 1485 static Name internArgument(Name n) { 1486 assert(n.isParam()) : "not param: " + n; 1487 assert(n.index < INTERNED_ARGUMENT_LIMIT); 1488 return argument(n.index, n.type); 1489 } 1490 static Name[] arguments(int extra, String types) { 1491 int length = types.length(); 1492 Name[] names = new Name[length + extra]; 1493 for (int i = 0; i < length; i++) 1494 names[i] = argument(i, types.charAt(i)); 1495 return names; 1496 } 1497 static Name[] arguments(int extra, char... types) { 1498 int length = types.length; 1499 Name[] names = new Name[length + extra]; 1500 for (int i = 0; i < length; i++) 1501 names[i] = argument(i, types[i]); 1502 return names; 1503 } 1504 static Name[] arguments(int extra, List<Class<?>> types) { 1505 int length = types.size(); 1506 Name[] names = new Name[length + extra]; 1507 for (int i = 0; i < length; i++) 1508 names[i] = argument(i, basicType(types.get(i))); 1509 return names; 1510 } 1511 static Name[] arguments(int extra, Class<?>... types) { 1512 int length = types.length; 1513 Name[] names = new Name[length + extra]; 1514 for (int i = 0; i < length; i++) 1515 names[i] = argument(i, basicType(types[i])); 1516 return names; 1517 } 1518 static Name[] arguments(int extra, MethodType types) { 1519 int length = types.parameterCount(); 1520 Name[] names = new Name[length + extra]; 1521 for (int i = 0; i < length; i++) 1522 names[i] = argument(i, basicType(types.parameterType(i))); 1523 return names; 1524 } 1525 static final String ALL_TYPES = "LIJFD"; // omit V, not an argument type 1526 static final int INTERNED_ARGUMENT_LIMIT = 10; 1527 private static final Name[][] INTERNED_ARGUMENTS 1528 = new Name[ALL_TYPES.length()][INTERNED_ARGUMENT_LIMIT]; 1529 static { 1530 for (int tn = 0; tn < ALL_TYPES.length(); tn++) { 1531 for (int i = 0; i < INTERNED_ARGUMENTS[tn].length; i++) { 1532 char type = ALL_TYPES.charAt(tn); 1533 INTERNED_ARGUMENTS[tn][i] = new Name(i, type); 1534 } 1535 } 1536 } 1537 1538 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 1539 1540 static Name constantZero(int which, char type) { 1541 return CONSTANT_ZERO[ALL_TYPES.indexOf(type)].newIndex(which); 1542 } 1543 private static final Name[] CONSTANT_ZERO 1544 = new Name[ALL_TYPES.length()]; 1545 static { 1546 for (int tn = 0; tn < ALL_TYPES.length(); tn++) { 1547 char bt = ALL_TYPES.charAt(tn); 1548 Wrapper wrap = Wrapper.forBasicType(bt); 1549 MemberName zmem = new MemberName(LambdaForm.class, "zero"+bt, MethodType.methodType(wrap.primitiveType()), REF_invokeStatic); 1550 try { 1551 zmem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zmem, null, NoSuchMethodException.class); 1552 } catch (IllegalAccessException|NoSuchMethodException ex) { 1553 throw newInternalError(ex); 1554 } 1555 NamedFunction zcon = new NamedFunction(zmem); 1556 Name n = new Name(zcon).newIndex(0); 1557 assert(n.type == ALL_TYPES.charAt(tn)); 1558 CONSTANT_ZERO[tn] = n; 1559 assert(n.isConstantZero()); 1560 } 1561 } 1562 1563 // Avoid appealing to ValueConversions at bootstrap time: 1564 private static int zeroI() { return 0; } 1565 private static long zeroJ() { return 0; } 1566 private static float zeroF() { return 0; } 1567 private static double zeroD() { return 0; } 1568 private static Object zeroL() { return null; } 1569 1570 // Put this last, so that previous static inits can run before. 1571 static { 1572 if (USE_PREDEFINED_INTERPRET_METHODS) 1573 PREPARED_FORMS.putAll(computeInitialPreparedForms()); 1574 } 1575 1576 /** 1577 * Internal marker for byte-compiled LambdaForms. 1578 */ 1579 /*non-public*/ 1580 @Target(ElementType.METHOD) 1581 @Retention(RetentionPolicy.RUNTIME) 1582 @interface Compiled { 1583 } 1584 1585 /** 1586 * Internal marker for LambdaForm interpreter frames. 1587 */ 1588 /*non-public*/ 1589 @Target(ElementType.METHOD) 1590 @Retention(RetentionPolicy.RUNTIME) 1591 @interface Hidden { 1592 } 1593 1594 1595 /* 1596 // Smoke-test for the invokers used in this file. 1597 static void testMethodHandleLinkers() throws Throwable { 1598 MemberName.Factory lookup = MemberName.getFactory(); 1599 MemberName asList_MN = new MemberName(Arrays.class, "asList", 1600 MethodType.methodType(List.class, Object[].class), 1601 REF_invokeStatic); 1602 //MethodHandleNatives.resolve(asList_MN, null); 1603 asList_MN = lookup.resolveOrFail(asList_MN, REF_invokeStatic, null, NoSuchMethodException.class); 1604 System.out.println("about to call "+asList_MN); 1605 Object[] abc = { "a", "bc" }; 1606 List<?> lst = (List<?>) MethodHandle.linkToStatic(abc, asList_MN); 1607 System.out.println("lst="+lst); 1608 MemberName toString_MN = new MemberName(Object.class.getMethod("toString")); 1609 String s1 = (String) MethodHandle.linkToVirtual(lst, toString_MN); 1610 toString_MN = new MemberName(Object.class.getMethod("toString"), true); 1611 String s2 = (String) MethodHandle.linkToSpecial(lst, toString_MN); 1612 System.out.println("[s1,s2,lst]="+Arrays.asList(s1, s2, lst.toString())); 1613 MemberName toArray_MN = new MemberName(List.class.getMethod("toArray")); 1614 Object[] arr = (Object[]) MethodHandle.linkToInterface(lst, toArray_MN); 1615 System.out.println("toArray="+Arrays.toString(arr)); 1616 } 1617 static { try { testMethodHandleLinkers(); } catch (Throwable ex) { throw new RuntimeException(ex); } } 1618 // Requires these definitions in MethodHandle: 1619 static final native Object linkToStatic(Object x1, MemberName mn) throws Throwable; 1620 static final native Object linkToVirtual(Object x1, MemberName mn) throws Throwable; 1621 static final native Object linkToSpecial(Object x1, MemberName mn) throws Throwable; 1622 static final native Object linkToInterface(Object x1, MemberName mn) throws Throwable; 1623 */ 1624 1625 static { NamedFunction.initializeInvokers(); } 1626 }