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