Search in sources :

Example 16 with CoreProviders

use of org.graalvm.compiler.nodes.spi.CoreProviders in project graal by oracle.

the class CheckGraalInvariants method runTest.

@SuppressWarnings("try")
public static void runTest(InvariantsTool tool) {
    RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class);
    Providers providers = rt.getHostBackend().getProviders();
    MetaAccessProvider metaAccess = providers.getMetaAccess();
    PhaseSuite<HighTierContext> graphBuilderSuite = new PhaseSuite<>();
    Plugins plugins = new Plugins(new InvocationPlugins());
    GraphBuilderConfiguration config = GraphBuilderConfiguration.getDefault(plugins).withEagerResolving(true).withUnresolvedIsError(true);
    graphBuilderSuite.appendPhase(new GraphBuilderPhase(config));
    HighTierContext context = new HighTierContext(providers, graphBuilderSuite, OptimisticOptimizations.NONE);
    Assume.assumeTrue(VerifyPhase.class.desiredAssertionStatus());
    String bootclasspath = tool.getClassPath();
    Assert.assertNotNull("Cannot find boot class path", bootclasspath);
    final List<String> classNames = new ArrayList<>();
    for (String path : bootclasspath.split(File.pathSeparator)) {
        if (tool.shouldProcess(path)) {
            try {
                if (path.equals(JRT_CLASS_PATH_ENTRY)) {
                    for (String className : ModuleSupport.getJRTGraalClassNames()) {
                        if (isGSON(className)) {
                            continue;
                        }
                        classNames.add(className);
                    }
                } else {
                    File file = new File(path);
                    if (!file.exists()) {
                        continue;
                    }
                    if (file.isDirectory()) {
                        Path root = file.toPath();
                        Files.walk(root).forEach(p -> {
                            String name = root.relativize(p).toString();
                            if (name.endsWith(".class") && !name.startsWith("META-INF/versions/")) {
                                String className = name.substring(0, name.length() - ".class".length()).replace('/', '.');
                                if (!(isInNativeImage(className) || isGSON(className))) {
                                    classNames.add(className);
                                }
                            }
                        });
                    } else {
                        final ZipFile zipFile = new ZipFile(file);
                        for (final Enumeration<? extends ZipEntry> entry = zipFile.entries(); entry.hasMoreElements(); ) {
                            final ZipEntry zipEntry = entry.nextElement();
                            String name = zipEntry.getName();
                            if (name.endsWith(".class") && !name.startsWith("META-INF/versions/")) {
                                String className = name.substring(0, name.length() - ".class".length()).replace('/', '.');
                                if (isInNativeImage(className) || isGSON(className)) {
                                    continue;
                                }
                                classNames.add(className);
                            }
                        }
                    }
                }
            } catch (IOException ex) {
                throw new AssertionError(ex);
            }
        }
    }
    Assert.assertFalse("Could not find graal jars on boot class path: " + bootclasspath, classNames.isEmpty());
    // Allows a subset of methods to be checked through use of a system property
    String property = System.getProperty(CheckGraalInvariants.class.getName() + ".filters");
    String[] filters = property == null ? null : property.split(",");
    OptionValues options = getInitialOptions();
    CompilerThreadFactory factory = new CompilerThreadFactory("CheckInvariantsThread");
    int availableProcessors = Runtime.getRuntime().availableProcessors();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(availableProcessors, availableProcessors, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), factory);
    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    List<VerifyPhase<CoreProviders>> verifiers = new ArrayList<>();
    // If you add a new type to test here, be sure to add appropriate
    // methods to the BadUsageWithEquals class below
    verifiers.add(new VerifyUsageWithEquals(Value.class));
    verifiers.add(new VerifyUsageWithEquals(Register.class));
    verifiers.add(new VerifyUsageWithEquals(RegisterCategory.class));
    verifiers.add(new VerifyUsageWithEquals(JavaType.class));
    verifiers.add(new VerifyUsageWithEquals(JavaMethod.class));
    verifiers.add(new VerifyUsageWithEquals(JavaField.class));
    verifiers.add(new VerifyUsageWithEquals(LocationIdentity.class));
    verifiers.add(new VerifyUsageWithEquals(LIRKind.class));
    verifiers.add(new VerifyUsageWithEquals(ArithmeticOpTable.class));
    verifiers.add(new VerifyUsageWithEquals(ArithmeticOpTable.Op.class));
    verifiers.add(new VerifyDebugUsage());
    verifiers.add(new VerifyVirtualizableUsage());
    verifiers.add(new VerifyUpdateUsages());
    verifiers.add(new VerifyBailoutUsage());
    verifiers.add(new VerifySystemPropertyUsage());
    verifiers.add(new VerifyInstanceOfUsage());
    verifiers.add(new VerifyGraphAddUsage());
    verifiers.add(new VerifyGetOptionsUsage());
    verifiers.add(new VerifyUnsafeAccess());
    verifiers.add(new VerifyVariableCasts());
    verifiers.add(new VerifyIterableNodeType());
    verifiers.add(new VerifyArchUsageInPlugins());
    verifiers.add(new VerifyStatelessPhases());
    loadVerifiers(verifiers);
    VerifyFoldableMethods foldableMethodsVerifier = new VerifyFoldableMethods();
    if (tool.shouldVerifyFoldableMethods()) {
        verifiers.add(foldableMethodsVerifier);
    }
    tool.updateVerifiers(verifiers);
    for (Method m : BadUsageWithEquals.class.getDeclaredMethods()) {
        ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m);
        try (DebugContext debug = new Builder(options).build()) {
            StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(method).build();
            try (DebugCloseable s = debug.disableIntercept();
                DebugContext.Scope ds = debug.scope("CheckingGraph", graph, method)) {
                graphBuilderSuite.apply(graph, context);
                // update phi stamps
                graph.getNodes().filter(PhiNode.class).forEach(PhiNode::inferStamp);
                checkGraph(verifiers, context, graph);
                errors.add(String.format("Expected error while checking %s", m));
            } catch (VerificationError e) {
            // expected!
            } catch (Throwable e) {
                errors.add(String.format("Error while checking %s:%n%s", m, printStackTraceToString(e)));
            }
        }
    }
    Map<ResolvedJavaField, Set<ResolvedJavaMethod>> optionFieldUsages = initOptionFieldUsagesMap(tool, metaAccess, errors);
    ResolvedJavaType optionDescriptorsType = metaAccess.lookupJavaType(OptionDescriptors.class);
    if (errors.isEmpty()) {
        // Order outer classes before the inner classes
        classNames.sort((String a, String b) -> a.compareTo(b));
        // Initialize classes in single thread to avoid deadlocking issues during initialization
        List<Class<?>> classes = initializeClasses(tool, classNames);
        for (Class<?> c : classes) {
            String className = c.getName();
            executor.execute(() -> {
                try {
                    checkClass(c, metaAccess, verifiers);
                } catch (Throwable e) {
                    errors.add(String.format("Error while checking %s:%n%s", className, printStackTraceToString(e)));
                }
            });
            ResolvedJavaType type = metaAccess.lookupJavaType(c);
            List<ResolvedJavaMethod> methods = new ArrayList<>();
            try {
                methods.addAll(Arrays.asList(type.getDeclaredMethods()));
                methods.addAll(Arrays.asList(type.getDeclaredConstructors()));
            } catch (Throwable e) {
                errors.add(String.format("Error while checking %s:%n%s", className, printStackTraceToString(e)));
            }
            ResolvedJavaMethod clinit = type.getClassInitializer();
            if (clinit != null) {
                methods.add(clinit);
            }
            for (ResolvedJavaMethod method : methods) {
                if (Modifier.isNative(method.getModifiers()) || Modifier.isAbstract(method.getModifiers())) {
                // ignore
                } else {
                    String methodName = className + "." + method.getName();
                    if (matches(filters, methodName)) {
                        executor.execute(() -> {
                            try (DebugContext debug = new Builder(options).build()) {
                                boolean isSubstitution = method.getAnnotation(Snippet.class) != null;
                                StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).setIsSubstitution(isSubstitution).build();
                                try (DebugCloseable s = debug.disableIntercept();
                                    DebugContext.Scope ds = debug.scope("CheckingGraph", graph, method)) {
                                    checkMethod(method);
                                    graphBuilderSuite.apply(graph, context);
                                    // update phi stamps
                                    graph.getNodes().filter(PhiNode.class).forEach(PhiNode::inferStamp);
                                    collectOptionFieldUsages(optionFieldUsages, optionDescriptorsType, method, graph);
                                    checkGraph(verifiers, context, graph);
                                } catch (VerificationError e) {
                                    errors.add(e.getMessage());
                                } catch (LinkageError e) {
                                // suppress linkages errors resulting from eager resolution
                                } catch (BailoutException e) {
                                // Graal bail outs on certain patterns in Java bytecode
                                // (e.g.,
                                // unbalanced monitors introduced by jacoco).
                                } catch (Throwable e) {
                                    try {
                                        tool.handleParsingException(e);
                                    } catch (Throwable t) {
                                        errors.add(String.format("Error while checking %s:%n%s", methodName, printStackTraceToString(e)));
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e1) {
            throw new RuntimeException(e1);
        }
        if (tool.shouldVerifyFoldableMethods()) {
            try {
                foldableMethodsVerifier.finish();
            } catch (Throwable e) {
                errors.add(e.getMessage());
            }
        }
    }
    checkOptionFieldUsages(errors, optionFieldUsages);
    if (!errors.isEmpty()) {
        StringBuilder msg = new StringBuilder();
        String nl = String.format("%n");
        for (String e : errors) {
            if (msg.length() != 0) {
                msg.append(nl);
            }
            msg.append(e);
        }
        Assert.fail(msg.toString());
    }
}
Also used : OptionValues(org.graalvm.compiler.options.OptionValues) VerificationError(org.graalvm.compiler.phases.VerifyPhase.VerificationError) Builder(org.graalvm.compiler.debug.DebugContext.Builder) ArrayList(java.util.ArrayList) VerifyPhase(org.graalvm.compiler.phases.VerifyPhase) ResolvedJavaField(jdk.vm.ci.meta.ResolvedJavaField) JavaField(jdk.vm.ci.meta.JavaField) JavaMethod(jdk.vm.ci.meta.JavaMethod) ResolvedJavaMethod(jdk.vm.ci.meta.ResolvedJavaMethod) LocationIdentity(org.graalvm.word.LocationIdentity) InvocationPlugins(org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins) PhiNode(org.graalvm.compiler.nodes.PhiNode) GraphBuilderConfiguration(org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration) Method(java.lang.reflect.Method) JavaMethod(jdk.vm.ci.meta.JavaMethod) ResolvedJavaMethod(jdk.vm.ci.meta.ResolvedJavaMethod) DebugContext(org.graalvm.compiler.debug.DebugContext) Snippet(org.graalvm.compiler.api.replacements.Snippet) ResolvedJavaType(jdk.vm.ci.meta.ResolvedJavaType) JavaType(jdk.vm.ci.meta.JavaType) Value(jdk.vm.ci.meta.Value) NodeClass(org.graalvm.compiler.graph.NodeClass) HighTierContext(org.graalvm.compiler.phases.tiers.HighTierContext) LIRKind(org.graalvm.compiler.core.common.LIRKind) DebugCloseable(org.graalvm.compiler.debug.DebugCloseable) ZipFile(java.util.zip.ZipFile) File(java.io.File) MetaAccessProvider(jdk.vm.ci.meta.MetaAccessProvider) CompilerThreadFactory(org.graalvm.compiler.core.CompilerThreadFactory) Set(java.util.Set) HashSet(java.util.HashSet) ZipEntry(java.util.zip.ZipEntry) RuntimeProvider(org.graalvm.compiler.runtime.RuntimeProvider) CoreProviders(org.graalvm.compiler.nodes.spi.CoreProviders) Providers(org.graalvm.compiler.phases.util.Providers) ResolvedJavaType(jdk.vm.ci.meta.ResolvedJavaType) ResolvedJavaField(jdk.vm.ci.meta.ResolvedJavaField) ArithmeticOpTable(org.graalvm.compiler.core.common.type.ArithmeticOpTable) StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) GraphBuilderPhase(org.graalvm.compiler.java.GraphBuilderPhase) InvocationPlugins(org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins) Plugins(org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins) Path(java.nio.file.Path) RegisterCategory(jdk.vm.ci.code.Register.RegisterCategory) IOException(java.io.IOException) BailoutException(jdk.vm.ci.code.BailoutException) ZipFile(java.util.zip.ZipFile) Register(jdk.vm.ci.code.Register) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) PhaseSuite(org.graalvm.compiler.phases.PhaseSuite) ResolvedJavaMethod(jdk.vm.ci.meta.ResolvedJavaMethod)

Example 17 with CoreProviders

use of org.graalvm.compiler.nodes.spi.CoreProviders in project graal by oracle.

the class SubstrateGraphBuilderPlugins method processFieldOffset.

private static boolean processFieldOffset(GraphBuilderContext b, Field targetField, ParsingReason reason, MetaAccessProvider metaAccess, boolean isSunMiscUnsafe) {
    if (!isValidField(targetField, isSunMiscUnsafe)) {
        return false;
    }
    if (SubstrateOptions.parseOnce() || reason == ParsingReason.PointsToAnalysis) {
        /* Register the field for unsafe access. */
        registerAsUnsafeAccessed(metaAccess, targetField);
    } else {
        HostedMetaAccess hostedMetaAccess = (HostedMetaAccess) metaAccess;
        HostedField hostedField = hostedMetaAccess.lookupJavaField(targetField);
        if (!hostedField.wrapped.isUnsafeAccessed()) {
            /*
                 * The target field was not constant folded during static analysis, so the above
                 * unsafe access registration did not run. A UnsupportedFeatureError will be thrown
                 * at run time for this call.
                 */
            return false;
        }
    }
    /* Usage of lambdas is not allowed in Graal nodes, so need explicit inner class. */
    Function<CoreProviders, JavaConstant> fieldOffsetConstantProvider = new Function<>() {

        @Override
        public JavaConstant apply(CoreProviders providers) {
            ResolvedJavaField rField = providers.getMetaAccess().lookupJavaField(targetField);
            if (rField instanceof SharedField) {
                long fieldOffset = ((SharedField) rField).getLocation();
                assert fieldOffset > 0;
                return JavaConstant.forLong(fieldOffset);
            }
            return null;
        }
    };
    b.addPush(JavaKind.Long, LazyConstantNode.create(StampFactory.forKind(JavaKind.Long), fieldOffsetConstantProvider, b));
    return true;
}
Also used : SharedField(com.oracle.svm.core.meta.SharedField) Function(java.util.function.Function) CoreProviders(org.graalvm.compiler.nodes.spi.CoreProviders) HostedField(com.oracle.svm.hosted.meta.HostedField) JavaConstant(jdk.vm.ci.meta.JavaConstant) HostedMetaAccess(com.oracle.svm.hosted.meta.HostedMetaAccess) ResolvedJavaField(jdk.vm.ci.meta.ResolvedJavaField)

Example 18 with CoreProviders

use of org.graalvm.compiler.nodes.spi.CoreProviders in project graal by oracle.

the class AArch64HotSpotBackendFactory method createSuites.

@Override
protected HotSpotSuitesProvider createSuites(GraalHotSpotVMConfig config, HotSpotGraalRuntimeProvider runtime, CompilerConfiguration compilerConfiguration, Plugins plugins, HotSpotRegistersProvider registers, HotSpotReplacementsImpl replacements, OptionValues options) {
    AArch64SuitesCreator suitesCreator = new AArch64SuitesCreator(compilerConfiguration, plugins, Arrays.asList(SchedulePhase.class));
    BasePhase<CoreProviders> addressLoweringPhase = new AddressLoweringByUsePhase(new AArch64AddressLoweringByUse(new AArch64LIRKindTool(), true));
    return new AddressLoweringHotSpotSuitesProvider(suitesCreator, config, runtime, addressLoweringPhase);
}
Also used : CoreProviders(org.graalvm.compiler.nodes.spi.CoreProviders) SchedulePhase(org.graalvm.compiler.phases.schedule.SchedulePhase) AddressLoweringHotSpotSuitesProvider(org.graalvm.compiler.hotspot.meta.AddressLoweringHotSpotSuitesProvider) AArch64AddressLoweringByUse(org.graalvm.compiler.core.aarch64.AArch64AddressLoweringByUse) AArch64LIRKindTool(org.graalvm.compiler.core.aarch64.AArch64LIRKindTool) AArch64SuitesCreator(org.graalvm.compiler.core.aarch64.AArch64SuitesCreator) AddressLoweringByUsePhase(org.graalvm.compiler.phases.common.AddressLoweringByUsePhase)

Example 19 with CoreProviders

use of org.graalvm.compiler.nodes.spi.CoreProviders in project graal by oracle.

the class PoorMansEATest method test.

@SuppressWarnings("try")
private void test(final String snippet) {
    DebugContext debug = getDebugContext();
    try (DebugContext.Scope s = debug.scope("PoorMansEATest", new DebugDumpScope(snippet))) {
        StructuredGraph graph = parseEager(snippet, AllowAssumptions.NO);
        HighTierContext highTierContext = getDefaultHighTierContext();
        createInliningPhase().apply(graph, highTierContext);
        CoreProviders context = getProviders();
        new LoweringPhase(createCanonicalizerPhase(), LoweringTool.StandardLoweringStage.HIGH_TIER).apply(graph, context);
        // remove framestates in order to trigger the simplification.
        cleanup: for (FrameState fs : graph.getNodes(FrameState.TYPE).snapshot()) {
            for (Node input : fs.inputs()) {
                if (input instanceof NewInstanceNode) {
                    fs.replaceAtUsages(null);
                    fs.safeDelete();
                    continue cleanup;
                }
            }
        }
        createCanonicalizerPhase().apply(graph, context);
    } catch (Throwable e) {
        throw debug.handle(e);
    }
}
Also used : CoreProviders(org.graalvm.compiler.nodes.spi.CoreProviders) StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) NewInstanceNode(org.graalvm.compiler.nodes.java.NewInstanceNode) DebugDumpScope(org.graalvm.compiler.debug.DebugDumpScope) Node(org.graalvm.compiler.graph.Node) NewInstanceNode(org.graalvm.compiler.nodes.java.NewInstanceNode) LoweringPhase(org.graalvm.compiler.phases.common.LoweringPhase) DebugContext(org.graalvm.compiler.debug.DebugContext) HighTierContext(org.graalvm.compiler.phases.tiers.HighTierContext) FrameState(org.graalvm.compiler.nodes.FrameState)

Example 20 with CoreProviders

use of org.graalvm.compiler.nodes.spi.CoreProviders in project graal by oracle.

the class LoopPhiCanonicalizerTest method test.

@Test
public void test() {
    StructuredGraph graph = parseEager("loopSnippet", AllowAssumptions.YES);
    NodePredicate loopPhis = node -> node instanceof PhiNode && ((PhiNode) node).merge() instanceof LoopBeginNode;
    CoreProviders context = getProviders();
    Assert.assertEquals(5, graph.getNodes().filter(loopPhis).count());
    createCanonicalizerPhase().apply(graph, context);
    Assert.assertEquals(2, graph.getNodes().filter(loopPhis).count());
    test("loopSnippet");
}
Also used : LoopBeginNode(org.graalvm.compiler.nodes.LoopBeginNode) NodePredicate(org.graalvm.compiler.graph.iterators.NodePredicate) StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) BeforeClass(org.junit.BeforeClass) Test(org.junit.Test) GraalCompilerTest(org.graalvm.compiler.core.test.GraalCompilerTest) CoreProviders(org.graalvm.compiler.nodes.spi.CoreProviders) Assert(org.junit.Assert) AllowAssumptions(org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions) PhiNode(org.graalvm.compiler.nodes.PhiNode) CoreProviders(org.graalvm.compiler.nodes.spi.CoreProviders) LoopBeginNode(org.graalvm.compiler.nodes.LoopBeginNode) StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) PhiNode(org.graalvm.compiler.nodes.PhiNode) NodePredicate(org.graalvm.compiler.graph.iterators.NodePredicate) Test(org.junit.Test) GraalCompilerTest(org.graalvm.compiler.core.test.GraalCompilerTest)

Aggregations

CoreProviders (org.graalvm.compiler.nodes.spi.CoreProviders)30 StructuredGraph (org.graalvm.compiler.nodes.StructuredGraph)25 LoweringPhase (org.graalvm.compiler.phases.common.LoweringPhase)16 CanonicalizerPhase (org.graalvm.compiler.phases.common.CanonicalizerPhase)15 DebugContext (org.graalvm.compiler.debug.DebugContext)9 ConditionalEliminationPhase (org.graalvm.compiler.phases.common.ConditionalEliminationPhase)7 FloatingReadPhase (org.graalvm.compiler.phases.common.FloatingReadPhase)7 Test (org.junit.Test)6 ResolvedJavaMethod (jdk.vm.ci.meta.ResolvedJavaMethod)5 IterativeConditionalEliminationPhase (org.graalvm.compiler.phases.common.IterativeConditionalEliminationPhase)5 DebugDumpScope (org.graalvm.compiler.debug.DebugDumpScope)4 MidTierContext (org.graalvm.compiler.phases.tiers.MidTierContext)4 Node (org.graalvm.compiler.graph.Node)3 FloatingReadNode (org.graalvm.compiler.nodes.memory.FloatingReadNode)3 GuardLoweringPhase (org.graalvm.compiler.phases.common.GuardLoweringPhase)3 SchedulePhase (org.graalvm.compiler.phases.schedule.SchedulePhase)3 Method (java.lang.reflect.Method)2 ArrayList (java.util.ArrayList)2 ResolvedJavaField (jdk.vm.ci.meta.ResolvedJavaField)2 FrameState (org.graalvm.compiler.nodes.FrameState)2