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