jdk/src/share/classes/java/dyn/CallSite.java
changeset 8823 7cd28219a1e4
parent 8717 f75a1efb1412
parent 8822 8145ab9f5f86
child 8824 0762fa26f813
child 9033 a88f5656f05d
equal deleted inserted replaced
8717:f75a1efb1412 8823:7cd28219a1e4
     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.*;
       
    29 import sun.dyn.empty.Empty;
       
    30 import sun.misc.Unsafe;
       
    31 import java.util.Collection;
       
    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     private static final Access IMPL_TOKEN = Access.getToken();
       
    89     static { MethodHandleImpl.initStatics(); }
       
    90 
       
    91     // Fields used only by the JVM.  Do not use or change.
       
    92     private MemberName vmmethod; // supplied by the JVM (ref. to calling method)
       
    93     private int        vmindex;  // supplied by the JVM (BCI within calling method)
       
    94 
       
    95     // The actual payload of this call site:
       
    96     /*package-private*/
       
    97     MethodHandle target;
       
    98 
       
    99     // Remove this field for PFD and delete deprecated methods:
       
   100     private MemberName calleeNameRemoveForPFD;
       
   101 
       
   102     /**
       
   103      * Make a blank call site object with the given method type.
       
   104      * An initial target method is supplied which will throw
       
   105      * an {@link IllegalStateException} if called.
       
   106      * <p>
       
   107      * Before this {@code CallSite} object is returned from a bootstrap method,
       
   108      * it is usually provided with a more useful target method,
       
   109      * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
       
   110      * @throws NullPointerException if the proposed type is null
       
   111      */
       
   112     /*package-private*/
       
   113     CallSite(MethodType type) {
       
   114         target = MethodHandles.invokers(type).uninitializedCallSite();
       
   115     }
       
   116 
       
   117     /**
       
   118      * Make a blank call site object, possibly equipped with an initial target method handle.
       
   119      * @param target the method handle which will be the initial target of the call site
       
   120      * @throws NullPointerException if the proposed target is null
       
   121      */
       
   122     /*package-private*/
       
   123     CallSite(MethodHandle target) {
       
   124         target.type();  // null check
       
   125         this.target = target;
       
   126     }
       
   127 
       
   128     /**
       
   129      * Returns the type of this call site's target.
       
   130      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
       
   131      * The {@code setTarget} method enforces this invariant by refusing any new target that does
       
   132      * not have the previous target's type.
       
   133      * @return the type of the current target, which is also the type of any future target
       
   134      */
       
   135     public MethodType type() {
       
   136         return target.type();
       
   137     }
       
   138 
       
   139     /** Called from JVM (or low-level Java code) after the BSM returns the newly created CallSite.
       
   140      *  The parameters are JVM-specific.
       
   141      */
       
   142     void initializeFromJVM(String name,
       
   143                            MethodType type,
       
   144                            MemberName callerMethod,
       
   145                            int        callerBCI) {
       
   146         if (this.vmmethod != null) {
       
   147             // FIXME
       
   148             throw new InvokeDynamicBootstrapError("call site has already been linked to an invokedynamic instruction");
       
   149         }
       
   150         if (!this.type().equals(type)) {
       
   151             throw wrongTargetType(target, type);
       
   152         }
       
   153         this.vmindex  = callerBCI;
       
   154         this.vmmethod = callerMethod;
       
   155     }
       
   156 
       
   157     /**
       
   158      * Returns the target method of the call site, according to the
       
   159      * behavior defined by this call site's specific class.
       
   160      * The immediate subclasses of {@code CallSite} document the
       
   161      * class-specific behaviors of this method.
       
   162      *
       
   163      * @return the current linkage state of the call site, its target method handle
       
   164      * @see ConstantCallSite
       
   165      * @see VolatileCallSite
       
   166      * @see #setTarget
       
   167      * @see ConstantCallSite#getTarget
       
   168      * @see MutableCallSite#getTarget
       
   169      * @see VolatileCallSite#getTarget
       
   170      */
       
   171     public abstract MethodHandle getTarget();
       
   172 
       
   173     /**
       
   174      * Updates the target method of this call site, according to the
       
   175      * behavior defined by this call site's specific class.
       
   176      * The immediate subclasses of {@code CallSite} document the
       
   177      * class-specific behaviors of this method.
       
   178      * <p>
       
   179      * The type of the new target must be {@linkplain MethodType#equals equal to}
       
   180      * the type of the old target.
       
   181      *
       
   182      * @param newTarget the new target
       
   183      * @throws NullPointerException if the proposed new target is null
       
   184      * @throws WrongMethodTypeException if the proposed new target
       
   185      *         has a method type that differs from the previous target
       
   186      * @see CallSite#getTarget
       
   187      * @see ConstantCallSite#setTarget
       
   188      * @see MutableCallSite#setTarget
       
   189      * @see VolatileCallSite#setTarget
       
   190      */
       
   191     public abstract void setTarget(MethodHandle newTarget);
       
   192 
       
   193     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
       
   194         MethodType oldType = oldTarget.type();
       
   195         MethodType newType = newTarget.type();  // null check!
       
   196         if (!newType.equals(oldType))
       
   197             throw wrongTargetType(newTarget, oldType);
       
   198     }
       
   199 
       
   200     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
       
   201         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
       
   202     }
       
   203 
       
   204     /**
       
   205      * Produce a method handle equivalent to an invokedynamic instruction
       
   206      * which has been linked to this call site.
       
   207      * <p>
       
   208      * This method is equivalent to the following code:
       
   209      * <blockquote><pre>
       
   210      * MethodHandle getTarget, invoker, result;
       
   211      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
       
   212      * invoker = MethodHandles.exactInvoker(this.type());
       
   213      * result = MethodHandles.foldArguments(invoker, getTarget)
       
   214      * </pre></blockquote>
       
   215      *
       
   216      * @return a method handle which always invokes this call site's current target
       
   217      */
       
   218     public abstract MethodHandle dynamicInvoker();
       
   219 
       
   220     /*non-public*/ MethodHandle makeDynamicInvoker() {
       
   221         MethodHandle getTarget = MethodHandleImpl.bindReceiver(IMPL_TOKEN, GET_TARGET, this);
       
   222         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
       
   223         return MethodHandles.foldArguments(invoker, getTarget);
       
   224     }
       
   225 
       
   226     private static final MethodHandle GET_TARGET;
       
   227     static {
       
   228         try {
       
   229             GET_TARGET = MethodHandles.Lookup.IMPL_LOOKUP.
       
   230                 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
       
   231         } catch (ReflectiveOperationException ignore) {
       
   232             throw new InternalError();
       
   233         }
       
   234     }
       
   235 
       
   236     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
       
   237     /*package-private*/
       
   238     static Empty uninitializedCallSite() {
       
   239         throw new IllegalStateException("uninitialized call site");
       
   240     }
       
   241 
       
   242     // unsafe stuff:
       
   243     private static final Unsafe unsafe = Unsafe.getUnsafe();
       
   244     private static final long TARGET_OFFSET;
       
   245 
       
   246     static {
       
   247         try {
       
   248             TARGET_OFFSET = unsafe.objectFieldOffset(CallSite.class.getDeclaredField("target"));
       
   249         } catch (Exception ex) { throw new Error(ex); }
       
   250     }
       
   251 
       
   252     /*package-private*/
       
   253     void setTargetNormal(MethodHandle newTarget) {
       
   254         target = newTarget;
       
   255         //CallSiteImpl.setCallSiteTarget(IMPL_TOKEN, this, newTarget);
       
   256     }
       
   257     /*package-private*/
       
   258     MethodHandle getTargetVolatile() {
       
   259         return (MethodHandle) unsafe.getObjectVolatile(this, TARGET_OFFSET);
       
   260     }
       
   261     /*package-private*/
       
   262     void setTargetVolatile(MethodHandle newTarget) {
       
   263         unsafe.putObjectVolatile(this, TARGET_OFFSET, newTarget);
       
   264         //CallSiteImpl.setCallSiteTarget(IMPL_TOKEN, this, newTarget);
       
   265     }
       
   266 }