1 /*
   2  * Copyright (c) 2008, 2017, 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.vm.annotation.Stable;
  29 import sun.invoke.util.ValueConversions;
  30 
  31 import java.util.ArrayList;
  32 import java.util.List;
  33 
  34 import static java.lang.invoke.LambdaForm.BasicType;
  35 import static java.lang.invoke.LambdaForm.BasicType.*;
  36 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE_NUM;
  37 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  38 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  39 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  40 import static java.lang.invoke.MethodHandleStatics.uncaughtException;
  41 
  42 /**
  43  * The flavor of method handle which emulates an invoke instruction
  44  * on a predetermined argument.  The JVM dispatches to the correct method
  45  * when the handle is created, not when it is invoked.
  46  *
  47  * All bound arguments are encapsulated in dedicated species.
  48  */
  49 /*non-public*/ abstract class BoundMethodHandle extends MethodHandle {
  50 
  51     /*non-public*/ BoundMethodHandle(MethodType type, LambdaForm form) {
  52         super(type, form);
  53         assert(speciesData() == speciesDataFor(form));
  54     }
  55 
  56     //
  57     // BMH API and internals
  58     //
  59 
  60     static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, BasicType xtype, Object x) {
  61         // for some type signatures, there exist pre-defined concrete BMH classes
  62         try {
  63             switch (xtype) {
  64             case L_TYPE:
  65                 return bindSingle(type, form, x);  // Use known fast path.
  66             case I_TYPE:
  67                 return (BoundMethodHandle) SPECIALIZER.topSpecies().extendWith(I_TYPE_NUM).factory().invokeBasic(type, form, ValueConversions.widenSubword(x));
  68             case J_TYPE:
  69                 return (BoundMethodHandle) SPECIALIZER.topSpecies().extendWith(J_TYPE_NUM).factory().invokeBasic(type, form, (long) x);
  70             case F_TYPE:
  71                 return (BoundMethodHandle) SPECIALIZER.topSpecies().extendWith(F_TYPE_NUM).factory().invokeBasic(type, form, (float) x);
  72             case D_TYPE:
  73                 return (BoundMethodHandle) SPECIALIZER.topSpecies().extendWith(D_TYPE_NUM).factory().invokeBasic(type, form, (double) x);
  74             default : throw newInternalError("unexpected xtype: " + xtype);
  75             }
  76         } catch (Throwable t) {
  77             throw uncaughtException(t);
  78         }
  79     }
  80 
  81     /*non-public*/
  82     LambdaFormEditor editor() {
  83         return form.editor();
  84     }
  85 
  86     static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, Object x) {
  87         return Species_L.make(type, form, x);
  88     }
  89 
  90     @Override // there is a default binder in the super class, for 'L' types only
  91     /*non-public*/
  92     BoundMethodHandle bindArgumentL(int pos, Object value) {
  93         return editor().bindArgumentL(this, pos, value);
  94     }
  95 
  96     /*non-public*/
  97     BoundMethodHandle bindArgumentI(int pos, int value) {
  98         return editor().bindArgumentI(this, pos, value);
  99     }
 100     /*non-public*/
 101     BoundMethodHandle bindArgumentJ(int pos, long value) {
 102         return editor().bindArgumentJ(this, pos, value);
 103     }
 104     /*non-public*/
 105     BoundMethodHandle bindArgumentF(int pos, float value) {
 106         return editor().bindArgumentF(this, pos, value);
 107     }
 108     /*non-public*/
 109     BoundMethodHandle bindArgumentD(int pos, double value) {
 110         return editor().bindArgumentD(this, pos, value);
 111     }
 112     @Override
 113     BoundMethodHandle rebind() {
 114         if (!tooComplex()) {
 115             return this;
 116         }
 117         return makeReinvoker(this);
 118     }
 119 
 120     private boolean tooComplex() {
 121         return (fieldCount() > FIELD_COUNT_THRESHOLD ||
 122                 form.expressionCount() > FORM_EXPRESSION_THRESHOLD);
 123     }
 124     private static final int FIELD_COUNT_THRESHOLD = 12;      // largest convenient BMH field count
 125     private static final int FORM_EXPRESSION_THRESHOLD = 24;  // largest convenient BMH expression count
 126 
 127     /**
 128      * A reinvoker MH has this form:
 129      * {@code lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) }}
 130      */
 131     static BoundMethodHandle makeReinvoker(MethodHandle target) {
 132         LambdaForm form = DelegatingMethodHandle.makeReinvokerForm(
 133                 target, MethodTypeForm.LF_REBIND,
 134                 Species_L.BMH_SPECIES, Species_L.BMH_SPECIES.getterFunction(0));
 135         return Species_L.make(target.type(), form, target);
 136     }
 137 
 138     /**
 139      * Return the {@link BoundMethodHandle.SpeciesData} instance representing this BMH species. All subclasses must provide a
 140      * static field containing this value, and they must accordingly implement this method.
 141      */
 142     /*non-public*/ abstract BoundMethodHandle.SpeciesData speciesData();
 143 
 144     /*non-public*/ static BoundMethodHandle.SpeciesData speciesDataFor(LambdaForm form) {
 145         Object c = form.names[0].constraint;
 146         if (c instanceof SpeciesData) {
 147             return (SpeciesData) c;
 148         }
 149         // if there is no BMH constraint, then use the null constraint
 150         return SPECIALIZER.topSpecies();
 151     }
 152 
 153     /**
 154      * Return the number of fields in this BMH.  Equivalent to speciesData().fieldCount().
 155      */
 156     /*non-public*/ final int fieldCount() { return speciesData().fieldCount(); }
 157 
 158     @Override
 159     Object internalProperties() {
 160         return "\n& BMH="+internalValues();
 161     }
 162 
 163     @Override
 164     final String internalValues() {
 165         int count = fieldCount();
 166         if (count == 1) {
 167             return "[" + arg(0) + "]";
 168         }
 169         StringBuilder sb = new StringBuilder("[");
 170         for (int i = 0; i < count; ++i) {
 171             sb.append("\n  ").append(i).append(": ( ").append(arg(i)).append(" )");
 172         }
 173         return sb.append("\n]").toString();
 174     }
 175 
 176     /*non-public*/ final Object arg(int i) {
 177         try {
 178             Class<?> fieldType = speciesData().fieldTypes().get(i);
 179             switch (BasicType.basicType(fieldType)) {
 180                 case L_TYPE: return          speciesData().getter(i).invokeBasic(this);
 181                 case I_TYPE: return (int)    speciesData().getter(i).invokeBasic(this);
 182                 case J_TYPE: return (long)   speciesData().getter(i).invokeBasic(this);
 183                 case F_TYPE: return (float)  speciesData().getter(i).invokeBasic(this);
 184                 case D_TYPE: return (double) speciesData().getter(i).invokeBasic(this);
 185             }
 186         } catch (Throwable ex) {
 187             throw uncaughtException(ex);
 188         }
 189         throw new InternalError("unexpected type: " + speciesData().key()+"."+i);
 190     }
 191 
 192     //
 193     // cloning API
 194     //
 195 
 196     /*non-public*/ abstract BoundMethodHandle copyWith(MethodType mt, LambdaForm lf);
 197     /*non-public*/ abstract BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg);
 198     /*non-public*/ abstract BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int    narg);
 199     /*non-public*/ abstract BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long   narg);
 200     /*non-public*/ abstract BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float  narg);
 201     /*non-public*/ abstract BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg);
 202 
 203     //
 204     // concrete BMH classes required to close bootstrap loops
 205     //
 206 
 207     private  // make it private to force users to access the enclosing class first
 208     static final class Species_L extends BoundMethodHandle {
 209 
 210         final Object argL0;
 211 
 212         private Species_L(MethodType mt, LambdaForm lf, Object argL0) {
 213             super(mt, lf);
 214             this.argL0 = argL0;
 215         }
 216 
 217         @Override
 218         /*non-public*/ SpeciesData speciesData() {
 219             return BMH_SPECIES;
 220         }
 221 
 222         /*non-public*/ static @Stable SpeciesData BMH_SPECIES;
 223 
 224         /*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) {
 225             return new Species_L(mt, lf, argL0);
 226         }
 227         @Override
 228         /*non-public*/ final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
 229             return new Species_L(mt, lf, argL0);
 230         }
 231         @Override
 232         /*non-public*/ final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
 233             try {
 234                 return (BoundMethodHandle) BMH_SPECIES.extendWith(L_TYPE_NUM).factory().invokeBasic(mt, lf, argL0, narg);
 235             } catch (Throwable ex) {
 236                 throw uncaughtException(ex);
 237             }
 238         }
 239         @Override
 240         /*non-public*/ final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
 241             try {
 242                 return (BoundMethodHandle) BMH_SPECIES.extendWith(I_TYPE_NUM).factory().invokeBasic(mt, lf, argL0, narg);
 243             } catch (Throwable ex) {
 244                 throw uncaughtException(ex);
 245             }
 246         }
 247         @Override
 248         /*non-public*/ final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
 249             try {
 250                 return (BoundMethodHandle) BMH_SPECIES.extendWith(J_TYPE_NUM).factory().invokeBasic(mt, lf, argL0, narg);
 251             } catch (Throwable ex) {
 252                 throw uncaughtException(ex);
 253             }
 254         }
 255         @Override
 256         /*non-public*/ final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
 257             try {
 258                 return (BoundMethodHandle) BMH_SPECIES.extendWith(F_TYPE_NUM).factory().invokeBasic(mt, lf, argL0, narg);
 259             } catch (Throwable ex) {
 260                 throw uncaughtException(ex);
 261             }
 262         }
 263         @Override
 264         /*non-public*/ final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
 265             try {
 266                 return (BoundMethodHandle) BMH_SPECIES.extendWith(D_TYPE_NUM).factory().invokeBasic(mt, lf, argL0, narg);
 267             } catch (Throwable ex) {
 268                 throw uncaughtException(ex);
 269             }
 270         }
 271     }
 272 
 273     //
 274     // BMH species meta-data
 275     //
 276 
 277     /*non-public*/
 278     static final class SpeciesData extends ClassSpecializer<BoundMethodHandle, String, SpeciesData>.SpeciesData {
 279         // This array is filled in lazily, as new species come into being over time.
 280         @Stable final private SpeciesData[] extensions = new SpeciesData[ARG_TYPE_LIMIT];
 281 
 282         public SpeciesData(Specializer outer, String key) {
 283             outer.super(key);
 284         }
 285 
 286         @Override
 287         protected String deriveClassName() {
 288             String typeString = deriveTypeString();
 289             if (typeString.isEmpty()) {
 290                 return SimpleMethodHandle.class.getName();
 291             }
 292             return BoundMethodHandle.class.getName() + "$Species_" + typeString;
 293         }
 294 
 295         @Override
 296         protected List<Class<?>> deriveFieldTypes(String key) {
 297             ArrayList<Class<?>> types = new ArrayList<>(key.length());
 298             for (int i = 0; i < key.length(); i++) {
 299                 types.add(basicType(key.charAt(i)).basicTypeClass());
 300             }
 301             return types;
 302         }
 303 
 304         @Override
 305         protected String deriveTypeString() {
 306             // (If/when we have to add nominal types, just inherit the more complex default.)
 307             return key();
 308         }
 309 
 310         @Override
 311         protected MethodHandle deriveTransformHelper(MemberName transform, int whichtm) {
 312             if (whichtm == Specializer.TN_COPY_NO_EXTEND) {
 313                 return factory();
 314             } else if (whichtm < ARG_TYPE_LIMIT) {
 315                 return extendWith((byte) whichtm).factory();
 316             } else {
 317                 throw newInternalError("bad transform");
 318             }
 319         }
 320 
 321         @Override
 322         protected <X> List<X> deriveTransformHelperArguments(MemberName transform, int whichtm, List<X> args, List<X> fields) {
 323             assert(verifyTHAargs(transform, whichtm, args, fields));
 324             // The rule is really simple:  Keep the first two arguments
 325             // the same, then put in the fields, then put any other argument.
 326             args.addAll(2, fields);
 327             return args;
 328         }
 329 
 330         private boolean verifyTHAargs(MemberName transform, int whichtm, List<?> args, List<?> fields) {
 331             assert(transform == Specializer.BMH_TRANSFORMS.get(whichtm));
 332             assert(args.size() == transform.getMethodType().parameterCount());
 333             assert(fields.size() == this.fieldCount());
 334             final int MH_AND_LF = 2;
 335             if (whichtm == Specializer.TN_COPY_NO_EXTEND) {
 336                 assert(transform.getMethodType().parameterCount() == MH_AND_LF);
 337             } else if (whichtm < ARG_TYPE_LIMIT) {
 338                 assert(transform.getMethodType().parameterCount() == MH_AND_LF+1);
 339                 final BasicType type = basicType((byte) whichtm);
 340                 assert(transform.getParameterTypes()[MH_AND_LF] == type.basicTypeClass());
 341             } else {
 342                 return false;
 343             }
 344             return true;
 345         }
 346 
 347         /*non-public*/ SpeciesData extendWith(byte typeNum) {
 348             SpeciesData sd = extensions[typeNum];
 349             if (sd != null)  return sd;
 350             sd = SPECIALIZER.findSpecies(key() + BasicType.basicType(typeNum).basicTypeChar());
 351             extensions[typeNum] = sd;
 352             return sd;
 353         }
 354     }
 355 
 356     /*non-public*/
 357     static final Specializer SPECIALIZER = new Specializer();
 358     static {
 359         SimpleMethodHandle.BMH_SPECIES = BoundMethodHandle.SPECIALIZER.findSpecies("");
 360         Species_L.BMH_SPECIES = BoundMethodHandle.SPECIALIZER.findSpecies("L");
 361     }
 362 
 363     /*non-public*/
 364     static final class Specializer extends ClassSpecializer<BoundMethodHandle, String, SpeciesData> {
 365 
 366         private static final MemberName SPECIES_DATA_ACCESSOR;
 367 
 368         static {
 369             try {
 370                 SPECIES_DATA_ACCESSOR = IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BoundMethodHandle.class,
 371                         "speciesData", MethodType.methodType(BoundMethodHandle.SpeciesData.class));
 372             } catch (ReflectiveOperationException ex) {
 373                 throw newInternalError("Bootstrap link error", ex);
 374             }
 375         }
 376 
 377         private Specializer() {
 378             super(  // Reified type parameters:
 379                     BoundMethodHandle.class, String.class, BoundMethodHandle.SpeciesData.class,
 380                     // Principal constructor type:
 381                     MethodType.methodType(void.class, MethodType.class, LambdaForm.class),
 382                     // Required linkage between class and species:
 383                     SPECIES_DATA_ACCESSOR,
 384                     "BMH_SPECIES",
 385                     BMH_TRANSFORMS);
 386         }
 387 
 388         @Override
 389         protected String topSpeciesKey() {
 390             return "";
 391         }
 392 
 393         @Override
 394         protected BoundMethodHandle.SpeciesData newSpeciesData(String key) {
 395             return new BoundMethodHandle.SpeciesData(this, key);
 396         }
 397 
 398         static final List<MemberName> BMH_TRANSFORMS;
 399         static final int TN_COPY_NO_EXTEND = V_TYPE_NUM;
 400         static {
 401             final Class<BoundMethodHandle> BMH = BoundMethodHandle.class;
 402             // copyWithExtendLIJFD + copyWith
 403             try {
 404                 BMH_TRANSFORMS = List.of(
 405                         IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BMH, "copyWithExtendL", MethodType.methodType(BMH, MethodType.class, LambdaForm.class, Object.class)),
 406                         IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BMH, "copyWithExtendI", MethodType.methodType(BMH, MethodType.class, LambdaForm.class, int.class)),
 407                         IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BMH, "copyWithExtendJ", MethodType.methodType(BMH, MethodType.class, LambdaForm.class, long.class)),
 408                         IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BMH, "copyWithExtendF", MethodType.methodType(BMH, MethodType.class, LambdaForm.class, float.class)),
 409                         IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BMH, "copyWithExtendD", MethodType.methodType(BMH, MethodType.class, LambdaForm.class, double.class)),
 410                         IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, BMH, "copyWith", MethodType.methodType(BMH, MethodType.class, LambdaForm.class))
 411                 );
 412             } catch (ReflectiveOperationException ex) {
 413                 throw newInternalError("Failed resolving copyWith methods", ex);
 414             }
 415 
 416             // as it happens, there is one transform per BasicType including V_TYPE
 417             assert(BMH_TRANSFORMS.size() == TYPE_LIMIT);
 418         }
 419 
 420         /**
 421          * Generation of concrete BMH classes.
 422          *
 423          * A concrete BMH species is fit for binding a number of values adhering to a
 424          * given type pattern. Reference types are erased.
 425          *
 426          * BMH species are cached by type pattern.
 427          *
 428          * A BMH species has a number of fields with the concrete (possibly erased) types of
 429          * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,
 430          * which can be included as names in lambda forms.
 431          */
 432         class Factory extends ClassSpecializer<BoundMethodHandle, String, BoundMethodHandle.SpeciesData>.Factory {
 433             @Override
 434             protected String chooseFieldName(Class<?> type, int index) {
 435                 return "arg" + super.chooseFieldName(type, index);
 436             }
 437         }
 438 
 439         @Override
 440         protected Factory makeFactory() {
 441             return new Factory();
 442         }
 443       }
 444 
 445     static SpeciesData speciesData_L()      { return Species_L.BMH_SPECIES; }
 446     static SpeciesData speciesData_LL()     { return SPECIALIZER.findSpecies("LL"); }
 447     static SpeciesData speciesData_LLL()    { return SPECIALIZER.findSpecies("LLL"); }
 448     static SpeciesData speciesData_LLLL()   { return SPECIALIZER.findSpecies("LLLL"); }
 449     static SpeciesData speciesData_LLLLL()  { return SPECIALIZER.findSpecies("LLLLL"); }
 450 }