Search in sources :

Example 1 with DeadCodeEliminationPhase

use of org.graalvm.compiler.phases.common.DeadCodeEliminationPhase in project graal by oracle.

the class OnStackReplacementPhase method run.

@Override
@SuppressWarnings("try")
protected void run(StructuredGraph graph) {
    DebugContext debug = graph.getDebug();
    if (graph.getEntryBCI() == JVMCICompiler.INVOCATION_ENTRY_BCI) {
        // used.
        assert graph.getNodes(EntryMarkerNode.TYPE).isEmpty();
        return;
    }
    debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement initial at bci %d", graph.getEntryBCI());
    EntryMarkerNode osr;
    int maxIterations = -1;
    int iterations = 0;
    final EntryMarkerNode originalOSRNode = getEntryMarker(graph);
    final LoopBeginNode originalOSRLoop = osrLoop(originalOSRNode);
    final boolean currentOSRWithLocks = osrWithLocks(originalOSRNode);
    if (originalOSRLoop == null) {
        /*
             * OSR with Locks: We do not have an OSR loop for the original OSR bci. Therefore we
             * cannot decide where to deopt and which framestate will be used. In the worst case the
             * framestate of the OSR entry would be used.
             */
        throw new PermanentBailoutException("OSR compilation without OSR entry loop.");
    }
    if (!supportOSRWithLocks(graph.getOptions()) && currentOSRWithLocks) {
        throw new PermanentBailoutException("OSR with locks disabled.");
    }
    do {
        osr = getEntryMarker(graph);
        LoopsData loops = new LoopsData(graph);
        // Find the loop that contains the EntryMarker
        Loop<Block> l = loops.getCFG().getNodeToBlock().get(osr).getLoop();
        if (l == null) {
            break;
        }
        iterations++;
        if (maxIterations == -1) {
            maxIterations = l.getDepth();
        } else if (iterations > maxIterations) {
            throw GraalError.shouldNotReachHere();
        }
        // Peel the outermost loop first
        while (l.getParent() != null) {
            l = l.getParent();
        }
        LoopTransformations.peel(loops.loop(l));
        osr.replaceAtUsages(InputType.Guard, AbstractBeginNode.prevBegin((FixedNode) osr.predecessor()));
        for (Node usage : osr.usages().snapshot()) {
            EntryProxyNode proxy = (EntryProxyNode) usage;
            proxy.replaceAndDelete(proxy.value());
        }
        GraphUtil.removeFixedWithUnusedInputs(osr);
        debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement loop peeling result");
    } while (true);
    StartNode start = graph.start();
    FrameState osrState = osr.stateAfter();
    OSRStartNode osrStart;
    try (DebugCloseable context = osr.withNodeSourcePosition()) {
        osr.setStateAfter(null);
        osrStart = graph.add(new OSRStartNode());
        FixedNode next = osr.next();
        osr.setNext(null);
        osrStart.setNext(next);
        graph.setStart(osrStart);
        osrStart.setStateAfter(osrState);
        debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after setting OSR start");
        final int localsSize = osrState.localsSize();
        final int locksSize = osrState.locksSize();
        for (int i = 0; i < localsSize + locksSize; i++) {
            ValueNode value = null;
            if (i >= localsSize) {
                value = osrState.lockAt(i - localsSize);
            } else {
                value = osrState.localAt(i);
            }
            if (value instanceof EntryProxyNode) {
                EntryProxyNode proxy = (EntryProxyNode) value;
                /*
                     * We need to drop the stamp since the types we see during OSR may be too
                     * precise (if a branch was not parsed for example). In cases when this is
                     * possible, we insert a guard and narrow the OSRLocal stamp at its usages.
                     */
                Stamp narrowedStamp = proxy.value().stamp(NodeView.DEFAULT);
                Stamp unrestrictedStamp = proxy.stamp(NodeView.DEFAULT).unrestricted();
                ValueNode osrLocal;
                if (i >= localsSize) {
                    osrLocal = graph.addOrUnique(new OSRLockNode(i - localsSize, unrestrictedStamp));
                } else {
                    osrLocal = graph.addOrUnique(new OSRLocalNode(i, unrestrictedStamp));
                }
                // Speculate on the OSRLocal stamps that could be more precise.
                OSRLocalSpeculationReason reason = new OSRLocalSpeculationReason(osrState.bci, narrowedStamp, i);
                if (graph.getSpeculationLog().maySpeculate(reason) && osrLocal instanceof OSRLocalNode && value.getStackKind().equals(JavaKind.Object) && !narrowedStamp.isUnrestricted()) {
                    // Add guard.
                    LogicNode check = graph.addOrUniqueWithInputs(InstanceOfNode.createHelper((ObjectStamp) narrowedStamp, osrLocal, null, null));
                    JavaConstant constant = graph.getSpeculationLog().speculate(reason);
                    FixedGuardNode guard = graph.add(new FixedGuardNode(check, DeoptimizationReason.OptimizedTypeCheckViolated, DeoptimizationAction.InvalidateRecompile, constant, false));
                    graph.addAfterFixed(osrStart, guard);
                    // Replace with a more specific type at usages.
                    // We know that we are at the root,
                    // so we need to replace the proxy in the state.
                    proxy.replaceAtMatchingUsages(osrLocal, n -> n == osrState);
                    osrLocal = graph.addOrUnique(new PiNode(osrLocal, narrowedStamp, guard));
                }
                proxy.replaceAndDelete(osrLocal);
            } else {
                assert value == null || value instanceof OSRLocalNode;
            }
        }
        osr.replaceAtUsages(InputType.Guard, osrStart);
    }
    debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after replacing entry proxies");
    GraphUtil.killCFG(start);
    debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
    new DeadCodeEliminationPhase(Required).apply(graph);
    if (currentOSRWithLocks) {
        OsrWithLocksCount.increment(debug);
        try (DebugCloseable context = osrStart.withNodeSourcePosition()) {
            for (int i = osrState.monitorIdCount() - 1; i >= 0; --i) {
                MonitorIdNode id = osrState.monitorIdAt(i);
                ValueNode lockedObject = osrState.lockAt(i);
                OSRMonitorEnterNode osrMonitorEnter = graph.add(new OSRMonitorEnterNode(lockedObject, id));
                for (Node usage : id.usages()) {
                    if (usage instanceof AccessMonitorNode) {
                        AccessMonitorNode access = (AccessMonitorNode) usage;
                        access.setObject(lockedObject);
                    }
                }
                FixedNode oldNext = osrStart.next();
                oldNext.replaceAtPredecessor(null);
                osrMonitorEnter.setNext(oldNext);
                osrStart.setNext(osrMonitorEnter);
            }
        }
        debug.dump(DebugContext.DETAILED_LEVEL, graph, "After inserting OSR monitor enters");
        /*
             * Ensure balanced monitorenter - monitorexit
             *
             * Ensure that there is no monitor exit without a monitor enter in the graph. If there
             * is one this can only be done by bytecode as we have the monitor enter before the OSR
             * loop but the exit in a path of the loop that must be under a condition, else it will
             * throw an IllegalStateException anyway in the 2.iteration
             */
        for (MonitorExitNode exit : graph.getNodes(MonitorExitNode.TYPE)) {
            MonitorIdNode id = exit.getMonitorId();
            if (id.usages().filter(MonitorEnterNode.class).count() != 1) {
                throw new PermanentBailoutException("Unbalanced monitor enter-exit in OSR compilation with locks. Object is locked before the loop but released inside the loop.");
            }
        }
    }
    debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
    new DeadCodeEliminationPhase(Required).apply(graph);
    /*
         * There must not be any parameter nodes left after OSR compilation.
         */
    assert graph.getNodes(ParameterNode.TYPE).count() == 0 : "OSR Compilation contains references to parameters.";
}
Also used : EntryMarkerNode(org.graalvm.compiler.nodes.EntryMarkerNode) AccessMonitorNode(org.graalvm.compiler.nodes.java.AccessMonitorNode) ObjectStamp(org.graalvm.compiler.core.common.type.ObjectStamp) OSRLockNode(org.graalvm.compiler.nodes.extended.OSRLockNode) MonitorIdNode(org.graalvm.compiler.nodes.java.MonitorIdNode) LoopBeginNode(org.graalvm.compiler.nodes.LoopBeginNode) OSRLocalNode(org.graalvm.compiler.nodes.extended.OSRLocalNode) EntryMarkerNode(org.graalvm.compiler.nodes.EntryMarkerNode) AbstractBeginNode(org.graalvm.compiler.nodes.AbstractBeginNode) EntryProxyNode(org.graalvm.compiler.nodes.EntryProxyNode) FixedGuardNode(org.graalvm.compiler.nodes.FixedGuardNode) PiNode(org.graalvm.compiler.nodes.PiNode) LogicNode(org.graalvm.compiler.nodes.LogicNode) ValueNode(org.graalvm.compiler.nodes.ValueNode) OSRMonitorEnterNode(org.graalvm.compiler.nodes.extended.OSRMonitorEnterNode) MonitorExitNode(org.graalvm.compiler.nodes.java.MonitorExitNode) StartNode(org.graalvm.compiler.nodes.StartNode) InstanceOfNode(org.graalvm.compiler.nodes.java.InstanceOfNode) ParameterNode(org.graalvm.compiler.nodes.ParameterNode) AccessMonitorNode(org.graalvm.compiler.nodes.java.AccessMonitorNode) FixedNode(org.graalvm.compiler.nodes.FixedNode) OSRStartNode(org.graalvm.compiler.nodes.extended.OSRStartNode) MonitorEnterNode(org.graalvm.compiler.nodes.java.MonitorEnterNode) Node(org.graalvm.compiler.graph.Node) JavaConstant(jdk.vm.ci.meta.JavaConstant) FixedNode(org.graalvm.compiler.nodes.FixedNode) PiNode(org.graalvm.compiler.nodes.PiNode) FrameState(org.graalvm.compiler.nodes.FrameState) MonitorExitNode(org.graalvm.compiler.nodes.java.MonitorExitNode) LoopBeginNode(org.graalvm.compiler.nodes.LoopBeginNode) DeadCodeEliminationPhase(org.graalvm.compiler.phases.common.DeadCodeEliminationPhase) PermanentBailoutException(org.graalvm.compiler.core.common.PermanentBailoutException) MonitorIdNode(org.graalvm.compiler.nodes.java.MonitorIdNode) StartNode(org.graalvm.compiler.nodes.StartNode) OSRStartNode(org.graalvm.compiler.nodes.extended.OSRStartNode) LoopsData(org.graalvm.compiler.loop.LoopsData) ObjectStamp(org.graalvm.compiler.core.common.type.ObjectStamp) Stamp(org.graalvm.compiler.core.common.type.Stamp) OSRLocalNode(org.graalvm.compiler.nodes.extended.OSRLocalNode) DebugContext(org.graalvm.compiler.debug.DebugContext) EntryProxyNode(org.graalvm.compiler.nodes.EntryProxyNode) OSRLockNode(org.graalvm.compiler.nodes.extended.OSRLockNode) OSRMonitorEnterNode(org.graalvm.compiler.nodes.extended.OSRMonitorEnterNode) FixedGuardNode(org.graalvm.compiler.nodes.FixedGuardNode) OSRStartNode(org.graalvm.compiler.nodes.extended.OSRStartNode) ValueNode(org.graalvm.compiler.nodes.ValueNode) Block(org.graalvm.compiler.nodes.cfg.Block) LogicNode(org.graalvm.compiler.nodes.LogicNode) DebugCloseable(org.graalvm.compiler.debug.DebugCloseable)

Example 2 with DeadCodeEliminationPhase

use of org.graalvm.compiler.phases.common.DeadCodeEliminationPhase in project graal by oracle.

the class InlineableGraph method parseBytecodes.

/**
 * This method builds the IR nodes for the given <code>method</code> and canonicalizes them.
 * Provided profiling info is mature, the resulting graph is cached. The caller is responsible
 * for cloning before modification.
 * </p>
 */
@SuppressWarnings("try")
private static StructuredGraph parseBytecodes(ResolvedJavaMethod method, HighTierContext context, CanonicalizerPhase canonicalizer, StructuredGraph caller, boolean trackNodeSourcePosition) {
    DebugContext debug = caller.getDebug();
    StructuredGraph newGraph = new StructuredGraph.Builder(caller.getOptions(), debug, AllowAssumptions.ifNonNull(caller.getAssumptions())).method(method).trackNodeSourcePosition(trackNodeSourcePosition).build();
    try (DebugContext.Scope s = debug.scope("InlineGraph", newGraph)) {
        if (!caller.isUnsafeAccessTrackingEnabled()) {
            newGraph.disableUnsafeAccessTracking();
        }
        if (context.getGraphBuilderSuite() != null) {
            context.getGraphBuilderSuite().apply(newGraph, context);
        }
        assert newGraph.start().next() != null : "graph needs to be populated by the GraphBuilderSuite " + method + ", " + method.canBeInlined();
        new DeadCodeEliminationPhase(Optional).apply(newGraph);
        canonicalizer.apply(newGraph, context);
        return newGraph;
    } catch (Throwable e) {
        throw debug.handle(e);
    }
}
Also used : StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) DebugContext(org.graalvm.compiler.debug.DebugContext) DeadCodeEliminationPhase(org.graalvm.compiler.phases.common.DeadCodeEliminationPhase)

Example 3 with DeadCodeEliminationPhase

use of org.graalvm.compiler.phases.common.DeadCodeEliminationPhase in project graal by oracle.

the class PartialEscapeAnalysisTreesTest method testGraph.

/**
 * Prepare a graph that includes some blackholes and then remove the blackholes and compile
 * normally to create an unusual situation for PEA.
 */
@SuppressWarnings("try")
public void testGraph(String name) {
    ResolvedJavaMethod method = getResolvedJavaMethod(name);
    prepareGraph(name, true);
    try (DebugContext.Scope s = graph.getDebug().scope(getClass(), method, getCodeCache(), graph)) {
        for (BlackholeNode node : graph.getNodes().filter(BlackholeNode.class)) {
            graph.removeFixed(node);
        }
        new DeadCodeEliminationPhase().apply(graph);
        new CanonicalizerPhase().apply(graph, context);
        InstalledCode code = getCode(method, graph, true);
        GraalCompilerTest.Result r = executeExpected(method, null, true);
        int expectedInstances = ((TreeNode) r.returnValue).countInstances();
        TreeNode r2 = (TreeNode) code.executeVarargs(true);
        Assert.assertEquals("Wrong number of nodes in tree", expectedInstances, r2.countInstances());
        r = executeExpected(method, null, false);
        expectedInstances = ((TreeNode) r.returnValue).countInstances();
        r2 = (TreeNode) code.executeVarargs(false);
        Assert.assertEquals("Wrong number of nodes in tree", expectedInstances, r2.countInstances());
    } catch (Throwable e) {
        throw graph.getDebug().handle(e);
    }
}
Also used : BlackholeNode(org.graalvm.compiler.nodes.debug.BlackholeNode) GraalCompilerTest(org.graalvm.compiler.core.test.GraalCompilerTest) InstalledCode(jdk.vm.ci.code.InstalledCode) CanonicalizerPhase(org.graalvm.compiler.phases.common.CanonicalizerPhase) DebugContext(org.graalvm.compiler.debug.DebugContext) DeadCodeEliminationPhase(org.graalvm.compiler.phases.common.DeadCodeEliminationPhase) ResolvedJavaMethod(jdk.vm.ci.meta.ResolvedJavaMethod)

Example 4 with DeadCodeEliminationPhase

use of org.graalvm.compiler.phases.common.DeadCodeEliminationPhase in project graal by oracle.

the class InliningTest method getGraph.

@SuppressWarnings("try")
private StructuredGraph getGraph(final String snippet, final boolean eagerInfopointMode) {
    DebugContext debug = getDebugContext();
    try (DebugContext.Scope s = debug.scope("InliningTest", new DebugDumpScope(snippet, true))) {
        ResolvedJavaMethod method = getResolvedJavaMethod(snippet);
        Builder builder = builder(method, AllowAssumptions.YES, debug);
        StructuredGraph graph = eagerInfopointMode ? parse(builder, getDebugGraphBuilderSuite()) : parse(builder, getEagerGraphBuilderSuite());
        try (DebugContext.Scope s2 = debug.scope("Inlining", graph)) {
            PhaseSuite<HighTierContext> graphBuilderSuite = eagerInfopointMode ? getCustomGraphBuilderSuite(GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withFullInfopoints(true)) : getDefaultGraphBuilderSuite();
            HighTierContext context = new HighTierContext(getProviders(), graphBuilderSuite, OptimisticOptimizations.ALL);
            debug.dump(DebugContext.BASIC_LEVEL, graph, "Graph");
            new CanonicalizerPhase().apply(graph, context);
            new InliningPhase(new CanonicalizerPhase()).apply(graph, context);
            debug.dump(DebugContext.BASIC_LEVEL, graph, "Graph");
            new CanonicalizerPhase().apply(graph, context);
            new DeadCodeEliminationPhase().apply(graph);
            return graph;
        }
    } catch (Throwable e) {
        throw debug.handle(e);
    }
}
Also used : StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) DebugDumpScope(org.graalvm.compiler.debug.DebugDumpScope) Builder(org.graalvm.compiler.nodes.StructuredGraph.Builder) CanonicalizerPhase(org.graalvm.compiler.phases.common.CanonicalizerPhase) DebugContext(org.graalvm.compiler.debug.DebugContext) HighTierContext(org.graalvm.compiler.phases.tiers.HighTierContext) InliningPhase(org.graalvm.compiler.phases.common.inlining.InliningPhase) DeadCodeEliminationPhase(org.graalvm.compiler.phases.common.DeadCodeEliminationPhase) ResolvedJavaMethod(jdk.vm.ci.meta.ResolvedJavaMethod)

Example 5 with DeadCodeEliminationPhase

use of org.graalvm.compiler.phases.common.DeadCodeEliminationPhase in project graal by oracle.

the class StampCanonicalizerTest method testZeroReturn.

private void testZeroReturn(String methodName) {
    StructuredGraph graph = parseEager(methodName, AllowAssumptions.YES);
    new CanonicalizerPhase().apply(graph, new PhaseContext(getProviders()));
    new DeadCodeEliminationPhase().apply(graph);
    assertConstantReturn(graph, 0);
}
Also used : PhaseContext(org.graalvm.compiler.phases.tiers.PhaseContext) StructuredGraph(org.graalvm.compiler.nodes.StructuredGraph) CanonicalizerPhase(org.graalvm.compiler.phases.common.CanonicalizerPhase) DeadCodeEliminationPhase(org.graalvm.compiler.phases.common.DeadCodeEliminationPhase)

Aggregations

DeadCodeEliminationPhase (org.graalvm.compiler.phases.common.DeadCodeEliminationPhase)23 StructuredGraph (org.graalvm.compiler.nodes.StructuredGraph)16 CanonicalizerPhase (org.graalvm.compiler.phases.common.CanonicalizerPhase)16 DebugContext (org.graalvm.compiler.debug.DebugContext)11 HighTierContext (org.graalvm.compiler.phases.tiers.HighTierContext)10 InliningPhase (org.graalvm.compiler.phases.common.inlining.InliningPhase)9 ResolvedJavaMethod (jdk.vm.ci.meta.ResolvedJavaMethod)8 Node (org.graalvm.compiler.graph.Node)6 Invoke (org.graalvm.compiler.nodes.Invoke)4 HashMap (java.util.HashMap)3 FrameState (org.graalvm.compiler.nodes.FrameState)3 LoweringPhase (org.graalvm.compiler.phases.common.LoweringPhase)3 InstalledCode (jdk.vm.ci.code.InstalledCode)2 GraalCompilerTest (org.graalvm.compiler.core.test.GraalCompilerTest)2 DebugCloseable (org.graalvm.compiler.debug.DebugCloseable)2 DebugDumpScope (org.graalvm.compiler.debug.DebugDumpScope)2 LoopsData (org.graalvm.compiler.loop.LoopsData)2 ConstantNode (org.graalvm.compiler.nodes.ConstantNode)2 ParameterNode (org.graalvm.compiler.nodes.ParameterNode)2 Builder (org.graalvm.compiler.nodes.StructuredGraph.Builder)2