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