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