package org.graalvm.compiler.nodes.graphbuilderconf;
import static jdk.vm.ci.services.Services.IS_IN_NATIVE_IMAGE;
import static org.graalvm.compiler.core.common.GraalOptions.UseEncodedGraphs;
import static org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext.CompilationContext.INLINE_AFTER_PARSING;
import static org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.resolveType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import org.graalvm.compiler.bytecode.BytecodeProvider;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.nodes.ValueNode;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.meta.ResolvedJavaType;
public final class MethodSubstitutionPlugin implements InvocationPlugin {
private InvocationPlugins.Registration registration;
private ResolvedJavaMethod cachedSubstitute;
private final Class<?> declaringClass;
private final String substituteName;
private final String originalName;
private final Type[] parameters;
private final boolean originalIsStatic;
private final BytecodeProvider bytecodeProvider;
public MethodSubstitutionPlugin(InvocationPlugins.Registration registration, BytecodeProvider bytecodeProvider, String originalName, Class<?> declaringClass, String substituteName,
Type... parameters) {
assert bytecodeProvider != null : "Requires a non-null methodSubstitutionBytecodeProvider";
this.registration = registration;
this.bytecodeProvider = bytecodeProvider;
this.originalName = originalName;
this.declaringClass = declaringClass;
this.substituteName = substituteName;
this.parameters = parameters;
this.originalIsStatic = parameters.length == 0 || parameters[0] != InvocationPlugin.Receiver.class;
}
public ResolvedJavaMethod getSubstitute(MetaAccessProvider metaAccess) {
if (cachedSubstitute == null) {
cachedSubstitute = metaAccess.lookupJavaMethod(getJavaSubstitute());
}
return cachedSubstitute;
}
public BytecodeProvider getBytecodeProvider() {
return bytecodeProvider;
}
public Class<?> getDeclaringClass() {
return declaringClass;
}
public Method getJavaSubstitute() throws GraalError {
Method substituteMethod = lookupSubstitute();
int modifiers = substituteMethod.getModifiers();
if (Modifier.isAbstract(modifiers) || Modifier.isNative(modifiers)) {
throw new GraalError("Substitution method must not be abstract or native: " + substituteMethod);
}
if (!Modifier.isStatic(modifiers)) {
throw new GraalError("Substitution method must be static: " + substituteMethod);
}
return substituteMethod;
}
private boolean isSubstitute(Method m) {
if (Modifier.isStatic(m.getModifiers()) && m.getName().equals(substituteName)) {
if (parameters.length == m.getParameterCount()) {
Class<?>[] mparams = m.getParameterTypes();
int start = 0;
if (!originalIsStatic) {
start = 1;
if (!mparams[0].isAssignableFrom(resolveType(parameters[0], false))) {
return false;
}
}
for (int i = start; i < mparams.length; i++) {
if (mparams[i] != resolveType(parameters[i], false)) {
return false;
}
}
return true;
}
}
return false;
}
private Method lookupSubstitute(Method excluding) {
for (Method m : declaringClass.getDeclaredMethods()) {
if (!m.equals(excluding) && isSubstitute(m)) {
return m;
}
}
return null;
}
private Method lookupSubstitute() {
Method m = lookupSubstitute(null);
if (m != null) {
assert lookupSubstitute(m) == null : String.format("multiple matches found for %s:%n%s%n%s", this, m, lookupSubstitute(m));
return m;
}
throw new GraalError("No method found specified by %s", this);
}
@Override
public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver) {
if (IS_IN_NATIVE_IMAGE || (UseEncodedGraphs.getValue(b.getOptions()) && !b.parsingIntrinsic())) {
StructuredGraph subst = b.getReplacements().getMethodSubstitution(this,
targetMethod,
INLINE_AFTER_PARSING,
StructuredGraph.AllowAssumptions.ifNonNull(b.getAssumptions()),
null ,
b.getOptions());
if (subst == null) {
throw new GraalError("No graphs found for substitution %s", this);
}
return b.intrinsify(targetMethod, subst, receiver, argsIncludingReceiver);
}
ResolvedJavaMethod substitute = getSubstitute(b.getMetaAccess());
return b.intrinsify(bytecodeProvider, targetMethod, substitute, receiver, argsIncludingReceiver);
}
@Override
public StackTraceElement getApplySourceLocation(MetaAccessProvider metaAccess) {
Class<?> c = getClass();
if (IS_IN_NATIVE_IMAGE) {
return new StackTraceElement(c.getName(), "execute", null, -1);
}
for (Method m : c.getDeclaredMethods()) {
if (m.getName().equals("execute")) {
return metaAccess.lookupJavaMethod(m).asStackTraceElement(0);
}
}
throw new GraalError("could not find method named \"execute\" in " + c.getName());
}
@Override
public String toString() {
return String.format("%s[%s.%s(%s)]", getClass().getSimpleName(), declaringClass.getName(), substituteName,
Arrays.asList(parameters).stream().map(c -> c.getTypeName()).collect(Collectors.joining(", ")));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MethodSubstitutionPlugin that = (MethodSubstitutionPlugin) o;
return originalIsStatic == that.originalIsStatic &&
Objects.equals(declaringClass, that.declaringClass) &&
Objects.equals(substituteName, that.substituteName) &&
Objects.equals(originalName, that.originalName) &&
Arrays.equals(parameters, that.parameters);
}
@Override
public int hashCode() {
int result = Objects.hash(declaringClass, substituteName, originalName, originalIsStatic);
return result;
}
public String originalMethodAsString() {
return String.format("%s.%s(%s)", declaringClass.getName(), substituteName, Arrays.asList(parameters).stream().map(c -> c.getTypeName()).collect(Collectors.joining(", ")));
}
public ResolvedJavaMethod getOriginalMethod(MetaAccessProvider metaAccess) {
Class<?> clazz = resolveType(registration.getDeclaringType(), false);
if (clazz == null) {
throw new GraalError("Can't find original class for " + this + " with class " + registration.getDeclaringType());
}
ResolvedJavaType type = metaAccess.lookupJavaType(clazz);
String argumentsDescriptor = InvocationPlugins.toArgumentDescriptor(originalIsStatic, this.parameters);
for (ResolvedJavaMethod declared : type.getDeclaredMethods()) {
if (declared.getName().equals(originalName) && declared.isStatic() == originalIsStatic &&
declared.getSignature().toMethodDescriptor().startsWith(argumentsDescriptor)) {
return declared;
}
}
throw new GraalError("Can't find original method for " + this + " with class " + registration.getDeclaringType());
}
}