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