diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java index f37585deb807..b078c19c0481 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java @@ -156,8 +156,7 @@ public HotSpotGraalRuntimeProvider getGraalRuntime() { private static final Unsafe UNSAFE = Unsafe.getUnsafe(); /** - * Implemented by - * {@code com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.compileMethod}. + * Implemented by {@code com.oracle.svm.graal.hotspot.guestgraal.GuestGraal#compileMethod}. */ public static native long compileMethodInLibgraal(long isolateThread, long methodHandle, diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java index 3f6c00e73db3..424258880492 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java @@ -60,7 +60,7 @@ public class LibGraalCompilerTest extends HotSpotGraalCompilerTest { * Computes a hash based on the static final Object fields in {@code typeHandle}. * * Implemented by - * {@code com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.hashConstantOopFields}. + * {@code com.oracle.svm.graal.hotspot.guestgraal.GuestGraal#hashConstantOopFields}. * * @param isolateThread * @param typeHandle the type whose constant object fields are to be hashed diff --git a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalCompiler.java b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalCompiler.java index 3a9f68039fd2..c10f37291698 100644 --- a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalCompiler.java +++ b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalCompiler.java @@ -251,18 +251,6 @@ private static String match(StructuredGraph graph, String methodPattern) { return label; } - /** - * Substituted by {@code com.oracle.svm.graal.hotspot.libgraal. - * Target_jdk_graal_compiler_core_GraalCompiler} to optionally test routing fatal error handling - * from libgraal to HotSpot. - * - * @return true if the caller should proceed to throw an exception - */ - @SuppressWarnings("unused") - private static boolean notifyCrash(String crashMessage) { - return true; - } - /** * Builds the graph, optimizes it. */ diff --git a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalServiceThread.java b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalServiceThread.java index 094fb5e0ade2..7c5f25485341 100644 --- a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalServiceThread.java +++ b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/core/GraalServiceThread.java @@ -71,15 +71,15 @@ protected void onAttachError(InternalError error) { } /** - * Substituted by {@code com.oracle.svm.graal.hotspot.libgraal. - * Target_jdk_graal_compiler_core_GraalServiceThread} to attach to the peer runtime if required. + * Substituted by {@code Target_jdk_graal_compiler_core_GraalServiceThread} to attach to the + * peer runtime if required. */ private void afterRun() { } /** - * Substituted by {@code com.oracle.svm.graal.hotspot.libgraal. - * Target_jdk_graal_compiler_core_GraalServiceThread} to attach to the peer runtime if required. + * Substituted by {@code Target_jdk_graal_compiler_core_GraalServiceThread} to attach to the + * peer runtime if required. */ private void beforeRun() { } diff --git a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/CompilerConfigurationFactory.java b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/CompilerConfigurationFactory.java index b530a1a4879a..f8c80955a659 100644 --- a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/CompilerConfigurationFactory.java +++ b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/CompilerConfigurationFactory.java @@ -285,6 +285,13 @@ private Object getLoadedFromLocation(boolean verbose) { private static String nativeImageLocationQualifier; + /** + * Gets the qualifier for the libgraal library (e.g., "PGO optimized"). + */ + public static String getNativeImageLocationQualifier() { + return nativeImageLocationQualifier; + } + /** * Records a qualifier for the libgraal library (e.g., "PGO optimized"). */ diff --git a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/HotSpotGraalOptionValues.java b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/HotSpotGraalOptionValues.java index a6895371634b..6ac4860637ad 100644 --- a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/HotSpotGraalOptionValues.java +++ b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/HotSpotGraalOptionValues.java @@ -168,8 +168,7 @@ private static String stripPrefix(String name, String prefix) { } /** - * Substituted by - * {@code com.oracle.svm.graal.hotspot.libgraal.Target_jdk_graal_compiler_hotspot_HotSpotGraalOptionValues}. + * Substituted by {@code Target_jdk_graal_compiler_hotspot_HotSpotGraalOptionValues}. * * @param settings unparsed libgraal option values */ @@ -195,8 +194,7 @@ static void printProperties(OptionValues compilerOptions, PrintStream out) { } /** - * Substituted by - * {@code com.oracle.svm.graal.hotspot.libgraal.Target_jdk_graal_compiler_hotspot_HotSpotGraalOptionValues}. + * Substituted by {@code Target_jdk_graal_compiler_hotspot_HotSpotGraalOptionValues}. * * @param out where help is to be printed * @param prefix system property prefix for libgraal VM options diff --git a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/BuildTime.java b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/BuildTime.java index 472e78ea0a0c..9a79963b77ef 100644 --- a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/BuildTime.java +++ b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/BuildTime.java @@ -40,6 +40,7 @@ import java.util.function.Supplier; import jdk.graal.compiler.core.ArchitectureSpecific; +import jdk.graal.compiler.hotspot.CompilerConfigurationFactory; import org.graalvm.collections.EconomicMap; import jdk.graal.compiler.core.common.spi.ForeignCallSignature; @@ -146,6 +147,7 @@ public static void configureGraalForLibGraal(String arch, List> guestServiceClasses, Consumer> registerAsInHeap, Consumer>> hostedGraalSetFoldNodePluginClasses, + String nativeImageLocationQualifier, String encodedGuestObjects) { GraalError.guarantee(VALID_LOADER_NAME.equals(LOADER.getName()), "Only call this method from classloader " + VALID_LOADER_NAME); @@ -154,6 +156,8 @@ public static void configureGraalForLibGraal(String arch, guestServiceClasses.forEach(c -> addProviders(services, arch, c)); GraalServices.setLibgraalServices(services); + CompilerConfigurationFactory.setNativeImageLocationQualifier(nativeImageLocationQualifier); + try { Field cachedHotSpotJVMCIBackendFactoriesField = ObjectCopier.getField(HotSpotJVMCIRuntime.class, "cachedHotSpotJVMCIBackendFactories"); GraalError.guarantee(cachedHotSpotJVMCIBackendFactoriesField.get(null) == null, "Expect cachedHotSpotJVMCIBackendFactories to be null"); diff --git a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/RunTime.java b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/RunTime.java index 2314e4df4014..4bcdbe44e0e7 100644 --- a/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/RunTime.java +++ b/compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/hotspot/guestgraal/RunTime.java @@ -116,6 +116,9 @@ public static long compileMethod(long methodHandle, boolean useProfilingInfo, HotSpotJVMCIRuntime runtime = HotSpotJVMCIRuntime.runtime(); HotSpotGraalCompiler compiler = (HotSpotGraalCompiler) runtime.getCompiler(); + if (methodHandle == 0L) { + return 0L; + } int entryBCI = JVMCICompiler.INVOCATION_ENTRY_BCI; HotSpotResolvedJavaMethod method = runtime.unhand(HotSpotResolvedJavaMethod.class, methodHandle); diff --git a/sdk/mx.sdk/mx_sdk_vm_impl.py b/sdk/mx.sdk/mx_sdk_vm_impl.py index e33d8978ee7a..70911e638e11 100644 --- a/sdk/mx.sdk/mx_sdk_vm_impl.py +++ b/sdk/mx.sdk/mx_sdk_vm_impl.py @@ -2508,7 +2508,6 @@ def get_build_args(self): '-H:APIFunctionPrefix=truffle_isolate_', ] + svm_experimental_options([ '-H:+IgnoreMaxHeapSizeWhileInVMOperation', - '-H:+BuildOutputPrefix', '-H:+GenerateBuildArtifactsFile', # generate 'build-artifacts.json' ]) + mx.get_runtime_jvm_args(self.subject.native_image_jar_distributions) + \ project.native_image_config.build_args + project.native_image_config.build_args_enterprise diff --git a/substratevm/mx.substratevm/mx_substratevm.py b/substratevm/mx.substratevm/mx_substratevm.py index 56af591175d5..f2ff18b58889 100644 --- a/substratevm/mx.substratevm/mx_substratevm.py +++ b/substratevm/mx.substratevm/mx_substratevm.py @@ -1428,7 +1428,7 @@ def _native_image_launcher_extra_jvm_args(): libgraal_jar_distributions = [ 'sdk:NATIVEBRIDGE', 'sdk:JNIUTILS', - 'substratevm:GRAAL_HOTSPOT_LIBRARY'] + 'substratevm:GUESTGRAAL_LIBRARY'] def allow_build_path_in_libgraal(): """ @@ -1458,13 +1458,18 @@ def prevent_build_path_in_libgraal(): return ['-H:NativeLinkerOption=-pdbaltpath:%_PDB%'] return [] +libgraal_features = [ + 'com.oracle.svm.graal.hotspot.guestgraal.GuestGraalFeature' +] + libgraal_build_args = [ + '--features=' + ','.join(libgraal_features), + ## Pass via JVM args opening up of packages needed for image builder early on '-J--add-exports=jdk.graal.compiler/jdk.graal.compiler.hotspot=ALL-UNNAMED', '-J--add-exports=jdk.graal.compiler/jdk.graal.compiler.options=ALL-UNNAMED', '-J--add-exports=jdk.graal.compiler/jdk.graal.compiler.truffle=ALL-UNNAMED', '-J--add-exports=jdk.graal.compiler/jdk.graal.compiler.truffle.hotspot=ALL-UNNAMED', - '-J--add-exports=org.graalvm.jniutils/org.graalvm.jniutils=ALL-UNNAMED', '-J--add-exports=org.graalvm.truffle.compiler/com.oracle.truffle.compiler.hotspot.libgraal=ALL-UNNAMED', '-J--add-exports=org.graalvm.truffle.compiler/com.oracle.truffle.compiler.hotspot=ALL-UNNAMED', '-J--add-exports=org.graalvm.truffle.compiler/com.oracle.truffle.compiler=ALL-UNNAMED', @@ -1537,7 +1542,7 @@ def prevent_build_path_in_libgraal(): destination="", jvm_library=True, jar_distributions=libgraal_jar_distributions, - build_args=libgraal_build_args + ['--features=com.oracle.svm.graal.hotspot.libgraal.LibGraalFeature,com.oracle.svm.graal.hotspot.libgraal.truffle.TruffleLibGraalFeature'], + build_args=libgraal_build_args, add_to_module='java.base', headers=False, home_finder=False, diff --git a/substratevm/mx.substratevm/suite.py b/substratevm/mx.substratevm/suite.py index ea0965010608..78eeb010f325 100644 --- a/substratevm/mx.substratevm/suite.py +++ b/substratevm/mx.substratevm/suite.py @@ -1351,39 +1351,6 @@ "jacoco" : "exclude", }, - "com.oracle.svm.graal.hotspot.libgraal" : { - "subDir": "src", - "sourceDirs": ["src"], - "dependencies": [ - "com.oracle.svm.graal.hotspot", - "com.oracle.svm.graal", - "compiler:GRAAL", - "sdk:NATIVEBRIDGE", - ], - "requires" : [ - "jdk.management" - ], - "requiresConcealed" : { - "java.base" : [ - "jdk.internal.misc", - ], - "jdk.internal.vm.ci": [ - "jdk.vm.ci.meta", - "jdk.vm.ci.code", - "jdk.vm.ci.hotspot", - ] - }, - "checkstyle" : "com.oracle.svm.hosted", - "javaCompliance" : "21+", - "annotationProcessors": [ - "truffle:TRUFFLE_LIBGRAAL_PROCESSOR", - "compiler:GRAAL_PROCESSOR", - "SVM_PROCESSOR", - ], - "defaultBuild": False, - "jacoco" : "exclude", - }, - "com.oracle.svm.configure": { "subDir": "src", "sourceDirs": [ @@ -1853,26 +1820,6 @@ "maven" : False, }, - "GRAAL_HOTSPOT_LIBRARY": { - "subDir": "src", - "description" : "SubstrateVM HotSpot Graal library support", - "javaCompliance" : "21+", - "dependencies": [ - "com.oracle.svm.graal.hotspot.libgraal", - ], - "overlaps" : [ - "LIBRARY_SUPPORT", - "GUESTGRAAL_LIBRARY" - ], - "distDependencies": [ - "SVM", - "sdk:JNIUTILS", - "sdk:NATIVEBRIDGE", - ], - "defaultBuild": False, - "maven": False, - }, - "GUESTGRAAL_LIBRARY": { "subDir": "src", "description" : "GuestGraal HotSpot Graal library support", diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/resources/META-INF/native-image/com.oracle.svm.graal.hotspot.guestgraal/native-image.properties b/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/resources/META-INF/native-image/com.oracle.svm.graal.hotspot.guestgraal/native-image.properties deleted file mode 100644 index a539ab28d1e6..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/resources/META-INF/native-image/com.oracle.svm.graal.hotspot.guestgraal/native-image.properties +++ /dev/null @@ -1,28 +0,0 @@ -JavaArgs = \ - --add-exports=jdk.graal.compiler/jdk.graal.compiler.options=ALL-UNNAMED \ - --add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.core.option=ALL-UNNAMED - -Args = \ - -Djdk.vm.ci.services.aot=true \ - -Dtruffle.TruffleRuntime= \ - --add-exports=org.graalvm.nativeimage.base/com.oracle.svm.util=ALL-UNNAMED \ - --add-exports=org.graalvm.nativeimage.builder/com.oracle.svm.core.feature=ALL-UNNAMED \ - --features=com.oracle.svm.graal.hotspot.guestgraal.GuestGraalFeature \ - --enable-monitoring=heapdump \ - --no-fallback \ - --shared \ - --initialize-at-build-time=jdk.graal.compiler,org.graalvm.libgraal,com.oracle.truffle \ - -o jvmcicompiler \ - -H:+UnlockExperimentalVMOptions \ - -H:+ReportExceptionStackTraces \ - -H:-UseServiceLoaderFeature \ - -H:+AllowFoldMethods \ - -H:+JNIEnhancedErrorCodes \ - -H:InitialCollectionPolicy=LibGraal \ - -H:+PreserveFramePointer \ - -H:-DeleteLocalSymbols \ - -H:HeapDumpDefaultFilenamePrefix=libgraal_pid \ - -H:-AllowVMInternalThreads \ - -R:-AutomaticReferenceHandling \ - -H:-UseContainerSupport \ - -H:+AssertInitializationSpecifiedForAllClasses \ No newline at end of file diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraal.java b/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraal.java index 5ba468977df9..911ba9f7b4fe 100644 --- a/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraal.java +++ b/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraal.java @@ -99,6 +99,11 @@ */ final class GuestGraal { + /* + * See jdk.graal.compiler.hotspot.guestgraal.BuildTime.getRuntimeHandles to see how these + * handles are initialized and what their target methods are. + */ + private final MethodHandle getJNIEnv; private final MethodHandle getSavedProperty; private final MethodHandle ttyPrintf; @@ -239,9 +244,6 @@ private static long compileMethod(JNIEnv jniEnv, long timeAndMemBufferAddress, long profilePathBufferAddress) { try (JNIMethodScope jniScope = new JNIMethodScope("compileMethod", jniEnv)) { - if (methodHandle == 0L) { - return 0L; - } String profileLoadPath; if (profilePathBufferAddress > 0) { profileLoadPath = CTypeConversion.toJavaString(WordFactory.pointer(profilePathBufferAddress)); diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraalFeature.java b/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraalFeature.java index 0c07feb9da4d..3c752f1e0cae 100644 --- a/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraalFeature.java +++ b/substratevm/src/com.oracle.svm.graal.hotspot.guestgraal/src/com/oracle/svm/graal/hotspot/guestgraal/GuestGraalFeature.java @@ -48,7 +48,7 @@ import com.oracle.svm.core.util.VMError; import com.oracle.svm.graal.hotspot.GetCompilerConfig; import com.oracle.svm.graal.hotspot.GetJNIConfig; -import com.oracle.svm.hosted.FeatureImpl; +import jdk.graal.compiler.hotspot.CompilerConfigurationFactory; import jdk.graal.compiler.options.OptionDescriptor; import jdk.graal.compiler.options.OptionKey; import jdk.graal.compiler.serviceprovider.LibGraalService; @@ -397,6 +397,9 @@ public void beforeAnalysis(BeforeAnalysisAccess baa) { List> serviceClasses = impl.getImageClassLoader().findAnnotatedClasses(LibGraalService.class, false); serviceClasses.stream().map(c -> loader.loadClassOrFail(c.getName())).forEach(guestServiceClasses::add); + // Transfer libgraal qualifier (e.g. "PGO optimized") from host to guest. + String nativeImageLocationQualifier = CompilerConfigurationFactory.getNativeImageLocationQualifier(); + MethodHandle configureGraalForLibGraal = mhl.findStatic(buildTimeClass, "configureGraalForLibGraal", methodType(void.class, @@ -404,6 +407,7 @@ public void beforeAnalysis(BeforeAnalysisAccess baa) { List.class, // guestServiceClasses Consumer.class, // registerAsInHeap Consumer.class, // hostedGraalSetFoldNodePluginClasses + String.class, // nativeImageLocationQualifier String.class // encodedGuestObjects )); GetCompilerConfig.Result configResult = GetCompilerConfig.from(Options.GuestJavaHome.getValue(), bb.getOptions()); @@ -417,6 +421,7 @@ public void beforeAnalysis(BeforeAnalysisAccess baa) { guestServiceClasses, registerAsInHeap, hostedGraalSetFoldNodePluginClasses, + nativeImageLocationQualifier, configResult.encodedConfig()); initGraalRuntimeHandles(mhl.findStatic(buildTimeClass, "getRuntimeHandles", methodType(Map.class))); @@ -461,7 +466,7 @@ public void afterAnalysis(AfterAnalysisAccess access) { classesPattern("jdk.graal.compiler.options", "ModifiableOptionValues", "Option.*"), classesPattern("jdk.graal.compiler.util.json", - "JsonWriter"), + "JsonWriter", "JsonBuilder.*"), classesPattern("org.graalvm.collections", "EconomicMap.*", "EmptyMap.*", "Equivalence.*", "Pair"), classesPattern("jdk.vm.ci.amd64", @@ -502,26 +507,12 @@ public void afterAnalysis(AfterAnalysisAccess access) { } } if (!forbiddenReachableTypes.isEmpty()) { + CallTreePrinter.print(bigBang, "reports", "report"); VMError.shouldNotReachHere("GuestGraal build found forbidden hosted types as reachable: %s", String.join(", ", forbiddenReachableTypes)); } optionCollector.afterAnalysis(access); } - @Override - public void beforeImageWrite(BeforeImageWriteAccess access) { - if (!Platform.includedIn(Platform.WINDOWS.class)) { - ((FeatureImpl.BeforeImageWriteAccessImpl) access).registerLinkerInvocationTransformer(linkerInvocation -> { - Path imageFilePath = linkerInvocation.getOutputFile(); - String imageName = imageFilePath.getFileName().toString(); - String posixLibraryPrefix = "lib"; - assert !imageName.startsWith(posixLibraryPrefix); - String posixImageName = posixLibraryPrefix + imageName; - linkerInvocation.setOutputFile(imageFilePath.getParent().resolve(posixImageName)); - return linkerInvocation; - }); - } - } - private static Pattern classesPattern(String packageName, String... regexes) { return Pattern.compile("%s(%s)".formatted(Pattern.quote(packageName + '.'), String.join("|", regexes))); } diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraal.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraal.java deleted file mode 100644 index 906d4c2c1a5f..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraal.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal; - -import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntime.runtime; - -import org.graalvm.word.PointerBase; -import org.graalvm.word.WordFactory; - -import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; -import jdk.vm.ci.hotspot.HotSpotObjectConstant; -import jdk.vm.ci.hotspot.HotSpotResolvedJavaType; -import jdk.vm.ci.services.Services; - -/** - * Access to libgraal, a shared library containing an AOT compiled version of Graal produced by - * GraalVM Native Image. The libgraal library is only available if: - *
    - *
  • the {@linkplain #inLibGraal() current runtime} is libgraal, or
  • - *
  • the HotSpot {@code UseJVMCINativeLibrary} flag is true and the current runtime includes the - * relevant JVMCI API additions for accessing libgraal.
  • - *
- * - * The {@link #isAvailable()} method is provided to test these conditions. It must be used to guard - * usage of all other methods in this class. In addition, only the following methods can be called - * from within libgraal: - *
    - *
  • {@link #isAvailable()}
  • - *
  • {@link #inLibGraal()}
  • - *
  • {@link #translate(Object)}
  • - *
  • {@link #unhand(Class, long)}
  • - *
- */ -public final class LibGraal { - - static final long initialIsolate = Services.IS_BUILDING_NATIVE_IMAGE ? 0L : initializeLibgraal(); - static final boolean available = initialIsolate != 0L; - - // NOTE: The use of reflection to access JVMCI API is to support - // compiling on JDKs with varying versions of JVMCI. - - static { - // Initialize JVMCI to ensure JVMCI opens its packages to Graal. - Services.initializeJVMCI(); - } - - /** - * Determines if libgraal is available for use. - */ - public static boolean isAvailable() { - return inLibGraal() || available; - } - - /** - * Determines if the current runtime is libgraal. - */ - public static boolean inLibGraal() { - return Services.IS_IN_NATIVE_IMAGE; - } - - /** - * Creates or retrieves an object in the peer runtime that mirrors {@code obj}. - * - * This mechanism can be used to pass and return values between the HotSpot and libgraal - * runtimes. In the receiving runtime, the value can be converted back to an object with - * {@link #unhand}. - * - * @param obj an object for which an equivalent instance in the peer runtime is requested - * @return a JNI global reference to the mirror of {@code obj} in the peer runtime - * @throws IllegalArgumentException if {@code obj} is not of a translatable type - */ - public static long translate(Object obj) { - return HotSpotJVMCIRuntime.runtime().translate(obj); - } - - /** - * Dereferences and returns the object referred to by the JNI global reference {@code handle}. - * The global reference is deleted prior to returning. Any further use of {@code handle} is - * invalid. - * - * @param handle a JNI global reference to an object in the current runtime - * @return the object referred to by {@code handle} - * @throws ClassCastException if the returned object cannot be cast to {@code type} - */ - @SuppressWarnings("unchecked") - public static T unhand(Class type, long handle) { - return HotSpotJVMCIRuntime.runtime().unhand(type, handle); - } - - /** - * @see HotSpotJVMCIRuntime#getJObjectValue(HotSpotObjectConstant) - */ - public static T getJObjectValue(HotSpotObjectConstant constant) { - return WordFactory.pointer(runtime().getJObjectValue(constant)); - } - - /** - * @see HotSpotJVMCIRuntime#asResolvedJavaType(long) - */ - public static HotSpotResolvedJavaType asResolvedJavaType(PointerBase pointer) { - return runtime().asResolvedJavaType(pointer.rawValue()); - } - - private static long initializeLibgraal() { - return HotSpotJVMCIRuntime.runtime().registerNativeMethods(LibGraal.class)[1]; - } - - /** - * Ensures the current thread is attached to the peer runtime. - * - * @param isDaemon if the thread is not yet attached, should it be attached as a daemon - * @param isolate if non-null, the isolate for the current thread is returned in element 0 - * @return {@code true} if this call attached the current thread, {@code false} if the current - * thread was already attached - */ - public static boolean attachCurrentThread(boolean isDaemon, long[] isolate) { - long[] javaVMInfo = isolate != null ? new long[4] : null; - boolean res = runtime().attachCurrentThread(isDaemon, javaVMInfo); - if (isolate != null) { - isolate[0] = javaVMInfo[1]; - } - return res; - } - - /** - * Detaches the current thread from the peer runtime. - * - * @param release if {@code true} and the VM supports releasing the {@code JavaVM} associated - * with libgraal runtimes and this is the last thread attached to a libgraal runtime, - * then this call destroys the associated {@code JavaVM} instance, releasing its - * resources - * @return {@code true} if the {@code JavaVM} associated with the libgraal runtime was destroyed - * as a result of this call - */ - public static boolean detachCurrentThread(boolean release) { - return runtime().detachCurrentThread(release); - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalEntryPoints.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalEntryPoints.java deleted file mode 100644 index a524e3eee666..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalEntryPoints.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright (c) 2019, 2019, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal; - -import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntime.runtime; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.lang.management.ManagementFactory; -import java.util.Arrays; -import java.util.Map; - -import org.graalvm.collections.EconomicMap; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.nativeimage.c.function.CEntryPoint; -import org.graalvm.nativeimage.c.type.CTypeConversion; -import org.graalvm.word.PointerBase; -import org.graalvm.word.WordFactory; - -import com.oracle.svm.core.heap.Heap; -import com.sun.management.ThreadMXBean; - -import jdk.graal.compiler.debug.GlobalMetrics; -import jdk.graal.compiler.hotspot.CompilationContext; -import jdk.graal.compiler.hotspot.CompilationTask; -import jdk.graal.compiler.hotspot.HotSpotGraalCompiler; -import jdk.graal.compiler.hotspot.HotSpotGraalRuntime; -import jdk.graal.compiler.hotspot.HotSpotGraalServices; -import jdk.graal.compiler.hotspot.ProfileReplaySupport; -import jdk.graal.compiler.hotspot.ProfileReplaySupport.Options; -import jdk.graal.compiler.options.OptionDescriptors; -import jdk.graal.compiler.options.OptionKey; -import jdk.graal.compiler.options.OptionValues; -import jdk.graal.compiler.options.OptionsParser; -import jdk.graal.compiler.util.OptionsEncoder; -import jdk.internal.misc.Unsafe; -import jdk.vm.ci.code.InstalledCode; -import jdk.vm.ci.hotspot.HotSpotCompilationRequest; -import jdk.vm.ci.hotspot.HotSpotInstalledCode; -import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; -import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod; -import jdk.vm.ci.hotspot.HotSpotResolvedJavaType; -import jdk.vm.ci.meta.ConstantReflectionProvider; -import jdk.vm.ci.meta.JavaConstant; -import jdk.vm.ci.meta.JavaKind; -import jdk.vm.ci.meta.ResolvedJavaField; -import jdk.vm.ci.runtime.JVMCIBackend; -import jdk.vm.ci.runtime.JVMCICompiler; - -/** - * Entry points in libgraal corresponding to native methods in the scope and - * {@code StandaloneBulkCompile}. - */ -public final class LibGraalEntryPoints { - - static class CachedOptions { - final OptionValues options; - final long hash; - - CachedOptions(OptionValues options, long hash) { - this.options = options; - this.hash = hash; - } - } - - /** - * Since reference handling is synchronous in libgraal, explicitly perform it here and then run - * any code which is expecting to process a reference queue to let it clean up. - */ - static void doReferenceHandling() { - Heap.getHeap().doReferenceHandling(); - synchronized (Target_jdk_vm_ci_hotspot_Cleaner.class) { - Target_jdk_vm_ci_hotspot_Cleaner.clean(); - } - } - - private static final ThreadLocal cachedOptions = new ThreadLocal<>(); - - private static OptionValues decodeOptions(long address, int size, int hash) { - CachedOptions options = cachedOptions.get(); - if (options == null || options.hash != hash) { - byte[] buffer = new byte[size]; - Unsafe.getUnsafe().copyMemory(null, address, buffer, Unsafe.ARRAY_BYTE_BASE_OFFSET, size); - int actualHash = Arrays.hashCode(buffer); - if (actualHash != hash) { - throw new IllegalArgumentException(actualHash + " != " + hash); - } - Map srcMap = OptionsEncoder.decode(buffer); - final EconomicMap, Object> dstMap = OptionValues.newOptionMap(); - final Iterable loader = OptionsParser.getOptionsLoader(); - for (Map.Entry e : srcMap.entrySet()) { - final String optionName = e.getKey(); - final Object optionValue = e.getValue(); - OptionsParser.parseOption(optionName, optionValue, dstMap, loader); - } - - options = new CachedOptions(new OptionValues(dstMap), hash); - cachedOptions.set(options); - } - return options.options; - } - - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_jdk_graal_compiler_hotspot_test_LibGraalCompilerTest_hashConstantOopFields", include = LibGraalFeature.IsEnabled.class) - private static long hashConstantOopFields(JNIEnv jniEnv, - PointerBase jclass, - @CEntryPoint.IsolateThreadContext long isolateThread, - long typeHandle, - boolean useScope, - int iterations, - int oopsPerIteration, - boolean verbose) { - HotSpotJVMCIRuntime runtime = runtime(); - JVMCIBackend backend = runtime.getHostJVMCIBackend(); - ConstantReflectionProvider constantReflection = backend.getConstantReflection(); - HotSpotResolvedJavaType type = LibGraal.unhand(HotSpotResolvedJavaType.class, typeHandle); - ResolvedJavaField[] staticFields = type.getStaticFields(); - JavaConstant receiver = null; - long hash = 13; - - Object scopeDescription = "TestingOopHandles"; - - int remainingIterations = iterations; - while (remainingIterations-- > 0) { - ResolvedJavaField lastReadField = null; - try (CompilationContext scope = useScope ? HotSpotGraalServices.openLocalCompilationContext(scopeDescription) : null) { - if (verbose && useScope) { - System.out.println("Opened " + scopeDescription); - } - int remainingOops = oopsPerIteration; - while (remainingOops-- > 0) { - for (ResolvedJavaField field : staticFields) { - if (field.getType().getJavaKind() == JavaKind.Object) { - JavaConstant value = constantReflection.readFieldValue(field, receiver); - if (value != null) { - lastReadField = field; - hash = hash ^ value.hashCode(); - } - } - } - } - } - if (!useScope) { - System.gc(); - if (verbose) { - System.out.println("calling reference handling"); - } - LibGraalEntryPoints.doReferenceHandling(); - if (verbose) { - System.out.println("called reference handling"); - } - // Need one more remote oop creation to trigger releasing - // of remote oops that were wrapped in weakly reachable - // IndirectHotSpotObjectConstantImpl objects just collected. - constantReflection.readFieldValue(lastReadField, receiver); - } else if (verbose) { - System.out.println(" Closed " + scopeDescription); - } - } - return hash; - } - - /** - * The implementation of - * {@code jdk.graal.compiler.hotspot.test.LibGraalCompilationDriver#compileMethodInLibgraal}. - * - * @param methodHandle the method to be compiled. This is a handle to a - * {@link HotSpotResolvedJavaMethod} in HotSpot's heap. A value of 0L can be passed - * to use this method for the side effect of initializing a - * {@link HotSpotGraalCompiler} instance without doing any compilation. - * @param useProfilingInfo specifies if profiling info should be used during the compilation - * @param installAsDefault specifies if the compiled code should be installed for the - * {@code Method*} associated with {@code methodHandle} - * @param printMetrics specifies if global metrics should be printed and reset - * @param optionsAddress native byte buffer storing a serialized {@link OptionValues} object - * @param optionsSize the number of bytes in the buffer - * @param optionsHash hash code of bytes in the buffer (computed with - * {@link Arrays#hashCode(byte[])}) - * @param stackTraceAddress a native buffer in which a serialized stack trace can be returned. - * The caller will only read from this buffer if this method returns 0. A returned - * serialized stack trace is returned in this buffer with the following format: - * - *
-     *            struct {
-     *                int   length;
-     *                byte  data[length]; // Bytes from a stack trace printed to a ByteArrayOutputStream.
-     *            }
-     *            
- * - * where {@code length} truncated to {@code stackTraceCapacity - 4} if necessary - * - * @param stackTraceCapacity the size of the stack trace buffer - * @param timeAndMemBufferAddress 16-byte native buffer to store result of time and memory - * measurements of the compilation - * @param profilePathBufferAddress native buffer containing a 0-terminated C string representing - * {@link Options#LoadProfiles} path. - * @return a handle to a {@link InstalledCode} in HotSpot's heap or 0 if compilation failed - */ - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_jdk_graal_compiler_hotspot_test_LibGraalCompilationDriver_compileMethodInLibgraal", include = LibGraalFeature.IsEnabled.class) - private static long compileMethod(JNIEnv jniEnv, - PointerBase jclass, - @CEntryPoint.IsolateThreadContext long isolateThread, - long methodHandle, - boolean useProfilingInfo, - boolean installAsDefault, - boolean printMetrics, - boolean eagerResolving, - long optionsAddress, - int optionsSize, - int optionsHash, - long stackTraceAddress, - int stackTraceCapacity, - long timeAndMemBufferAddress, - long profilePathBufferAddress) { - try (JNIMethodScope jniScope = new JNIMethodScope("compileMethod", jniEnv)) { - HotSpotJVMCIRuntime runtime = runtime(); - HotSpotGraalCompiler compiler = (HotSpotGraalCompiler) runtime.getCompiler(); - if (methodHandle == 0L) { - return 0L; - } - HotSpotResolvedJavaMethod method = LibGraal.unhand(HotSpotResolvedJavaMethod.class, methodHandle); - - int entryBCI = JVMCICompiler.INVOCATION_ENTRY_BCI; - HotSpotCompilationRequest request = new HotSpotCompilationRequest(method, entryBCI, 0L); - try (CompilationContext scope = HotSpotGraalServices.openLocalCompilationContext(request)) { - OptionValues options = decodeOptions(optionsAddress, optionsSize, optionsHash); - CompilationTask task = new CompilationTask(runtime, compiler, request, useProfilingInfo, false, false, eagerResolving, installAsDefault); - if (profilePathBufferAddress > 0) { - String profileLoadPath = CTypeConversion.toJavaString(WordFactory.pointer(profilePathBufferAddress)); - options = new OptionValues(options, ProfileReplaySupport.Options.LoadProfiles, profileLoadPath); - } - long allocatedBytesBefore = 0; - ThreadMXBean threadMXBean = null; - long timeBefore = 0; - if (timeAndMemBufferAddress != 0) { - threadMXBean = (ThreadMXBean) ManagementFactory.getThreadMXBean(); - allocatedBytesBefore = threadMXBean.getCurrentThreadAllocatedBytes(); - timeBefore = System.currentTimeMillis(); - } - task.runCompilation(options); - if (timeAndMemBufferAddress != 0) { - long allocatedBytesAfter = threadMXBean.getCurrentThreadAllocatedBytes(); - long bytesAllocated = allocatedBytesAfter - allocatedBytesBefore; - long timeAfter = System.currentTimeMillis(); - long timeSpent = timeAfter - timeBefore; - Unsafe.getUnsafe().putLong(timeAndMemBufferAddress, bytesAllocated); - Unsafe.getUnsafe().putLong(timeAndMemBufferAddress + 8, timeSpent); - } - HotSpotInstalledCode installedCode = task.getInstalledCode(); - if (printMetrics) { - GlobalMetrics metricValues = ((HotSpotGraalRuntime) compiler.getGraalRuntime()).getMetricValues(); - metricValues.print(options); - metricValues.clear(); - } - return LibGraal.translate(installedCode); - } - } catch (Throwable t) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - t.printStackTrace(new PrintStream(baos)); - byte[] stackTrace = baos.toByteArray(); - int length = Math.min(stackTraceCapacity - Integer.BYTES, stackTrace.length); - Unsafe.getUnsafe().putInt(stackTraceAddress, length); - Unsafe.getUnsafe().copyMemory(stackTrace, Unsafe.ARRAY_BYTE_BASE_OFFSET, null, stackTraceAddress + Integer.BYTES, length); - return 0L; - } finally { - /* - * libgraal doesn't use a dedicated reference handler thread, so we trigger the - * reference handling manually when a compilation finishes. - */ - LibGraalEntryPoints.doReferenceHandling(); - } - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalFeature.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalFeature.java deleted file mode 100644 index 4646b33bffd5..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalFeature.java +++ /dev/null @@ -1,564 +0,0 @@ -/* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal; - -import java.io.PrintStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.BooleanSupplier; - -import jdk.graal.compiler.hotspot.GraalHotSpotVMConfigAccess; -import jdk.graal.compiler.serviceprovider.LibGraalService; -import org.graalvm.collections.EconomicMap; -import org.graalvm.nativeimage.ImageSingletons; -import org.graalvm.nativeimage.hosted.Feature; - -import com.oracle.graal.pointsto.BigBang; -import com.oracle.graal.pointsto.ObjectScanner; -import com.oracle.graal.pointsto.meta.AnalysisMethod; -import com.oracle.graal.pointsto.meta.AnalysisUniverse; -import com.oracle.graal.pointsto.meta.InvokeInfo; -import com.oracle.graal.pointsto.meta.ObjectReachableCallback; -import com.oracle.svm.core.RuntimeAssertionsSupport; -import com.oracle.svm.core.SubstrateUtil; -import com.oracle.svm.core.annotate.Delete; -import com.oracle.svm.core.annotate.Substitute; -import com.oracle.svm.core.annotate.TargetClass; -import com.oracle.svm.core.annotate.TargetElement; -import com.oracle.svm.core.feature.InternalFeature; -import com.oracle.svm.core.graal.meta.RuntimeConfiguration; -import com.oracle.svm.core.graal.snippets.NodeLoweringProvider; -import com.oracle.svm.core.heap.UnknownObjectField; -import com.oracle.svm.core.option.RuntimeOptionKey; -import com.oracle.svm.core.option.RuntimeOptionValues; -import com.oracle.svm.core.option.XOptions; -import com.oracle.svm.core.util.UserError; -import com.oracle.svm.core.util.VMError; -import com.oracle.svm.graal.hosted.GraalCompilerFeature; -import com.oracle.svm.graal.hotspot.GetJNIConfig; -import com.oracle.svm.hosted.FeatureImpl; -import com.oracle.svm.hosted.FeatureImpl.DuringSetupAccessImpl; -import com.oracle.svm.hosted.ImageClassLoader; -import com.oracle.svm.hosted.jni.JNIFeature; -import com.oracle.svm.hosted.reflect.ReflectionFeature; -import com.oracle.svm.util.ModuleSupport; -import com.oracle.svm.util.ReflectionUtil; - -import jdk.graal.compiler.core.ArchitectureSpecific; -import jdk.graal.compiler.core.GraalServiceThread; -import jdk.graal.compiler.core.target.Backend; -import jdk.graal.compiler.debug.GraalError; -import jdk.graal.compiler.graph.Node; -import jdk.graal.compiler.graph.NodeClass; -import jdk.graal.compiler.hotspot.EncodedSnippets; -import jdk.graal.compiler.hotspot.HotSpotBackend; -import jdk.graal.compiler.hotspot.HotSpotForeignCallLinkage; -import jdk.graal.compiler.hotspot.HotSpotGraalCompiler; -import jdk.graal.compiler.hotspot.HotSpotReplacementsImpl; -import jdk.graal.compiler.hotspot.SnippetObjectConstant; -import jdk.graal.compiler.hotspot.meta.HotSpotHostForeignCallsProvider; -import jdk.graal.compiler.hotspot.meta.HotSpotProviders; -import jdk.graal.compiler.nodes.graphbuilderconf.GeneratedPluginFactory; -import jdk.graal.compiler.nodes.spi.SnippetParameterInfo; -import jdk.graal.compiler.options.OptionDescriptor; -import jdk.graal.compiler.options.OptionDescriptors; -import jdk.graal.compiler.options.OptionDescriptorsMap; -import jdk.graal.compiler.options.OptionKey; -import jdk.graal.compiler.options.OptionValues; -import jdk.graal.compiler.options.OptionsParser; -import jdk.graal.compiler.phases.util.Providers; -import jdk.graal.compiler.serviceprovider.GraalServices; -import jdk.graal.compiler.serviceprovider.SpeculationReasonGroup; -import jdk.graal.compiler.truffle.hotspot.HotSpotTruffleCompilerImpl; -import jdk.vm.ci.hotspot.HotSpotConstantReflectionProvider; -import jdk.vm.ci.hotspot.HotSpotJVMCIBackendFactory; -import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; -import jdk.vm.ci.meta.JavaConstant; -import jdk.vm.ci.meta.ResolvedJavaMethod; -import jdk.vm.ci.services.Services; - -public class LibGraalFeature implements InternalFeature { - - private final OptionCollector optionCollector = new OptionCollector(HotSpotGraalOptionValuesUtil.vmOptionDescriptors); - private HotSpotReplacementsImpl hotSpotSubstrateReplacements; - - public LibGraalFeature() { - /* Open up all modules needed to build LibGraal image */ - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "java.base", "jdk.internal.misc"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "jdk.internal.vm.ci"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "jdk.graal.compiler"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "jdk.graal.compiler.management"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "org.graalvm.collections"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "org.graalvm.word"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "org.graalvm.nativeimage", "org.graalvm.nativeimage.impl"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "org.graalvm.nativeimage.base"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, false, "org.graalvm.nativeimage.builder"); - ModuleSupport.accessPackagesToClass(ModuleSupport.Access.EXPORT, LibGraalFeature.class, true, "org.graalvm.nativeimage.llvm"); - } - - @Override - public List> getRequiredFeatures() { - /* - * LibGraal needs JNIFeature for the upcalls from HotSpot and ReflectionFeature to construct - * exceptions in jdk.internal.vm.TranslatedException.create(). However, both of these - * features are automatically registered (i.e. annotated by @AutomaticallyRegisteredFeature) - * so no need to explicitly add them here. Simply trying to look them up ensures that they - * are available. - */ - ImageSingletons.lookup(ReflectionFeature.class); - ImageSingletons.lookup(JNIFeature.class); - - return List.of(GraalCompilerFeature.class); - } - - public static final class IsEnabled implements BooleanSupplier { - @Override - public boolean getAsBoolean() { - return ImageSingletons.contains(LibGraalFeature.class); - } - } - - @Override - public void duringSetup(DuringSetupAccess a) { - DuringSetupAccessImpl access = (DuringSetupAccessImpl) a; - access.registerObjectReachableCallback(OptionKey.class, optionCollector::doCallback); - - ImageClassLoader imageClassLoader = access.getImageClassLoader(); - GetJNIConfig.register(imageClassLoader.getClassLoader()); - } - - /** - * Collects all {@link OptionKey}s that are reachable at run time. - *

- * This {@linkplain OptionsParser#setLibgraalOptions} initializes} the set of compiler options - * available in libgraal to an empty set that is populated after analysis. - */ - private static class OptionCollector implements ObjectReachableCallback> { - private final ConcurrentHashMap, OptionKey> options = new ConcurrentHashMap<>(); - - /** - * Libgraal compiler options. This is disjoint from {@link #vmOptionDescriptors}. - * {@link #vmOptionDescriptors}. - */ - private final OptionsParser.LibGraalOptionsInfo compilerOptions; - - /** - * Libgraal VM options. This is disjoint from {@link #compilerOptions}. - */ - private final EconomicMap vmOptionDescriptors; - - private boolean sealed; - - OptionCollector(EconomicMap vmOptionDescriptors) { - this.compilerOptions = OptionsParser.setLibgraalOptions(OptionsParser.LibGraalOptionsInfo.create()); - this.vmOptionDescriptors = vmOptionDescriptors; - } - - @Override - public void doCallback(DuringAnalysisAccess access, OptionKey option, ObjectScanner.ScanReason reason) { - if (sealed) { - GraalError.guarantee(options.contains(option), "All options must have been discovered during static analysis"); - } else { - options.put(option, option); - } - } - - void afterAnalysis(AfterAnalysisAccess access) { - sealed = true; - for (OptionKey option : options.keySet()) { - OptionDescriptor descriptor = option.getDescriptor(); - if (descriptor.isServiceLoaded()) { - VMError.guarantee(access.isReachable(option.getClass())); - VMError.guarantee(access.isReachable(descriptor.getClass())); - String name = option.getName(); - if (isCompilerOption(descriptor)) { - if (option instanceof RuntimeOptionKey) { - throw VMError.shouldNotReachHere("%s cannot be a compiler option", descriptor.getLocation()); - } - compilerOptions.descriptors().put(name, descriptor); - String module = descriptor.getDeclaringClass().getModule().getName(); - if (module.contains("enterprise")) { - compilerOptions.enterpriseOptions().add(name); - } - } else { - vmOptionDescriptors.put(name, descriptor); - } - } - } - } - } - - @Override - public void registerLowerings(RuntimeConfiguration runtimeConfig, OptionValues options, Providers substrateProviders, - Map, NodeLoweringProvider> lowerings, boolean hosted) { - hotSpotSubstrateReplacements = getReplacements(); - } - - /** - * Determines if {@code provider} should be added as a provider of a service. - * - * @param arch a value compatible with {@link ArchitectureSpecific#getArchitecture()} - */ - protected boolean shouldAddProvider(Object provider, String arch) { - if (provider instanceof ArchitectureSpecific as) { - if (!as.getArchitecture().equals(arch)) { - return false; - } - } else { - String name = provider.getClass().getName(); - for (var knownArch : GraalHotSpotVMConfigAccess.KNOWN_ARCHITECTURES) { - String archPackage = ".%s.".formatted(knownArch); - if (name.contains(archPackage)) { - throw VMError.shouldNotReachHere("%s should implement %s", name, ArchitectureSpecific.class); - } - } - } - Module module = provider.getClass().getModule(); - return isGraalModule(module); - } - - private static boolean isGraalModule(Module module) { - String name = module.getName(); - if (name != null) { - // Only services in the core graal modules should be added - return name.equals("jdk.graal.compiler") || - name.equals("jdk.graal.compiler.management") || - name.equals("com.oracle.graal.graal_enterprise"); - } - return false; - } - - @SuppressWarnings("unchecked") - private void addProviders(Map, List> services, String arch, Class service) { - List providers = (List) services.computeIfAbsent(service, key -> new ArrayList<>()); - ModuleLayer layer = GraalServices.class.getModule().getLayer(); - ServiceLoader.load(layer, service).stream().map(ServiceLoader.Provider::get).filter(provider -> shouldAddProvider(provider, arch)).forEach(providers::add); - } - - @SuppressWarnings({"try", "unchecked"}) - @Override - public void beforeAnalysis(BeforeAnalysisAccess access) { - FeatureImpl.BeforeAnalysisAccessImpl impl = (FeatureImpl.BeforeAnalysisAccessImpl) access; - BigBang bb = impl.getBigBang(); - - HotSpotGraalCompiler compiler = (HotSpotGraalCompiler) HotSpotJVMCIRuntime.runtime().getCompiler(); - String arch = compiler.getGraalRuntime().getTarget().arch.getName(); - - ImageClassLoader imageClassLoader = impl.getImageClassLoader(); - List> serviceClasses = imageClassLoader.findAnnotatedClasses(LibGraalService.class, false); - Map, List> services = new HashMap<>(); - for (var c : serviceClasses) { - addProviders(services, arch, c); - } - GraalServices.setLibgraalServices(services); - - // Instantiate the truffle compiler to ensure the backends it uses are initialized. - List truffleBackends = HotSpotTruffleCompilerImpl.ensureBackendsInitialized(RuntimeOptionValues.singleton()); - - // Filter out any cached services which are for a different architecture - try { - final Field servicesCacheField = ReflectionUtil.lookupField(Services.class, "servicesCache"); - Map, List> servicesCache = (Map, List>) servicesCacheField.get(null); - filterArchitectureServices(arch, servicesCache); - servicesCache.remove(GeneratedPluginFactory.class); - - Field cachedHotSpotJVMCIBackendFactoriesField = ReflectionUtil.lookupField(HotSpotJVMCIRuntime.class, "cachedHotSpotJVMCIBackendFactories"); - List cachedHotSpotJVMCIBackendFactories = (List) cachedHotSpotJVMCIBackendFactoriesField.get(null); - cachedHotSpotJVMCIBackendFactories.removeIf(factory -> !factory.getArchitecture().equalsIgnoreCase(arch)); - } catch (ReflectiveOperationException ex) { - throw VMError.shouldNotReachHere(ex); - } - - // Force construction of all stubs so their types are known. - HotSpotProviders providers = getReplacements().getProviders(); - registerForeignCalls(providers); - - for (Backend backend : truffleBackends) { - registerForeignCalls((HotSpotProviders) backend.getProviders()); - } - - hotSpotSubstrateReplacements.encode(bb.getOptions()); - if (!RuntimeAssertionsSupport.singleton().desiredAssertionStatus(SnippetParameterInfo.class)) { - // Clear the saved names if assertions aren't enabled - hotSpotSubstrateReplacements.clearSnippetParameterNames(); - } - - // Mark all the Node classes as allocated so they are available during graph decoding. - EncodedSnippets encodedSnippets = HotSpotReplacementsImpl.getEncodedSnippets(); - for (NodeClass nodeClass : encodedSnippets.getSnippetNodeClasses()) { - impl.getMetaAccess().lookupJavaType(nodeClass.getClazz()).registerAsInstantiated("All " + NodeClass.class.getName() + " classes are marked as instantiated eagerly."); - } - } - - private static void registerForeignCalls(HotSpotProviders providers) { - HotSpotHostForeignCallsProvider foreignCalls = providers.getForeignCalls(); - foreignCalls.forEachForeignCall((sig, linkage) -> { - if (linkage == null || linkage.isCompiledStub()) { - if (HotSpotForeignCallLinkage.Stubs.initStub(sig)) { - if (linkage != null) { - // Construct the stub so that all types it uses are registered in - // SymbolicSnippetEncoder.snippetTypes - foreignCalls.lookupForeignCall(sig); - } - } - } - }); - } - - private static void filterArchitectureServices(String archPackage, Map, List> services) { - for (List list : services.values()) { - list.removeIf(o -> { - String name = o.getClass().getName(); - if (name.contains(".aarch64.") || name.contains(".amd64.") || name.contains(".riscv64.")) { - return !name.contains(archPackage); - } - return false; - }); - } - } - - @Override - public void afterAnalysis(AfterAnalysisAccess access) { - optionCollector.afterAnalysis(access); - verifyReachableTruffleClasses(access); - } - - /** - * Verifies that the Truffle compiler does not bring Truffle API types into an image. We need to - * use the points to analysis to verify that the Truffle API types are not reachable. - */ - private static void verifyReachableTruffleClasses(AfterAnalysisAccess access) { - AnalysisUniverse universe = ((FeatureImpl.AfterAnalysisAccessImpl) access).getUniverse(); - Map seen = new LinkedHashMap<>(); - for (AnalysisMethod analysisMethod : universe.getMethods()) { - if (analysisMethod.isDirectRootMethod() && analysisMethod.isSimplyImplementationInvoked()) { - seen.put(analysisMethod, "direct root"); - } - if (analysisMethod.isVirtualRootMethod()) { - for (AnalysisMethod impl : analysisMethod.collectMethodImplementations(false)) { - VMError.guarantee(impl.isImplementationInvoked()); - seen.put(impl, "virtual root"); - } - } - } - Deque todo = new ArrayDeque<>(seen.keySet()); - SortedSet disallowedTypes = new TreeSet<>(); - while (!todo.isEmpty()) { - AnalysisMethod m = todo.removeFirst(); - String className = m.getDeclaringClass().toClassName(); - if (!isAllowedType(className)) { - StringBuilder msg = new StringBuilder(className); - Object reason = m; - while (true) { - msg.append("<-"); - if (reason instanceof ResolvedJavaMethod) { - msg.append(((ResolvedJavaMethod) reason).format("%H.%n(%p)")); - reason = seen.get(reason); - } else { - msg.append(reason); - break; - } - } - disallowedTypes.add(msg.toString()); - } - for (InvokeInfo invoke : m.getInvokes()) { - for (AnalysisMethod callee : invoke.getOriginalCallees()) { - if (seen.putIfAbsent(callee, m) == null) { - todo.add(callee); - } - } - } - } - if (!disallowedTypes.isEmpty()) { - throw UserError.abort("Following non allowed Truffle types are reachable on heap: %s", String.join(", ", disallowedTypes)); - } - } - - private static boolean isAllowedType(String className) { - if (className.startsWith("com.oracle.truffle.")) { - return className.startsWith("com.oracle.truffle.compiler."); - } - return true; - } - - static HotSpotReplacementsImpl getReplacements() { - HotSpotGraalCompiler compiler = (HotSpotGraalCompiler) HotSpotJVMCIRuntime.runtime().getCompiler(); - HotSpotProviders originalProvider = compiler.getGraalRuntime().getHostProviders(); - return (HotSpotReplacementsImpl) originalProvider.getReplacements(); - } - - private static boolean isCompilerOption(OptionDescriptor descriptor) { - return isGraalModule(descriptor.getDeclaringClass().getModule()); - } -} - -@TargetClass(className = "jdk.vm.ci.hotspot.SharedLibraryJVMCIReflection", onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_vm_ci_hotspot_SharedLibraryJVMCIReflection { - - @Substitute - static Object convertUnknownValue(Object object) { - return object; - } - - // Annotations are currently unsupported in libgraal. These substitutions will turn their use - // into an image time build error. - @Delete - static native Annotation[] getClassAnnotations(String className); - - @Delete - static native Annotation[][] getParameterAnnotations(String className, String methodName); - - @Delete - static native Annotation[] getMethodAnnotationsInternal(ResolvedJavaMethod javaMethod); -} - -@TargetClass(value = SpeculationReasonGroup.class, onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_graal_compiler_serviceprovider_SpeculationReasonGroup { - - /** - * Delete this constructor to ensure {@link SpeculationReasonGroup} ids are in the libgraal - * image and thus global across all libgraal isolates. - */ - @Delete - @TargetElement(name = TargetElement.CONSTRUCTOR_NAME) - native void constructor(String name, Class... signature); -} - -/** - * {@link HotSpotConstantReflectionProvider#forObject} can only be used to wrap compiler objects so - * interpose to return a {@link SnippetObjectConstant}. - */ -@TargetClass(className = "jdk.vm.ci.hotspot.HotSpotConstantReflectionProvider", onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_vm_ci_hotspot_HotSpotConstantReflectionProvider { - - @Substitute - public JavaConstant forString(String value) { - return forObject(value); - } - - @Substitute - @SuppressWarnings({"static-method", "unused"}) - public JavaConstant forObject(Object value) { - return new SnippetObjectConstant(value); - } -} - -@TargetClass(className = "jdk.vm.ci.hotspot.DirectHotSpotObjectConstantImpl", onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_vm_ci_hotspot_DirectHotSpotObjectConstantImpl { - - @Substitute - @SuppressWarnings({"static-method", "unused"}) - @TargetElement(name = TargetElement.CONSTRUCTOR_NAME) - void constructor(Object object, boolean compressed) { - throw new InternalError("DirectHotSpotObjectConstantImpl unsupported"); - } -} - -@TargetClass(className = "jdk.graal.compiler.hotspot.HotSpotGraalOptionValues", onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_graal_compiler_hotspot_HotSpotGraalOptionValues { - - @Substitute - private static void notifyLibgraalOptions(Map vmOptionSettings) { - HotSpotGraalOptionValuesUtil.initializeOptions(vmOptionSettings); - } - - @Substitute - private static void printLibgraalProperties(PrintStream out, String prefix) { - HotSpotGraalOptionValuesUtil.printOptions(out, prefix); - } -} - -/** - * Support for {@link Target_jdk_graal_compiler_hotspot_HotSpotGraalOptionValues}. - */ -final class HotSpotGraalOptionValuesUtil { - /** - * Options configuring the VM in which libgraal is running. - */ - @UnknownObjectField(fullyQualifiedTypes = "org.graalvm.collections.EconomicMapImpl") // - static EconomicMap vmOptionDescriptors = EconomicMap.create(); - - static void initializeOptions(Map settings) { - processXOptions(settings); - EconomicMap, Object> vmOptionValues = OptionValues.newOptionMap(); - Iterable vmOptionLoader = List.of(new OptionDescriptorsMap(vmOptionDescriptors)); - OptionsParser.parseOptions(EconomicMap.wrapMap(settings), vmOptionValues, vmOptionLoader); - RuntimeOptionValues.singleton().update(vmOptionValues); - } - - private static void processXOptions(Map settings) { - for (var i = settings.entrySet().iterator(); i.hasNext();) { - var e = i.next(); - String key = e.getKey(); - String value = e.getValue(); - if (key.startsWith("X") && value.isEmpty()) { - String xarg = key.substring(1); - if (XOptions.setOption(xarg)) { - i.remove(); - } - } - } - } - - static void printOptions(PrintStream out, String prefix) { - RuntimeOptionValues vmOptions = RuntimeOptionValues.singleton(); - Iterable vmOptionLoader = Collections.singletonList(new OptionDescriptorsMap(vmOptionDescriptors)); - vmOptions.printHelp(vmOptionLoader, out, prefix, true); - } -} - -@TargetClass(className = "jdk.graal.compiler.core.GraalServiceThread", onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_graal_compiler_core_GraalServiceThread { - @Substitute() - void beforeRun() { - GraalServiceThread thread = SubstrateUtil.cast(this, GraalServiceThread.class); - if (!LibGraal.attachCurrentThread(thread.isDaemon(), null)) { - throw new InternalError("Couldn't attach to HotSpot runtime"); - } - } - - @Substitute - @SuppressWarnings("static-method") - void afterRun() { - LibGraal.detachCurrentThread(false); - } -} - -@TargetClass(className = "jdk.graal.compiler.hotspot.SymbolicSnippetEncoder", onlyWith = LibGraalFeature.IsEnabled.class) -@Delete("shouldn't appear in libgraal") -final class Target_jdk_graal_compiler_hotspot_SymbolicSnippetEncoder { -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalSubstitutions.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalSubstitutions.java deleted file mode 100644 index e573465489e0..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalSubstitutions.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal; - -import java.lang.ref.ReferenceQueue; -import java.util.Map; - -import com.oracle.svm.core.annotate.Alias; -import com.oracle.svm.core.annotate.RecomputeFieldValue; -import com.oracle.svm.core.annotate.Substitute; -import com.oracle.svm.core.annotate.TargetClass; - -import com.oracle.svm.core.heap.GCCause; -import com.oracle.svm.core.heap.Heap; -import com.oracle.svm.core.log.FunctionPointerLogHandler; -import com.oracle.svm.core.util.VMError; -import jdk.graal.compiler.serviceprovider.VMSupport; -import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; -import jdk.vm.ci.hotspot.HotSpotVMConfigAccess; -import jdk.vm.ci.hotspot.HotSpotVMConfigStore; -import jdk.vm.ci.services.Services; -import org.graalvm.jniutils.JNI; -import org.graalvm.jniutils.JNIExceptionWrapper; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.JNIUtil; -import org.graalvm.nativeimage.CurrentIsolate; -import org.graalvm.nativeimage.ImageSingletons; -import org.graalvm.nativeimage.LogHandler; -import org.graalvm.nativeimage.StackValue; -import org.graalvm.nativeimage.VMRuntime; -import org.graalvm.nativeimage.impl.IsolateSupport; -import org.graalvm.word.WordFactory; - -/** - * Contains support code for the substitutions declared in this file. - */ -public final class LibGraalSubstitutions { - - static long jniEnvironmentOffset = Integer.MAX_VALUE; - - static long getJniEnvironmentOffset() { - if (jniEnvironmentOffset == Integer.MAX_VALUE) { - HotSpotJVMCIRuntime jvmciRuntime = HotSpotJVMCIRuntime.runtime(); - HotSpotVMConfigStore store = jvmciRuntime.getConfigStore(); - HotSpotVMConfigAccess config = new HotSpotVMConfigAccess(store); - jniEnvironmentOffset = config.getFieldOffset("JavaThread::_jni_environment", Integer.class, "JNIEnv"); - } - return jniEnvironmentOffset; - } -} - -@TargetClass(value = Services.class, onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_vm_ci_services_Services { - // Checkstyle: stop - @Alias // - @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.FromAlias, isFinal = true)// - public static boolean IS_IN_NATIVE_IMAGE = true; - // Checkstyle: resume - - /* - * Ideally, the original field should be annotated with @NativeImageReinitialize. But that - * requires a larger JVMCI change because the annotation is not visible in that project, so we - * use this substitution instead. - */ - @Alias // - @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.Reset) // - private static Map savedProperties; -} - -@TargetClass(className = "jdk.vm.ci.hotspot.Cleaner", onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_vm_ci_hotspot_Cleaner { - @Alias // - @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.NewInstance, isFinal = true, declClass = ReferenceQueue.class)// - private static ReferenceQueue queue; - - @Alias - static native void clean(); -} - -@TargetClass(value = VMSupport.class, onlyWith = LibGraalFeature.IsEnabled.class) -final class Target_jdk_graal_compiler_serviceprovider_VMSupport { - - @Substitute - public static long getIsolateAddress() { - return CurrentIsolate.getIsolate().rawValue(); - } - - @Substitute - public static long getIsolateID() { - return ImageSingletons.lookup(IsolateSupport.class).getIsolateID(); - } - - /** - * Performs the following actions around a libgraal compilation: - *
    - *
  • before: opens a JNIMethodScope to allow Graal compilations of Truffle host methods to - * call methods on the TruffleCompilerRuntime.
  • - *
  • after: closes the above JNIMethodScope
  • - *
  • after: triggers GC weak reference processing as SVM does not use a separate thread for - * this in libgraal
  • - *
- */ - static class LibGraalCompilationRequestScope implements AutoCloseable { - final JNIMethodScope scope; - - LibGraalCompilationRequestScope() { - HotSpotJVMCIRuntime jvmciRuntime = HotSpotJVMCIRuntime.runtime(); - long offset = LibGraalSubstitutions.getJniEnvironmentOffset(); - long javaThreadAddr = jvmciRuntime.getCurrentJavaThread(); - JNI.JNIEnv env = (JNI.JNIEnv) WordFactory.unsigned(javaThreadAddr).add(WordFactory.unsigned(offset)); - // This scope is required to allow Graal compilations of host methods to call methods - // on the TruffleCompilerRuntime. This is, for example, required to find out about - // Truffle-specific method annotations. - scope = LibGraalUtil.openScope("", env); - } - - @Override - public void close() { - try { - scope.close(); - } finally { - /* - * libgraal doesn't use a dedicated reference handler thread, so we trigger the - * reference handling manually when a compilation finishes. - */ - LibGraalEntryPoints.doReferenceHandling(); - } - } - } - - @Substitute - public static AutoCloseable getCompilationRequestScope() { - return new LibGraalCompilationRequestScope(); - } - - @Substitute - public static void fatalError(String message, int delayMS) { - LogHandler handler = ImageSingletons.lookup(LogHandler.class); - if (handler instanceof FunctionPointerLogHandler) { - try { - Thread.sleep(delayMS); - } catch (InterruptedException e) { - // ignore - } - VMError.shouldNotReachHere(message); - } - } - - @Substitute - public static void startupLibGraal() { - VMRuntime.initialize(); - } - - @Substitute - public static void shutdownLibGraal() { - VMRuntime.shutdown(); - } - - @Substitute - public static void invokeShutdownCallback(String cbClassName, String cbMethodName) { - long offset = LibGraalSubstitutions.getJniEnvironmentOffset(); - long javaThreadAddr = HotSpotJVMCIRuntime.runtime().getCurrentJavaThread(); - JNI.JNIEnv env = (JNI.JNIEnv) WordFactory.unsigned(javaThreadAddr).add(WordFactory.unsigned(offset)); - JNI.JClass cbClass = JNIUtil.findClass(env, JNIUtil.getSystemClassLoader(env), - JNIUtil.getBinaryName(cbClassName), true); - JNI.JMethodID cbMethod = JNIUtil.findMethod(env, cbClass, true, cbMethodName, "()V"); - env.getFunctions().getCallStaticVoidMethodA().call(env, cbClass, cbMethod, StackValue.get(0)); - JNIExceptionWrapper.wrapAndThrowPendingJNIException(env); - } - - @Substitute - public static void notifyLowMemoryPoint(boolean hintFullGC, boolean forceFullGC) { - if (forceFullGC) { - Heap.getHeap().getGC().collectCompletely(GCCause.JavaLangSystemGC); - } else { - Heap.getHeap().getGC().collectionHint(hintFullGC); - } - LibGraalEntryPoints.doReferenceHandling(); - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalUtil.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalUtil.java deleted file mode 100644 index 0fe14aca7835..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/LibGraalUtil.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal; - -import java.util.Objects; - -import com.oracle.svm.graal.hotspot.LibGraalJNIMethodScope; -import com.oracle.svm.util.ClassUtil; -import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; -import jdk.vm.ci.hotspot.HotSpotVMConfigAccess; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.nativeimage.c.type.CLongPointer; -import org.graalvm.word.PointerBase; -import org.graalvm.word.WordFactory; - -public final class LibGraalUtil { - - private LibGraalUtil() { - } - - public static JNIMethodScope openScope(Class entryPointClass, Enum id, JNIEnv env) { - Objects.requireNonNull(id, "Id must be non null."); - String scopeName = ClassUtil.getUnqualifiedName(entryPointClass) + "::" + id; - return LibGraalJNIMethodScope.open(scopeName, env, hasJavaFrameAnchor()); - } - - public static JNIMethodScope openScope(String scopeName, JNIEnv env) { - return LibGraalJNIMethodScope.open(scopeName, env, hasJavaFrameAnchor()); - } - - public static boolean hasJavaFrameAnchor() { - return getJavaFrameAnchor().isNonNull(); - } - - private static volatile int lastJavaPCOffset = -1; - - private static PointerBase getJavaFrameAnchor() { - CLongPointer currentThreadLastJavaPCOffset = (CLongPointer) WordFactory.unsigned(HotSpotJVMCIRuntime.runtime().getCurrentJavaThread()).add(getLastJavaPCOffset()); - return WordFactory.pointer(currentThreadLastJavaPCOffset.read()); - } - - private static int getLastJavaPCOffset() { - int res = lastJavaPCOffset; - if (res == -1) { - HotSpotVMConfigAccess configAccess = new HotSpotVMConfigAccess(HotSpotJVMCIRuntime.runtime().getConfigStore()); - int anchor = configAccess.getFieldOffset("JavaThread::_anchor", Integer.class, "JavaFrameAnchor"); - int lastJavaPc = configAccess.getFieldOffset("JavaFrameAnchor::_last_Java_pc", Integer.class, "address"); - res = anchor + lastJavaPc; - lastJavaPCOffset = res; - } - return res; - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/FromLibGraalCalls.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/FromLibGraalCalls.java deleted file mode 100644 index e4fa8c45226d..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/FromLibGraalCalls.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import static org.graalvm.jniutils.JNIExceptionWrapper.wrapAndThrowPendingJNIException; -import static org.graalvm.jniutils.JNIUtil.GetStaticMethodID; -import static org.graalvm.nativeimage.c.type.CTypeConversion.toCString; - -import java.util.EnumMap; -import java.util.function.Function; - -import org.graalvm.jniutils.JNI.JClass; -import org.graalvm.jniutils.JNI.JMethodID; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JValue; -import org.graalvm.jniutils.JNICalls; -import org.graalvm.nativeimage.c.type.CTypeConversion.CCharPointerHolder; - -import com.oracle.truffle.compiler.hotspot.libgraal.FromLibGraalId; - -/** - * Helpers for calling methods in HotSpot heap via JNI. - */ -public abstract class FromLibGraalCalls & FromLibGraalId> { - - private final EnumMap> methods; - private final JNICalls hotSpotCalls; - private final JClass peer; - - protected FromLibGraalCalls(Class idType, JClass peer) { - this.methods = new EnumMap<>(idType); - this.hotSpotCalls = JNICalls.getDefault(); - this.peer = peer; - } - - /** - * Describes a class and holds a reference to its {@linkplain #jclass JNI value}. - */ - static final class JNIClass { - final String className; - final JClass jclass; - - JNIClass(String className, JClass clazz) { - this.className = className; - this.jclass = clazz; - } - } - - /** - * Describes a method in HotSpot peer class}. - */ - static final class JNIMethodImpl & FromLibGraalId> implements JNICalls.JNIMethod { - final T hcId; - final JMethodID jniId; - - JNIMethodImpl(T hcId, JMethodID jniId) { - this.hcId = hcId; - this.jniId = jniId; - } - - @Override - public JMethodID getJMethodID() { - return jniId; - } - - @Override - public String getDisplayName() { - return hcId.getName(); - } - - @Override - public String toString() { - return hcId + "[0x" + Long.toHexString(jniId.rawValue()) + ']'; - } - } - - public final void callVoid(JNIEnv env, T id, JValue args) { - JNIMethodImpl method = getJNIMethod(env, id, void.class); - hotSpotCalls.callStaticVoid(env, peer, method, args); - } - - public final boolean callBoolean(JNIEnv env, T id, JValue args) { - JNIMethodImpl method = getJNIMethod(env, id, boolean.class); - return hotSpotCalls.callStaticBoolean(env, peer, method, args); - } - - public final long callLong(JNIEnv env, T id, JValue args) { - JNIMethodImpl method = getJNIMethod(env, id, long.class); - return hotSpotCalls.callStaticLong(env, peer, method, args); - } - - public final int callInt(JNIEnv env, T id, JValue args) { - JNIMethodImpl method = getJNIMethod(env, id, int.class); - return hotSpotCalls.callStaticInt(env, peer, method, args); - } - - @SuppressWarnings("unchecked") - public final R callJObject(JNIEnv env, T id, JValue args) { - JNIMethodImpl method = getJNIMethod(env, id, Object.class); - return hotSpotCalls.callStaticJObject(env, peer, method, args); - } - - private JNIMethodImpl getJNIMethod(JNIEnv env, T hcId, Class expectedReturnType) { - assert hcId.getReturnType() == expectedReturnType || expectedReturnType.isAssignableFrom(hcId.getReturnType()); - try { - return methods.computeIfAbsent(hcId, new Function>() { - @Override - public JNIMethodImpl apply(T id) { - JClass c = peer; - String methodName = id.getMethodName(); - try (CCharPointerHolder name = toCString(methodName); CCharPointerHolder sig = toCString(id.getSignature())) { - JMethodID jniId = GetStaticMethodID(env, c, name.get(), sig.get()); - if (jniId.isNull()) { - throw new InternalError("No such method: " + methodName); - } - return new JNIMethodImpl<>(id, jniId); - } - } - }); - } catch (InternalError ie) { - wrapAndThrowPendingJNIException(env); - throw ie; - } - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilable.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilable.java deleted file mode 100644 index b9ebec5e353c..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilable.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callAsJavaConstant; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callCancelCompilation; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callCompilableToString; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callCountDirectCallNodes; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callCreateStringSupplier; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callGetCompilableCallCount; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callGetCompilableName; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callGetFailedSpeculationsAddress; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callGetKnownCallSiteCount; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callGetNonTrivialNodeCount; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callIsSameOrSplit; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callIsTrivial; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callOnCompilationFailed; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilableGen.callPrepareForCompilation; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.AsJavaConstant; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.CancelCompilation; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.CompilableToString; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.CreateStringSupplier; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetCompilableCallCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetCompilableName; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetFailedSpeculationsAddress; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetKnownCallSiteCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetNonTrivialNodeCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.IsSameOrSplit; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.IsTrivial; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnCompilationFailed; -import static org.graalvm.jniutils.JNIMethodScope.env; -import static org.graalvm.jniutils.JNIUtil.createString; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.function.Supplier; - -import jdk.graal.compiler.debug.GraalError; -import jdk.graal.compiler.hotspot.HotSpotGraalServices; -import org.graalvm.jniutils.HSObject; -import org.graalvm.jniutils.JNI; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JString; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.JNIUtil; -import org.graalvm.nativebridge.BinaryInput; - -import com.oracle.svm.graal.hotspot.libgraal.LibGraal; -import com.oracle.truffle.compiler.TruffleCompilable; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id; - -import jdk.vm.ci.meta.JavaConstant; -import jdk.vm.ci.meta.SpeculationLog; -import org.graalvm.word.WordFactory; - -/** - * Proxy for a {@code HotSpotOptimizedCallTarget} object in the HotSpot heap. - */ -final class HSTruffleCompilable extends HSObject implements TruffleCompilable { - - private final TruffleFromLibGraalCalls calls; - private volatile String cachedName; - - /** - * Handle to {@code speculationLog} field of the {@code OptimizedCallTarget}. - */ - private Long cachedFailedSpeculationsAddress; - - /** - * Creates a new {@link HSTruffleCompilable} holding the JNI {@code JObject} by a local - * reference. - * - * @param scope the owning scope - * @param handle the JNI object reference - */ - HSTruffleCompilable(JNIMethodScope scope, JObject handle, HSTruffleCompilerRuntime runtime) { - super(scope, handle); - this.calls = runtime.calls; - } - - @TruffleFromLibGraal(GetFailedSpeculationsAddress) - @Override - public SpeculationLog getCompilationSpeculationLog() { - Long res = cachedFailedSpeculationsAddress; - if (res == null) { - res = callGetFailedSpeculationsAddress(calls, env(), getHandle()); - cachedFailedSpeculationsAddress = res; - } - return HotSpotGraalServices.newHotSpotSpeculationLog(cachedFailedSpeculationsAddress); - } - - @Override - @TruffleFromLibGraal(Id.GetCompilerOptions) - public Map getCompilerOptions() { - JNIEnv env = env(); - JNI.JByteArray res = HSTruffleCompilableGen.callGetCompilerOptions(calls, env, getHandle()); - byte[] realArray = JNIUtil.createArray(env, res); - return readDebugMap(BinaryInput.create(realArray)); - } - - private static Map readDebugMap(BinaryInput in) { - int size = in.readInt(); - Map map = new LinkedHashMap<>(); - for (int i = 0; i < size; i++) { - String key = in.readUTF(); - map.put(key, in.readUTF()); - } - return map; - } - - @Override - @TruffleFromLibGraal(Id.EngineId) - public long engineId() { - return HSTruffleCompilableGen.callEngineId(calls, env(), getHandle()); - } - - @Override - @TruffleFromLibGraal(Id.PrepareForCompilation) - public void prepareForCompilation() { - callPrepareForCompilation(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(IsTrivial) - @Override - public boolean isTrivial() { - return callIsTrivial(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(AsJavaConstant) - @Override - public JavaConstant asJavaConstant() { - return LibGraal.unhand(JavaConstant.class, callAsJavaConstant(calls, env(), getHandle())); - } - - @TruffleFromLibGraal(CreateStringSupplier) - @TruffleFromLibGraal(OnCompilationFailed) - @Override - public void onCompilationFailed(Supplier serializedException, boolean silent, boolean bailout, boolean permanentBailout, boolean graphTooBig) { - long serializedExceptionHandle = LibGraalObjectHandles.create(serializedException); - boolean success = false; - JNIEnv env = env(); - try { - JObject instance = callCreateStringSupplier(calls, env, serializedExceptionHandle); - callOnCompilationFailed(calls, env, getHandle(), instance, silent, bailout, permanentBailout, graphTooBig); - success = true; - } finally { - if (!success) { - LibGraalObjectHandles.remove(serializedExceptionHandle); - } - } - } - - @TruffleFromLibGraal(GetCompilableName) - @Override - public String getName() { - String res = cachedName; - if (res == null) { - JNIEnv env = JNIMethodScope.env(); - JString name = callGetCompilableName(calls, env, getHandle()); - res = createString(env, name); - cachedName = res; - } - return res; - } - - @TruffleFromLibGraal(GetNonTrivialNodeCount) - @Override - public int getNonTrivialNodeCount() { - return callGetNonTrivialNodeCount(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(Id.CountDirectCallNodes) - @Override - public int countDirectCallNodes() { - return callCountDirectCallNodes(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(GetCompilableCallCount) - @Override - public int getCallCount() { - return callGetCompilableCallCount(calls, env(), getHandle()); - } - - private volatile String cachedString; - - @TruffleFromLibGraal(CompilableToString) - @Override - public String toString() { - String res = cachedString; - if (res == null) { - JNIEnv env = JNIMethodScope.env(); - JString value = callCompilableToString(calls, env, getHandle()); - res = createString(env, value); - cachedString = res; - } - return res; - } - - @TruffleFromLibGraal(CancelCompilation) - @Override - public boolean cancelCompilation(CharSequence reason) { - JNIEnv env = env(); - JString jniReason = JNIUtil.createHSString(env, reason.toString()); - return callCancelCompilation(calls, env, getHandle(), jniReason); - } - - @TruffleFromLibGraal(IsSameOrSplit) - @Override - public boolean isSameOrSplit(TruffleCompilable ast) { - JObject astHandle = ast == null ? WordFactory.nullPointer() : ((HSTruffleCompilable) ast).getHandle(); - return callIsSameOrSplit(calls, env(), getHandle(), astHandle); - } - - @TruffleFromLibGraal(GetKnownCallSiteCount) - @Override - public int getKnownCallSiteCount() { - return callGetKnownCallSiteCount(calls, env(), getHandle()); - } - - @Override - public boolean onInvalidate(Object source, CharSequence reason, boolean wasActive) { - throw GraalError.shouldNotReachHere("Should not be reachable."); // ExcludeFromJacocoGeneratedReport - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilationTask.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilationTask.java deleted file mode 100644 index 8e3893584c6d..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilationTask.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callAddInlinedTarget; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callAddTargetToDequeue; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetDebugProperties; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetDescription; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetLanguage; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetLineNumber; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetNodeClassName; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetNodeId; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetOffsetEnd; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetOffsetStart; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetPosition; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callGetURI; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callHasNextTier; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callIsCancelled; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callIsLastTier; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilationTaskGen.callSetCallCounts; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.AddInlinedTarget; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.AddTargetToDequeue; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetDescription; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetLanguage; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetLineNumber; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetNodeClassName; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetNodeId; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetOffsetEnd; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetOffsetStart; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetPosition; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetURI; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.HasNextTier; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.IsCancelled; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.IsLastTier; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.SetCallCounts; -import static org.graalvm.jniutils.JNIMethodScope.env; -import static org.graalvm.jniutils.JNIUtil.createString; - -import java.net.URI; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.graalvm.jniutils.HSObject; -import org.graalvm.jniutils.JNI; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JString; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.JNIUtil; -import org.graalvm.nativebridge.BinaryInput; - -import com.oracle.svm.graal.hotspot.libgraal.LibGraal; -import com.oracle.truffle.compiler.TruffleCompilable; -import com.oracle.truffle.compiler.TruffleCompilationTask; -import com.oracle.truffle.compiler.TruffleSourceLanguagePosition; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id; - -import jdk.vm.ci.meta.JavaConstant; - -/** - * Proxy for a {@code Supplier} object in the HotSpot heap. - */ -final class HSTruffleCompilationTask extends HSObject implements TruffleCompilationTask { - - private final TruffleFromLibGraalCalls calls; - - HSTruffleCompilationTask(JNIMethodScope scope, JObject handle, HSTruffleCompilerRuntime runtime) { - super(scope, handle); - this.calls = runtime.calls; - } - - @TruffleFromLibGraal(IsCancelled) - @Override - public boolean isCancelled() { - return callIsCancelled(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(HasNextTier) - @Override - public boolean hasNextTier() { - return callHasNextTier(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(IsLastTier) - @Override - public boolean isLastTier() { - return callIsLastTier(calls, env(), getHandle()); - } - - @TruffleFromLibGraal(GetPosition) - @Override - public TruffleSourceLanguagePosition getPosition(JavaConstant node) { - long nodeHandle = LibGraal.translate(node); - JObject res = callGetPosition(calls, env(), getHandle(), nodeHandle); - if (res.isNull()) { - return null; - } - return new HSTruffleSourceLanguagePosition(JNIMethodScope.scope(), res, calls); - } - - @TruffleFromLibGraal(AddTargetToDequeue) - @Override - public void addTargetToDequeue(TruffleCompilable target) { - JObject hsCompilable = ((HSTruffleCompilable) target).getHandle(); - callAddTargetToDequeue(calls, env(), getHandle(), hsCompilable); - } - - @TruffleFromLibGraal(SetCallCounts) - @Override - public void setCallCounts(int total, int inlined) { - callSetCallCounts(calls, env(), getHandle(), total, inlined); - } - - @TruffleFromLibGraal(AddInlinedTarget) - @Override - public void addInlinedTarget(TruffleCompilable target) { - JObject hsCompilable = ((HSTruffleCompilable) target).getHandle(); - callAddInlinedTarget(calls, env(), getHandle(), hsCompilable); - } - - @TruffleFromLibGraal(Id.GetDebugProperties) - @Override - public Map getDebugProperties(JavaConstant node) { - long nodeHandle = LibGraal.translate(node); - JNIEnv env = env(); - JNI.JByteArray res = callGetDebugProperties(calls, env, getHandle(), nodeHandle); - byte[] realArray = JNIUtil.createArray(env, res); - return readDebugMap(BinaryInput.create(realArray)); - } - - private static Map readDebugMap(BinaryInput in) { - int size = in.readInt(); - Map map = new LinkedHashMap<>(); - for (int i = 0; i < size; i++) { - String key = in.readUTF(); - Object value = in.readTypedValue(); - map.put(key, value); - } - return map; - } - - /** - * Proxy for a {@link TruffleSourceLanguagePosition} object in the HotSpot heap. - */ - private static final class HSTruffleSourceLanguagePosition extends HSObject implements TruffleSourceLanguagePosition { - - private final TruffleFromLibGraalCalls calls; - - HSTruffleSourceLanguagePosition(JNIMethodScope scope, JObject handle, TruffleFromLibGraalCalls calls) { - super(scope, handle); - this.calls = calls; - } - - @TruffleFromLibGraal(GetOffsetStart) - @Override - public int getOffsetStart() { - return callGetOffsetStart(calls, JNIMethodScope.env(), getHandle()); - } - - @TruffleFromLibGraal(GetOffsetEnd) - @Override - public int getOffsetEnd() { - return callGetOffsetEnd(calls, JNIMethodScope.env(), getHandle()); - } - - @TruffleFromLibGraal(GetLineNumber) - @Override - public int getLineNumber() { - return callGetLineNumber(calls, JNIMethodScope.env(), getHandle()); - } - - @TruffleFromLibGraal(GetLanguage) - @Override - public String getLanguage() { - JString res = callGetLanguage(calls, JNIMethodScope.env(), getHandle()); - return createString(JNIMethodScope.env(), res); - } - - @TruffleFromLibGraal(GetDescription) - @Override - public String getDescription() { - JString res = callGetDescription(calls, JNIMethodScope.env(), getHandle()); - return createString(JNIMethodScope.env(), res); - } - - @TruffleFromLibGraal(GetURI) - @Override - public URI getURI() { - JString res = callGetURI(calls, JNIMethodScope.env(), getHandle()); - String stringifiedURI = createString(JNIMethodScope.env(), res); - return stringifiedURI == null ? null : URI.create(stringifiedURI); - } - - @TruffleFromLibGraal(GetNodeClassName) - @Override - public String getNodeClassName() { - JString res = callGetNodeClassName(calls, JNIMethodScope.env(), getHandle()); - return createString(JNIMethodScope.env(), res); - } - - @TruffleFromLibGraal(GetNodeId) - @Override - public int getNodeId() { - return callGetNodeId(calls, JNIMethodScope.env(), getHandle()); - } - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilerListener.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilerListener.java deleted file mode 100644 index 43e7ba005c31..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilerListener.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnCompilationRetry; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnFailure; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnGraalTierFinished; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnSuccess; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnTruffleTierFinished; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerListenerGen.callOnCompilationRetry; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerListenerGen.callOnFailure; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerListenerGen.callOnGraalTierFinished; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerListenerGen.callOnSuccess; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerListenerGen.callOnTruffleTierFinished; -import static org.graalvm.jniutils.JNIUtil.createHSString; - -import java.io.Closeable; -import java.util.function.Supplier; - -import org.graalvm.jniutils.HSObject; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JString; - -import com.oracle.truffle.compiler.TruffleCompilable; -import com.oracle.truffle.compiler.TruffleCompilationTask; -import com.oracle.truffle.compiler.TruffleCompilerListener; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal; - -import org.graalvm.jniutils.JNIMethodScope; - -/** - * Proxy for a {@link TruffleCompilerListener} object in the HotSpot heap. - */ -final class HSTruffleCompilerListener extends HSObject implements TruffleCompilerListener { - - private final TruffleFromLibGraalCalls calls; - - HSTruffleCompilerListener(JNIMethodScope scope, JObject handle, HSTruffleCompilerRuntime runtime) { - super(scope, handle); - this.calls = runtime.calls; - } - - @TruffleFromLibGraal(OnSuccess) - @Override - public void onSuccess(TruffleCompilable compilable, TruffleCompilationTask task, GraphInfo graphInfo, CompilationResultInfo compilationResultInfo, int tier) { - JObject hsCompilable = ((HSTruffleCompilable) compilable).getHandle(); - JObject hsTask = ((HSTruffleCompilationTask) task).getHandle(); - JNIEnv env = JNIMethodScope.env(); - try (LibGraalObjectHandleScope graphInfoScope = LibGraalObjectHandleScope.forObject(graphInfo); - LibGraalObjectHandleScope compilationResultInfoScope = LibGraalObjectHandleScope.forObject(compilationResultInfo)) { - callOnSuccess(calls, env, getHandle(), hsCompilable, hsTask, graphInfoScope.getHandle(), compilationResultInfoScope.getHandle(), tier); - } - } - - @TruffleFromLibGraal(OnTruffleTierFinished) - @Override - public void onTruffleTierFinished(TruffleCompilable compilable, TruffleCompilationTask task, GraphInfo graph) { - JObject hsCompilable = ((HSTruffleCompilable) compilable).getHandle(); - JObject hasTask = ((HSTruffleCompilationTask) task).getHandle(); - JNIEnv env = JNIMethodScope.env(); - try (LibGraalObjectHandleScope graphInfoScope = LibGraalObjectHandleScope.forObject(graph)) { - callOnTruffleTierFinished(calls, env, getHandle(), hsCompilable, hasTask, graphInfoScope.getHandle()); - } - - } - - @TruffleFromLibGraal(OnGraalTierFinished) - @Override - public void onGraalTierFinished(TruffleCompilable compilable, GraphInfo graph) { - JObject hsCompilable = ((HSTruffleCompilable) compilable).getHandle(); - JNIEnv env = JNIMethodScope.env(); - try (LibGraalObjectHandleScope graphInfoScope = LibGraalObjectHandleScope.forObject(graph)) { - callOnGraalTierFinished(calls, env, getHandle(), hsCompilable, graphInfoScope.getHandle()); - } - } - - @TruffleFromLibGraal(OnFailure) - @Override - public void onFailure(TruffleCompilable compilable, String reason, boolean bailout, boolean permanentBailout, int tier, Supplier lazyStackTrace) { - try (LibGraalObjectHandleScope lazyStackTraceScope = lazyStackTrace != null ? LibGraalObjectHandleScope.forObject(lazyStackTrace) : null) { - JObject hsCompilable = ((HSTruffleCompilable) compilable).getHandle(); - JNIEnv env = JNIMethodScope.env(); - JString hsReason = createHSString(env, reason); - callOnFailure(calls, env, getHandle(), hsCompilable, hsReason, bailout, permanentBailout, tier, lazyStackTraceScope != null ? lazyStackTraceScope.getHandle() : 0L); - } - } - - @TruffleFromLibGraal(OnCompilationRetry) - @Override - public void onCompilationRetry(TruffleCompilable compilable, TruffleCompilationTask task) { - JObject hsCompilable = ((HSTruffleCompilable) compilable).getHandle(); - JObject hsTask = ((HSTruffleCompilationTask) task).getHandle(); - JNIEnv env = JNIMethodScope.env(); - callOnCompilationRetry(calls, env, getHandle(), hsCompilable, hsTask); - } - - private static final class LibGraalObjectHandleScope implements Closeable { - - private long handle; - - private LibGraalObjectHandleScope(long handle) { - this.handle = handle; - } - - @Override - public void close() { - LibGraalObjectHandles.remove(handle); - handle = 0; - } - - long getHandle() { - if (handle == 0) { - throw new IllegalStateException("Reading handle from a closed scope."); - } - return handle; - } - - static LibGraalObjectHandleScope forObject(Object object) { - return new LibGraalObjectHandleScope(LibGraalObjectHandles.create(object)); - } - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilerRuntime.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilerRuntime.java deleted file mode 100644 index 7f52049a2a2a..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/HSTruffleCompilerRuntime.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callConsumeOptimizedAssumptionDependency; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callCreateStringSupplier; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callGetConstantFieldInfo; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callIsSuppressedFailure; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callIsValueType; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callLog; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callOnCodeInstallation; -import static com.oracle.svm.graal.hotspot.libgraal.truffle.HSTruffleCompilerRuntimeGen.callRegisterOptimizedAssumptionDependency; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.ConsumeOptimizedAssumptionDependency; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.CreateStringSupplier; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetConstantFieldInfo; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.GetPartialEvaluationMethodInfo; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.IsSuppressedFailure; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.IsValueType; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.Log; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.OnCodeInstallation; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id.RegisterOptimizedAssumptionDependency; -import static jdk.vm.ci.hotspot.HotSpotJVMCIRuntime.runtime; -import static org.graalvm.jniutils.JNIMethodScope.env; -import static org.graalvm.jniutils.JNIMethodScope.scope; -import static org.graalvm.jniutils.JNIUtil.getInternalName; - -import java.util.Arrays; -import java.util.function.Consumer; -import java.util.function.Supplier; - -import com.oracle.svm.graal.hotspot.libgraal.LibGraalUtil; -import org.graalvm.jniutils.HSObject; -import org.graalvm.jniutils.JNI.JByteArray; -import org.graalvm.jniutils.JNI.JClass; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JString; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.JNIUtil; -import org.graalvm.nativebridge.BinaryInput; -import org.graalvm.nativeimage.StackValue; -import org.graalvm.nativeimage.c.type.CCharPointer; -import org.graalvm.word.WordFactory; - -import com.oracle.svm.graal.hotspot.libgraal.LibGraal; -import com.oracle.truffle.compiler.ConstantFieldInfo; -import com.oracle.truffle.compiler.HostMethodInfo; -import com.oracle.truffle.compiler.OptimizedAssumptionDependency; -import com.oracle.truffle.compiler.PartialEvaluationMethodInfo; -import com.oracle.truffle.compiler.TruffleCompilable; -import com.oracle.truffle.compiler.TruffleCompilerAssumptionDependency; -import com.oracle.truffle.compiler.TruffleCompilerRuntime; -import com.oracle.truffle.compiler.hotspot.libgraal.FromLibGraalEntryPointsResolver; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id; - -import jdk.vm.ci.code.InstalledCode; -import jdk.vm.ci.hotspot.HotSpotObjectConstant; -import jdk.vm.ci.hotspot.HotSpotResolvedObjectType; -import jdk.vm.ci.meta.JavaConstant; -import jdk.vm.ci.meta.JavaType; -import jdk.vm.ci.meta.MetaAccessProvider; -import jdk.vm.ci.meta.ResolvedJavaField; -import jdk.vm.ci.meta.ResolvedJavaMethod; -import jdk.vm.ci.meta.ResolvedJavaType; -import jdk.vm.ci.meta.UnresolvedJavaType; - -/** - * Proxy for a {@link TruffleCompilerRuntime} object in the HotSpot heap. - */ -@FromLibGraalEntryPointsResolver(value = TruffleFromLibGraal.Id.class, entryPointsClassName = "com.oracle.truffle.runtime.hotspot.libgraal.TruffleFromLibGraalEntryPoints") -final class HSTruffleCompilerRuntime extends HSObject implements TruffleCompilerRuntime { - - private static final Class TRANSLATED_EXCEPTION; - static { - Class clz; - try { - clz = Class.forName("jdk.internal.vm.TranslatedException"); - } catch (ClassNotFoundException cnf) { - clz = null; - } - TRANSLATED_EXCEPTION = clz; - } - - private final ResolvedJavaType classLoaderDelegate; - final TruffleFromLibGraalCalls calls; - - HSTruffleCompilerRuntime(JNIEnv env, JObject handle, ResolvedJavaType classLoaderDelegate, JClass peer) { - /* - * Note global duplicates may happen if the compiler is initialized by a host compilation. - */ - super(env, handle, true, false); - this.classLoaderDelegate = classLoaderDelegate; - this.calls = new TruffleFromLibGraalCalls(env, peer); - } - - @TruffleFromLibGraal(GetPartialEvaluationMethodInfo) - @Override - public PartialEvaluationMethodInfo getPartialEvaluationMethodInfo(ResolvedJavaMethod method) { - long methodHandle = LibGraal.translate(method); - JByteArray hsByteArray = HSTruffleCompilerRuntimeGen.callGetPartialEvaluationMethodInfo(calls, env(), getHandle(), methodHandle); - CCharPointer buffer = StackValue.get(5); - JNIUtil.GetByteArrayRegion(env(), hsByteArray, 0, 5, buffer); - BinaryInput in = BinaryInput.create(buffer, 5); - LoopExplosionKind loopExplosionKind = LoopExplosionKind.values()[in.readByte()]; - InlineKind peInlineKind = InlineKind.values()[in.readByte()]; - InlineKind inlineKind = InlineKind.values()[in.readByte()]; - boolean inlineable = in.readBoolean(); - boolean isSpecializationMethod = in.readBoolean(); - return new PartialEvaluationMethodInfo(loopExplosionKind, peInlineKind, inlineKind, inlineable, isSpecializationMethod); - } - - @TruffleFromLibGraal(Id.GetHostMethodInfo) - @Override - public HostMethodInfo getHostMethodInfo(ResolvedJavaMethod method) { - long methodHandle = LibGraal.translate(method); - JByteArray hsByteArray = HSTruffleCompilerRuntimeGen.callGetHostMethodInfo(calls, env(), getHandle(), methodHandle); - CCharPointer buffer = StackValue.get(4); - JNIUtil.GetByteArrayRegion(env(), hsByteArray, 0, 4, buffer); - BinaryInput in = BinaryInput.create(buffer, 4); - boolean truffleBoundary = in.readBoolean(); - boolean bytecodeInterpreterSwitch = in.readBoolean(); - boolean bytecodeInterpreterSwitchBoundary = in.readBoolean(); - boolean callIsInliningCutoff = in.readBoolean(); - return new HostMethodInfo(truffleBoundary, bytecodeInterpreterSwitch, bytecodeInterpreterSwitchBoundary, callIsInliningCutoff); - } - - @Override - public TruffleCompilable asCompilableTruffleAST(JavaConstant constant) { - if (constant.isNull()) { - return null; - } - JNIMethodScope scope = JNIMethodScope.scopeOrNull(); - if (scope == null) { - return null; - } - /* - * TODO: GR-57161: IllegalStateException: Cannot call getJObjectValue without Java frame - * anchor - */ - if (!LibGraalUtil.hasJavaFrameAnchor()) { - return null; - } - JObject hsCompilable = JNIUtil.NewLocalRef(scope.getEnv(), LibGraal.getJObjectValue((HotSpotObjectConstant) constant)); - return new HSTruffleCompilable(scope, hsCompilable, this); - } - - @TruffleFromLibGraal(OnCodeInstallation) - @Override - public void onCodeInstallation(TruffleCompilable compilable, InstalledCode installedCode) { - long installedCodeHandle = LibGraal.translate(installedCode); - JNIEnv env = env(); - callOnCodeInstallation(calls, env, getHandle(), ((HSTruffleCompilable) compilable).getHandle(), installedCodeHandle); - } - - @TruffleFromLibGraal(RegisterOptimizedAssumptionDependency) - @Override - public Consumer registerOptimizedAssumptionDependency(JavaConstant optimizedAssumption) { - long optimizedAssumptionHandle = LibGraal.translate(optimizedAssumption); - JNIEnv env = env(); - JObject assumptionConsumer = callRegisterOptimizedAssumptionDependency(calls, env, getHandle(), optimizedAssumptionHandle); - return assumptionConsumer.isNull() ? null : new HSConsumer(scope(), assumptionConsumer, calls); - } - - @TruffleFromLibGraal(IsValueType) - @Override - public boolean isValueType(ResolvedJavaType type) { - return callIsValueType(calls, env(), getHandle(), LibGraal.translate(type)); - } - - @TruffleFromLibGraal(GetConstantFieldInfo) - @Override - public ConstantFieldInfo getConstantFieldInfo(ResolvedJavaField field) { - ResolvedJavaType enclosingType = field.getDeclaringClass(); - boolean isStatic = field.isStatic(); - ResolvedJavaField[] declaredFields = isStatic ? enclosingType.getStaticFields() : enclosingType.getInstanceFields(false); - int fieldIndex = -1; - for (int i = 0; i < declaredFields.length; i++) { - if (field.equals(declaredFields[i])) { - fieldIndex = i; - break; - } - } - if (fieldIndex == -1) { - throw new IllegalStateException(String.format( - "%s field: %s declared in: %s is not in declared fields: %s", - isStatic ? "Static" : "Instance", - field, - enclosingType, - Arrays.toString(declaredFields))); - } - long typeHandle = LibGraal.translate(enclosingType); - int rawValue = callGetConstantFieldInfo(calls, env(), getHandle(), typeHandle, isStatic, fieldIndex); - switch (rawValue) { - case Integer.MIN_VALUE: - return null; - case -1: - return ConstantFieldInfo.CHILD; - case -2: - return ConstantFieldInfo.CHILDREN; - default: - return ConstantFieldInfo.forDimensions(rawValue); - } - } - - @Override - public ResolvedJavaType resolveType(MetaAccessProvider metaAccess, String className, boolean required) { - String internalName = getInternalName(className); - JavaType jt; - try { - jt = runtime().lookupType(internalName, (HotSpotResolvedObjectType) classLoaderDelegate, required); - } catch (Exception e) { - if (TRANSLATED_EXCEPTION != null && TRANSLATED_EXCEPTION.isInstance(e)) { - /* - * As of JDK 24 (JDK-8335553), a translated exception is boxed in a - * TranslatedException. Unbox a translated unchecked exception as they are the only - * ones that can be expected by callers since this method is not declared in checked - * exceptions. - */ - Throwable cause = e.getCause(); - if (cause instanceof Error) { - throw (Error) cause; - } - if (cause instanceof RuntimeException) { - throw (RuntimeException) cause; - } - } - throw e; - } - if (jt instanceof UnresolvedJavaType) { - if (required) { - throw new NoClassDefFoundError(internalName); - } else { - return null; - } - } - ResolvedJavaType resolvedType = (ResolvedJavaType) jt; - // In some situations, we may need the class to be linked now, especially if we are - // compiling immediately (e.g., to successfully devirtualize FrameWithoutBoxing methods). - resolvedType.link(); - return resolvedType; - } - - @TruffleFromLibGraal(Log) - @Override - public void log(String loggerId, TruffleCompilable compilable, String message) { - JNIEnv env = env(); - JString jniLoggerId = JNIUtil.createHSString(env, loggerId); - JString jniMessage = JNIUtil.createHSString(env, message); - callLog(calls, env, getHandle(), jniLoggerId, ((HSTruffleCompilable) compilable).getHandle(), jniMessage); - } - - @TruffleFromLibGraal(CreateStringSupplier) - @TruffleFromLibGraal(IsSuppressedFailure) - @Override - public boolean isSuppressedFailure(TruffleCompilable compilable, Supplier serializedException) { - long serializedExceptionHandle = LibGraalObjectHandles.create(serializedException); - boolean success = false; - JNIEnv env = env(); - try { - JObject instance = callCreateStringSupplier(calls, env, serializedExceptionHandle); - boolean res = callIsSuppressedFailure(calls, env, getHandle(), ((HSTruffleCompilable) compilable).getHandle(), instance); - success = true; - return res; - } finally { - if (!success) { - LibGraalObjectHandles.remove(serializedExceptionHandle); - } - } - } - - private static class HSConsumer extends HSObject implements Consumer { - private final TruffleFromLibGraalCalls calls; - - HSConsumer(JNIMethodScope scope, JObject handle, TruffleFromLibGraalCalls calls) { - super(scope, handle); - this.calls = calls; - } - - @TruffleFromLibGraal(ConsumeOptimizedAssumptionDependency) - @Override - public void accept(OptimizedAssumptionDependency optimizedDependency) { - TruffleCompilerAssumptionDependency dependency = (TruffleCompilerAssumptionDependency) optimizedDependency; - JObject compilable; - long installedCode; - if (dependency == null) { - compilable = WordFactory.nullPointer(); - installedCode = 0; - } else { - TruffleCompilable ast = dependency.getCompilable(); - if (ast == null) { - /* - * Compilable may be null if the compilation was triggered by a libgraal host - * compilation. - */ - compilable = WordFactory.nullPointer(); - } else { - compilable = ((HSTruffleCompilable) dependency.getCompilable()).getHandle(); - } - installedCode = LibGraal.translate(dependency.getInstalledCode()); - } - callConsumeOptimizedAssumptionDependency(calls, env(), getHandle(), compilable, installedCode); - } - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalChecker.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalChecker.java deleted file mode 100644 index 1271ee40f08e..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalChecker.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.util.EnumSet; -import java.util.Set; - -import org.graalvm.jniutils.JNI; -import org.graalvm.nativeimage.Platform; -import org.graalvm.nativeimage.Platforms; -import org.graalvm.nativeimage.c.function.CEntryPoint; - -final class LibGraalChecker { - - private LibGraalChecker() { - } - - /*----------------- CHECKING ------------------*/ - - /** - * Checks that all {@code ToLibGraal}s are implemented and their HotSpot/libgraal ends points - * match. - */ - @Platforms(Platform.HOSTED_ONLY.class) - public static void checkToLibGraalCalls(Class toLibGraalEntryPointsClass, Class toLibGraalCallsClass, Class annotationClass) throws InternalError { - try { - Method valueMethod = annotationClass.getDeclaredMethod("value"); - Type t = valueMethod.getGenericReturnType(); - check(t instanceof Class && ((Class) t).isEnum(), "Annotation value must be enum."); - @SuppressWarnings("unchecked") - Set> unimplemented = EnumSet.allOf(((Class) t).asSubclass(Enum.class)); - for (Method libGraalMethod : toLibGraalEntryPointsClass.getDeclaredMethods()) { - Annotation call = libGraalMethod.getAnnotation(annotationClass); - if (call != null) { - check(Modifier.isStatic(libGraalMethod.getModifiers()), "Method annotated by %s must be static: %s", annotationClass, libGraalMethod); - CEntryPoint ep = libGraalMethod.getAnnotation(CEntryPoint.class); - check(ep != null, "Method annotated by %s must also be annotated by %s: %s", annotationClass, CEntryPoint.class, libGraalMethod); - String name = ep.name(); - String prefix = "Java_" + toLibGraalCallsClass.getName().replace('.', '_') + '_'; - check(name.startsWith(prefix), "Method must be a JNI entry point for a method in %s: %s", toLibGraalCallsClass, libGraalMethod); - name = name.substring(prefix.length()); - Method hsMethod = findHSMethod(toLibGraalCallsClass, name, annotationClass); - Class[] libGraalParameters = libGraalMethod.getParameterTypes(); - Class[] hsParameters = hsMethod.getParameterTypes(); - check(hsParameters.length + 2 == libGraalParameters.length, "%s should have 2 more parameters than %s", libGraalMethod, hsMethod); - check(libGraalParameters.length >= 3, "Expect at least 3 parameters: %s", libGraalMethod); - check(libGraalParameters[0] == JNI.JNIEnv.class, "Parameter 0 must be of type %s: %s", JNI.JNIEnv.class, libGraalMethod); - check(libGraalParameters[1] == JNI.JClass.class, "Parameter 1 must be of type %s: %s", JNI.JClass.class, libGraalMethod); - check(libGraalParameters[2] == long.class, "Parameter 2 must be of type long: %s", libGraalMethod); - - check(hsParameters[0] == long.class, "Parameter 0 must be of type long: %s", hsMethod); - - for (int i = 3, j = 1; i < libGraalParameters.length; i++, j++) { - Class libgraal = libGraalParameters[i]; - Class hs = hsParameters[j]; - Class hsExpect; - if (hs.isPrimitive()) { - hsExpect = libgraal; - } else { - if (libgraal == JNI.JString.class) { - hsExpect = String.class; - } else if (libgraal == JNI.JByteArray.class) { - hsExpect = byte[].class; - } else if (libgraal == JNI.JLongArray.class) { - hsExpect = long[].class; - } else if (libgraal == JNI.JObjectArray.class) { - hsExpect = Object[].class; - } else if (libgraal == JNI.JObject.class) { - hsExpect = Object.class; - } else if (libgraal == JNI.JClass.class) { - hsExpect = Class.class; - } else { - throw fail("Method %s must only use supported parameters but uses unsupported class %s", libGraalMethod, libgraal.getName()); - } - } - check(hsExpect.isAssignableFrom(hs), "HotSpot parameter %d (%s) incompatible with libgraal parameter %d (%s): %s", j, hs.getName(), i, libgraal.getName(), hsMethod); - } - unimplemented.remove(valueMethod.invoke(call)); - } - } - check(unimplemented.isEmpty(), "Unimplemented libgraal calls: %s", unimplemented); - } catch (ReflectiveOperationException e) { - throw new InternalError(e); - } - } - - @Platforms(Platform.HOSTED_ONLY.class) - private static void check(boolean condition, String format, Object... args) { - if (!condition) { - throw fail(format, args); - } - } - - @Platforms(Platform.HOSTED_ONLY.class) - private static InternalError fail(String format, Object... args) { - return new InternalError(String.format(format, args)); - } - - @Platforms(Platform.HOSTED_ONLY.class) - private static Method findHSMethod(Class hsClass, String name, Class annotationClass) { - Method res = null; - for (Method m : hsClass.getDeclaredMethods()) { - if (m.getName().equals(name)) { - check(res == null, "More than one method named \"%s\" in %s", name, hsClass); - Annotation call = m.getAnnotation(annotationClass); - check(call != null, "Method must be annotated by %s: %s", annotationClass, m); - check(Modifier.isStatic(m.getModifiers()) && Modifier.isNative(m.getModifiers()), "Method must be static and native: %s", m); - res = m; - } - } - check(res != null, "Could not find method named \"%s\" in %s", name, hsClass); - return res; - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalNativeBridgeSupport.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalNativeBridgeSupport.java deleted file mode 100644 index 5d8e7ed34a3b..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalNativeBridgeSupport.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import java.util.concurrent.atomic.AtomicInteger; - -import jdk.graal.compiler.debug.TTY; -import jdk.graal.compiler.serviceprovider.GraalServices; -import jdk.graal.compiler.serviceprovider.IsolateUtil; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.NativeBridgeSupport; - -public final class LibGraalNativeBridgeSupport implements NativeBridgeSupport { - - private static final String JNI_LIBGRAAL_TRACE_LEVEL_PROPERTY_NAME = "JNI_LIBGRAAL_TRACE_LEVEL"; - private static final int UNINITIALIZED_TRACE_LEVEL = Integer.MIN_VALUE; - - private final ThreadLocal inTrace = ThreadLocal.withInitial(() -> false); - - private final AtomicInteger traceLevel = new AtomicInteger(UNINITIALIZED_TRACE_LEVEL); - - @Override - public String getFeatureName() { - return "LIBGRAAL"; - } - - @Override - public boolean isTracingEnabled(int level) { - return traceLevel() >= level; - } - - @Override - public void trace(String message) { - // Prevents nested tracing of JNI calls originated from this method. - // The TruffleCompilerImpl redirects the TTY using a TTY.Filter to the - // TruffleCompilerRuntime#log(). In libgraal the HSTruffleCompilerRuntime#log() uses a - // FromLibGraalCalls#callVoid() to do the JNI call to the GraalTruffleRuntime#log(). - // The FromLibGraalCalls#callVoid() also traces the JNI call by calling trace(). - // The nested trace call should be ignored. - if (!inTrace.get()) { - inTrace.set(true); - try { - StringBuilder sb = new StringBuilder(); - sb.append('[').append(IsolateUtil.getIsolateID()).append(':').append(Thread.currentThread().getName()).append(']'); - JNIMethodScope scope = JNIMethodScope.scopeOrNull(); - if (scope != null) { - sb.append(" ".repeat(2 + (scope.depth() * 2))); - } - sb.append(message); - TTY.println(sb.toString()); - } finally { - inTrace.remove(); - } - } - } - - private int traceLevel() { - int res = traceLevel.get(); - if (res == UNINITIALIZED_TRACE_LEVEL) { - String var = GraalServices.getSavedProperty(JNI_LIBGRAAL_TRACE_LEVEL_PROPERTY_NAME); - if (var != null) { - try { - res = Integer.parseInt(var); - } catch (NumberFormatException e) { - TTY.printf("Invalid value for %s: %s%n", JNI_LIBGRAAL_TRACE_LEVEL_PROPERTY_NAME, e); - res = 0; - } - } else { - res = 0; - } - traceLevel.set(res); - } - return res; - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalObjectHandles.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalObjectHandles.java deleted file mode 100644 index 8d5b4ed54947..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalObjectHandles.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import org.graalvm.nativeimage.ObjectHandles; -import org.graalvm.word.WordFactory; - -/** - * Manages handles to libgraal objects whose lifetime is controlled by - * {@code com.oracle.truffle.runtime.hotspot.libgraal.LibGraalObject} instances in the HotSpot heap. - */ -final class LibGraalObjectHandles { - - /** - * Creates a handle to {@code object}. The object is kept alive at least until - * {@link #remove(long)} is called on the returned handle. - */ - static long create(Object object) { - return ObjectHandles.getGlobal().create(object).rawValue(); - } - - /** - * Resolves {@code handle} to an object and casts it to {@code type}. - * - * @param type the expected type of the object - * @return the object identified by the handle - * @throws IllegalArgumentException if {@code} is invalid - */ - static T resolve(long handle, Class type) { - return type.cast(ObjectHandles.getGlobal().get(WordFactory.pointer(handle))); - } - - /** - * Releases the reference to the object associated with {@code handle}. After calling this - * method, the handle must not be used anymore. - */ - static void remove(long handle) { - ObjectHandles.getGlobal().destroy(WordFactory.pointer(handle)); - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalTruffleHostEnvironment.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalTruffleHostEnvironment.java deleted file mode 100644 index 013eda5802c8..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalTruffleHostEnvironment.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import jdk.graal.compiler.core.common.util.MethodKey; -import jdk.graal.compiler.hotspot.CompilationContext; -import jdk.graal.compiler.hotspot.HotSpotGraalServices; -import jdk.graal.compiler.truffle.TruffleCompilerImpl; -import jdk.graal.compiler.truffle.TruffleElementCache; -import jdk.graal.compiler.truffle.host.TruffleHostEnvironment; -import jdk.graal.compiler.truffle.hotspot.HotSpotTruffleCompilerImpl; - -import com.oracle.truffle.compiler.HostMethodInfo; -import com.oracle.truffle.compiler.TruffleCompilable; -import com.oracle.truffle.compiler.TruffleCompilerRuntime; - -import jdk.vm.ci.meta.MetaAccessProvider; -import jdk.vm.ci.meta.ResolvedJavaMethod; - -final class LibGraalTruffleHostEnvironment extends TruffleHostEnvironment { - - private final HostMethodInfoCache hostCache = new HostMethodInfoCache(); - - LibGraalTruffleHostEnvironment(TruffleCompilerRuntime runtime, MetaAccessProvider metaAccess) { - super(runtime, metaAccess); - } - - @Override - public HostMethodInfo getHostMethodInfo(ResolvedJavaMethod method) { - return hostCache.get(method); - } - - @Override - @SuppressWarnings("try") - protected TruffleCompilerImpl createCompiler(TruffleCompilable ast) { - try (CompilationContext compilationContext = HotSpotGraalServices.enterGlobalCompilationContext()) { - HotSpotTruffleCompilerImpl compiler = HotSpotTruffleCompilerImpl.create(runtime()); - compiler.initialize(ast, true); - return compiler; - } - } - - final class HostMethodInfoCache extends TruffleElementCache { - - HostMethodInfoCache() { - super(HOST_METHOD_CACHE_SIZE); // cache size - } - - @Override - protected Object createKey(ResolvedJavaMethod method) { - /* - * On libgraal we cannot reference ResolvedJavaMethod as part of a cache as it may - * become invalid between compilations. - */ - return new MethodKey(method); - } - - @Override - protected HostMethodInfo computeValue(ResolvedJavaMethod method) { - return runtime().getHostMethodInfo(method); - } - - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalTruffleHostEnvironmentLookup.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalTruffleHostEnvironmentLookup.java deleted file mode 100644 index 788b4e1355e4..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/LibGraalTruffleHostEnvironmentLookup.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import jdk.graal.compiler.debug.GraalError; -import jdk.graal.compiler.serviceprovider.GlobalAtomicLong; -import jdk.graal.compiler.truffle.host.TruffleHostEnvironment; -import org.graalvm.jniutils.JNI.JClass; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JWeak; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.JNIUtil; -import org.graalvm.word.WordFactory; - -import com.oracle.svm.core.annotate.RecomputeFieldValue; -import com.oracle.svm.core.annotate.RecomputeFieldValue.Kind; -import com.oracle.svm.graal.hotspot.libgraal.LibGraal; - -import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; -import jdk.vm.ci.meta.ResolvedJavaType; - -/** - * This handles the Truffle host environment lookup on HotSpot with Libgraal. - *

- * For Libgraal the Truffle runtime needs to be discovered across multiple isolates. When a Truffle - * runtime in libgraal configuration gets initialized then {@link #registerRuntime(JNIEnv, JObject)} - * gets called in any libgraal isolate. We remember the registered Truffle runtime using a weak - * global JNI reference in a {@link GlobalAtomicLong}. Since we use a {@link GlobalAtomicLong} to - * remember the reference, all libgraal isolates now see the registered runtime and can provide - * access to it. This way any libgraal host compilation isolate can see Truffle after it was first - * initialized even if none of the Truffle compilation isolates are still alive. Another positive - * side-effect of this is that Truffle related host compilation intrinsics and phases are never - * applied if no Truffle runtime was ever registered. - */ -public final class LibGraalTruffleHostEnvironmentLookup implements TruffleHostEnvironment.Lookup { - - private static final int NO_TRUFFLE_REGISTERED = 0; - private static final GlobalAtomicLong WEAK_TRUFFLE_RUNTIME_INSTANCE = new GlobalAtomicLong(NO_TRUFFLE_REGISTERED); - - @RecomputeFieldValue(kind = Kind.Reset) private TruffleHostEnvironment previousRuntime; - - @Override - public TruffleHostEnvironment lookup(ResolvedJavaType forType) { - long globalReference = WEAK_TRUFFLE_RUNTIME_INSTANCE.get(); - if (globalReference == NO_TRUFFLE_REGISTERED) { - // fast path if Truffle was not initialized - return null; - } - JNIEnv env = JNIMethodScope.env(); - JObject runtimeLocalRef = JNIUtil.NewLocalRef(env, WordFactory.pointer(globalReference)); - if (runtimeLocalRef.isNull()) { - // The Truffle runtime was collected by the GC - return null; - } - TruffleHostEnvironment environment = this.previousRuntime; - if (environment != null) { - JObject cached = hsRuntime(environment).getHandle(); - if (JNIUtil.IsSameObject(env, cached, runtimeLocalRef)) { - // fast path for registered and cached Truffle runtime handle - return environment; - } - } - JClass runtimeClass = JNIUtil.GetObjectClass(env, runtimeLocalRef); - ResolvedJavaType runtimeType = LibGraal.asResolvedJavaType(runtimeClass); - if (runtimeType == null) { - throw GraalError.shouldNotReachHere("The object class needs to be available for a Truffle runtime object."); - } - /* - * We do not currently validate the forType. But in the future we want to lookup the runtime - * per type. So in theory multiple truffle runtimes can be loaded. - */ - HSTruffleCompilerRuntime runtime = new HSTruffleCompilerRuntime(env, runtimeLocalRef, runtimeType, runtimeClass); - this.previousRuntime = environment = new LibGraalTruffleHostEnvironment(runtime, HotSpotJVMCIRuntime.runtime().getHostJVMCIBackend().getMetaAccess()); - assert JNIUtil.IsSameObject(env, hsRuntime(environment).getHandle(), runtimeLocalRef); - return environment; - } - - private static HSTruffleCompilerRuntime hsRuntime(TruffleHostEnvironment environment) { - return (HSTruffleCompilerRuntime) environment.runtime(); - } - - static JClass lookupPeer(JNIEnv env) { - long globalReference = WEAK_TRUFFLE_RUNTIME_INSTANCE.get(); - if (globalReference == NO_TRUFFLE_REGISTERED) { - // fast path if Truffle was not initialized - return WordFactory.nullPointer(); - } - JObject runtimeLocalRef = JNIUtil.NewLocalRef(env, WordFactory.pointer(globalReference)); - if (runtimeLocalRef.isNull()) { - // The Truffle runtime was collected by the GC - return WordFactory.nullPointer(); - } - return JNIUtil.GetObjectClass(env, runtimeLocalRef); - } - - public static boolean registerRuntime(JNIEnv env, JObject truffleRuntime) { - // TODO GR-44222 support multiple runtimes. - JWeak globalRuntimeRef = JNIUtil.NewWeakGlobalRef(env, truffleRuntime, ""); - return WEAK_TRUFFLE_RUNTIME_INSTANCE.compareAndSet(0, globalRuntimeRef.rawValue()); - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleFromLibGraalCalls.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleFromLibGraalCalls.java deleted file mode 100644 index 509d0eec4f92..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleFromLibGraalCalls.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import org.graalvm.jniutils.JNI.JClass; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; - -import static org.graalvm.jniutils.JNIUtil.NewGlobalRef; - -import org.graalvm.jniutils.JNIUtil; - -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal.Id; - -final class TruffleFromLibGraalCalls extends FromLibGraalCalls { - - private static final String ENTRY_POINT_CLASS_NAME = "com.oracle.truffle.runtime.hotspot.libgraal.TruffleFromLibGraalEntryPoints"; - private static final String CLASS_ENTRY_POINT_CLASS_NAME = "Class<" + ENTRY_POINT_CLASS_NAME + ">"; - - TruffleFromLibGraalCalls(JNIEnv env, JClass runtimeClass) { - super(Id.class, resolvePeer(env, runtimeClass)); - } - - private static JClass resolvePeer(JNIEnv env, JClass runtimeClass) { - JObject classLoader = JNIUtil.getClassLoader(env, runtimeClass); - JClass clazz = JNIUtil.findClass(env, classLoader, ENTRY_POINT_CLASS_NAME); - return NewGlobalRef(env, clazz, CLASS_ENTRY_POINT_CLASS_NAME); - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleLibGraalFeature.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleLibGraalFeature.java deleted file mode 100644 index cbbc8d2805d9..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleLibGraalFeature.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import jdk.graal.compiler.truffle.host.TruffleHostEnvironment; -import org.graalvm.jniutils.NativeBridgeSupport; -import org.graalvm.nativeimage.ImageSingletons; -import org.graalvm.nativeimage.hosted.Feature; - -public class TruffleLibGraalFeature implements Feature { - - @SuppressWarnings({"try", "unchecked"}) - @Override - public void beforeAnalysis(BeforeAnalysisAccess access) { - TruffleHostEnvironment.overrideLookup(new LibGraalTruffleHostEnvironmentLookup()); - } - - @Override - public void afterRegistration(AfterRegistrationAccess access) { - ImageSingletons.add(NativeBridgeSupport.class, new LibGraalNativeBridgeSupport()); - } -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleLibGraalShutdownHook.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleLibGraalShutdownHook.java deleted file mode 100644 index e51f868916cc..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleLibGraalShutdownHook.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import jdk.graal.compiler.serviceprovider.IsolateUtil; -import jdk.graal.compiler.serviceprovider.ServiceProvider; -import org.graalvm.jniutils.JNI.JClass; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JavaVM; -import org.graalvm.jniutils.JNIUtil; - -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleFromLibGraal; - -import jdk.vm.ci.hotspot.HotSpotVMEventListener; -import jdk.vm.ci.services.JVMCIServiceLocator; - -@ServiceProvider(JVMCIServiceLocator.class) -public class TruffleLibGraalShutdownHook extends JVMCIServiceLocator { - - private static volatile ShutdownHook registeredHook; - - @Override - protected S getProvider(Class service) { - ShutdownHook hook = registeredHook; - if (hook != null && service == HotSpotVMEventListener.class) { - return service.cast(hook); - } - return null; - } - - static void registerShutdownHook(JNIEnv env, JClass runtimeClass) { - JavaVM vm = JNIUtil.GetJavaVM(env); - ShutdownHook hook = registeredHook; - assert hook == null || hook.javaVm.isNull() || hook.javaVm.equal(vm); - registeredHook = new ShutdownHook(vm, new TruffleFromLibGraalCalls(env, runtimeClass)); - } - - static class ShutdownHook implements HotSpotVMEventListener { - - private final JavaVM javaVm; - private final TruffleFromLibGraalCalls calls; - - ShutdownHook(JavaVM javaVm, TruffleFromLibGraalCalls calls) { - this.javaVm = javaVm; - this.calls = calls; - } - - @Override - @TruffleFromLibGraal(TruffleFromLibGraal.Id.OnIsolateShutdown) - public void notifyShutdown() { - JNIEnv env = JNIUtil.GetEnv(javaVm); - assert env.isNonNull(); - TruffleLibGraalShutdownHookGen.callOnIsolateShutdown(calls, env, IsolateUtil.getIsolateID()); - } - - } - -} diff --git a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleToLibGraalEntryPoints.java b/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleToLibGraalEntryPoints.java deleted file mode 100644 index 3036a56ab3cc..000000000000 --- a/substratevm/src/com.oracle.svm.graal.hotspot.libgraal/src/com/oracle/svm/graal/hotspot/libgraal/truffle/TruffleToLibGraalEntryPoints.java +++ /dev/null @@ -1,556 +0,0 @@ -/* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -package com.oracle.svm.graal.hotspot.libgraal.truffle; - -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.DoCompile; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetCompilerConfigurationFactoryName; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetCompilerVersion; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetDataPatchesCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetExceptionHandlersCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetInfopoints; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetInfopointsCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetMarksCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetNodeCount; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetNodeTypes; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetSuppliedString; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetTargetCodeSize; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.GetTotalFrameSize; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.InitializeCompiler; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.InitializeRuntime; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.InstallTruffleCallBoundaryMethod; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.NewCompiler; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.PendingTransferToInterpreterOffset; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.PurgePartialEvaluationCaches; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.RegisterRuntime; -import static com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id.Shutdown; -import static org.graalvm.jniutils.JNIUtil.NewObjectArray; -import static org.graalvm.jniutils.JNIUtil.SetObjectArrayElement; -import static org.graalvm.jniutils.JNIUtil.createHSString; - -import java.util.function.Supplier; - -import jdk.graal.compiler.hotspot.CompilationContext; -import jdk.graal.compiler.hotspot.HotSpotGraalServices; -import jdk.graal.compiler.serviceprovider.IsolateUtil; -import jdk.graal.compiler.truffle.TruffleCompilerOptions; -import jdk.graal.compiler.truffle.hotspot.HotSpotTruffleCompilationSupport; -import jdk.graal.compiler.truffle.hotspot.HotSpotTruffleCompilerImpl; -import org.graalvm.jniutils.JNI.JByteArray; -import org.graalvm.jniutils.JNI.JClass; -import org.graalvm.jniutils.JNI.JNIEnv; -import org.graalvm.jniutils.JNI.JObject; -import org.graalvm.jniutils.JNI.JObjectArray; -import org.graalvm.jniutils.JNI.JString; -import org.graalvm.jniutils.JNIExceptionWrapper; -import org.graalvm.jniutils.JNIMethodScope; -import org.graalvm.jniutils.JNIUtil; -import org.graalvm.nativebridge.BinaryOutput; -import org.graalvm.nativebridge.BinaryOutput.ByteArrayBinaryOutput; -import org.graalvm.nativeimage.Isolate; -import org.graalvm.nativeimage.IsolateThread; -import org.graalvm.nativeimage.ObjectHandles; -import org.graalvm.nativeimage.c.function.CEntryPoint; -import org.graalvm.nativeimage.c.function.CEntryPoint.Builtin; -import org.graalvm.nativeimage.c.function.CEntryPoint.IsolateContext; -import org.graalvm.word.PointerBase; -import org.graalvm.word.WordFactory; - -import com.oracle.svm.core.heap.Heap; -import com.oracle.svm.graal.hotspot.libgraal.LibGraal; -import com.oracle.svm.graal.hotspot.libgraal.LibGraalUtil; -import com.oracle.truffle.compiler.TruffleCompilable; -import com.oracle.truffle.compiler.TruffleCompilationTask; -import com.oracle.truffle.compiler.TruffleCompilerListener; -import com.oracle.truffle.compiler.TruffleCompilerListener.CompilationResultInfo; -import com.oracle.truffle.compiler.TruffleCompilerListener.GraphInfo; -import com.oracle.truffle.compiler.TruffleCompilerOptionDescriptor; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal; -import com.oracle.truffle.compiler.hotspot.libgraal.TruffleToLibGraal.Id; - -import jdk.vm.ci.meta.ResolvedJavaMethod; -import jdk.vm.ci.meta.ResolvedJavaType; - -/** - * Entry points in libgraal for {@link TruffleToLibGraal calls} from HotSpot. - * - * To trace Truffle calls between HotSpot and libgraal, set the {@code JNI_LIBGRAAL_TRACE_LEVEL} - * system property to {@code 1}. For detailed tracing set the {@code JNI_LIBGRAAL_TRACE_LEVEL} - * system property to {@code 3}. - */ -final class TruffleToLibGraalEntryPoints { - - private static final String COMPILER_VERSION = HotSpotTruffleCompilationSupport.readCompilerVersion(); - - @CEntryPoint(builtin = Builtin.GET_CURRENT_THREAD, name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_LibGraalScope_getIsolateThreadIn") - private static native IsolateThread getIsolateThreadIn(PointerBase env, PointerBase hsClazz, @IsolateContext Isolate isolate); - - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_LibGraalScope_attachThreadTo", builtin = CEntryPoint.Builtin.ATTACH_THREAD) - static native long attachThreadTo(PointerBase env, PointerBase hsClazz, @CEntryPoint.IsolateContext long isolate); - - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_LibGraalScope_detachThreadFrom", builtin = CEntryPoint.Builtin.DETACH_THREAD) - static native void detachThreadFrom(PointerBase env, PointerBase hsClazz, @CEntryPoint.IsolateThreadContext long isolateThread); - - @SuppressWarnings({"unused"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_LibGraalObject_releaseHandle") - public static boolean releaseHandle(PointerBase jniEnv, - PointerBase jclass, - @CEntryPoint.IsolateThreadContext long isolateThreadId, - long handle) { - try { - ObjectHandles.getGlobal().destroy(WordFactory.pointer(handle)); - return true; - } catch (Throwable t) { - return false; - } - } - - @SuppressWarnings({"unused"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_LibGraalScope_getIsolateId") - public static long getIsolateId(PointerBase jniEnv, - PointerBase jclass, - @CEntryPoint.IsolateThreadContext long isolateThreadId) { - try { - return IsolateUtil.getIsolateID(); - } catch (Throwable t) { - return 0L; - } - } - - @TruffleToLibGraal(Id.InitializeIsolate) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_initializeIsolate") - public static void initializeIsolate(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, JClass runtimeClass) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, Id.InitializeIsolate, env)) { - TruffleLibGraalShutdownHook.registerShutdownHook(env, runtimeClass); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(RegisterRuntime) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_registerRuntime") - public static boolean registerRuntime(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, JObject truffleRuntime) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, RegisterRuntime, env)) { - return LibGraalTruffleHostEnvironmentLookup.registerRuntime(env, truffleRuntime); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return false; - } - } - - @TruffleToLibGraal(InitializeRuntime) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_initializeRuntime") - public static long initializeRuntime(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, - JObject truffleRuntime, JClass hsClassLoaderDelegate) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, InitializeRuntime, env)) { - ResolvedJavaType classLoaderDelegate = LibGraal.asResolvedJavaType(hsClassLoaderDelegate); - HSTruffleCompilerRuntime hsTruffleRuntime = new HSTruffleCompilerRuntime(env, truffleRuntime, classLoaderDelegate, hsClassLoaderDelegate); - long truffleRuntimeHandle = LibGraalObjectHandles.create(hsTruffleRuntime); - return truffleRuntimeHandle; - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0L; - } - } - - @TruffleToLibGraal(NewCompiler) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_newCompiler") - public static long newCompiler(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long truffleRuntimeHandle) { - /* - * Unlike `LibGraalTruffleHostEnvironment`, Truffle libgraal entry points use the global - * compilation context by default, so we don't need to call - * `HotSpotGraalServices.enterGlobalCompilationContext()` before creating - * `TruffleCompilerImpl`. The `doCompile` method enters a local compilation context through - * its own call to `HotSpotGraalServices.openLocalCompilationContext`. - */ - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, NewCompiler, env)) { - HSTruffleCompilerRuntime hsTruffleRuntime = LibGraalObjectHandles.resolve(truffleRuntimeHandle, HSTruffleCompilerRuntime.class); - HotSpotTruffleCompilerImpl compiler = HotSpotTruffleCompilerImpl.create(hsTruffleRuntime); - return LibGraalObjectHandles.create(compiler); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - private static JClass getStringClass(JNIEnv env) { - return JNIUtil.NewGlobalRef(env, JNIUtil.findClass(env, "java/lang/String"), "Class"); - } - - @TruffleToLibGraal(InitializeCompiler) - @SuppressWarnings("unused") - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_initializeCompiler") - public static void initializeCompiler(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long compilerHandle, JObject hsCompilable, - boolean firstInitialization) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, InitializeCompiler, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(compilerHandle, HotSpotTruffleCompilerImpl.class); - HSTruffleCompilerRuntime runtime = (HSTruffleCompilerRuntime) compiler.getConfig().runtime(); - TruffleCompilable compilable = new HSTruffleCompilable(s, hsCompilable, runtime); - compiler.initialize(compilable, firstInitialization); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(GetCompilerConfigurationFactoryName) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getCompilerConfigurationFactoryName") - public static JString getCompilerConfigurationFactoryName(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long truffleRuntimeHandle) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetCompilerConfigurationFactoryName, env); - try (JNIMethodScope s = scope) { - String name = HotSpotTruffleCompilationSupport.getLazyCompilerConfigurationName(); - scope.setObjectResult(createHSString(env, name)); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - @TruffleToLibGraal(DoCompile) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_doCompile") - public static void doCompile(JNIEnv env, - JClass hsClazz, - @CEntryPoint.IsolateThreadContext long isolateThreadId, - long compilerHandle, - JObject hsTask, - JObject hsCompilable, - JObject hsListener) { - try (JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, DoCompile, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(compilerHandle, HotSpotTruffleCompilerImpl.class); - HSTruffleCompilerRuntime runtime = (HSTruffleCompilerRuntime) compiler.getConfig().runtime(); - HSTruffleCompilable compilable = new HSTruffleCompilable(scope, hsCompilable, runtime); - TruffleCompilationTask task = hsTask.isNull() ? null : new HSTruffleCompilationTask(scope, hsTask, runtime); - try (CompilationContext hotSpotObjectConstantScope = HotSpotGraalServices.openLocalCompilationContext(compilable)) { - TruffleCompilerListener listener = hsListener.isNull() ? null : new HSTruffleCompilerListener(scope, hsListener, runtime); - compiler.doCompile(task, compilable, listener); - } finally { - Heap.getHeap().doReferenceHandling(); - Heap.getHeap().getGC().collectionHint(true); - } - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(Shutdown) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_shutdown") - public static void shutdown(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, Shutdown, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(handle, HotSpotTruffleCompilerImpl.class); - compiler.shutdown(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(InstallTruffleCallBoundaryMethod) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_installTruffleCallBoundaryMethod") - public static void installTruffleCallBoundaryMethod(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle, long methodHandle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, InstallTruffleCallBoundaryMethod, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(handle, HotSpotTruffleCompilerImpl.class); - compiler.installTruffleCallBoundaryMethod(LibGraal.unhand(ResolvedJavaMethod.class, methodHandle), null); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(Id.InstallTruffleReservedOopMethod) - @SuppressWarnings({"unused", "try"}) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_installTruffleReservedOopMethod") - public static void installTruffleReservedOopMethod(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle, long methodHandle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, Id.InstallTruffleReservedOopMethod, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(handle, HotSpotTruffleCompilerImpl.class); - compiler.installTruffleReservedOopMethod(LibGraal.unhand(ResolvedJavaMethod.class, methodHandle), null); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(PendingTransferToInterpreterOffset) - @SuppressWarnings("unused") - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_pendingTransferToInterpreterOffset") - public static int pendingTransferToInterpreterOffset(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle, JObject hsCompilable) { - try (JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, PendingTransferToInterpreterOffset, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(handle, HotSpotTruffleCompilerImpl.class); - HSTruffleCompilerRuntime runtime = (HSTruffleCompilerRuntime) compiler.getConfig().runtime(); - TruffleCompilable compilable = new HSTruffleCompilable(scope, hsCompilable, runtime); - return compiler.pendingTransferToInterpreterOffset(compilable); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetSuppliedString) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getSuppliedString") - @SuppressWarnings({"unused", "unchecked", "try"}) - public static JString getString(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetSuppliedString, env); - try (JNIMethodScope s = scope) { - Supplier orig = LibGraalObjectHandles.resolve(handle, Supplier.class); - if (orig != null) { - String stackTrace = orig.get(); - scope.setObjectResult(JNIUtil.createHSString(env, stackTrace)); - } else { - scope.setObjectResult(WordFactory.nullPointer()); - } - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - @TruffleToLibGraal(GetNodeCount) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getNodeCount") - @SuppressWarnings({"unused", "try"}) - public static int getNodeCount(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetNodeCount, env)) { - GraphInfo orig = LibGraalObjectHandles.resolve(handle, GraphInfo.class); - return orig.getNodeCount(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetNodeTypes) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getNodeTypes") - @SuppressWarnings({"unused", "try"}) - public static JObjectArray getNodeTypes(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle, boolean simpleNames) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetNodeTypes, env); - try (JNIMethodScope s = scope) { - GraphInfo orig = LibGraalObjectHandles.resolve(handle, GraphInfo.class); - String[] nodeTypes = orig.getNodeTypes(simpleNames); - JClass componentType = getStringClass(env); - JObjectArray res = NewObjectArray(env, nodeTypes.length, componentType, WordFactory.nullPointer()); - for (int i = 0; i < nodeTypes.length; i++) { - SetObjectArrayElement(env, res, i, JNIUtil.createHSString(env, nodeTypes[i])); - } - scope.setObjectResult(res); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - @TruffleToLibGraal(GetTargetCodeSize) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getTargetCodeSize") - @SuppressWarnings({"unused", "try"}) - public static int getTargetCodeSize(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetTargetCodeSize, env)) { - return LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getTargetCodeSize(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetTotalFrameSize) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getTotalFrameSize") - @SuppressWarnings({"unused", "try"}) - public static int getTotalFrameSize(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetTotalFrameSize, env)) { - return LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getTotalFrameSize(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetExceptionHandlersCount) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getExceptionHandlersCount") - @SuppressWarnings({"unused", "try"}) - public static int getExceptionHandlersCount(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetExceptionHandlersCount, env)) { - return LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getExceptionHandlersCount(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetInfopointsCount) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getInfopointsCount") - @SuppressWarnings({"unused", "try"}) - public static int getInfopointsCount(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetInfopointsCount, env)) { - return LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getInfopointsCount(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetInfopoints) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getInfopoints") - @SuppressWarnings({"unused", "try"}) - public static JObjectArray getInfopoints(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetInfopoints, env); - try (JNIMethodScope s = scope) { - String[] infoPoints = LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getInfopoints(); - JClass componentType = getStringClass(env); - JObjectArray res = NewObjectArray(env, infoPoints.length, componentType, WordFactory.nullPointer()); - for (int i = 0; i < infoPoints.length; i++) { - SetObjectArrayElement(env, res, i, createHSString(env, infoPoints[i])); - } - scope.setObjectResult(res); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - @TruffleToLibGraal(Id.ListCompilerOptions) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_listCompilerOptions") - @SuppressWarnings({"unused", "try"}) - public static JByteArray listCompilerOptions(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, Id.ListCompilerOptions, env); - try (JNIMethodScope s = scope) { - TruffleCompilerOptionDescriptor[] options = TruffleCompilerOptions.listOptions(); - ByteArrayBinaryOutput out = BinaryOutput.create(); - - out.writeInt(options.length); - for (int i = 0; i < options.length; i++) { - TruffleCompilerOptionDescriptor descriptor = options[i]; - out.writeUTF(descriptor.name()); - out.writeInt(descriptor.type().ordinal()); - out.writeBoolean(descriptor.deprecated()); - out.writeUTF(descriptor.help()); - out.writeUTF(descriptor.deprecationMessage()); - } - - JByteArray res = JNIUtil.createHSArray(env, out.getArray()); - scope.setObjectResult(res); - - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - @TruffleToLibGraal(Id.CompilerOptionExists) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_compilerOptionExists") - @SuppressWarnings({"unused", "try"}) - public static boolean existsCompilerOption(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, JString optionName) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, Id.CompilerOptionExists, env); - try (JNIMethodScope s = scope) { - return TruffleCompilerOptions.optionExists(JNIUtil.createString(env, optionName)); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return false; - } - } - - @TruffleToLibGraal(Id.ValidateCompilerOption) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_validateCompilerOption") - @SuppressWarnings({"unused", "try"}) - public static JString validateCompilerOption(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, JString optionName, JString optionValue) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, Id.ValidateCompilerOption, env); - try (JNIMethodScope s = scope) { - scope.setObjectResult(JNIUtil.createHSString(env, TruffleCompilerOptions.validateOption(JNIUtil.createString(env, optionName), JNIUtil.createString(env, optionValue)))); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - @TruffleToLibGraal(GetMarksCount) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getMarksCount") - @SuppressWarnings({"unused", "try"}) - public static int getMarksCount(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetMarksCount, env)) { - return LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getMarksCount(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(GetDataPatchesCount) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getDataPatchesCount") - @SuppressWarnings({"unused", "try"}) - public static int getDataPatchesCount(JNIEnv env, JClass hsClazz, @CEntryPoint.IsolateThreadContext long isolateThreadId, long handle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetDataPatchesCount, env)) { - return LibGraalObjectHandles.resolve(handle, CompilationResultInfo.class).getDataPatchesCount(); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - return 0; - } - } - - @TruffleToLibGraal(PurgePartialEvaluationCaches) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_purgePartialEvaluationCaches") - @SuppressWarnings({"unused", "try"}) - public static void purgePartialEvaluationCaches(JNIEnv env, JClass hsClass, @CEntryPoint.IsolateThreadContext long isolateThreadId, long compilerHandle) { - try (JNIMethodScope s = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, PurgePartialEvaluationCaches, env)) { - HotSpotTruffleCompilerImpl compiler = LibGraalObjectHandles.resolve(compilerHandle, HotSpotTruffleCompilerImpl.class); - if (compiler != null) { - compiler.purgePartialEvaluationCaches(); - } - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - } - } - - @TruffleToLibGraal(GetCompilerVersion) - @CEntryPoint(name = "Java_com_oracle_truffle_runtime_hotspot_libgraal_TruffleToLibGraalCalls_getCompilerVersion") - @SuppressWarnings({"unused", "try"}) - public static JString getCompilerVersion(JNIEnv env, JClass hsClass, @CEntryPoint.IsolateThreadContext long isolateThreadId) { - JNIMethodScope scope = LibGraalUtil.openScope(TruffleToLibGraalEntryPoints.class, GetCompilerVersion, env); - try (JNIMethodScope s = scope) { - scope.setObjectResult(createHSString(env, COMPILER_VERSION)); - } catch (Throwable t) { - JNIExceptionWrapper.throwInHotSpot(env, t); - scope.setObjectResult(WordFactory.nullPointer()); - } - return scope.getObjectResult(); - } - - static { - Class callsClass; - try { - callsClass = Class.forName("com.oracle.truffle.runtime.hotspot.libgraal.TruffleToLibGraalCalls"); - LibGraalChecker.checkToLibGraalCalls(TruffleToLibGraalEntryPoints.class, callsClass, TruffleToLibGraal.class); - } catch (ClassNotFoundException e) { - /* - * Truffle might not be on the class path if libgraal is built. If it is, we should - * validate the usage. - */ - } - } - -} diff --git a/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalObject.java b/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalObject.java index 4dd400e6e3b5..4b4092f068e3 100644 --- a/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalObject.java +++ b/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalObject.java @@ -113,7 +113,7 @@ public long getHandle() { * @return {@code false} if {@code} is not a valid handle in the isolate */ // Implementation: - // com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.releaseHandle + // com.oracle.svm.graal.hotspot.guestgraal.GuestGraalTruffleToLibGraalEntryPoints.releaseHandle static native boolean releaseHandle(long isolateThreadId, long handle); @Override diff --git a/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalScope.java b/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalScope.java index 8f002d7b47d6..b56cd354755a 100644 --- a/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalScope.java +++ b/truffle/src/com.oracle.truffle.runtime/src/com/oracle/truffle/runtime/hotspot/libgraal/LibGraalScope.java @@ -197,14 +197,14 @@ public String toString() { * @return the address of the attached IsolateThread */ // Implementation: - // com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.attachThreadTo + // com.oracle.svm.graal.hotspot.guestgraal.GuestGraalLibGraalScope.attachThreadTo static native long attachThreadTo(long isolateAddress); /** * Detaches the current thread from the isolate at {@code isolateAddress}. */ // Implementation: - // com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.detachThreadFrom + // com.oracle.svm.graal.hotspot.guestgraal.GuestGraalLibGraalScope.detachThreadFrom static native void detachThreadFrom(long isolateThreadAddress); /** @@ -213,7 +213,7 @@ public String toString() { * @return 0L if the current thread is not attached to the isolate at {@code isolateAddress} */ // Implementation: - // com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.getIsolateThreadIn + // com.oracle.svm.graal.hotspot.guestgraal.GuestGraalLibGraalScope.getIsolateThreadIn @SuppressWarnings("unused") static native long getIsolateThreadIn(long isolateAddress); @@ -222,7 +222,7 @@ public String toString() { * to be unique for the first {@code 2^64 - 1} isolates in the process. */ // Implementation: - // com.oracle.svm.graal.hotspot.libgraal.LibGraalEntryPoints.getIsolateId + // com.oracle.svm.graal.hotspot.guestgraal.GuestGraalLibGraalScope.getIsolateId private static native long getIsolateId(long isolateThreadAddress); /** diff --git a/vm/ci/ci_common/libgraal.jsonnet b/vm/ci/ci_common/libgraal.jsonnet index f358b5aea3ee..4a0eb6a16d3f 100644 --- a/vm/ci/ci_common/libgraal.jsonnet +++ b/vm/ci/ci_common/libgraal.jsonnet @@ -80,63 +80,6 @@ local galahad = import '../../../ci/ci_common/galahad-common.libsonnet'; # Use economy mode for coverage testing libgraal_truffle_coverage: self.libgraal_truffle_base(['-Ob'], coverage=true), - # Gate for guestgraal - guestgraal_base(extra_vm_args=[]):: { - local pathsep = if self.os == "windows" then ";" else ":", - local guestgraal_env = std.strReplace(vm.libgraal_env, "libgraal", "guestgraal"), - run+: [ - ['mx', '--env', guestgraal_env, 'build'], - ['set-export', 'JNIUTILS_PATH', ['mx', '--env', guestgraal_env, '--quiet', 'path', 'JNIUTILS']], - ['set-export', 'NATIVEBRIDGE_PATH', ['mx', '--env', guestgraal_env, '--quiet', 'path', 'NATIVEBRIDGE']], - ['set-export', 'GUESTGRAAL_LIBRARY_PATH', ['mx', '--env', guestgraal_env, '--quiet', 'path', 'GUESTGRAAL_LIBRARY']], - ] + (if vm.edition == "ee" then [ - ['set-export', 'ENTERPRISE_GUESTGRAAL_LIBRARY_PATH', ['mx', '--env', guestgraal_env, '--quiet', 'path', 'ENTERPRISE_GUESTGRAAL_LIBRARY']] - ] else []) + [ - ['mx', '--env', guestgraal_env, 'native-image', '-J-esa', '-J-ea', '-esa', '-ea', - '-p', '$JNIUTILS_PATH' + pathsep + '$NATIVEBRIDGE_PATH', - '-cp', '$GUESTGRAAL_LIBRARY_PATH' + pathsep + '$ENTERPRISE_GUESTGRAAL_LIBRARY_PATH', - '-H:+UnlockExperimentalVMOptions', '-H:+VerifyGraalGraphs', '-H:+VerifyPhases'], - ['mx', '--env', guestgraal_env, 'gate', '--task', std.join(",", self.tasks), '--extra-vm-argument=-XX:JVMCILibPath=$PWD/' + vm.vm_dir, '--extra-vm-argument=' + std.join(" ", extra_vm_args)] - ], - logs+: [ - '*/graal-compiler.log', - '*/graal-compiler-ctw.log', - ], - }, - - guestgraal_compiler:: self.guestgraal_base(extra_vm_args=[]) + { - # LibGraal gate tasks currently expected to work - tasks: [ - "LibGraal Compiler:Basic", - "LibGraal Compiler:FatalErrorHandling", - "LibGraal Compiler:OOMEDumping", - "LibGraal Compiler:SystemicFailureDetection", - "LibGraal Compiler:CompilationTimeout:JIT", - "LibGraal Compiler:CTW", - "LibGraal Compiler:DaCapo", - "LibGraal Compiler:ScalaDaCapo" - ] + - # Renaissance is missing the msvc redistributable on Windows [GR-50132] - if self.os == "windows" then [] else ["LibGraal Compiler:Renaissance"], - timelimit: '1:00:00', - }, - - guestgraal_truffle:: self.guestgraal_base(extra_vm_args=['-DGCUtils.saveHeapDumpTo=.']) + { - # Truffle LibGraal gate tasks - tasks: [ - "LibGraal Truffle", - "LibGraal Compiler:CompilationTimeout:Truffle" - ], - environment+: { - # The Truffle TCK tests run as a part of Truffle TCK gate, tools tests run as a part of tools gate - TEST_LIBGRAAL_EXCLUDE: 'com.oracle.truffle.tck.tests.* com.oracle.truffle.tools.* com.oracle.truffle.regex.*' - }, - logs+: [ - '*/gcutils_heapdump_*.hprof.gz' - ], - timelimit: '1:00:00', - }, - # See definition of `gates` local variable in ../../compiler/ci_common/gate.jsonnet local gate_jobs = { "gate-vm-libgraal_compiler-labsjdk-latest-linux-amd64": {}, @@ -145,9 +88,7 @@ local galahad = import '../../../ci/ci_common/galahad-common.libsonnet'; "gate-vm-libgraal_compiler_quickbuild-labsjdk-latest-linux-amd64": {}, "gate-vm-libgraal_compiler-labsjdk-21-linux-amd64": {}, - "gate-vm-libgraal_truffle-labsjdk-21-linux-amd64": {}, - "gate-vm-guestgraal_compiler-labsjdk-latest-linux-amd64": {}, - "gate-vm-guestgraal_truffle-labsjdk-latest-linux-amd64": {}, + "gate-vm-libgraal_truffle-labsjdk-21-linux-amd64": {} }, local gates = g.as_gates(gate_jobs), @@ -206,9 +147,7 @@ local galahad = import '../../../ci/ci_common/galahad-common.libsonnet'; "libgraal_compiler", "libgraal_truffle", "libgraal_compiler_quickbuild", - "libgraal_truffle_quickbuild", - "guestgraal_compiler", - "guestgraal_truffle" + "libgraal_truffle_quickbuild" ] ],