1 /* 2 * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.loader.BootLoader; 29 import jdk.internal.org.objectweb.asm.ClassWriter; 30 import jdk.internal.org.objectweb.asm.FieldVisitor; 31 import jdk.internal.org.objectweb.asm.MethodVisitor; 32 import jdk.internal.vm.annotation.Stable; 33 import sun.invoke.util.BytecodeName; 34 35 import java.lang.reflect.*; 36 import java.security.AccessController; 37 import java.security.PrivilegedAction; 38 import java.security.ProtectionDomain; 39 import java.util.*; 40 import java.util.concurrent.ConcurrentHashMap; 41 import java.util.concurrent.ConcurrentMap; 42 import java.util.function.Function; 43 44 import static java.lang.invoke.LambdaForm.*; 45 import static java.lang.invoke.MethodHandleNatives.Constants.REF_getStatic; 46 import static java.lang.invoke.MethodHandleNatives.Constants.REF_putStatic; 47 import static java.lang.invoke.MethodHandleStatics.*; 48 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 49 import static jdk.internal.org.objectweb.asm.Opcodes.*; 50 51 /** 52 * Class specialization code. 53 * @param <T> top class under which species classes are created. 54 * @param <K> key which identifies individual specializations. 55 * @param <S> species data type. 56 */ 57 /*non-public*/ 58 abstract class ClassSpecializer<T,K,S extends ClassSpecializer<T,K,S>.SpeciesData> { 59 private final Class<T> topClass; 60 private final Class<K> keyType; 61 private final Class<S> metaType; 62 private final MemberName sdAccessor; 63 private final String sdFieldName; 64 private final List<MemberName> transformMethods; 65 private final MethodType baseConstructorType; 66 private final S topSpecies; 67 private final ConcurrentMap<K, S> cache = new ConcurrentHashMap<>(); 68 private final Factory factory; 69 private @Stable boolean topClassIsSuper; 70 71 /** Return the top type mirror, for type {@code T} */ 72 public final Class<T> topClass() { return topClass; } 73 74 /** Return the key type mirror, for type {@code K} */ 75 public final Class<K> keyType() { return keyType; } 76 77 /** Return the species metadata type mirror, for type {@code S} */ 78 public final Class<S> metaType() { return metaType; } 79 80 /** Report the leading arguments (if any) required by every species factory. 81 * Every species factory adds its own field types as additional arguments, 82 * but these arguments always come first, in every factory method. 83 */ 84 protected MethodType baseConstructorType() { return baseConstructorType; } 85 86 /** Return the trivial species for the null sequence of arguments. */ 87 protected final S topSpecies() { return topSpecies; } 88 89 /** Return the list of transform methods originally given at creation of this specializer. */ 90 protected final List<MemberName> transformMethods() { return transformMethods; } 91 92 /** Return the factory object used to build and load concrete species code. */ 93 protected final Factory factory() { return factory; } 94 95 /** 96 * Constructor for this class specializer. 97 * @param topClass type mirror for T 98 * @param keyType type mirror for K 99 * @param metaType type mirror for S 100 * @param baseConstructorType principal constructor type 101 * @param sdAccessor the method used to get the speciesData 102 * @param sdFieldName the name of the species data field, inject the speciesData object 103 * @param transformMethods optional list of transformMethods 104 */ 105 protected ClassSpecializer(Class<T> topClass, 106 Class<K> keyType, 107 Class<S> metaType, 108 MethodType baseConstructorType, 109 MemberName sdAccessor, 110 String sdFieldName, 111 List<MemberName> transformMethods) { 112 this.topClass = topClass; 113 this.keyType = keyType; 114 this.metaType = metaType; 115 this.sdAccessor = sdAccessor; 116 // FIXME: use List.copyOf once 8177290 is in 117 this.transformMethods = List.of(transformMethods.toArray(new MemberName[transformMethods.size()])); 118 this.sdFieldName = sdFieldName; 119 this.baseConstructorType = baseConstructorType.changeReturnType(void.class); 120 this.factory = makeFactory(); 121 K tsk = topSpeciesKey(); 122 S topSpecies = null; 123 if (tsk != null && topSpecies == null) { 124 // if there is a key, build the top species if needed: 125 topSpecies = findSpecies(tsk); 126 } 127 this.topSpecies = topSpecies; 128 } 129 130 // Utilities for subclass constructors: 131 protected static <T> Constructor<T> reflectConstructor(Class<T> defc, Class<?>... ptypes) { 132 try { 133 return defc.getDeclaredConstructor(ptypes); 134 } catch (NoSuchMethodException ex) { 135 throw newIAE(defc.getName()+"("+MethodType.methodType(void.class, ptypes)+")", ex); 136 } 137 } 138 139 protected static Field reflectField(Class<?> defc, String name) { 140 try { 141 return defc.getDeclaredField(name); 142 } catch (NoSuchFieldException ex) { 143 throw newIAE(defc.getName()+"."+name, ex); 144 } 145 } 146 147 private static RuntimeException newIAE(String message, Throwable cause) { 148 return new IllegalArgumentException(message, cause); 149 } 150 151 public final S findSpecies(K key) { 152 if (TRACE_RESOLVE) { 153 System.out.println("[SPECIES_RESOLVE] findSpecies " + key); 154 } 155 S speciesData = cache.computeIfAbsent(key, new Function<>() { 156 @Override 157 public S apply(K key1) { 158 return factory.loadSpecies(newSpeciesData(key1)); 159 } 160 }); 161 if (TRACE_RESOLVE) { 162 System.out.println("[SPECIES_RESOLVE] findSpecies " + key + " => " + speciesData); 163 } 164 // Note: Species instantiation may throw VirtualMachineError because of 165 // code cache overflow. If this happens the species bytecode may be 166 // loaded but not linked to its species metadata (with MH's etc). 167 // That will cause a throw out of CHM.computeIfAbsent, 168 // which will shut down the caller thread. 169 // 170 // In a latter attempt to get the same species, the already-loaded 171 // class will be present in the system dictionary, causing an 172 // error when the species generator tries to reload it. 173 // We try to detect this case and link the pre-existing code. 174 // 175 // Although it would be better to start fresh by loading a new 176 // copy, we have to salvage the previously loaded but broken code. 177 // (As an alternative, we might spin a new class with a new name, 178 // or use the anonymous class mechanism.) 179 // 180 // In the end, as long as everybody goes through the same CHM, 181 // CHM.computeIfAbsent will ensure only one SpeciesData will be set 182 // successfully on a concrete class if ever. 183 // The concrete class is published via SpeciesData instance 184 // returned here only after the class and species data are linked together. 185 assert(speciesData != null); 186 return speciesData; 187 } 188 189 /** 190 * Meta-data wrapper for concrete subtypes of the top class. 191 * Each concrete subtype corresponds to a given sequence of basic field types (LIJFD). 192 * The fields are immutable; their values are fully specified at object construction. 193 * Each species supplies an array of getter functions which may be used in lambda forms. 194 * A concrete value is always constructed from the full tuple of its field values, 195 * accompanied by the required constructor parameters. 196 * There *may* also be transforms which cloning a species instance and 197 * either replace a constructor parameter or add one or more new field values. 198 * The shortest possible species has zero fields. 199 * Subtypes are not interrelated among themselves by subtyping, even though 200 * it would appear that a shorter species could serve as a supertype of a 201 * longer one which extends it. 202 */ 203 public abstract class SpeciesData { 204 // Bootstrapping requires circular relations Class -> SpeciesData -> Class 205 // Therefore, we need non-final links in the chain. Use @Stable fields. 206 private final K key; 207 private final List<Class<?>> fieldTypes; 208 @Stable private Class<? extends T> speciesCode; 209 @Stable private List<MethodHandle> factories; 210 @Stable private List<MethodHandle> getters; 211 @Stable private List<LambdaForm.NamedFunction> nominalGetters; 212 @Stable private final MethodHandle[] transformHelpers = new MethodHandle[transformMethods.size()]; 213 214 protected SpeciesData(K key) { 215 this.key = keyType.cast(Objects.requireNonNull(key)); 216 List<Class<?>> types = deriveFieldTypes(key); 217 // TODO: List.copyOf 218 int arity = types.size(); 219 this.fieldTypes = List.of(types.toArray(new Class<?>[arity])); 220 } 221 222 public final K key() { 223 return key; 224 } 225 226 protected final List<Class<?>> fieldTypes() { 227 return fieldTypes; 228 } 229 230 protected final int fieldCount() { 231 return fieldTypes.size(); 232 } 233 234 protected ClassSpecializer<T,K,S> outer() { 235 return ClassSpecializer.this; 236 } 237 238 protected final boolean isResolved() { 239 return speciesCode != null && factories != null && !factories.isEmpty(); 240 } 241 242 @Override public String toString() { 243 return metaType.getSimpleName() + "[" + key.toString() + " => " + (isResolved() ? speciesCode.getSimpleName() : "UNRESOLVED") + "]"; 244 } 245 246 @Override 247 public int hashCode() { 248 return key.hashCode(); 249 } 250 251 @Override 252 public boolean equals(Object obj) { 253 if (!(obj instanceof ClassSpecializer.SpeciesData)) { 254 return false; 255 } 256 @SuppressWarnings("rawtypes") 257 ClassSpecializer.SpeciesData that = (ClassSpecializer.SpeciesData) obj; 258 return this.outer() == that.outer() && this.key.equals(that.key); 259 } 260 261 /** Throws NPE if this species is not yet resolved. */ 262 protected final Class<? extends T> speciesCode() { 263 return Objects.requireNonNull(speciesCode); 264 } 265 266 /** 267 * Return a {@link MethodHandle} which can get the indexed field of this species. 268 * The return type is the type of the species field it accesses. 269 * The argument type is the {@code fieldHolder} class of this species. 270 */ 271 protected MethodHandle getter(int i) { 272 return getters.get(i); 273 } 274 275 /** 276 * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that 277 * represents a MH bound to a generic invoker, which in turn forwards to the corresponding 278 * getter. 279 */ 280 protected LambdaForm.NamedFunction getterFunction(int i) { 281 LambdaForm.NamedFunction nf = nominalGetters.get(i); 282 assert(nf.memberDeclaringClassOrNull() == speciesCode()); 283 assert(nf.returnType() == BasicType.basicType(fieldTypes.get(i))); 284 return nf; 285 } 286 287 protected List<LambdaForm.NamedFunction> getterFunctions() { 288 return nominalGetters; 289 } 290 291 protected List<MethodHandle> getters() { 292 return getters; 293 } 294 295 protected MethodHandle factory() { 296 return factories.get(0); 297 } 298 299 protected MethodHandle transformHelper(int whichtm) { 300 MethodHandle mh = transformHelpers[whichtm]; 301 if (mh != null) return mh; 302 mh = deriveTransformHelper(transformMethods().get(whichtm), whichtm); 303 // Do a little type checking before we start using the MH. 304 // (It will be called with invokeBasic, so this is our only chance.) 305 final MethodType mt = transformHelperType(whichtm); 306 mh = mh.asType(mt); 307 return transformHelpers[whichtm] = mh; 308 } 309 310 private final MethodType transformHelperType(int whichtm) { 311 MemberName tm = transformMethods().get(whichtm); 312 ArrayList<Class<?>> args = new ArrayList<>(); 313 ArrayList<Class<?>> fields = new ArrayList<>(); 314 Collections.addAll(args, tm.getParameterTypes()); 315 fields.addAll(fieldTypes()); 316 List<Class<?>> helperArgs = deriveTransformHelperArguments(tm, whichtm, args, fields); 317 return MethodType.methodType(tm.getReturnType(), helperArgs); 318 } 319 320 // Hooks for subclasses: 321 322 /** 323 * Given a key, derive the list of field types, which all instances of this 324 * species must store. 325 */ 326 protected abstract List<Class<?>> deriveFieldTypes(K key); 327 328 /** 329 * Given the index of a method in the transforms list, supply a factory 330 * method that takes the arguments of the transform, plus the local fields, 331 * and produce a value of the required type. 332 * You can override this to return null or throw if there are no transforms. 333 * This method exists so that the transforms can be "grown" lazily. 334 * This is necessary if the transform *adds* a field to an instance, 335 * which sometimtes requires the creation, on the fly, of an extended species. 336 * This method is only called once for any particular parameter. 337 * The species caches the result in a private array. 338 * 339 * @param transform the transform being implemented 340 * @param whichtm the index of that transform in the original list of transforms 341 * @return the method handle which creates a new result from a mix of transform 342 * arguments and field values 343 */ 344 protected abstract MethodHandle deriveTransformHelper(MemberName transform, int whichtm); 345 346 /** 347 * During code generation, this method is called once per transform to determine 348 * what is the mix of arguments to hand to the transform-helper. The bytecode 349 * which marshals these arguments is open-coded in the species-specific transform. 350 * The two lists are of opaque objects, which you shouldn't do anything with besides 351 * reordering them into the output list. (They are both mutable, to make editing 352 * easier.) The imputed types of the args correspond to the transform's parameter 353 * list, while the imputed types of the fields correspond to the species field types. 354 * After code generation, this method may be called occasionally by error-checking code. 355 * 356 * @param transform the transform being implemented 357 * @param whichtm the index of that transform in the original list of transforms 358 * @param args a list of opaque objects representing the incoming transform arguments 359 * @param fields a list of opaque objects representing the field values of the receiver 360 * @param <X> the common element type of the various lists 361 * @return a new list 362 */ 363 protected abstract <X> List<X> deriveTransformHelperArguments(MemberName transform, int whichtm, 364 List<X> args, List<X> fields); 365 366 /** Given a key, generate the name of the class which implements the species for that key. 367 * This algorithm must be stable. 368 * 369 * @return class name, which by default is {@code outer().topClass().getName() + "$Species_" + deriveTypeString(key)} 370 */ 371 protected String deriveClassName() { 372 return outer().topClass().getName() + "$Species_" + deriveTypeString(); 373 } 374 375 /** 376 * Default implementation collects basic type characters, 377 * plus possibly type names, if some types don't correspond 378 * to basic types. 379 * 380 * @return a string suitable for use in a class name 381 */ 382 protected String deriveTypeString() { 383 List<Class<?>> types = fieldTypes(); 384 StringBuilder buf = new StringBuilder(); 385 StringBuilder end = new StringBuilder(); 386 for (Class<?> type : types) { 387 BasicType basicType = BasicType.basicType(type); 388 if (basicType.basicTypeClass() == type) { 389 buf.append(basicType.basicTypeChar()); 390 } else { 391 buf.append('V'); 392 end.append(classSig(type)); 393 } 394 } 395 String typeString; 396 if (end.length() > 0) { 397 typeString = BytecodeName.toBytecodeName(buf.append("_").append(end).toString()); 398 } else { 399 typeString = buf.toString(); 400 } 401 return LambdaForm.shortenSignature(typeString); 402 } 403 404 /** 405 * Report what immediate super-class to use for the concrete class of this species. 406 * Normally this is {@code topClass}, but if that is an interface, the factory must override. 407 * The super-class must provide a constructor which takes the {@code baseConstructorType} arguments, if any. 408 * This hook also allows the code generator to use more than one canned supertype for species. 409 * 410 * @return the super-class of the class to be generated 411 */ 412 protected Class<? extends T> deriveSuperClass() { 413 final Class<T> topc = topClass(); 414 if (!topClassIsSuper) { 415 try { 416 final Constructor<T> con = reflectConstructor(topc, baseConstructorType().parameterArray()); 417 if (!topc.isInterface() && !Modifier.isPrivate(con.getModifiers())) { 418 topClassIsSuper = true; 419 } 420 } catch (Exception|InternalError ex) { 421 // fall through... 422 } 423 if (!topClassIsSuper) { 424 throw newInternalError("must override if the top class cannot serve as a super class"); 425 } 426 } 427 return topc; 428 } 429 } 430 431 protected abstract S newSpeciesData(K key); 432 433 protected K topSpeciesKey() { 434 return null; // null means don't report a top species 435 } 436 437 /** 438 * Code generation support for instances. 439 * Subclasses can modify the behavior. 440 */ 441 public class Factory { 442 /** 443 * Get a concrete subclass of the top class for a given combination of bound types. 444 * 445 * @param speciesData the species requiring the class, not yet linked 446 * @return a linked version of the same species 447 */ 448 S loadSpecies(S speciesData) { 449 String className = speciesData.deriveClassName(); 450 assert(className.indexOf('/') < 0) : className; 451 Class<?> salvage = null; 452 try { 453 salvage = BootLoader.loadClassOrNull(className); 454 if (TRACE_RESOLVE && salvage != null) { 455 // Used by jlink species pregeneration plugin, see 456 // jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin 457 System.out.println("[SPECIES_RESOLVE] " + className + " (salvaged)"); 458 } 459 } catch (Error ex) { 460 if (TRACE_RESOLVE) { 461 System.out.println("[SPECIES_FRESOLVE] " + className + " (Error) " + ex.getMessage()); 462 } 463 } 464 final Class<? extends T> speciesCode; 465 if (salvage != null) { 466 speciesCode = salvage.asSubclass(topClass()); 467 factory.linkSpeciesDataToCode(speciesData, speciesCode); 468 factory.linkCodeToSpeciesData(speciesCode, speciesData, true); 469 } else { 470 // Not pregenerated, generate the class 471 try { 472 speciesCode = generateConcreteSpeciesCode(className, speciesData); 473 if (TRACE_RESOLVE) { 474 // Used by jlink species pregeneration plugin, see 475 // jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin 476 System.out.println("[SPECIES_RESOLVE] " + className + " (generated)"); 477 } 478 // This operation causes a lot of churn: 479 linkSpeciesDataToCode(speciesData, speciesCode); 480 // This operation commits the relation, but causes little churn: 481 linkCodeToSpeciesData(speciesCode, speciesData, false); 482 } catch (Error ex) { 483 if (TRACE_RESOLVE) { 484 System.out.println("[SPECIES_RESOLVE] " + className + " (Error #2)" ); 485 } 486 // We can get here if there is a race condition loading a class. 487 // Or maybe we are out of resources. Back out of the CHM.get and retry. 488 throw ex; 489 } 490 } 491 492 if (!speciesData.isResolved()) { 493 throw newInternalError("bad species class linkage for " + className + ": " + speciesData); 494 } 495 assert(speciesData == factory.loadSpeciesDataFromCode(speciesCode)); 496 return speciesData; 497 } 498 499 /** 500 * Generate a concrete subclass of the top class for a given combination of bound types. 501 * 502 * A concrete species subclass roughly matches the following schema: 503 * 504 * <pre> 505 * class Species_[[types]] extends [[T]] { 506 * final [[S]] speciesData() { return ... } 507 * static [[T]] make([[fields]]) { return ... } 508 * [[fields]] 509 * final [[T]] transform([[args]]) { return ... } 510 * } 511 * </pre> 512 * 513 * The {@code [[types]]} signature is precisely the key for the species. 514 * 515 * The {@code [[fields]]} section consists of one field definition per character in 516 * the type signature, adhering to the naming schema described in the definition of 517 * {@link #chooseFieldName}. 518 * 519 * For example, a concrete species for two references and one integral bound value 520 * has a shape like the following: 521 * 522 * <pre> 523 * class TopClass { ... private static 524 * final class Species_LLI extends TopClass { 525 * final Object argL0; 526 * final Object argL1; 527 * final int argI2; 528 * private Species_LLI(CT ctarg, ..., Object argL0, Object argL1, int argI2) { 529 * super(ctarg, ...); 530 * this.argL0 = argL0; 531 * this.argL1 = argL1; 532 * this.argI2 = argI2; 533 * } 534 * final SpeciesData speciesData() { return BMH_SPECIES; } 535 * @Stable static SpeciesData BMH_SPECIES; // injected afterwards 536 * static TopClass make(CT ctarg, ..., Object argL0, Object argL1, int argI2) { 537 * return new Species_LLI(ctarg, ..., argL0, argL1, argI2); 538 * } 539 * final TopClass copyWith(CT ctarg, ...) { 540 * return new Species_LLI(ctarg, ..., argL0, argL1, argI2); 541 * } 542 * // two transforms, for the sake of illustration: 543 * final TopClass copyWithExtendL(CT ctarg, ..., Object narg) { 544 * return BMH_SPECIES.transform(L_TYPE).invokeBasic(ctarg, ..., argL0, argL1, argI2, narg); 545 * } 546 * final TopClass copyWithExtendI(CT ctarg, ..., int narg) { 547 * return BMH_SPECIES.transform(I_TYPE).invokeBasic(ctarg, ..., argL0, argL1, argI2, narg); 548 * } 549 * } 550 * </pre> 551 * 552 * @param className of the species 553 * @param speciesData what species we are generating 554 * @return the generated concrete TopClass class 555 */ 556 Class<? extends T> generateConcreteSpeciesCode(String className, ClassSpecializer<T,K,S>.SpeciesData speciesData) { 557 byte[] classFile = generateConcreteSpeciesCodeFile(className, speciesData); 558 559 // load class 560 InvokerBytecodeGenerator.maybeDump(classBCName(className), classFile); 561 Class<?> speciesCode; 562 563 ClassLoader cl = topClass().getClassLoader(); 564 ProtectionDomain pd = null; 565 if (cl != null) { 566 pd = AccessController.doPrivileged( 567 new PrivilegedAction<>() { 568 @Override 569 public ProtectionDomain run() { 570 return topClass().getProtectionDomain(); 571 } 572 }); 573 } 574 try { 575 speciesCode = UNSAFE.defineClass(className, classFile, 0, classFile.length, cl, pd); 576 } catch (Exception ex) { 577 throw newInternalError(ex); 578 } 579 580 return speciesCode.asSubclass(topClass()); 581 } 582 583 // These are named like constants because there is only one per specialization scheme: 584 private final String SPECIES_DATA = classBCName(metaType); 585 private final String SPECIES_DATA_SIG = classSig(SPECIES_DATA); 586 private final String SPECIES_DATA_NAME = sdAccessor.getName(); 587 private final int SPECIES_DATA_MODS = sdAccessor.getModifiers(); 588 private final List<String> TRANSFORM_NAMES; // derived from transformMethods 589 private final List<MethodType> TRANSFORM_TYPES; 590 private final List<Integer> TRANSFORM_MODS; 591 { 592 // Tear apart transformMethods to get the names, types, and modifiers. 593 List<String> tns = new ArrayList<>(); 594 List<MethodType> tts = new ArrayList<>(); 595 List<Integer> tms = new ArrayList<>(); 596 for (int i = 0; i < transformMethods.size(); i++) { 597 MemberName tm = transformMethods.get(i); 598 tns.add(tm.getName()); 599 final MethodType tt = tm.getMethodType(); 600 tts.add(tt); 601 tms.add(tm.getModifiers()); 602 } 603 TRANSFORM_NAMES = List.of(tns.toArray(new String[0])); 604 TRANSFORM_TYPES = List.of(tts.toArray(new MethodType[0])); 605 TRANSFORM_MODS = List.of(tms.toArray(new Integer[0])); 606 } 607 private static final int ACC_PPP = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED; 608 609 /*non-public*/ byte[] generateConcreteSpeciesCodeFile(String className0, ClassSpecializer<T,K,S>.SpeciesData speciesData) { 610 final String className = classBCName(className0); 611 final String superClassName = classBCName(speciesData.deriveSuperClass()); 612 613 final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 614 final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC 615 cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, superClassName, null); 616 617 final String sourceFile = className.substring(className.lastIndexOf('.')+1); 618 cw.visitSource(sourceFile, null); 619 620 // emit static types and BMH_SPECIES fields 621 FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, sdFieldName, SPECIES_DATA_SIG, null, null); 622 fw.visitAnnotation(STABLE_SIG, true); 623 fw.visitEnd(); 624 625 // handy holder for dealing with groups of typed values (ctor arguments and fields) 626 class Var { 627 final int index; 628 final String name; 629 final Class<?> type; 630 final String desc; 631 final BasicType basicType; 632 final int slotIndex; 633 Var(int index, int slotIndex) { 634 this.index = index; 635 this.slotIndex = slotIndex; 636 name = null; type = null; desc = null; 637 basicType = BasicType.V_TYPE; 638 } 639 Var(String name, Class<?> type, Var prev) { 640 int slotIndex = prev.nextSlotIndex(); 641 int index = prev.nextIndex(); 642 if (name == null) name = "x"; 643 if (name.endsWith("#")) 644 name = name.substring(0, name.length()-1) + index; 645 assert(!type.equals(void.class)); 646 String desc = classSig(type); 647 BasicType basicType = BasicType.basicType(type); 648 this.index = index; 649 this.name = name; 650 this.type = type; 651 this.desc = desc; 652 this.basicType = basicType; 653 this.slotIndex = slotIndex; 654 } 655 Var lastOf(List<Var> vars) { 656 int n = vars.size(); 657 return (n == 0 ? this : vars.get(n-1)); 658 } 659 <X> List<Var> fromTypes(List<X> types) { 660 Var prev = this; 661 ArrayList<Var> result = new ArrayList<>(types.size()); 662 int i = 0; 663 for (X x : types) { 664 String vn = name; 665 Class<?> vt; 666 if (x instanceof Class) { 667 vt = (Class<?>) x; 668 // make the names friendlier if debugging 669 assert((vn = vn + "_" + (i++)) != null); 670 } else { 671 @SuppressWarnings("unchecked") 672 Var v = (Var) x; 673 vn = v.name; 674 vt = v.type; 675 } 676 prev = new Var(vn, vt, prev); 677 result.add(prev); 678 } 679 return result; 680 } 681 682 int slotSize() { return basicType.basicTypeSlots(); } 683 int nextIndex() { return index + (slotSize() == 0 ? 0 : 1); } 684 int nextSlotIndex() { return slotIndex >= 0 ? slotIndex + slotSize() : slotIndex; } 685 boolean isInHeap() { return slotIndex < 0; } 686 void emitVarInstruction(int asmop, MethodVisitor mv) { 687 if (asmop == ALOAD) 688 asmop = typeLoadOp(basicType.basicTypeChar()); 689 else 690 throw new AssertionError("bad op="+asmop+" for desc="+desc); 691 mv.visitVarInsn(asmop, slotIndex); 692 } 693 public void emitFieldInsn(int asmop, MethodVisitor mv) { 694 mv.visitFieldInsn(asmop, className, name, desc); 695 } 696 } 697 698 final Var NO_THIS = new Var(0, 0), 699 AFTER_THIS = new Var(0, 1), 700 IN_HEAP = new Var(0, -1); 701 702 // figure out the field types 703 final List<Class<?>> fieldTypes = speciesData.fieldTypes(); 704 final List<Var> fields = new ArrayList<>(fieldTypes.size()); 705 { 706 Var nextF = IN_HEAP; 707 for (Class<?> ft : fieldTypes) { 708 String fn = chooseFieldName(ft, nextF.nextIndex()); 709 nextF = new Var(fn, ft, nextF); 710 fields.add(nextF); 711 } 712 } 713 714 // emit bound argument fields 715 for (Var field : fields) { 716 cw.visitField(ACC_FINAL, field.name, field.desc, null, null).visitEnd(); 717 } 718 719 MethodVisitor mv; 720 721 // emit implementation of speciesData() 722 mv = cw.visitMethod((SPECIES_DATA_MODS & ACC_PPP) + ACC_FINAL, 723 SPECIES_DATA_NAME, "()" + SPECIES_DATA_SIG, null, null); 724 mv.visitCode(); 725 mv.visitFieldInsn(GETSTATIC, className, sdFieldName, SPECIES_DATA_SIG); 726 mv.visitInsn(ARETURN); 727 mv.visitMaxs(0, 0); 728 mv.visitEnd(); 729 730 // figure out the constructor arguments 731 MethodType superCtorType = ClassSpecializer.this.baseConstructorType(); 732 MethodType thisCtorType = superCtorType.appendParameterTypes(fieldTypes); 733 734 // emit constructor 735 { 736 mv = cw.visitMethod(ACC_PRIVATE, 737 "<init>", methodSig(thisCtorType), null, null); 738 mv.visitCode(); 739 mv.visitVarInsn(ALOAD, 0); // this 740 741 final List<Var> ctorArgs = AFTER_THIS.fromTypes(superCtorType.parameterList()); 742 for (Var ca : ctorArgs) { 743 ca.emitVarInstruction(ALOAD, mv); 744 } 745 746 // super(ca...) 747 mv.visitMethodInsn(INVOKESPECIAL, superClassName, 748 "<init>", methodSig(superCtorType), false); 749 750 // store down fields 751 Var lastFV = AFTER_THIS.lastOf(ctorArgs); 752 for (Var f : fields) { 753 // this.argL1 = argL1 754 mv.visitVarInsn(ALOAD, 0); // this 755 lastFV = new Var(f.name, f.type, lastFV); 756 lastFV.emitVarInstruction(ALOAD, mv); 757 f.emitFieldInsn(PUTFIELD, mv); 758 } 759 760 mv.visitInsn(RETURN); 761 mv.visitMaxs(0, 0); 762 mv.visitEnd(); 763 } 764 765 // emit make() ...factory method wrapping constructor 766 { 767 MethodType ftryType = thisCtorType.changeReturnType(topClass()); 768 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, 769 "make", methodSig(ftryType), null, null); 770 mv.visitCode(); 771 // make instance 772 mv.visitTypeInsn(NEW, className); 773 mv.visitInsn(DUP); 774 // load factory method arguments: ctarg... and arg... 775 for (Var v : NO_THIS.fromTypes(ftryType.parameterList())) { 776 v.emitVarInstruction(ALOAD, mv); 777 } 778 779 // finally, invoke the constructor and return 780 mv.visitMethodInsn(INVOKESPECIAL, className, 781 "<init>", methodSig(thisCtorType), false); 782 mv.visitInsn(ARETURN); 783 mv.visitMaxs(0, 0); 784 mv.visitEnd(); 785 } 786 787 // For each transform, emit the customized override of the transform method. 788 // This method mixes together some incoming arguments (from the transform's 789 // static type signature) with the field types themselves, and passes 790 // the resulting mish-mosh of values to a method handle produced by 791 // the species itself. (Typically this method handle is the factory 792 // method of this species or a related one.) 793 for (int whichtm = 0; whichtm < TRANSFORM_NAMES.size(); whichtm++) { 794 final String TNAME = TRANSFORM_NAMES.get(whichtm); 795 final MethodType TTYPE = TRANSFORM_TYPES.get(whichtm); 796 final int TMODS = TRANSFORM_MODS.get(whichtm); 797 mv = cw.visitMethod((TMODS & ACC_PPP) | ACC_FINAL, 798 TNAME, TTYPE.toMethodDescriptorString(), null, E_THROWABLE); 799 mv.visitCode(); 800 // return a call to the corresponding "transform helper", something like this: 801 // MY_SPECIES.transformHelper(whichtm).invokeBasic(ctarg, ..., argL0, ..., xarg) 802 mv.visitFieldInsn(GETSTATIC, className, 803 sdFieldName, SPECIES_DATA_SIG); 804 emitIntConstant(whichtm, mv); 805 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, 806 "transformHelper", "(I)" + MH_SIG, false); 807 808 List<Var> targs = AFTER_THIS.fromTypes(TTYPE.parameterList()); 809 List<Var> tfields = new ArrayList<>(fields); 810 // mix them up and load them for the transform helper: 811 List<Var> helperArgs = speciesData.deriveTransformHelperArguments(transformMethods.get(whichtm), whichtm, targs, tfields); 812 List<Class<?>> helperTypes = new ArrayList<>(helperArgs.size()); 813 for (Var ha : helperArgs) { 814 helperTypes.add(ha.basicType.basicTypeClass()); 815 if (ha.isInHeap()) { 816 assert(tfields.contains(ha)); 817 mv.visitVarInsn(ALOAD, 0); 818 ha.emitFieldInsn(GETFIELD, mv); 819 } else { 820 assert(targs.contains(ha)); 821 ha.emitVarInstruction(ALOAD, mv); 822 } 823 } 824 825 // jump into the helper (which is probably a factory method) 826 final Class<?> rtype = TTYPE.returnType(); 827 final BasicType rbt = BasicType.basicType(rtype); 828 MethodType invokeBasicType = MethodType.methodType(rbt.basicTypeClass(), helperTypes); 829 mv.visitMethodInsn(INVOKEVIRTUAL, MH, 830 "invokeBasic", methodSig(invokeBasicType), false); 831 if (rbt == BasicType.L_TYPE) { 832 mv.visitTypeInsn(CHECKCAST, classBCName(rtype)); 833 mv.visitInsn(ARETURN); 834 } else { 835 throw newInternalError("NYI: transform of type "+rtype); 836 } 837 mv.visitMaxs(0, 0); 838 mv.visitEnd(); 839 } 840 841 cw.visitEnd(); 842 843 return cw.toByteArray(); 844 } 845 846 private int typeLoadOp(char t) { 847 switch (t) { 848 case 'L': return ALOAD; 849 case 'I': return ILOAD; 850 case 'J': return LLOAD; 851 case 'F': return FLOAD; 852 case 'D': return DLOAD; 853 default : throw newInternalError("unrecognized type " + t); 854 } 855 } 856 857 private void emitIntConstant(int con, MethodVisitor mv) { 858 if (ICONST_M1 - ICONST_0 <= con && con <= ICONST_5 - ICONST_0) 859 mv.visitInsn(ICONST_0 + con); 860 else if (con == (byte) con) 861 mv.visitIntInsn(BIPUSH, con); 862 else if (con == (short) con) 863 mv.visitIntInsn(SIPUSH, con); 864 else { 865 mv.visitLdcInsn(con); 866 } 867 868 } 869 870 // 871 // Getter MH generation. 872 // 873 874 private MethodHandle findGetter(Class<?> speciesCode, List<Class<?>> types, int index) { 875 Class<?> fieldType = types.get(index); 876 String fieldName = chooseFieldName(fieldType, index); 877 try { 878 return IMPL_LOOKUP.findGetter(speciesCode, fieldName, fieldType); 879 } catch (NoSuchFieldException | IllegalAccessException e) { 880 throw newInternalError(e); 881 } 882 } 883 884 private List<MethodHandle> findGetters(Class<?> speciesCode, List<Class<?>> types) { 885 MethodHandle[] mhs = new MethodHandle[types.size()]; 886 for (int i = 0; i < mhs.length; ++i) { 887 mhs[i] = findGetter(speciesCode, types, i); 888 assert(mhs[i].internalMemberName().getDeclaringClass() == speciesCode); 889 } 890 return List.of(mhs); 891 } 892 893 private List<MethodHandle> findFactories(Class<? extends T> speciesCode, List<Class<?>> types) { 894 MethodHandle[] mhs = new MethodHandle[1]; 895 mhs[0] = findFactory(speciesCode, types); 896 return List.of(mhs); 897 } 898 899 List<LambdaForm.NamedFunction> makeNominalGetters(List<Class<?>> types, List<MethodHandle> getters) { 900 LambdaForm.NamedFunction[] nfs = new LambdaForm.NamedFunction[types.size()]; 901 for (int i = 0; i < nfs.length; ++i) { 902 nfs[i] = new LambdaForm.NamedFunction(getters.get(i)); 903 } 904 return List.of(nfs); 905 } 906 907 // 908 // Auxiliary methods. 909 // 910 911 protected void linkSpeciesDataToCode(ClassSpecializer<T,K,S>.SpeciesData speciesData, Class<? extends T> speciesCode) { 912 speciesData.speciesCode = speciesCode.asSubclass(topClass); 913 final List<Class<?>> types = speciesData.fieldTypes; 914 speciesData.factories = this.findFactories(speciesCode, types); 915 speciesData.getters = this.findGetters(speciesCode, types); 916 speciesData.nominalGetters = this.makeNominalGetters(types, speciesData.getters); 917 } 918 919 private Field reflectSDField(Class<? extends T> speciesCode) { 920 final Field field = reflectField(speciesCode, sdFieldName); 921 assert(field.getType() == metaType); 922 assert(Modifier.isStatic(field.getModifiers())); 923 return field; 924 } 925 926 private S readSpeciesDataFromCode(Class<? extends T> speciesCode) { 927 try { 928 MemberName sdField = IMPL_LOOKUP.resolveOrFail(REF_getStatic, speciesCode, sdFieldName, metaType); 929 Object base = MethodHandleNatives.staticFieldBase(sdField); 930 long offset = MethodHandleNatives.staticFieldOffset(sdField); 931 UNSAFE.loadFence(); 932 return metaType.cast(UNSAFE.getObject(base, offset)); 933 } catch (Error err) { 934 throw err; 935 } catch (Exception ex) { 936 throw newInternalError("Failed to load speciesData from speciesCode: " + speciesCode.getName(), ex); 937 } catch (Throwable t) { 938 throw uncaughtException(t); 939 } 940 } 941 942 protected S loadSpeciesDataFromCode(Class<? extends T> speciesCode) { 943 if (speciesCode == topClass()) { 944 return topSpecies; 945 } 946 S result = readSpeciesDataFromCode(speciesCode); 947 if (result.outer() != ClassSpecializer.this) { 948 throw newInternalError("wrong class"); 949 } 950 return result; 951 } 952 953 protected void linkCodeToSpeciesData(Class<? extends T> speciesCode, ClassSpecializer<T,K,S>.SpeciesData speciesData, boolean salvage) { 954 try { 955 assert(readSpeciesDataFromCode(speciesCode) == null || 956 (salvage && readSpeciesDataFromCode(speciesCode).equals(speciesData))); 957 958 MemberName sdField = IMPL_LOOKUP.resolveOrFail(REF_putStatic, speciesCode, sdFieldName, metaType); 959 Object base = MethodHandleNatives.staticFieldBase(sdField); 960 long offset = MethodHandleNatives.staticFieldOffset(sdField); 961 UNSAFE.storeFence(); 962 UNSAFE.putObject(base, offset, speciesData); 963 UNSAFE.storeFence(); 964 } catch (Error err) { 965 throw err; 966 } catch (Exception ex) { 967 throw newInternalError("Failed to link speciesData to speciesCode: " + speciesCode.getName(), ex); 968 } catch (Throwable t) { 969 throw uncaughtException(t); 970 } 971 } 972 973 /** 974 * Field names in concrete species classes adhere to this pattern: 975 * type + index, where type is a single character (L, I, J, F, D). 976 * The factory subclass can customize this. 977 * The name is purely cosmetic, since it applies to a private field. 978 */ 979 protected String chooseFieldName(Class<?> type, int index) { 980 BasicType bt = BasicType.basicType(type); 981 return "" + bt.basicTypeChar() + index; 982 } 983 984 MethodHandle findFactory(Class<? extends T> speciesCode, List<Class<?>> types) { 985 final MethodType type = baseConstructorType().changeReturnType(topClass()).appendParameterTypes(types); 986 try { 987 return IMPL_LOOKUP.findStatic(speciesCode, "make", type); 988 } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) { 989 throw newInternalError(e); 990 } 991 } 992 } 993 994 /** Hook that virtualizes the Factory class, allowing subclasses to extend it. */ 995 protected Factory makeFactory() { 996 return new Factory(); 997 } 998 999 1000 // Other misc helpers: 1001 private static final String MH = "java/lang/invoke/MethodHandle"; 1002 private static final String MH_SIG = "L" + MH + ";"; 1003 private static final String STABLE = "jdk/internal/vm/annotation/Stable"; 1004 private static final String STABLE_SIG = "L" + STABLE + ";"; 1005 private static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" }; 1006 static { 1007 assert(MH_SIG.equals(classSig(MethodHandle.class))); 1008 assert(MH.equals(classBCName(MethodHandle.class))); 1009 } 1010 1011 static String methodSig(MethodType mt) { 1012 return mt.toMethodDescriptorString(); 1013 } 1014 static String classSig(Class<?> cls) { 1015 if (cls.isPrimitive() || cls.isArray()) 1016 return MethodType.methodType(cls).toMethodDescriptorString().substring(2); 1017 return classSig(classBCName(cls)); 1018 } 1019 static String classSig(String bcName) { 1020 assert(bcName.indexOf('.') < 0); 1021 assert(!bcName.endsWith(";")); 1022 assert(!bcName.startsWith("[")); 1023 return "L" + bcName + ";"; 1024 } 1025 static String classBCName(Class<?> cls) { 1026 return classBCName(className(cls)); 1027 } 1028 static String classBCName(String str) { 1029 assert(str.indexOf('/') < 0) : str; 1030 return str.replace('.', '/'); 1031 } 1032 static String className(Class<?> cls) { 1033 assert(!cls.isArray() && !cls.isPrimitive()); 1034 return cls.getName(); 1035 } 1036 }