1 /*
   2  * Copyright (c) 2012, 2019, 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.hotspot.stubs;
  26 
  27 import static jdk.vm.ci.code.BytecodeFrame.UNKNOWN_BCI;
  28 import static jdk.vm.ci.hotspot.HotSpotCallingConventionType.JavaCall;
  29 import static jdk.vm.ci.hotspot.HotSpotCallingConventionType.JavaCallee;
  30 import static jdk.vm.ci.hotspot.HotSpotCallingConventionType.NativeCall;
  31 import static org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage.RegisterEffect.COMPUTES_REGISTERS_KILLED;
  32 import static org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage.RegisterEffect.DESTROYS_ALL_CALLER_SAVE_REGISTERS;
  33 import static org.graalvm.compiler.nodes.CallTargetNode.InvokeKind.Static;
  34 import static org.graalvm.compiler.nodes.ConstantNode.forBoolean;
  35 
  36 import org.graalvm.compiler.core.common.CompilationIdentifier;
  37 import org.graalvm.compiler.core.common.LIRKind;
  38 import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor;
  39 import org.graalvm.compiler.core.common.type.Stamp;
  40 import org.graalvm.compiler.core.common.type.StampFactory;
  41 import org.graalvm.compiler.core.common.type.StampPair;
  42 import org.graalvm.compiler.debug.DebugContext;
  43 import org.graalvm.compiler.debug.GraalError;
  44 import org.graalvm.compiler.debug.JavaMethodContext;
  45 import org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage;
  46 import org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage.Reexecutability;
  47 import org.graalvm.compiler.hotspot.HotSpotForeignCallLinkage.Transition;
  48 import org.graalvm.compiler.hotspot.HotSpotForeignCallLinkageImpl;
  49 import org.graalvm.compiler.hotspot.meta.HotSpotLoweringProvider;
  50 import org.graalvm.compiler.hotspot.meta.HotSpotProviders;
  51 import org.graalvm.compiler.hotspot.nodes.StubForeignCallNode;
  52 import org.graalvm.compiler.hotspot.stubs.ForeignCallSnippets.Templates;
  53 import org.graalvm.compiler.nodes.InvokeNode;
  54 import org.graalvm.compiler.nodes.ParameterNode;
  55 import org.graalvm.compiler.nodes.ReturnNode;
  56 import org.graalvm.compiler.nodes.StructuredGraph;
  57 import org.graalvm.compiler.nodes.ValueNode;
  58 import org.graalvm.compiler.options.OptionValues;
  59 import org.graalvm.compiler.phases.common.RemoveValueProxyPhase;
  60 import org.graalvm.compiler.replacements.GraphKit;
  61 import org.graalvm.compiler.replacements.nodes.ReadRegisterNode;
  62 import org.graalvm.compiler.word.Word;
  63 import org.graalvm.compiler.word.WordTypes;
  64 import jdk.internal.vm.compiler.word.LocationIdentity;
  65 
  66 import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime;
  67 import jdk.vm.ci.hotspot.HotSpotSignature;
  68 import jdk.vm.ci.meta.JavaKind;
  69 import jdk.vm.ci.meta.JavaMethod;
  70 import jdk.vm.ci.meta.JavaType;
  71 import jdk.vm.ci.meta.MetaAccessProvider;
  72 import jdk.vm.ci.meta.ResolvedJavaMethod;
  73 import jdk.vm.ci.meta.ResolvedJavaType;
  74 import jdk.vm.ci.meta.Signature;
  75 
  76 /**
  77  * A {@linkplain #getGraph generated} stub for a {@link Transition non-leaf} foreign call from
  78  * compiled code. A stub is required for such calls as the caller may be scheduled for
  79  * deoptimization while the call is in progress. And since these are foreign/runtime calls on slow
  80  * paths, we don't want to force the register allocator to spill around the call. As such, this stub
  81  * saves and restores all allocatable registers. It also
  82  * {@linkplain ForeignCallSnippets#handlePendingException handles} any exceptions raised during the
  83  * foreign call.
  84  */
  85 public class ForeignCallStub extends Stub {
  86 
  87     private final HotSpotJVMCIRuntime jvmciRuntime;
  88 
  89     /**
  90      * The target of the call.
  91      */
  92     private final HotSpotForeignCallLinkage target;
  93 
  94     /**
  95      * Specifies if the JavaThread value for the current thread is to be prepended to the arguments
  96      * for the call to {@link #target}.
  97      */
  98     protected final boolean prependThread;
  99 
 100     /**
 101      * Creates a stub for a call to code at a given address.
 102      *
 103      * @param address the address of the code to call
 104      * @param descriptor the signature of the call to this stub
 105      * @param prependThread true if the JavaThread value for the current thread is to be prepended
 106      *            to the arguments for the call to {@code address}
 107      * @param reexecutability specifies if the stub call can be re-executed without (meaningful)
 108      *            side effects. Deoptimization will not return to a point before a stub call that
 109      *            cannot be re-executed.
 110      * @param killedLocations the memory locations killed by the stub call
 111      */
 112     public ForeignCallStub(OptionValues options, HotSpotJVMCIRuntime runtime, HotSpotProviders providers, long address, ForeignCallDescriptor descriptor, boolean prependThread,
 113                     Transition transition, Reexecutability reexecutability, LocationIdentity... killedLocations) {
 114         super(options, providers, HotSpotForeignCallLinkageImpl.create(providers.getMetaAccess(), providers.getCodeCache(), providers.getWordTypes(), providers.getForeignCalls(), descriptor, 0L,
 115                         COMPUTES_REGISTERS_KILLED, JavaCall, JavaCallee, transition, reexecutability, killedLocations));
 116         this.jvmciRuntime = runtime;
 117         this.prependThread = prependThread;
 118         MetaAccessProvider metaAccess = providers.getMetaAccess();
 119         Class<?>[] targetParameterTypes = createTargetParameters(descriptor);
 120         ForeignCallDescriptor targetSig = new ForeignCallDescriptor(descriptor.getName() + ":C", descriptor.getResultType(), targetParameterTypes);
 121         target = HotSpotForeignCallLinkageImpl.create(metaAccess, providers.getCodeCache(), providers.getWordTypes(), providers.getForeignCalls(), targetSig, address,
 122                         DESTROYS_ALL_CALLER_SAVE_REGISTERS, NativeCall, NativeCall, transition, reexecutability, killedLocations);
 123     }
 124 
 125     /**
 126      * Gets the linkage information for the call from this stub.
 127      */
 128     public HotSpotForeignCallLinkage getTargetLinkage() {
 129         return target;
 130     }
 131 
 132     private Class<?>[] createTargetParameters(ForeignCallDescriptor descriptor) {
 133         Class<?>[] parameters = descriptor.getArgumentTypes();
 134         if (prependThread) {
 135             Class<?>[] newParameters = new Class<?>[parameters.length + 1];
 136             System.arraycopy(parameters, 0, newParameters, 1, parameters.length);
 137             newParameters[0] = Word.class;
 138             return newParameters;
 139         }
 140         return parameters;
 141     }
 142 
 143     @Override
 144     protected ResolvedJavaMethod getInstalledCodeOwner() {
 145         return null;
 146     }
 147 
 148     private class DebugScopeContext implements JavaMethod, JavaMethodContext {
 149         @Override
 150         public JavaMethod asJavaMethod() {
 151             return this;
 152         }
 153 
 154         @Override
 155         public Signature getSignature() {
 156             ForeignCallDescriptor d = linkage.getDescriptor();
 157             MetaAccessProvider metaAccess = providers.getMetaAccess();
 158             Class<?>[] arguments = d.getArgumentTypes();
 159             ResolvedJavaType[] parameters = new ResolvedJavaType[arguments.length];
 160             for (int i = 0; i < arguments.length; i++) {
 161                 parameters[i] = metaAccess.lookupJavaType(arguments[i]);
 162             }
 163             return new HotSpotSignature(jvmciRuntime, metaAccess.lookupJavaType(d.getResultType()), parameters);
 164         }
 165 
 166         @Override
 167         public String getName() {
 168             return linkage.getDescriptor().getName();
 169         }
 170 
 171         @Override
 172         public JavaType getDeclaringClass() {
 173             return providers.getMetaAccess().lookupJavaType(ForeignCallStub.class);
 174         }
 175 
 176         @Override
 177         public String toString() {
 178             return format("ForeignCallStub<%n(%p)>");
 179         }
 180     }
 181 
 182     @Override
 183     protected Object debugScopeContext() {
 184         return new DebugScopeContext() {
 185 
 186         };
 187     }
 188 
 189     /**
 190      * Creates a graph for this stub.
 191      * <p>
 192      * If the stub returns an object, the graph created corresponds to this pseudo code:
 193      *
 194      * <pre>
 195      *     Object foreignFunctionStub(args...) {
 196      *         foreignFunction(currentThread,  args);
 197      *         if ((shouldClearException && clearPendingException(thread())) || (!shouldClearException && hasPendingException(thread)) {
 198      *             getAndClearObjectResult(thread());
 199      *             DeoptimizeCallerNode.deopt(None, RuntimeConstraint);
 200      *         }
 201      *         return verifyObject(getAndClearObjectResult(thread()));
 202      *     }
 203      * </pre>
 204      *
 205      * If the stub returns a primitive or word, the graph created corresponds to this pseudo code
 206      * (using {@code int} as the primitive return type):
 207      *
 208      * <pre>
 209      *     int foreignFunctionStub(args...) {
 210      *         int result = foreignFunction(currentThread,  args);
 211      *         if ((shouldClearException && clearPendingException(thread())) || (!shouldClearException && hasPendingException(thread)) {
 212      *             DeoptimizeCallerNode.deopt(None, RuntimeConstraint);
 213      *         }
 214      *         return result;
 215      *     }
 216      * </pre>
 217      *
 218      * If the stub is void, the graph created corresponds to this pseudo code:
 219      *
 220      * <pre>
 221      *     void foreignFunctionStub(args...) {
 222      *         foreignFunction(currentThread,  args);
 223      *         if ((shouldClearException && clearPendingException(thread())) || (!shouldClearException && hasPendingException(thread)) {
 224      *             DeoptimizeCallerNode.deopt(None, RuntimeConstraint);
 225      *         }
 226      *     }
 227      * </pre>
 228      *
 229      * In each example above, the {@code currentThread} argument is the C++ JavaThread value (i.e.,
 230      * %r15 on AMD64) and is only prepended if {@link #prependThread} is true.
 231      */
 232     @Override
 233     @SuppressWarnings("try")
 234     protected StructuredGraph getGraph(DebugContext debug, CompilationIdentifier compilationId) {
 235         WordTypes wordTypes = providers.getWordTypes();
 236         Class<?>[] args = linkage.getDescriptor().getArgumentTypes();
 237         boolean isObjectResult = !LIRKind.isValue(linkage.getOutgoingCallingConvention().getReturn());
 238         // Do we want to clear the pending exception?
 239         boolean shouldClearException = linkage.isReexecutable();
 240         try {
 241             HotSpotLoweringProvider lowerer = (HotSpotLoweringProvider) providers.getLowerer();
 242             Templates foreignCallSnippets = lowerer.getForeignCallSnippets();
 243             ResolvedJavaMethod handlePendingException = foreignCallSnippets.handlePendingException.getMethod();
 244             ResolvedJavaMethod getAndClearObjectResult = foreignCallSnippets.getAndClearObjectResult.getMethod();
 245             ResolvedJavaMethod verifyObject = foreignCallSnippets.verifyObject.getMethod();
 246             ResolvedJavaMethod thisMethod = getGraphMethod();
 247             GraphKit kit = new GraphKit(debug, thisMethod, providers, wordTypes, providers.getGraphBuilderPlugins(), compilationId, toString());
 248             StructuredGraph graph = kit.getGraph();
 249             ParameterNode[] params = createParameters(kit, args);
 250             ReadRegisterNode thread = kit.append(new ReadRegisterNode(providers.getRegisters().getThreadRegister(), wordTypes.getWordKind(), true, false));
 251             ValueNode result = createTargetCall(kit, params, thread);
 252             createStaticInvoke(kit, handlePendingException, thread, forBoolean(shouldClearException, graph), forBoolean(isObjectResult, graph));
 253             if (isObjectResult) {
 254                 InvokeNode object = createStaticInvoke(kit, getAndClearObjectResult, thread);
 255                 result = createStaticInvoke(kit, verifyObject, object);
 256             }
 257             kit.append(new ReturnNode(linkage.getDescriptor().getResultType() == void.class ? null : result));
 258             debug.dump(DebugContext.VERBOSE_LEVEL, graph, "Initial stub graph");
 259 
 260             kit.inlineInvokes("Foreign call stub.", "Backend");
 261             new RemoveValueProxyPhase().apply(graph);
 262 
 263             debug.dump(DebugContext.VERBOSE_LEVEL, graph, "Stub graph before compilation");
 264             return graph;
 265         } catch (Exception e) {
 266             throw GraalError.shouldNotReachHere(e);
 267         }
 268     }
 269 
 270     private static InvokeNode createStaticInvoke(GraphKit kit, ResolvedJavaMethod method, ValueNode... args) {
 271         return kit.createInvoke(method, Static, null, UNKNOWN_BCI, args);
 272     }
 273 
 274     private ResolvedJavaMethod getGraphMethod() {
 275         ResolvedJavaMethod thisMethod = null;
 276         for (ResolvedJavaMethod method : providers.getMetaAccess().lookupJavaType(ForeignCallStub.class).getDeclaredMethods()) {
 277             if (method.getName().equals("getGraph")) {
 278                 if (thisMethod == null) {
 279                     thisMethod = method;
 280                 } else {
 281                     throw new InternalError("getGraph is ambiguous");
 282                 }
 283             }
 284         }
 285         if (thisMethod == null) {
 286             throw new InternalError("Can't find getGraph");
 287         }
 288         return thisMethod;
 289     }
 290 
 291     private ParameterNode[] createParameters(GraphKit kit, Class<?>[] args) {
 292         ParameterNode[] params = new ParameterNode[args.length];
 293         ResolvedJavaType accessingClass = providers.getMetaAccess().lookupJavaType(getClass());
 294         for (int i = 0; i < args.length; i++) {
 295             ResolvedJavaType type = providers.getMetaAccess().lookupJavaType(args[i]).resolve(accessingClass);
 296             StampPair stamp = StampFactory.forDeclaredType(kit.getGraph().getAssumptions(), type, false);
 297             ParameterNode param = kit.unique(new ParameterNode(i, stamp));
 298             params[i] = param;
 299         }
 300         return params;
 301     }
 302 
 303     private StubForeignCallNode createTargetCall(GraphKit kit, ParameterNode[] params, ReadRegisterNode thread) {
 304         Stamp stamp = StampFactory.forKind(JavaKind.fromJavaClass(target.getDescriptor().getResultType()));
 305         if (prependThread) {
 306             ValueNode[] targetArguments = new ValueNode[1 + params.length];
 307             targetArguments[0] = thread;
 308             System.arraycopy(params, 0, targetArguments, 1, params.length);
 309             return kit.append(new StubForeignCallNode(providers.getForeignCalls(), stamp, target.getDescriptor(), targetArguments));
 310         } else {
 311             return kit.append(new StubForeignCallNode(providers.getForeignCalls(), stamp, target.getDescriptor(), params));
 312         }
 313     }
 314 }