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