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