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