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