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