rt/emul/compact/src/main/java/java/lang/invoke/CallSite.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 06:13:36 +0200
branchjdk8
changeset 1651 5c990ed353e9
parent 1646 c880a8a8803b
permissions -rw-r--r--
Almost compiled java.lang.invoke, except the parts that deal with Asm bytecode generator
jaroslav@1646
     1
/*
jaroslav@1646
     2
 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1646
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1646
     4
 *
jaroslav@1646
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1646
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1646
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1646
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1646
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1646
    10
 *
jaroslav@1646
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1646
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1646
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1646
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1646
    15
 * accompanied this code).
jaroslav@1646
    16
 *
jaroslav@1646
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1646
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1646
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1646
    20
 *
jaroslav@1646
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1646
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1646
    23
 * questions.
jaroslav@1646
    24
 */
jaroslav@1646
    25
jaroslav@1646
    26
package java.lang.invoke;
jaroslav@1646
    27
jaroslav@1646
    28
import sun.invoke.empty.Empty;
jaroslav@1646
    29
import static java.lang.invoke.MethodHandleStatics.*;
jaroslav@1646
    30
import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
jaroslav@1646
    31
jaroslav@1646
    32
/**
jaroslav@1646
    33
 * A {@code CallSite} is a holder for a variable {@link MethodHandle},
jaroslav@1646
    34
 * which is called its {@code target}.
jaroslav@1646
    35
 * An {@code invokedynamic} instruction linked to a {@code CallSite} delegates
jaroslav@1646
    36
 * all calls to the site's current target.
jaroslav@1646
    37
 * A {@code CallSite} may be associated with several {@code invokedynamic}
jaroslav@1646
    38
 * instructions, or it may be "free floating", associated with none.
jaroslav@1646
    39
 * In any case, it may be invoked through an associated method handle
jaroslav@1646
    40
 * called its {@linkplain #dynamicInvoker dynamic invoker}.
jaroslav@1646
    41
 * <p>
jaroslav@1646
    42
 * {@code CallSite} is an abstract class which does not allow
jaroslav@1646
    43
 * direct subclassing by users.  It has three immediate,
jaroslav@1646
    44
 * concrete subclasses that may be either instantiated or subclassed.
jaroslav@1646
    45
 * <ul>
jaroslav@1646
    46
 * <li>If a mutable target is not required, an {@code invokedynamic} instruction
jaroslav@1646
    47
 * may be permanently bound by means of a {@linkplain ConstantCallSite constant call site}.
jaroslav@1646
    48
 * <li>If a mutable target is required which has volatile variable semantics,
jaroslav@1646
    49
 * because updates to the target must be immediately and reliably witnessed by other threads,
jaroslav@1646
    50
 * a {@linkplain VolatileCallSite volatile call site} may be used.
jaroslav@1646
    51
 * <li>Otherwise, if a mutable target is required,
jaroslav@1646
    52
 * a {@linkplain MutableCallSite mutable call site} may be used.
jaroslav@1646
    53
 * </ul>
jaroslav@1646
    54
 * <p>
jaroslav@1646
    55
 * A non-constant call site may be <em>relinked</em> by changing its target.
jaroslav@1646
    56
 * The new target must have the same {@linkplain MethodHandle#type() type}
jaroslav@1646
    57
 * as the previous target.
jaroslav@1646
    58
 * Thus, though a call site can be relinked to a series of
jaroslav@1646
    59
 * successive targets, it cannot change its type.
jaroslav@1646
    60
 * <p>
jaroslav@1646
    61
 * Here is a sample use of call sites and bootstrap methods which links every
jaroslav@1646
    62
 * dynamic call site to print its arguments:
jaroslav@1646
    63
<blockquote><pre>{@code
jaroslav@1646
    64
static void test() throws Throwable {
jaroslav@1646
    65
    // THE FOLLOWING LINE IS PSEUDOCODE FOR A JVM INSTRUCTION
jaroslav@1646
    66
    InvokeDynamic[#bootstrapDynamic].baz("baz arg", 2, 3.14);
jaroslav@1646
    67
}
jaroslav@1646
    68
private static void printArgs(Object... args) {
jaroslav@1646
    69
  System.out.println(java.util.Arrays.deepToString(args));
jaroslav@1646
    70
}
jaroslav@1646
    71
private static final MethodHandle printArgs;
jaroslav@1646
    72
static {
jaroslav@1646
    73
  MethodHandles.Lookup lookup = MethodHandles.lookup();
jaroslav@1646
    74
  Class thisClass = lookup.lookupClass();  // (who am I?)
jaroslav@1646
    75
  printArgs = lookup.findStatic(thisClass,
jaroslav@1646
    76
      "printArgs", MethodType.methodType(void.class, Object[].class));
jaroslav@1646
    77
}
jaroslav@1646
    78
private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String name, MethodType type) {
jaroslav@1646
    79
  // ignore caller and name, but match the type:
jaroslav@1646
    80
  return new ConstantCallSite(printArgs.asType(type));
jaroslav@1646
    81
}
jaroslav@1646
    82
}</pre></blockquote>
jaroslav@1646
    83
 * @author John Rose, JSR 292 EG
jaroslav@1646
    84
 */
jaroslav@1646
    85
abstract
jaroslav@1646
    86
public class CallSite {
jaroslav@1646
    87
    static { MethodHandleImpl.initStatics(); }
jaroslav@1646
    88
jaroslav@1646
    89
    // The actual payload of this call site:
jaroslav@1646
    90
    /*package-private*/
jaroslav@1646
    91
    MethodHandle target;    // Note: This field is known to the JVM.  Do not change.
jaroslav@1646
    92
jaroslav@1646
    93
    /**
jaroslav@1646
    94
     * Make a blank call site object with the given method type.
jaroslav@1646
    95
     * An initial target method is supplied which will throw
jaroslav@1646
    96
     * an {@link IllegalStateException} if called.
jaroslav@1646
    97
     * <p>
jaroslav@1646
    98
     * Before this {@code CallSite} object is returned from a bootstrap method,
jaroslav@1646
    99
     * it is usually provided with a more useful target method,
jaroslav@1646
   100
     * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
jaroslav@1646
   101
     * @throws NullPointerException if the proposed type is null
jaroslav@1646
   102
     */
jaroslav@1646
   103
    /*package-private*/
jaroslav@1646
   104
    CallSite(MethodType type) {
jaroslav@1646
   105
        target = type.invokers().uninitializedCallSite();
jaroslav@1646
   106
    }
jaroslav@1646
   107
jaroslav@1646
   108
    /**
jaroslav@1646
   109
     * Make a call site object equipped with an initial target method handle.
jaroslav@1646
   110
     * @param target the method handle which will be the initial target of the call site
jaroslav@1646
   111
     * @throws NullPointerException if the proposed target is null
jaroslav@1646
   112
     */
jaroslav@1646
   113
    /*package-private*/
jaroslav@1646
   114
    CallSite(MethodHandle target) {
jaroslav@1646
   115
        target.type();  // null check
jaroslav@1646
   116
        this.target = target;
jaroslav@1646
   117
    }
jaroslav@1646
   118
jaroslav@1646
   119
    /**
jaroslav@1646
   120
     * Make a call site object equipped with an initial target method handle.
jaroslav@1646
   121
     * @param targetType the desired type of the call site
jaroslav@1646
   122
     * @param createTargetHook a hook which will bind the call site to the target method handle
jaroslav@1646
   123
     * @throws WrongMethodTypeException if the hook cannot be invoked on the required arguments,
jaroslav@1646
   124
     *         or if the target returned by the hook is not of the given {@code targetType}
jaroslav@1646
   125
     * @throws NullPointerException if the hook returns a null value
jaroslav@1646
   126
     * @throws ClassCastException if the hook returns something other than a {@code MethodHandle}
jaroslav@1646
   127
     * @throws Throwable anything else thrown by the hook function
jaroslav@1646
   128
     */
jaroslav@1646
   129
    /*package-private*/
jaroslav@1646
   130
    CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable {
jaroslav@1646
   131
        this(targetType);
jaroslav@1646
   132
        ConstantCallSite selfCCS = (ConstantCallSite) this;
jaroslav@1646
   133
        MethodHandle boundTarget = (MethodHandle) createTargetHook.invokeWithArguments(selfCCS);
jaroslav@1646
   134
        checkTargetChange(this.target, boundTarget);
jaroslav@1646
   135
        this.target = boundTarget;
jaroslav@1646
   136
    }
jaroslav@1646
   137
jaroslav@1646
   138
    /**
jaroslav@1646
   139
     * Returns the type of this call site's target.
jaroslav@1646
   140
     * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
jaroslav@1646
   141
     * The {@code setTarget} method enforces this invariant by refusing any new target that does
jaroslav@1646
   142
     * not have the previous target's type.
jaroslav@1646
   143
     * @return the type of the current target, which is also the type of any future target
jaroslav@1646
   144
     */
jaroslav@1646
   145
    public MethodType type() {
jaroslav@1646
   146
        // warning:  do not call getTarget here, because CCS.getTarget can throw IllegalStateException
jaroslav@1646
   147
        return target.type();
jaroslav@1646
   148
    }
jaroslav@1646
   149
jaroslav@1646
   150
    /**
jaroslav@1646
   151
     * Returns the target method of the call site, according to the
jaroslav@1646
   152
     * behavior defined by this call site's specific class.
jaroslav@1646
   153
     * The immediate subclasses of {@code CallSite} document the
jaroslav@1646
   154
     * class-specific behaviors of this method.
jaroslav@1646
   155
     *
jaroslav@1646
   156
     * @return the current linkage state of the call site, its target method handle
jaroslav@1646
   157
     * @see ConstantCallSite
jaroslav@1646
   158
     * @see VolatileCallSite
jaroslav@1646
   159
     * @see #setTarget
jaroslav@1646
   160
     * @see ConstantCallSite#getTarget
jaroslav@1646
   161
     * @see MutableCallSite#getTarget
jaroslav@1646
   162
     * @see VolatileCallSite#getTarget
jaroslav@1646
   163
     */
jaroslav@1646
   164
    public abstract MethodHandle getTarget();
jaroslav@1646
   165
jaroslav@1646
   166
    /**
jaroslav@1646
   167
     * Updates the target method of this call site, according to the
jaroslav@1646
   168
     * behavior defined by this call site's specific class.
jaroslav@1646
   169
     * The immediate subclasses of {@code CallSite} document the
jaroslav@1646
   170
     * class-specific behaviors of this method.
jaroslav@1646
   171
     * <p>
jaroslav@1646
   172
     * The type of the new target must be {@linkplain MethodType#equals equal to}
jaroslav@1646
   173
     * the type of the old target.
jaroslav@1646
   174
     *
jaroslav@1646
   175
     * @param newTarget the new target
jaroslav@1646
   176
     * @throws NullPointerException if the proposed new target is null
jaroslav@1646
   177
     * @throws WrongMethodTypeException if the proposed new target
jaroslav@1646
   178
     *         has a method type that differs from the previous target
jaroslav@1646
   179
     * @see CallSite#getTarget
jaroslav@1646
   180
     * @see ConstantCallSite#setTarget
jaroslav@1646
   181
     * @see MutableCallSite#setTarget
jaroslav@1646
   182
     * @see VolatileCallSite#setTarget
jaroslav@1646
   183
     */
jaroslav@1646
   184
    public abstract void setTarget(MethodHandle newTarget);
jaroslav@1646
   185
jaroslav@1646
   186
    void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
jaroslav@1646
   187
        MethodType oldType = oldTarget.type();
jaroslav@1646
   188
        MethodType newType = newTarget.type();  // null check!
jaroslav@1646
   189
        if (!newType.equals(oldType))
jaroslav@1646
   190
            throw wrongTargetType(newTarget, oldType);
jaroslav@1646
   191
    }
jaroslav@1646
   192
jaroslav@1646
   193
    private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
jaroslav@1646
   194
        return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
jaroslav@1646
   195
    }
jaroslav@1646
   196
jaroslav@1646
   197
    /**
jaroslav@1646
   198
     * Produces a method handle equivalent to an invokedynamic instruction
jaroslav@1646
   199
     * which has been linked to this call site.
jaroslav@1646
   200
     * <p>
jaroslav@1646
   201
     * This method is equivalent to the following code:
jaroslav@1646
   202
     * <blockquote><pre>{@code
jaroslav@1646
   203
     * MethodHandle getTarget, invoker, result;
jaroslav@1646
   204
     * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
jaroslav@1646
   205
     * invoker = MethodHandles.exactInvoker(this.type());
jaroslav@1646
   206
     * result = MethodHandles.foldArguments(invoker, getTarget)
jaroslav@1646
   207
     * }</pre></blockquote>
jaroslav@1646
   208
     *
jaroslav@1646
   209
     * @return a method handle which always invokes this call site's current target
jaroslav@1646
   210
     */
jaroslav@1646
   211
    public abstract MethodHandle dynamicInvoker();
jaroslav@1646
   212
jaroslav@1646
   213
    /*non-public*/ MethodHandle makeDynamicInvoker() {
jaroslav@1646
   214
        MethodHandle getTarget = GET_TARGET.bindReceiver(this);
jaroslav@1646
   215
        MethodHandle invoker = MethodHandles.exactInvoker(this.type());
jaroslav@1646
   216
        return MethodHandles.foldArguments(invoker, getTarget);
jaroslav@1646
   217
    }
jaroslav@1646
   218
jaroslav@1646
   219
    private static final MethodHandle GET_TARGET;
jaroslav@1646
   220
    static {
jaroslav@1646
   221
        try {
jaroslav@1646
   222
            GET_TARGET = IMPL_LOOKUP.
jaroslav@1646
   223
                findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
jaroslav@1646
   224
        } catch (ReflectiveOperationException e) {
jaroslav@1646
   225
            throw newInternalError(e);
jaroslav@1646
   226
        }
jaroslav@1646
   227
    }
jaroslav@1646
   228
jaroslav@1646
   229
    /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
jaroslav@1646
   230
    /*package-private*/
jaroslav@1646
   231
    static Empty uninitializedCallSite() {
jaroslav@1646
   232
        throw new IllegalStateException("uninitialized call site");
jaroslav@1646
   233
    }
jaroslav@1646
   234
jaroslav@1646
   235
    /*package-private*/
jaroslav@1646
   236
    void setTargetNormal(MethodHandle newTarget) {
jaroslav@1646
   237
        MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
jaroslav@1646
   238
    }
jaroslav@1646
   239
    /*package-private*/
jaroslav@1646
   240
    MethodHandle getTargetVolatile() {
jaroslav@1651
   241
        return target;
jaroslav@1646
   242
    }
jaroslav@1646
   243
    /*package-private*/
jaroslav@1646
   244
    void setTargetVolatile(MethodHandle newTarget) {
jaroslav@1646
   245
        MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
jaroslav@1646
   246
    }
jaroslav@1646
   247
jaroslav@1646
   248
    // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
jaroslav@1646
   249
    static CallSite makeSite(MethodHandle bootstrapMethod,
jaroslav@1646
   250
                             // Callee information:
jaroslav@1646
   251
                             String name, MethodType type,
jaroslav@1646
   252
                             // Extra arguments for BSM, if any:
jaroslav@1646
   253
                             Object info,
jaroslav@1646
   254
                             // Caller information:
jaroslav@1646
   255
                             Class<?> callerClass) {
jaroslav@1646
   256
        MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
jaroslav@1646
   257
        CallSite site;
jaroslav@1646
   258
        try {
jaroslav@1646
   259
            Object binding;
jaroslav@1646
   260
            info = maybeReBox(info);
jaroslav@1646
   261
            if (info == null) {
jaroslav@1646
   262
                binding = bootstrapMethod.invoke(caller, name, type);
jaroslav@1646
   263
            } else if (!info.getClass().isArray()) {
jaroslav@1646
   264
                binding = bootstrapMethod.invoke(caller, name, type, info);
jaroslav@1646
   265
            } else {
jaroslav@1646
   266
                Object[] argv = (Object[]) info;
jaroslav@1646
   267
                maybeReBoxElements(argv);
jaroslav@1646
   268
                switch (argv.length) {
jaroslav@1646
   269
                case 0:
jaroslav@1646
   270
                    binding = bootstrapMethod.invoke(caller, name, type);
jaroslav@1646
   271
                    break;
jaroslav@1646
   272
                case 1:
jaroslav@1646
   273
                    binding = bootstrapMethod.invoke(caller, name, type,
jaroslav@1646
   274
                                                     argv[0]);
jaroslav@1646
   275
                    break;
jaroslav@1646
   276
                case 2:
jaroslav@1646
   277
                    binding = bootstrapMethod.invoke(caller, name, type,
jaroslav@1646
   278
                                                     argv[0], argv[1]);
jaroslav@1646
   279
                    break;
jaroslav@1646
   280
                case 3:
jaroslav@1646
   281
                    binding = bootstrapMethod.invoke(caller, name, type,
jaroslav@1646
   282
                                                     argv[0], argv[1], argv[2]);
jaroslav@1646
   283
                    break;
jaroslav@1646
   284
                case 4:
jaroslav@1646
   285
                    binding = bootstrapMethod.invoke(caller, name, type,
jaroslav@1646
   286
                                                     argv[0], argv[1], argv[2], argv[3]);
jaroslav@1646
   287
                    break;
jaroslav@1646
   288
                case 5:
jaroslav@1646
   289
                    binding = bootstrapMethod.invoke(caller, name, type,
jaroslav@1646
   290
                                                     argv[0], argv[1], argv[2], argv[3], argv[4]);
jaroslav@1646
   291
                    break;
jaroslav@1646
   292
                case 6:
jaroslav@1646
   293
                    binding = bootstrapMethod.invoke(caller, name, type,
jaroslav@1646
   294
                                                     argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
jaroslav@1646
   295
                    break;
jaroslav@1646
   296
                default:
jaroslav@1646
   297
                    final int NON_SPREAD_ARG_COUNT = 3;  // (caller, name, type)
jaroslav@1646
   298
                    if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY)
jaroslav@1646
   299
                        throw new BootstrapMethodError("too many bootstrap method arguments");
jaroslav@1646
   300
                    MethodType bsmType = bootstrapMethod.type();
jaroslav@1646
   301
                    MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length);
jaroslav@1646
   302
                    MethodHandle typedBSM = bootstrapMethod.asType(invocationType);
jaroslav@1646
   303
                    MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT);
jaroslav@1646
   304
                    binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv);
jaroslav@1646
   305
                }
jaroslav@1646
   306
            }
jaroslav@1646
   307
            //System.out.println("BSM for "+name+type+" => "+binding);
jaroslav@1646
   308
            if (binding instanceof CallSite) {
jaroslav@1646
   309
                site = (CallSite) binding;
jaroslav@1646
   310
            }  else {
jaroslav@1646
   311
                throw new ClassCastException("bootstrap method failed to produce a CallSite");
jaroslav@1646
   312
            }
jaroslav@1646
   313
            if (!site.getTarget().type().equals(type))
jaroslav@1646
   314
                throw new WrongMethodTypeException("wrong type: "+site.getTarget());
jaroslav@1646
   315
        } catch (Throwable ex) {
jaroslav@1646
   316
            BootstrapMethodError bex;
jaroslav@1646
   317
            if (ex instanceof BootstrapMethodError)
jaroslav@1646
   318
                bex = (BootstrapMethodError) ex;
jaroslav@1646
   319
            else
jaroslav@1646
   320
                bex = new BootstrapMethodError("call site initialization exception", ex);
jaroslav@1646
   321
            throw bex;
jaroslav@1646
   322
        }
jaroslav@1646
   323
        return site;
jaroslav@1646
   324
    }
jaroslav@1646
   325
jaroslav@1646
   326
    private static Object maybeReBox(Object x) {
jaroslav@1646
   327
        if (x instanceof Integer) {
jaroslav@1646
   328
            int xi = (int) x;
jaroslav@1646
   329
            if (xi == (byte) xi)
jaroslav@1646
   330
                x = xi;  // must rebox; see JLS 5.1.7
jaroslav@1646
   331
        }
jaroslav@1646
   332
        return x;
jaroslav@1646
   333
    }
jaroslav@1646
   334
    private static void maybeReBoxElements(Object[] xa) {
jaroslav@1646
   335
        for (int i = 0; i < xa.length; i++) {
jaroslav@1646
   336
            xa[i] = maybeReBox(xa[i]);
jaroslav@1646
   337
        }
jaroslav@1646
   338
    }
jaroslav@1646
   339
}