1 /*
   2  * Copyright (c) 2015, 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 package org.graalvm.compiler.nodes.graphbuilderconf;
  24 
  25 import static org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.resolveType;
  26 
  27 import java.lang.reflect.Method;
  28 import java.lang.reflect.Modifier;
  29 import java.lang.reflect.Type;
  30 import java.util.Arrays;
  31 import java.util.stream.Collectors;
  32 
  33 import org.graalvm.compiler.bytecode.BytecodeProvider;
  34 import org.graalvm.compiler.debug.GraalError;
  35 import org.graalvm.compiler.nodes.ValueNode;
  36 
  37 import jdk.vm.ci.meta.MetaAccessProvider;
  38 import jdk.vm.ci.meta.ResolvedJavaMethod;
  39 
  40 /**
  41  * An {@link InvocationPlugin} for a method where the implementation of the method is provided by a
  42  * {@linkplain #getSubstitute(MetaAccessProvider) substitute} method. A substitute method must be
  43  * static even if the substituted method is not.
  44  *
  45  * While performing intrinsification with method substitutions is simpler than writing an
  46  * {@link InvocationPlugin} that does manual graph weaving, it has a higher compile time cost than
  47  * the latter; parsing bytecodes to create nodes is slower than simply creating nodes. As such, the
  48  * recommended practice is to use {@link MethodSubstitutionPlugin} only for complex
  49  * intrinsifications which is typically those using non-straight-line control flow.
  50  */
  51 public final class MethodSubstitutionPlugin implements InvocationPlugin {
  52 
  53     private ResolvedJavaMethod cachedSubstitute;
  54 
  55     /**
  56      * The class in which the substitute method is declared.
  57      */
  58     private final Class<?> declaringClass;
  59 
  60     /**
  61      * The name of the original and substitute method.
  62      */
  63     private final String name;
  64 
  65     /**
  66      * The parameter types of the substitute method.
  67      */
  68     private final Type[] parameters;
  69 
  70     private final boolean originalIsStatic;
  71 
  72     private final BytecodeProvider bytecodeProvider;
  73 
  74     /**
  75      * Creates a method substitution plugin.
  76      *
  77      * @param bytecodeProvider used to get the bytecodes to parse for the substitute method
  78      * @param declaringClass the class in which the substitute method is declared
  79      * @param name the name of the substitute method
  80      * @param parameters the parameter types of the substitute method. If the original method is not
  81      *            static, then {@code parameters[0]} must be the {@link Class} value denoting
  82      *            {@link InvocationPlugin.Receiver}
  83      */
  84     public MethodSubstitutionPlugin(BytecodeProvider bytecodeProvider, Class<?> declaringClass, String name, Type... parameters) {
  85         this.bytecodeProvider = bytecodeProvider;
  86         this.declaringClass = declaringClass;
  87         this.name = name;
  88         this.parameters = parameters;
  89         this.originalIsStatic = parameters.length == 0 || parameters[0] != InvocationPlugin.Receiver.class;
  90     }
  91 
  92     @Override
  93     public boolean inlineOnly() {
  94         // Conservatively assume MacroNodes may be used in a substitution
  95         return true;
  96     }
  97 
  98     /**
  99      * Gets the substitute method, resolving it first if necessary.
 100      */
 101     public ResolvedJavaMethod getSubstitute(MetaAccessProvider metaAccess) {
 102         if (cachedSubstitute == null) {
 103             cachedSubstitute = metaAccess.lookupJavaMethod(getJavaSubstitute());
 104         }
 105         return cachedSubstitute;
 106     }
 107 
 108     /**
 109      * Gets the reflection API version of the substitution method.
 110      */
 111     Method getJavaSubstitute() throws GraalError {
 112         Method substituteMethod = lookupSubstitute();
 113         int modifiers = substituteMethod.getModifiers();
 114         if (Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) {
 115             throw new GraalError("Substitution method must not be abstract or native: " + substituteMethod);
 116         }
 117         if (!Modifier.isStatic(modifiers)) {
 118             throw new GraalError("Substitution method must be static: " + substituteMethod);
 119         }
 120         return substituteMethod;
 121     }
 122 
 123     /**
 124      * Determines if a given method is the substitute method of this plugin.
 125      */
 126     private boolean isSubstitute(Method m) {
 127         if (Modifier.isStatic(m.getModifiers()) && m.getName().equals(name)) {
 128             if (parameters.length == m.getParameterCount()) {
 129                 Class<?>[] mparams = m.getParameterTypes();
 130                 int start = 0;
 131                 if (!originalIsStatic) {
 132                     start = 1;
 133                     if (!mparams[0].isAssignableFrom(resolveType(parameters[0], false))) {
 134                         return false;
 135                     }
 136                 }
 137                 for (int i = start; i < mparams.length; i++) {
 138                     if (mparams[i] != resolveType(parameters[i], false)) {
 139                         return false;
 140                     }
 141                 }
 142             }
 143             return true;
 144         }
 145         return false;
 146     }
 147 
 148     /**
 149      * Gets the substitute method of this plugin.
 150      */
 151     private Method lookupSubstitute() {
 152         for (Method m : declaringClass.getDeclaredMethods()) {
 153             if (isSubstitute(m)) {
 154                 return m;
 155             }
 156         }
 157         throw new GraalError("No method found specified by %s", this);
 158     }
 159 
 160     @Override
 161     public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver) {
 162         ResolvedJavaMethod subst = getSubstitute(b.getMetaAccess());
 163         return b.intrinsify(bytecodeProvider, targetMethod, subst, receiver, argsIncludingReceiver);
 164     }
 165 
 166     @Override
 167     public StackTraceElement getApplySourceLocation(MetaAccessProvider metaAccess) {
 168         Class<?> c = getClass();
 169         for (Method m : c.getDeclaredMethods()) {
 170             if (m.getName().equals("execute")) {
 171                 return metaAccess.lookupJavaMethod(m).asStackTraceElement(0);
 172             }
 173         }
 174         throw new GraalError("could not find method named \"execute\" in " + c.getName());
 175     }
 176 
 177     @Override
 178     public String toString() {
 179         return String.format("%s[%s.%s(%s)]", getClass().getSimpleName(), declaringClass.getName(), name,
 180                         Arrays.asList(parameters).stream().map(c -> c.getTypeName()).collect(Collectors.joining(", ")));
 181     }
 182 }