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