1 /* 2 * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.loader.BootLoader; 29 import jdk.internal.org.objectweb.asm.ClassWriter; 30 import jdk.internal.org.objectweb.asm.FieldVisitor; 31 import jdk.internal.org.objectweb.asm.MethodVisitor; 32 import jdk.internal.vm.annotation.Stable; 33 import sun.invoke.util.ValueConversions; 34 import sun.invoke.util.Wrapper; 35 36 import java.lang.invoke.LambdaForm.NamedFunction; 37 import java.lang.invoke.MethodHandles.Lookup; 38 import java.lang.reflect.Field; 39 import java.util.concurrent.ConcurrentHashMap; 40 import java.util.concurrent.ConcurrentMap; 41 import java.util.function.Function; 42 43 import static java.lang.invoke.LambdaForm.BasicType; 44 import static java.lang.invoke.LambdaForm.BasicType.*; 45 import static java.lang.invoke.MethodHandleStatics.*; 46 import static jdk.internal.org.objectweb.asm.Opcodes.*; 47 48 /** 49 * The flavor of method handle which emulates an invoke instruction 50 * on a predetermined argument. The JVM dispatches to the correct method 51 * when the handle is created, not when it is invoked. 52 * 53 * All bound arguments are encapsulated in dedicated species. 54 */ 55 /*non-public*/ abstract class BoundMethodHandle extends MethodHandle { 56 57 /*non-public*/ BoundMethodHandle(MethodType type, LambdaForm form) { 58 super(type, form); 59 assert(speciesData() == speciesData(form)); 60 } 61 62 // 63 // BMH API and internals 64 // 65 66 static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, BasicType xtype, Object x) { 67 // for some type signatures, there exist pre-defined concrete BMH classes 68 try { 69 switch (xtype) { 70 case L_TYPE: 71 return bindSingle(type, form, x); // Use known fast path. 72 case I_TYPE: 73 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(I_TYPE).constructor().invokeBasic(type, form, ValueConversions.widenSubword(x)); 74 case J_TYPE: 75 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(J_TYPE).constructor().invokeBasic(type, form, (long) x); 76 case F_TYPE: 77 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(F_TYPE).constructor().invokeBasic(type, form, (float) x); 78 case D_TYPE: 79 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(D_TYPE).constructor().invokeBasic(type, form, (double) x); 80 default : throw newInternalError("unexpected xtype: " + xtype); 81 } 82 } catch (Throwable t) { 83 throw uncaughtException(t); 84 } 85 } 86 87 /*non-public*/ 88 LambdaFormEditor editor() { 89 return form.editor(); 90 } 91 92 static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, Object x) { 93 return Species_L.make(type, form, x); 94 } 95 96 @Override // there is a default binder in the super class, for 'L' types only 97 /*non-public*/ 98 BoundMethodHandle bindArgumentL(int pos, Object value) { 99 return editor().bindArgumentL(this, pos, value); 100 } 101 /*non-public*/ 102 BoundMethodHandle bindArgumentI(int pos, int value) { 103 return editor().bindArgumentI(this, pos, value); 104 } 105 /*non-public*/ 106 BoundMethodHandle bindArgumentJ(int pos, long value) { 107 return editor().bindArgumentJ(this, pos, value); 108 } 109 /*non-public*/ 110 BoundMethodHandle bindArgumentF(int pos, float value) { 111 return editor().bindArgumentF(this, pos, value); 112 } 113 /*non-public*/ 114 BoundMethodHandle bindArgumentD(int pos, double value) { 115 return editor().bindArgumentD(this, pos, value); 116 } 117 /*non-public*/ 118 BoundMethodHandle bindArgumentQ(int pos, Object value, MethodHandle unbox) { 119 return editor().bindArgumentQ(this, pos, value, unbox); 120 } 121 @Override 122 BoundMethodHandle rebind() { 123 if (!tooComplex()) { 124 return this; 125 } 126 return makeReinvoker(this); 127 } 128 129 private boolean tooComplex() { 130 return (fieldCount() > FIELD_COUNT_THRESHOLD || 131 form.expressionCount() > FORM_EXPRESSION_THRESHOLD); 132 } 133 private static final int FIELD_COUNT_THRESHOLD = 12; // largest convenient BMH field count 134 private static final int FORM_EXPRESSION_THRESHOLD = 24; // largest convenient BMH expression count 135 136 /** 137 * A reinvoker MH has this form: 138 * {@code lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) }} 139 */ 140 static BoundMethodHandle makeReinvoker(MethodHandle target) { 141 LambdaForm form = DelegatingMethodHandle.makeReinvokerForm( 142 target, MethodTypeForm.LF_REBIND, 143 Species_L.SPECIES_DATA, Species_L.SPECIES_DATA.getterFunction(0)); 144 return Species_L.make(target.type(), form, target); 145 } 146 147 /** 148 * Return the {@link SpeciesData} instance representing this BMH species. All subclasses must provide a 149 * static field containing this value, and they must accordingly implement this method. 150 */ 151 /*non-public*/ abstract SpeciesData speciesData(); 152 153 /*non-public*/ static SpeciesData speciesData(LambdaForm form) { 154 Object c = form.names[0].constraint; 155 if (c instanceof SpeciesData) 156 return (SpeciesData) c; 157 // if there is no BMH constraint, then use the null constraint 158 return SpeciesData.EMPTY; 159 } 160 161 /** 162 * Return the number of fields in this BMH. Equivalent to speciesData().fieldCount(). 163 */ 164 /*non-public*/ abstract int fieldCount(); 165 166 @Override 167 Object internalProperties() { 168 return "\n& BMH="+internalValues(); 169 } 170 171 @Override 172 final String internalValues() { 173 int count = speciesData().fieldCount(); 174 if (count == 1) { 175 return "[" + arg(0) + "]"; 176 } 177 StringBuilder sb = new StringBuilder("["); 178 for (int i = 0; i < count; ++i) { 179 sb.append("\n ").append(i).append(": ( ").append(arg(i)).append(" )"); 180 } 181 return sb.append("\n]").toString(); 182 } 183 184 /*non-public*/ final Object arg(int i) { 185 try { 186 switch (speciesData().fieldType(i)) { 187 case L_TYPE: return speciesData().getters[i].invokeBasic(this); 188 case I_TYPE: return (int) speciesData().getters[i].invokeBasic(this); 189 case J_TYPE: return (long) speciesData().getters[i].invokeBasic(this); 190 case F_TYPE: return (float) speciesData().getters[i].invokeBasic(this); 191 case D_TYPE: return (double) speciesData().getters[i].invokeBasic(this); 192 } 193 } catch (Throwable ex) { 194 throw uncaughtException(ex); 195 } 196 throw new InternalError("unexpected type: " + speciesData().typeChars+"."+i); 197 } 198 199 // 200 // cloning API 201 // 202 203 /*non-public*/ abstract BoundMethodHandle copyWith(MethodType mt, LambdaForm lf); 204 /*non-public*/ abstract BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg); 205 /*non-public*/ abstract BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg); 206 /*non-public*/ abstract BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg); 207 /*non-public*/ abstract BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg); 208 /*non-public*/ abstract BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg); 209 210 // 211 // concrete BMH classes required to close bootstrap loops 212 // 213 214 private // make it private to force users to access the enclosing class first 215 static final class Species_L extends BoundMethodHandle { 216 final Object argL0; 217 private Species_L(MethodType mt, LambdaForm lf, Object argL0) { 218 super(mt, lf); 219 this.argL0 = argL0; 220 } 221 @Override 222 /*non-public*/ SpeciesData speciesData() { 223 return SPECIES_DATA; 224 } 225 @Override 226 /*non-public*/ int fieldCount() { 227 return 1; 228 } 229 /*non-public*/ static final SpeciesData SPECIES_DATA = new SpeciesData("L", Species_L.class); 230 /*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) { 231 return new Species_L(mt, lf, argL0); 232 } 233 @Override 234 /*non-public*/ final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) { 235 return new Species_L(mt, lf, argL0); 236 } 237 @Override 238 /*non-public*/ final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) { 239 try { 240 return (BoundMethodHandle) SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, narg); 241 } catch (Throwable ex) { 242 throw uncaughtException(ex); 243 } 244 } 245 @Override 246 /*non-public*/ final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) { 247 try { 248 return (BoundMethodHandle) SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, narg); 249 } catch (Throwable ex) { 250 throw uncaughtException(ex); 251 } 252 } 253 @Override 254 /*non-public*/ final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) { 255 try { 256 return (BoundMethodHandle) SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, narg); 257 } catch (Throwable ex) { 258 throw uncaughtException(ex); 259 } 260 } 261 @Override 262 /*non-public*/ final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) { 263 try { 264 return (BoundMethodHandle) SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, narg); 265 } catch (Throwable ex) { 266 throw uncaughtException(ex); 267 } 268 } 269 @Override 270 /*non-public*/ final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) { 271 try { 272 return (BoundMethodHandle) SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, narg); 273 } catch (Throwable ex) { 274 throw uncaughtException(ex); 275 } 276 } 277 } 278 279 // 280 // BMH species meta-data 281 // 282 283 /** 284 * Meta-data wrapper for concrete BMH types. 285 * Each BMH type corresponds to a given sequence of basic field types (LIJFD). 286 * The fields are immutable; their values are fully specified at object construction. 287 * Each BMH type supplies an array of getter functions which may be used in lambda forms. 288 * A BMH is constructed by cloning a shorter BMH and adding one or more new field values. 289 * The shortest possible BMH has zero fields; its class is SimpleMethodHandle. 290 * BMH species are not interrelated by subtyping, even though it would appear that 291 * a shorter BMH could serve as a supertype of a longer one which extends it. 292 */ 293 static class SpeciesData { 294 private final String typeChars; 295 private final BasicType[] typeCodes; 296 private final Class<? extends BoundMethodHandle> clazz; 297 // Bootstrapping requires circular relations MH -> BMH -> SpeciesData -> MH 298 // Therefore, we need a non-final link in the chain. Use array elements. 299 @Stable private final MethodHandle[] constructor; 300 @Stable private final MethodHandle[] getters; 301 @Stable private final NamedFunction[] nominalGetters; 302 @Stable private final SpeciesData[] extensions; 303 304 /*non-public*/ int fieldCount() { 305 return typeCodes.length; 306 } 307 /*non-public*/ BasicType fieldType(int i) { 308 return typeCodes[i]; 309 } 310 /*non-public*/ char fieldTypeChar(int i) { 311 return typeChars.charAt(i); 312 } 313 String fieldSignature() { 314 return typeChars; 315 } 316 public Class<? extends BoundMethodHandle> fieldHolder() { 317 return clazz; 318 } 319 public String toString() { 320 return "SpeciesData<"+fieldSignature()+">"; 321 } 322 323 /** 324 * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that 325 * represents a MH bound to a generic invoker, which in turn forwards to the corresponding 326 * getter. 327 */ 328 NamedFunction getterFunction(int i) { 329 NamedFunction nf = nominalGetters[i]; 330 assert(nf.memberDeclaringClassOrNull() == fieldHolder()); 331 assert(nf.returnType() == fieldType(i)); 332 return nf; 333 } 334 335 NamedFunction[] getterFunctions() { 336 return nominalGetters; 337 } 338 339 MethodHandle[] getterHandles() { return getters; } 340 341 MethodHandle constructor() { 342 return constructor[0]; 343 } 344 345 static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class); 346 347 SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) { 348 this.typeChars = types; 349 this.typeCodes = basicTypes(types); 350 this.clazz = clazz; 351 if (!INIT_DONE) { 352 this.constructor = new MethodHandle[1]; // only one ctor 353 this.getters = new MethodHandle[types.length()]; 354 this.nominalGetters = new NamedFunction[types.length()]; 355 } else { 356 this.constructor = Factory.makeCtors(clazz, types, null); 357 this.getters = Factory.makeGetters(clazz, types, null); 358 this.nominalGetters = Factory.makeNominalGetters(types, null, this.getters); 359 } 360 this.extensions = new SpeciesData[ARG_TYPE_LIMIT]; 361 } 362 363 private void initForBootstrap() { 364 assert(!INIT_DONE); 365 if (constructor() == null) { 366 String types = typeChars; 367 CACHE.put(types, this); 368 Factory.makeCtors(clazz, types, this.constructor); 369 Factory.makeGetters(clazz, types, this.getters); 370 Factory.makeNominalGetters(types, this.nominalGetters, this.getters); 371 } 372 } 373 374 private static final ConcurrentMap<String, SpeciesData> CACHE = new ConcurrentHashMap<>(); 375 private static final boolean INIT_DONE; // set after <clinit> finishes... 376 377 SpeciesData extendWith(byte type) { 378 return extendWith(BasicType.basicType(type)); 379 } 380 381 SpeciesData extendWith(BasicType type) { 382 int ord = type.ordinal(); 383 SpeciesData d = extensions[ord]; 384 if (d != null) return d; 385 extensions[ord] = d = get(typeChars+type.basicTypeChar()); 386 return d; 387 } 388 389 private static SpeciesData get(String types) { 390 return CACHE.computeIfAbsent(types, new Function<String, SpeciesData>() { 391 @Override 392 public SpeciesData apply(String types) { 393 Class<? extends BoundMethodHandle> bmhcl = Factory.getConcreteBMHClass(types); 394 // SpeciesData instantiation may throw VirtualMachineError because of 395 // code cache overflow... 396 SpeciesData speciesData = new SpeciesData(types, bmhcl); 397 // CHM.computeIfAbsent ensures only one SpeciesData will be set 398 // successfully on the concrete BMH class if ever 399 Factory.setSpeciesDataToConcreteBMHClass(bmhcl, speciesData); 400 // the concrete BMH class is published via SpeciesData instance 401 // returned here only after it's SPECIES_DATA field is set 402 return speciesData; 403 } 404 }); 405 } 406 407 /** 408 * This is to be called when assertions are enabled. It checks whether SpeciesData for all of the statically 409 * defined species subclasses of BoundMethodHandle has been added to the SpeciesData cache. See below in the 410 * static initializer for 411 */ 412 static boolean speciesDataCachePopulated() { 413 Class<BoundMethodHandle> rootCls = BoundMethodHandle.class; 414 for (Class<?> c : rootCls.getDeclaredClasses()) { 415 if (rootCls.isAssignableFrom(c)) { 416 final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class); 417 SpeciesData d = Factory.getSpeciesDataFromConcreteBMHClass(cbmh); 418 assert(d != null) : cbmh.getName(); 419 assert(d.clazz == cbmh); 420 assert(CACHE.get(d.typeChars) == d); 421 } 422 } 423 return true; 424 } 425 426 static { 427 // Pre-fill the BMH species-data cache with EMPTY and all BMH's inner subclasses. 428 EMPTY.initForBootstrap(); 429 Species_L.SPECIES_DATA.initForBootstrap(); 430 // check that all static SpeciesData instances have been initialized 431 assert speciesDataCachePopulated(); 432 // Note: Do not simplify this, because INIT_DONE must not be 433 // a compile-time constant during bootstrapping. 434 INIT_DONE = Boolean.TRUE; 435 } 436 } 437 438 static SpeciesData getSpeciesData(String types) { 439 return SpeciesData.get(types); 440 } 441 442 /** 443 * Generation of concrete BMH classes. 444 * 445 * A concrete BMH species is fit for binding a number of values adhering to a 446 * given type pattern. Reference types are erased. 447 * 448 * BMH species are cached by type pattern. 449 * 450 * A BMH species has a number of fields with the concrete (possibly erased) types of 451 * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs, 452 * which can be included as names in lambda forms. 453 */ 454 static class Factory { 455 456 private static final String JLO_SIG = "Ljava/lang/Object;"; 457 private static final String MH = "java/lang/invoke/MethodHandle"; 458 private static final String MH_SIG = "L"+MH+";"; 459 private static final String BMH = "java/lang/invoke/BoundMethodHandle"; 460 private static final String BMH_NAME = "java.lang.invoke.BoundMethodHandle"; 461 private static final String BMH_SIG = "L"+BMH+";"; 462 private static final String SPECIES_DATA = "java/lang/invoke/BoundMethodHandle$SpeciesData"; 463 private static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";"; 464 private static final String STABLE_SIG = "Ljdk/internal/vm/annotation/Stable;"; 465 466 private static final String SPECIES_PREFIX_NAME = "Species_"; 467 private static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME; 468 private static final String SPECIES_CLASS_PREFIX = BMH_NAME + "$" + SPECIES_PREFIX_NAME; 469 470 private static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG; 471 private static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG; 472 private static final String INT_SIG = "()I"; 473 474 private static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;"; 475 476 private static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" }; 477 478 private static final ConcurrentMap<String, Class<? extends BoundMethodHandle>> CLASS_CACHE = new ConcurrentHashMap<>(); 479 480 /** 481 * Get a concrete subclass of BMH for a given combination of bound types. 482 * 483 * @param types the type signature, wherein reference types are erased to 'L' 484 * @return the concrete BMH class 485 */ 486 static Class<? extends BoundMethodHandle> getConcreteBMHClass(String types) { 487 // CHM.computeIfAbsent ensures generateConcreteBMHClass is called 488 // only once per key. 489 return CLASS_CACHE.computeIfAbsent( 490 types, new Function<String, Class<? extends BoundMethodHandle>>() { 491 @Override 492 public Class<? extends BoundMethodHandle> apply(String types) { 493 String shortTypes = LambdaForm.shortenSignature(types); 494 String className = SPECIES_CLASS_PREFIX + shortTypes; 495 Class<?> c = BootLoader.loadClassOrNull(className); 496 if (TRACE_RESOLVE) { 497 System.out.println("[BMH_RESOLVE] " + shortTypes + 498 (c != null ? " (success)" : " (fail)") ); 499 } 500 if (c != null) { 501 return c.asSubclass(BoundMethodHandle.class); 502 } else { 503 // Not pregenerated, generate the class 504 return generateConcreteBMHClass(shortTypes, types); 505 } 506 } 507 }); 508 } 509 510 /** 511 * Generate a concrete subclass of BMH for a given combination of bound types. 512 * 513 * A concrete BMH species adheres to the following schema: 514 * 515 * <pre> 516 * class Species_[[types]] extends BoundMethodHandle { 517 * [[fields]] 518 * final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); } 519 * } 520 * </pre> 521 * 522 * The {@code [[types]]} signature is precisely the string that is passed to this 523 * method. 524 * 525 * The {@code [[fields]]} section consists of one field definition per character in 526 * the type signature, adhering to the naming schema described in the definition of 527 * {@link #makeFieldName}. 528 * 529 * For example, a concrete BMH species for two reference and one integral bound values 530 * would have the following shape: 531 * 532 * <pre> 533 * class BoundMethodHandle { ... private static 534 * final class Species_LLI extends BoundMethodHandle { 535 * final Object argL0; 536 * final Object argL1; 537 * final int argI2; 538 * private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { 539 * super(mt, lf); 540 * this.argL0 = argL0; 541 * this.argL1 = argL1; 542 * this.argI2 = argI2; 543 * } 544 * final SpeciesData speciesData() { return SPECIES_DATA; } 545 * final int fieldCount() { return 3; } 546 * @Stable static SpeciesData SPECIES_DATA; // injected afterwards 547 * static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { 548 * return new Species_LLI(mt, lf, argL0, argL1, argI2); 549 * } 550 * final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) { 551 * return new Species_LLI(mt, lf, argL0, argL1, argI2); 552 * } 553 * final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) { 554 * return SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 555 * } 556 * final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) { 557 * return SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 558 * } 559 * final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) { 560 * return SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 561 * } 562 * final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) { 563 * return SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 564 * } 565 * public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) { 566 * return SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 567 * } 568 * } 569 * </pre> 570 * 571 * @param types the type signature, wherein reference types are erased to 'L' 572 * @return the generated concrete BMH class 573 */ 574 static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String shortTypes, 575 String types) { 576 final String className = speciesInternalClassName(shortTypes); 577 byte[] classFile = generateConcreteBMHClassBytes(shortTypes, types, className); 578 579 // load class 580 InvokerBytecodeGenerator.maybeDump(className, classFile); 581 Class<? extends BoundMethodHandle> bmhClass = 582 UNSAFE.defineClass(className, classFile, 0, classFile.length, 583 BoundMethodHandle.class.getClassLoader(), null) 584 .asSubclass(BoundMethodHandle.class); 585 586 return bmhClass; 587 } 588 589 static String speciesInternalClassName(String shortTypes) { 590 return SPECIES_PREFIX_PATH + shortTypes; 591 } 592 593 static byte[] generateConcreteBMHClassBytes(final String shortTypes, 594 final String types, final String className) { 595 final String sourceFile = SPECIES_PREFIX_NAME + shortTypes; 596 597 final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 598 final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC 599 cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null); 600 cw.visitSource(sourceFile, null); 601 602 // emit static types and SPECIES_DATA fields 603 FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null); 604 fw.visitAnnotation(STABLE_SIG, true); 605 fw.visitEnd(); 606 607 // emit bound argument fields 608 for (int i = 0; i < types.length(); ++i) { 609 final char t = types.charAt(i); 610 final String fieldName = makeFieldName(types, i); 611 final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t); 612 cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd(); 613 } 614 615 MethodVisitor mv; 616 617 // emit constructor 618 mv = cw.visitMethod(ACC_PRIVATE, "<init>", makeSignature(types, true), null, null); 619 mv.visitCode(); 620 mv.visitVarInsn(ALOAD, 0); // this 621 mv.visitVarInsn(ALOAD, 1); // type 622 mv.visitVarInsn(ALOAD, 2); // form 623 624 mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true), false); 625 626 for (int i = 0, j = 0; i < types.length(); ++i, ++j) { 627 // i counts the arguments, j counts corresponding argument slots 628 char t = types.charAt(i); 629 mv.visitVarInsn(ALOAD, 0); 630 mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3 631 mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t)); 632 if (t == 'J' || t == 'D') { 633 ++j; // adjust argument register access 634 } 635 } 636 637 mv.visitInsn(RETURN); 638 mv.visitMaxs(0, 0); 639 mv.visitEnd(); 640 641 // emit implementation of speciesData() 642 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null); 643 mv.visitCode(); 644 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); 645 mv.visitInsn(ARETURN); 646 mv.visitMaxs(0, 0); 647 mv.visitEnd(); 648 649 // emit implementation of fieldCount() 650 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null); 651 mv.visitCode(); 652 int fc = types.length(); 653 if (fc <= (ICONST_5 - ICONST_0)) { 654 mv.visitInsn(ICONST_0 + fc); 655 } else { 656 mv.visitIntInsn(SIPUSH, fc); 657 } 658 mv.visitInsn(IRETURN); 659 mv.visitMaxs(0, 0); 660 mv.visitEnd(); 661 // emit make() ...factory method wrapping constructor 662 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, false), null, null); 663 mv.visitCode(); 664 // make instance 665 mv.visitTypeInsn(NEW, className); 666 mv.visitInsn(DUP); 667 // load mt, lf 668 mv.visitVarInsn(ALOAD, 0); // type 669 mv.visitVarInsn(ALOAD, 1); // form 670 // load factory method arguments 671 for (int i = 0, j = 0; i < types.length(); ++i, ++j) { 672 // i counts the arguments, j counts corresponding argument slots 673 char t = types.charAt(i); 674 mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3 675 if (t == 'J' || t == 'D') { 676 ++j; // adjust argument register access 677 } 678 } 679 680 // finally, invoke the constructor and return 681 mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false); 682 mv.visitInsn(ARETURN); 683 mv.visitMaxs(0, 0); 684 mv.visitEnd(); 685 686 // emit copyWith() 687 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null); 688 mv.visitCode(); 689 // make instance 690 mv.visitTypeInsn(NEW, className); 691 mv.visitInsn(DUP); 692 // load mt, lf 693 mv.visitVarInsn(ALOAD, 1); 694 mv.visitVarInsn(ALOAD, 2); 695 // put fields on the stack 696 emitPushFields(types, className, mv); 697 // finally, invoke the constructor and return 698 mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false); 699 mv.visitInsn(ARETURN); 700 mv.visitMaxs(0, 0); 701 mv.visitEnd(); 702 703 // for each type, emit copyWithExtendT() 704 for (BasicType type : BasicType.ARG_TYPES) { 705 if (type == Q_TYPE) continue; 706 int ord = type.ordinal(); 707 char btChar = type.basicTypeChar(); 708 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + btChar, makeSignature(String.valueOf(btChar), false), null, E_THROWABLE); 709 mv.visitCode(); 710 // return SPECIES_DATA.extendWith(t).constructor().invokeBasic(mt, lf, argL0, ..., narg) 711 // obtain constructor 712 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); 713 int iconstInsn = ICONST_0 + ord; 714 assert(iconstInsn <= ICONST_5); 715 mv.visitInsn(iconstInsn); 716 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false); 717 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "constructor", "()" + MH_SIG, false); 718 // load mt, lf 719 mv.visitVarInsn(ALOAD, 1); 720 mv.visitVarInsn(ALOAD, 2); 721 // put fields on the stack 722 emitPushFields(types, className, mv); 723 // put narg on stack 724 mv.visitVarInsn(typeLoadOp(btChar), 3); 725 // finally, invoke the constructor and return 726 mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + btChar, false), false); 727 mv.visitInsn(ARETURN); 728 mv.visitMaxs(0, 0); 729 mv.visitEnd(); 730 } 731 732 cw.visitEnd(); 733 734 return cw.toByteArray(); 735 } 736 737 private static int typeLoadOp(char t) { 738 switch (t) { 739 case 'L': return ALOAD; 740 case 'I': return ILOAD; 741 case 'J': return LLOAD; 742 case 'F': return FLOAD; 743 case 'D': return DLOAD; 744 default : throw newInternalError("unrecognized type " + t); 745 } 746 } 747 748 private static void emitPushFields(String types, String className, MethodVisitor mv) { 749 for (int i = 0; i < types.length(); ++i) { 750 char tc = types.charAt(i); 751 mv.visitVarInsn(ALOAD, 0); 752 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc)); 753 } 754 } 755 756 static String typeSig(char t) { 757 return t == 'L' ? JLO_SIG : String.valueOf(t); 758 } 759 760 // 761 // Getter MH generation. 762 // 763 764 private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) { 765 String fieldName = makeFieldName(types, index); 766 Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType(); 767 try { 768 return LOOKUP.findGetter(cbmhClass, fieldName, fieldType); 769 } catch (NoSuchFieldException | IllegalAccessException e) { 770 throw newInternalError(e); 771 } 772 } 773 774 static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) { 775 if (mhs == null) mhs = new MethodHandle[types.length()]; 776 for (int i = 0; i < mhs.length; ++i) { 777 mhs[i] = makeGetter(cbmhClass, types, i); 778 assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass); 779 } 780 return mhs; 781 } 782 783 static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) { 784 if (mhs == null) mhs = new MethodHandle[1]; 785 if (types.equals("")) return mhs; // hack for empty BMH species 786 mhs[0] = makeCbmhCtor(cbmh, types); 787 return mhs; 788 } 789 790 static NamedFunction[] makeNominalGetters(String types, NamedFunction[] nfs, MethodHandle[] getters) { 791 if (nfs == null) nfs = new NamedFunction[types.length()]; 792 for (int i = 0; i < nfs.length; ++i) { 793 nfs[i] = new NamedFunction(getters[i]); 794 } 795 return nfs; 796 } 797 798 // 799 // Auxiliary methods. 800 // 801 802 static SpeciesData getSpeciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) { 803 try { 804 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA"); 805 return (SpeciesData) F_SPECIES_DATA.get(null); 806 } catch (ReflectiveOperationException ex) { 807 throw newInternalError(ex); 808 } 809 } 810 811 static void setSpeciesDataToConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh, SpeciesData speciesData) { 812 try { 813 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA"); 814 // ## FIXME: annotation parser can't create proxy classes until module system is fully initialzed 815 // assert F_SPECIES_DATA.getDeclaredAnnotation(Stable.class) != null; 816 F_SPECIES_DATA.set(null, speciesData); 817 } catch (ReflectiveOperationException ex) { 818 throw newInternalError(ex); 819 } 820 } 821 822 /** 823 * Field names in concrete BMHs adhere to this pattern: 824 * arg + type + index 825 * where type is a single character (L, I, J, F, D). 826 */ 827 private static String makeFieldName(String types, int index) { 828 assert index >= 0 && index < types.length(); 829 return "arg" + types.charAt(index) + index; 830 } 831 832 private static String makeSignature(String types, boolean ctor) { 833 StringBuilder buf = new StringBuilder(SIG_INCIPIT); 834 int len = types.length(); 835 for (int i = 0; i < len; i++) { 836 buf.append(typeSig(types.charAt(i))); 837 } 838 return buf.append(')').append(ctor ? "V" : BMH_SIG).toString(); 839 } 840 841 private static MethodType makeConstructorType(String types) { 842 int length = types.length(); 843 Class<?> ptypes[] = new Class<?>[length + 2]; 844 ptypes[0] = MethodType.class; 845 ptypes[1] = LambdaForm.class; 846 for (int i = 0; i < length; i++) { 847 ptypes[i + 2] = BasicType.basicType(types.charAt(i)).basicTypeClass(); 848 } 849 return MethodType.makeImpl(BoundMethodHandle.class, ptypes, true); 850 } 851 852 static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) { 853 try { 854 return LOOKUP.findStatic(cbmh, "make", makeConstructorType(types)); 855 } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) { 856 throw newInternalError(e); 857 } 858 } 859 } 860 861 static final Lookup LOOKUP = Lookup.IMPL_LOOKUP; 862 863 /** 864 * All subclasses must provide such a value describing their type signature. 865 */ 866 static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY; 867 868 private static final SpeciesData[] SPECIES_DATA_CACHE = new SpeciesData[6]; 869 private static SpeciesData checkCache(int size, String types) { 870 int idx = size - 1; 871 SpeciesData data = SPECIES_DATA_CACHE[idx]; 872 if (data != null) return data; 873 SPECIES_DATA_CACHE[idx] = data = getSpeciesData(types); 874 return data; 875 } 876 static SpeciesData speciesData_L() { return checkCache(1, "L"); } 877 static SpeciesData speciesData_LL() { return checkCache(2, "LL"); } 878 static SpeciesData speciesData_LLL() { return checkCache(3, "LLL"); } 879 static SpeciesData speciesData_LLLL() { return checkCache(4, "LLLL"); } 880 static SpeciesData speciesData_LLLLL() { return checkCache(5, "LLLLL"); } 881 }