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