jdk/src/share/classes/java/dyn/CallSite.java
changeset 8822 8145ab9f5f86
parent 8821 2836ee97ee27
child 8823 7cd28219a1e4
equal deleted inserted replaced
8821:2836ee97ee27 8822:8145ab9f5f86
     1 /*
       
     2  * Copyright (c) 2008, 2011, 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.dyn;
       
    27 
       
    28 import sun.dyn.empty.Empty;
       
    29 import sun.misc.Unsafe;
       
    30 import static java.dyn.MethodHandleStatics.*;
       
    31 import static java.dyn.MethodHandles.Lookup.IMPL_LOOKUP;
       
    32 
       
    33 /**
       
    34  * A {@code CallSite} is a holder for a variable {@link MethodHandle},
       
    35  * which is called its {@code target}.
       
    36  * An {@code invokedynamic} instruction linked to a {@code CallSite} delegates
       
    37  * all calls to the site's current target.
       
    38  * A {@code CallSite} may be associated with several {@code invokedynamic}
       
    39  * instructions, or it may be "free floating", associated with none.
       
    40  * In any case, it may be invoked through an associated method handle
       
    41  * called its {@linkplain #dynamicInvoker dynamic invoker}.
       
    42  * <p>
       
    43  * {@code CallSite} is an abstract class which does not allow
       
    44  * direct subclassing by users.  It has three immediate,
       
    45  * concrete subclasses that may be either instantiated or subclassed.
       
    46  * <ul>
       
    47  * <li>If a mutable target is not required, an {@code invokedynamic} instruction
       
    48  * may be permanently bound by means of a {@linkplain ConstantCallSite constant call site}.
       
    49  * <li>If a mutable target is required which has volatile variable semantics,
       
    50  * because updates to the target must be immediately and reliably witnessed by other threads,
       
    51  * a {@linkplain VolatileCallSite volatile call site} may be used.
       
    52  * <li>Otherwise, if a mutable target is required,
       
    53  * a {@linkplain MutableCallSite mutable call site} may be used.
       
    54  * </ul>
       
    55  * <p>
       
    56  * A non-constant call site may be <em>relinked</em> by changing its target.
       
    57  * The new target must have the same {@linkplain MethodHandle#type() type}
       
    58  * as the previous target.
       
    59  * Thus, though a call site can be relinked to a series of
       
    60  * successive targets, it cannot change its type.
       
    61  * <p>
       
    62  * Here is a sample use of call sites and bootstrap methods which links every
       
    63  * dynamic call site to print its arguments:
       
    64 <blockquote><pre><!-- see indy-demo/src/PrintArgsDemo.java -->
       
    65 static void test() throws Throwable {
       
    66     // THE FOLLOWING LINE IS PSEUDOCODE FOR A JVM INSTRUCTION
       
    67     InvokeDynamic[#bootstrapDynamic].baz("baz arg", 2, 3.14);
       
    68 }
       
    69 private static void printArgs(Object... args) {
       
    70   System.out.println(java.util.Arrays.deepToString(args));
       
    71 }
       
    72 private static final MethodHandle printArgs;
       
    73 static {
       
    74   MethodHandles.Lookup lookup = MethodHandles.lookup();
       
    75   Class thisClass = lookup.lookupClass();  // (who am I?)
       
    76   printArgs = lookup.findStatic(thisClass,
       
    77       "printArgs", MethodType.methodType(void.class, Object[].class));
       
    78 }
       
    79 private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String name, MethodType type) {
       
    80   // ignore caller and name, but match the type:
       
    81   return new ConstantCallSite(printArgs.asType(type));
       
    82 }
       
    83 </pre></blockquote>
       
    84  * @author John Rose, JSR 292 EG
       
    85  */
       
    86 abstract
       
    87 public class CallSite {
       
    88     static { MethodHandleImpl.initStatics(); }
       
    89 
       
    90     // Fields used only by the JVM.  Do not use or change.
       
    91     private MemberName vmmethod; // supplied by the JVM (ref. to calling method)
       
    92     private int        vmindex;  // supplied by the JVM (BCI within calling method)
       
    93 
       
    94     // The actual payload of this call site:
       
    95     /*package-private*/
       
    96     MethodHandle target;
       
    97 
       
    98     // Remove this field for PFD and delete deprecated methods:
       
    99     private MemberName calleeNameRemoveForPFD;
       
   100 
       
   101     /**
       
   102      * Make a blank call site object with the given method type.
       
   103      * An initial target method is supplied which will throw
       
   104      * an {@link IllegalStateException} if called.
       
   105      * <p>
       
   106      * Before this {@code CallSite} object is returned from a bootstrap method,
       
   107      * it is usually provided with a more useful target method,
       
   108      * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
       
   109      * @throws NullPointerException if the proposed type is null
       
   110      */
       
   111     /*package-private*/
       
   112     CallSite(MethodType type) {
       
   113         target = type.invokers().uninitializedCallSite();
       
   114     }
       
   115 
       
   116     /**
       
   117      * Make a blank call site object, possibly equipped with an initial target method handle.
       
   118      * @param target the method handle which will be the initial target of the call site
       
   119      * @throws NullPointerException if the proposed target is null
       
   120      */
       
   121     /*package-private*/
       
   122     CallSite(MethodHandle target) {
       
   123         target.type();  // null check
       
   124         this.target = target;
       
   125     }
       
   126 
       
   127     /**
       
   128      * Returns the type of this call site's target.
       
   129      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
       
   130      * The {@code setTarget} method enforces this invariant by refusing any new target that does
       
   131      * not have the previous target's type.
       
   132      * @return the type of the current target, which is also the type of any future target
       
   133      */
       
   134     public MethodType type() {
       
   135         return target.type();
       
   136     }
       
   137 
       
   138     /** Called from JVM (or low-level Java code) after the BSM returns the newly created CallSite.
       
   139      *  The parameters are JVM-specific.
       
   140      */
       
   141     void initializeFromJVM(String name,
       
   142                            MethodType type,
       
   143                            MemberName callerMethod,
       
   144                            int        callerBCI) {
       
   145         if (this.vmmethod != null) {
       
   146             // FIXME
       
   147             throw new InvokeDynamicBootstrapError("call site has already been linked to an invokedynamic instruction");
       
   148         }
       
   149         if (!this.type().equals(type)) {
       
   150             throw wrongTargetType(target, type);
       
   151         }
       
   152         this.vmindex  = callerBCI;
       
   153         this.vmmethod = callerMethod;
       
   154     }
       
   155 
       
   156     /**
       
   157      * Returns the target method of the call site, according to the
       
   158      * behavior defined by this call site's specific class.
       
   159      * The immediate subclasses of {@code CallSite} document the
       
   160      * class-specific behaviors of this method.
       
   161      *
       
   162      * @return the current linkage state of the call site, its target method handle
       
   163      * @see ConstantCallSite
       
   164      * @see VolatileCallSite
       
   165      * @see #setTarget
       
   166      * @see ConstantCallSite#getTarget
       
   167      * @see MutableCallSite#getTarget
       
   168      * @see VolatileCallSite#getTarget
       
   169      */
       
   170     public abstract MethodHandle getTarget();
       
   171 
       
   172     /**
       
   173      * Updates the target method of this call site, according to the
       
   174      * behavior defined by this call site's specific class.
       
   175      * The immediate subclasses of {@code CallSite} document the
       
   176      * class-specific behaviors of this method.
       
   177      * <p>
       
   178      * The type of the new target must be {@linkplain MethodType#equals equal to}
       
   179      * the type of the old target.
       
   180      *
       
   181      * @param newTarget the new target
       
   182      * @throws NullPointerException if the proposed new target is null
       
   183      * @throws WrongMethodTypeException if the proposed new target
       
   184      *         has a method type that differs from the previous target
       
   185      * @see CallSite#getTarget
       
   186      * @see ConstantCallSite#setTarget
       
   187      * @see MutableCallSite#setTarget
       
   188      * @see VolatileCallSite#setTarget
       
   189      */
       
   190     public abstract void setTarget(MethodHandle newTarget);
       
   191 
       
   192     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
       
   193         MethodType oldType = oldTarget.type();
       
   194         MethodType newType = newTarget.type();  // null check!
       
   195         if (!newType.equals(oldType))
       
   196             throw wrongTargetType(newTarget, oldType);
       
   197     }
       
   198 
       
   199     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
       
   200         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
       
   201     }
       
   202 
       
   203     /**
       
   204      * Produce a method handle equivalent to an invokedynamic instruction
       
   205      * which has been linked to this call site.
       
   206      * <p>
       
   207      * This method is equivalent to the following code:
       
   208      * <blockquote><pre>
       
   209      * MethodHandle getTarget, invoker, result;
       
   210      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
       
   211      * invoker = MethodHandles.exactInvoker(this.type());
       
   212      * result = MethodHandles.foldArguments(invoker, getTarget)
       
   213      * </pre></blockquote>
       
   214      *
       
   215      * @return a method handle which always invokes this call site's current target
       
   216      */
       
   217     public abstract MethodHandle dynamicInvoker();
       
   218 
       
   219     /*non-public*/ MethodHandle makeDynamicInvoker() {
       
   220         MethodHandle getTarget = MethodHandleImpl.bindReceiver(GET_TARGET, this);
       
   221         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
       
   222         return MethodHandles.foldArguments(invoker, getTarget);
       
   223     }
       
   224 
       
   225     private static final MethodHandle GET_TARGET;
       
   226     static {
       
   227         try {
       
   228             GET_TARGET = IMPL_LOOKUP.
       
   229                 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
       
   230         } catch (ReflectiveOperationException ignore) {
       
   231             throw new InternalError();
       
   232         }
       
   233     }
       
   234 
       
   235     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
       
   236     /*package-private*/
       
   237     static Empty uninitializedCallSite() {
       
   238         throw new IllegalStateException("uninitialized call site");
       
   239     }
       
   240 
       
   241     // unsafe stuff:
       
   242     private static final Unsafe unsafe = Unsafe.getUnsafe();
       
   243     private static final long TARGET_OFFSET;
       
   244 
       
   245     static {
       
   246         try {
       
   247             TARGET_OFFSET = unsafe.objectFieldOffset(CallSite.class.getDeclaredField("target"));
       
   248         } catch (Exception ex) { throw new Error(ex); }
       
   249     }
       
   250 
       
   251     /*package-private*/
       
   252     void setTargetNormal(MethodHandle newTarget) {
       
   253         target = newTarget;
       
   254     }
       
   255     /*package-private*/
       
   256     MethodHandle getTargetVolatile() {
       
   257         return (MethodHandle) unsafe.getObjectVolatile(this, TARGET_OFFSET);
       
   258     }
       
   259     /*package-private*/
       
   260     void setTargetVolatile(MethodHandle newTarget) {
       
   261         unsafe.putObjectVolatile(this, TARGET_OFFSET, newTarget);
       
   262     }
       
   263 
       
   264     // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
       
   265     static CallSite makeSite(MethodHandle bootstrapMethod,
       
   266                              // Callee information:
       
   267                              String name, MethodType type,
       
   268                              // Extra arguments for BSM, if any:
       
   269                              Object info,
       
   270                              // Caller information:
       
   271                              MemberName callerMethod, int callerBCI) {
       
   272         Class<?> callerClass = callerMethod.getDeclaringClass();
       
   273         Object caller;
       
   274         if (bootstrapMethod.type().parameterType(0) == Class.class && TRANSITIONAL_BEFORE_PFD)
       
   275             caller = callerClass;  // remove for PFD
       
   276         else
       
   277             caller = IMPL_LOOKUP.in(callerClass);
       
   278         if (bootstrapMethod == null && TRANSITIONAL_BEFORE_PFD) {
       
   279             // If there is no bootstrap method, throw IncompatibleClassChangeError.
       
   280             // This is a valid generic error type for resolution (JLS 12.3.3).
       
   281             throw new IncompatibleClassChangeError
       
   282                 ("Class "+callerClass.getName()+" has not declared a bootstrap method for invokedynamic");
       
   283         }
       
   284         CallSite site;
       
   285         try {
       
   286             Object binding;
       
   287             info = maybeReBox(info);
       
   288             if (info == null) {
       
   289                 binding = bootstrapMethod.invokeGeneric(caller, name, type);
       
   290             } else if (!info.getClass().isArray()) {
       
   291                 binding = bootstrapMethod.invokeGeneric(caller, name, type, info);
       
   292             } else {
       
   293                 Object[] argv = (Object[]) info;
       
   294                 maybeReBoxElements(argv);
       
   295                 if (3 + argv.length > 255)
       
   296                     throw new InvokeDynamicBootstrapError("too many bootstrap method arguments");
       
   297                 MethodType bsmType = bootstrapMethod.type();
       
   298                 if (bsmType.parameterCount() == 4 && bsmType.parameterType(3) == Object[].class)
       
   299                     binding = bootstrapMethod.invokeGeneric(caller, name, type, argv);
       
   300                 else
       
   301                     binding = MethodHandles.spreadInvoker(bsmType, 3)
       
   302                         .invokeGeneric(bootstrapMethod, caller, name, type, argv);
       
   303             }
       
   304             //System.out.println("BSM for "+name+type+" => "+binding);
       
   305             if (binding instanceof CallSite) {
       
   306                 site = (CallSite) binding;
       
   307             } else if (binding instanceof MethodHandle && TRANSITIONAL_BEFORE_PFD) {
       
   308                 // Transitional!
       
   309                 MethodHandle target = (MethodHandle) binding;
       
   310                 site = new ConstantCallSite(target);
       
   311             } else {
       
   312                 throw new ClassCastException("bootstrap method failed to produce a CallSite");
       
   313             }
       
   314             if (TRANSITIONAL_BEFORE_PFD)
       
   315                 PRIVATE_INITIALIZE_CALL_SITE.invokeExact(site, name, type,
       
   316                                                          callerMethod, callerBCI);
       
   317             assert(site.getTarget() != null);
       
   318             assert(site.getTarget().type().equals(type));
       
   319         } catch (Throwable ex) {
       
   320             InvokeDynamicBootstrapError bex;
       
   321             if (ex instanceof InvokeDynamicBootstrapError)
       
   322                 bex = (InvokeDynamicBootstrapError) ex;
       
   323             else
       
   324                 bex = new InvokeDynamicBootstrapError("call site initialization exception", ex);
       
   325             throw bex;
       
   326         }
       
   327         return site;
       
   328     }
       
   329 
       
   330     private static final boolean TRANSITIONAL_BEFORE_PFD = true;  // FIXME: remove for PFD
       
   331     // booby trap to force removal after package rename:
       
   332     static { if (TRANSITIONAL_BEFORE_PFD)  assert(CallSite.class.getName().startsWith("java.dyn.")); }
       
   333 
       
   334     private static Object maybeReBox(Object x) {
       
   335         if (x instanceof Integer) {
       
   336             int xi = (int) x;
       
   337             if (xi == (byte) xi)
       
   338                 x = xi;  // must rebox; see JLS 5.1.7
       
   339         }
       
   340         return x;
       
   341     }
       
   342     private static void maybeReBoxElements(Object[] xa) {
       
   343         for (int i = 0; i < xa.length; i++) {
       
   344             xa[i] = maybeReBox(xa[i]);
       
   345         }
       
   346     }
       
   347 
       
   348     // This method is private in CallSite because it touches private fields in CallSite.
       
   349     // These private fields (vmmethod, vmindex) are specific to the JVM.
       
   350     private static final MethodHandle PRIVATE_INITIALIZE_CALL_SITE;
       
   351     static {
       
   352         try {
       
   353             PRIVATE_INITIALIZE_CALL_SITE =
       
   354             !TRANSITIONAL_BEFORE_PFD ? null :
       
   355             IMPL_LOOKUP.findVirtual(CallSite.class, "initializeFromJVM",
       
   356                 MethodType.methodType(void.class,
       
   357                                       String.class, MethodType.class,
       
   358                                       MemberName.class, int.class));
       
   359         } catch (ReflectiveOperationException ex) {
       
   360             throw uncaughtException(ex);
       
   361         }
       
   362     }
       
   363 }