1 /*
   2  * Copyright (c) 2015, 2018, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.nodes.graphbuilderconf;
  26 
  27 import static org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.resolveType;
  28 
  29 import java.lang.reflect.Method;
  30 import java.lang.reflect.Modifier;
  31 import java.lang.reflect.Type;
  32 import java.util.Arrays;
  33 import java.util.stream.Collectors;
  34 
  35 import org.graalvm.compiler.bytecode.BytecodeProvider;
  36 import org.graalvm.compiler.debug.GraalError;
  37 import org.graalvm.compiler.nodes.ValueNode;
  38 
  39 import jdk.vm.ci.meta.MetaAccessProvider;
  40 import jdk.vm.ci.meta.ResolvedJavaMethod;
  41 
  42 /**
  43  * An {@link InvocationPlugin} for a method where the implementation of the method is provided by a
  44  * {@linkplain #getSubstitute(MetaAccessProvider) substitute} method. A substitute method must be
  45  * static even if the substituted method is not.
  46  *
  47  * While performing intrinsification with method substitutions is simpler than writing an
  48  * {@link InvocationPlugin} that does manual graph weaving, it has a higher compile time cost than
  49  * the latter; parsing bytecodes to create nodes is slower than simply creating nodes. As such, the
  50  * recommended practice is to use {@link MethodSubstitutionPlugin} only for complex
  51  * intrinsifications which is typically those using non-straight-line control flow.
  52  */
  53 public final class MethodSubstitutionPlugin implements InvocationPlugin {
  54 
  55     private ResolvedJavaMethod cachedSubstitute;
  56 
  57     /**
  58      * The class in which the substitute method is declared.
  59      */
  60     private final Class<?> declaringClass;
  61 
  62     /**
  63      * The name of the original and substitute method.
  64      */
  65     private final String name;
  66 
  67     /**
  68      * The parameter types of the substitute method.
  69      */
  70     private final Type[] parameters;
  71 
  72     private final boolean originalIsStatic;
  73 
  74     private final BytecodeProvider bytecodeProvider;
  75 
  76     /**
  77      * Creates a method substitution plugin.
  78      *
  79      * @param bytecodeProvider used to get the bytecodes to parse for the substitute method
  80      * @param declaringClass the class in which the substitute method is declared
  81      * @param name the name of the substitute method
  82      * @param parameters the parameter types of the substitute method. If the original method is not
  83      *            static, then {@code parameters[0]} must be the {@link Class} value denoting
  84      *            {@link InvocationPlugin.Receiver}
  85      */
  86     public MethodSubstitutionPlugin(BytecodeProvider bytecodeProvider, Class<?> declaringClass, String name, Type... parameters) {
  87         this.bytecodeProvider = bytecodeProvider;
  88         this.declaringClass = declaringClass;
  89         this.name = name;
  90         this.parameters = parameters;
  91         this.originalIsStatic = parameters.length == 0 || parameters[0] != InvocationPlugin.Receiver.class;
  92     }
  93 
  94     @Override
  95     public boolean inlineOnly() {
  96         // Conservatively assume MacroNodes may be used in a substitution
  97         return true;
  98     }
  99 
 100     /**
 101      * Gets the substitute method, resolving it first if necessary.
 102      */
 103     public ResolvedJavaMethod getSubstitute(MetaAccessProvider metaAccess) {
 104         if (cachedSubstitute == null) {
 105             cachedSubstitute = metaAccess.lookupJavaMethod(getJavaSubstitute());
 106         }
 107         return cachedSubstitute;
 108     }
 109 
 110     /**
 111      * Gets the object used to access the bytecodes of the substitute method.
 112      */
 113     public BytecodeProvider getBytecodeProvider() {
 114         return bytecodeProvider;
 115     }
 116 
 117     /**
 118      * Gets the reflection API version of the substitution method.
 119      */
 120     Method getJavaSubstitute() throws GraalError {
 121         Method substituteMethod = lookupSubstitute();
 122         int modifiers = substituteMethod.getModifiers();
 123         if (Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) {
 124             throw new GraalError("Substitution method must not be abstract or native: " + substituteMethod);
 125         }
 126         if (!Modifier.isStatic(modifiers)) {
 127             throw new GraalError("Substitution method must be static: " + substituteMethod);
 128         }
 129         return substituteMethod;
 130     }
 131 
 132     /**
 133      * Determines if a given method is the substitute method of this plugin.
 134      */
 135     private boolean isSubstitute(Method m) {
 136         if (Modifier.isStatic(m.getModifiers()) && m.getName().equals(name)) {
 137             if (parameters.length == m.getParameterCount()) {
 138                 Class<?>[] mparams = m.getParameterTypes();
 139                 int start = 0;
 140                 if (!originalIsStatic) {
 141                     start = 1;
 142                     if (!mparams[0].isAssignableFrom(resolveType(parameters[0], false))) {
 143                         return false;
 144                     }
 145                 }
 146                 for (int i = start; i < mparams.length; i++) {
 147                     if (mparams[i] != resolveType(parameters[i], false)) {
 148                         return false;
 149                     }
 150                 }
 151                 return true;
 152             }
 153         }
 154         return false;
 155     }
 156 
 157     private Method lookupSubstitute(Method excluding) {
 158         for (Method m : declaringClass.getDeclaredMethods()) {
 159             if (!m.equals(excluding) && isSubstitute(m)) {
 160                 return m;
 161             }
 162         }
 163         return null;
 164     }
 165 
 166     /**
 167      * Gets the substitute method of this plugin.
 168      */
 169     private Method lookupSubstitute() {
 170         Method m = lookupSubstitute(null);
 171         if (m != null) {
 172             assert lookupSubstitute(m) == null : String.format("multiple matches found for %s:%n%s%n%s", this, m, lookupSubstitute(m));
 173             return m;
 174         }
 175         throw new GraalError("No method found specified by %s", this);
 176     }
 177 
 178     @Override
 179     public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver) {
 180         ResolvedJavaMethod subst = getSubstitute(b.getMetaAccess());
 181         return b.intrinsify(bytecodeProvider, targetMethod, subst, receiver, argsIncludingReceiver);
 182     }
 183 
 184     @Override
 185     public StackTraceElement getApplySourceLocation(MetaAccessProvider metaAccess) {
 186         Class<?> c = getClass();
 187         for (Method m : c.getDeclaredMethods()) {
 188             if (m.getName().equals("execute")) {
 189                 return metaAccess.lookupJavaMethod(m).asStackTraceElement(0);
 190             }
 191         }
 192         throw new GraalError("could not find method named \"execute\" in " + c.getName());
 193     }
 194 
 195     @Override
 196     public String toString() {
 197         return String.format("%s[%s.%s(%s)]", getClass().getSimpleName(), declaringClass.getName(), name,
 198                         Arrays.asList(parameters).stream().map(c -> c.getTypeName()).collect(Collectors.joining(", ")));
 199     }
 200 }