1 /*
   2  * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.hotspot.phases;
  26 
  27 import static jdk.vm.ci.meta.SpeculationLog.SpeculationReason;
  28 import static org.graalvm.compiler.phases.common.DeadCodeEliminationPhase.Optionality.Required;
  29 
  30 import org.graalvm.compiler.core.common.PermanentBailoutException;
  31 import org.graalvm.compiler.core.common.cfg.Loop;
  32 import org.graalvm.compiler.core.common.type.ObjectStamp;
  33 import org.graalvm.compiler.core.common.type.Stamp;
  34 import org.graalvm.compiler.debug.CounterKey;
  35 import org.graalvm.compiler.debug.DebugCloseable;
  36 import org.graalvm.compiler.debug.DebugContext;
  37 import org.graalvm.compiler.debug.GraalError;
  38 import org.graalvm.compiler.graph.Node;
  39 import org.graalvm.compiler.graph.iterators.NodeIterable;
  40 import org.graalvm.compiler.loop.LoopsData;
  41 import org.graalvm.compiler.loop.phases.LoopTransformations;
  42 import org.graalvm.compiler.nodeinfo.InputType;
  43 import org.graalvm.compiler.nodeinfo.Verbosity;
  44 import org.graalvm.compiler.nodes.AbstractBeginNode;
  45 import org.graalvm.compiler.nodes.EntryMarkerNode;
  46 import org.graalvm.compiler.nodes.EntryProxyNode;
  47 import org.graalvm.compiler.nodes.FixedGuardNode;
  48 import org.graalvm.compiler.nodes.FixedNode;
  49 import org.graalvm.compiler.nodes.FrameState;
  50 import org.graalvm.compiler.nodes.LogicNode;
  51 import org.graalvm.compiler.nodes.LoopBeginNode;
  52 import org.graalvm.compiler.nodes.NodeView;
  53 import org.graalvm.compiler.nodes.ParameterNode;
  54 import org.graalvm.compiler.nodes.PiNode;
  55 import org.graalvm.compiler.nodes.StartNode;
  56 import org.graalvm.compiler.nodes.StructuredGraph;
  57 import org.graalvm.compiler.nodes.ValueNode;
  58 import org.graalvm.compiler.nodes.cfg.Block;
  59 import org.graalvm.compiler.nodes.extended.OSRLocalNode;
  60 import org.graalvm.compiler.nodes.extended.OSRLockNode;
  61 import org.graalvm.compiler.nodes.extended.OSRMonitorEnterNode;
  62 import org.graalvm.compiler.nodes.extended.OSRStartNode;
  63 import org.graalvm.compiler.nodes.java.AccessMonitorNode;
  64 import org.graalvm.compiler.nodes.java.InstanceOfNode;
  65 import org.graalvm.compiler.nodes.java.MonitorEnterNode;
  66 import org.graalvm.compiler.nodes.java.MonitorExitNode;
  67 import org.graalvm.compiler.nodes.java.MonitorIdNode;
  68 import org.graalvm.compiler.nodes.util.GraphUtil;
  69 import org.graalvm.compiler.options.Option;
  70 import org.graalvm.compiler.options.OptionKey;
  71 import org.graalvm.compiler.options.OptionType;
  72 import org.graalvm.compiler.options.OptionValues;
  73 import org.graalvm.compiler.phases.Phase;
  74 import org.graalvm.compiler.phases.common.DeadCodeEliminationPhase;
  75 
  76 import jdk.vm.ci.meta.DeoptimizationAction;
  77 import jdk.vm.ci.meta.DeoptimizationReason;
  78 import jdk.vm.ci.meta.JavaKind;
  79 import jdk.vm.ci.meta.SpeculationLog;
  80 import jdk.vm.ci.runtime.JVMCICompiler;
  81 
  82 public class OnStackReplacementPhase extends Phase {
  83 
  84     public static class Options {
  85         // @formatter:off
  86         @Option(help = "Deoptimize OSR compiled code when the OSR entry loop is finished " +
  87                        "if there is no mature profile available for the rest of the method.", type = OptionType.Debug)
  88         public static final OptionKey<Boolean> DeoptAfterOSR = new OptionKey<>(true);
  89         @Option(help = "Support OSR compilations with locks. If DeoptAfterOSR is true we can per definition not have " +
  90                        "unbalaced enter/extis mappings. If DeoptAfterOSR is false insert artificial monitor enters after " +
  91                        "the OSRStart to have balanced enter/exits in the graph.", type = OptionType.Debug)
  92         public static final OptionKey<Boolean> SupportOSRWithLocks = new OptionKey<>(true);
  93         // @formatter:on
  94     }
  95 
  96     private static final CounterKey OsrWithLocksCount = DebugContext.counter("OSRWithLocks");
  97 
  98     private static boolean supportOSRWithLocks(OptionValues options) {
  99         return Options.SupportOSRWithLocks.getValue(options);
 100     }
 101 
 102     @Override
 103     @SuppressWarnings("try")
 104     protected void run(StructuredGraph graph) {
 105         DebugContext debug = graph.getDebug();
 106         if (graph.getEntryBCI() == JVMCICompiler.INVOCATION_ENTRY_BCI) {
 107             // This happens during inlining in a OSR method, because the same phase plan will be
 108             // used.
 109             assert graph.getNodes(EntryMarkerNode.TYPE).isEmpty();
 110             return;
 111         }
 112         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement initial at bci %d", graph.getEntryBCI());
 113 
 114         EntryMarkerNode osr;
 115         int maxIterations = -1;
 116         int iterations = 0;
 117 
 118         final EntryMarkerNode originalOSRNode = getEntryMarker(graph);
 119         final LoopBeginNode originalOSRLoop = osrLoop(originalOSRNode);
 120         final boolean currentOSRWithLocks = osrWithLocks(originalOSRNode);
 121 
 122         if (originalOSRLoop == null) {
 123             /*
 124              * OSR with Locks: We do not have an OSR loop for the original OSR bci. Therefore we
 125              * cannot decide where to deopt and which framestate will be used. In the worst case the
 126              * framestate of the OSR entry would be used.
 127              */
 128             throw new PermanentBailoutException("OSR compilation without OSR entry loop.");
 129         }
 130 
 131         if (!supportOSRWithLocks(graph.getOptions()) && currentOSRWithLocks) {
 132             throw new PermanentBailoutException("OSR with locks disabled.");
 133         }
 134 
 135         do {
 136             osr = getEntryMarker(graph);
 137             LoopsData loops = new LoopsData(graph);
 138             // Find the loop that contains the EntryMarker
 139             Loop<Block> l = loops.getCFG().getNodeToBlock().get(osr).getLoop();
 140             if (l == null) {
 141                 break;
 142             }
 143 
 144             iterations++;
 145             if (maxIterations == -1) {
 146                 maxIterations = l.getDepth();
 147             } else if (iterations > maxIterations) {
 148                 throw GraalError.shouldNotReachHere();
 149             }
 150             // Peel the outermost loop first
 151             while (l.getParent() != null) {
 152                 l = l.getParent();
 153             }
 154 
 155             LoopTransformations.peel(loops.loop(l));
 156             osr.replaceAtUsages(InputType.Guard, AbstractBeginNode.prevBegin((FixedNode) osr.predecessor()));
 157             for (Node usage : osr.usages().snapshot()) {
 158                 EntryProxyNode proxy = (EntryProxyNode) usage;
 159                 proxy.replaceAndDelete(proxy.value());
 160             }
 161             GraphUtil.removeFixedWithUnusedInputs(osr);
 162             debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement loop peeling result");
 163         } while (true);
 164 
 165         StartNode start = graph.start();
 166         FrameState osrState = osr.stateAfter();
 167         OSRStartNode osrStart;
 168         try (DebugCloseable context = osr.withNodeSourcePosition()) {
 169             osr.setStateAfter(null);
 170             osrStart = graph.add(new OSRStartNode());
 171             FixedNode next = osr.next();
 172             osr.setNext(null);
 173             osrStart.setNext(next);
 174             graph.setStart(osrStart);
 175             osrStart.setStateAfter(osrState);
 176 
 177             debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after setting OSR start");
 178             final int localsSize = osrState.localsSize();
 179             final int locksSize = osrState.locksSize();
 180 
 181             for (int i = 0; i < localsSize + locksSize; i++) {
 182                 ValueNode value = null;
 183                 if (i >= localsSize) {
 184                     value = osrState.lockAt(i - localsSize);
 185                 } else {
 186                     value = osrState.localAt(i);
 187                 }
 188                 if (value instanceof EntryProxyNode) {
 189                     EntryProxyNode proxy = (EntryProxyNode) value;
 190                     /*
 191                      * We need to drop the stamp since the types we see during OSR may be too
 192                      * precise (if a branch was not parsed for example). In cases when this is
 193                      * possible, we insert a guard and narrow the OSRLocal stamp at its usages.
 194                      */
 195                     Stamp narrowedStamp = proxy.value().stamp(NodeView.DEFAULT);
 196                     Stamp unrestrictedStamp = proxy.stamp(NodeView.DEFAULT).unrestricted();
 197                     ValueNode osrLocal;
 198                     if (i >= localsSize) {
 199                         osrLocal = graph.addOrUnique(new OSRLockNode(i - localsSize, unrestrictedStamp));
 200                     } else {
 201                         osrLocal = graph.addOrUnique(new OSRLocalNode(i, unrestrictedStamp));
 202                     }
 203                     // Speculate on the OSRLocal stamps that could be more precise.
 204                     OSRLocalSpeculationReason reason = new OSRLocalSpeculationReason(osrState.bci, narrowedStamp, i);
 205                     if (graph.getSpeculationLog().maySpeculate(reason) && osrLocal instanceof OSRLocalNode && value.getStackKind().equals(JavaKind.Object) && !narrowedStamp.isUnrestricted()) {
 206                         // Add guard.
 207                         LogicNode check = graph.addOrUniqueWithInputs(InstanceOfNode.createHelper((ObjectStamp) narrowedStamp, osrLocal, null, null));
 208                         SpeculationLog.Speculation constant = graph.getSpeculationLog().speculate(reason);
 209                         FixedGuardNode guard = graph.add(new FixedGuardNode(check, DeoptimizationReason.OptimizedTypeCheckViolated, DeoptimizationAction.InvalidateRecompile, constant, false));
 210                         graph.addAfterFixed(osrStart, guard);
 211 
 212                         // Replace with a more specific type at usages.
 213                         // We know that we are at the root,
 214                         // so we need to replace the proxy in the state.
 215                         proxy.replaceAtMatchingUsages(osrLocal, n -> n == osrState);
 216                         osrLocal = graph.addOrUnique(new PiNode(osrLocal, narrowedStamp, guard));
 217                     }
 218                     proxy.replaceAndDelete(osrLocal);
 219                 } else {
 220                     assert value == null || value instanceof OSRLocalNode;
 221                 }
 222             }
 223 
 224             osr.replaceAtUsages(InputType.Guard, osrStart);
 225         }
 226         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement after replacing entry proxies");
 227         GraphUtil.killCFG(start);
 228         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
 229         new DeadCodeEliminationPhase(Required).apply(graph);
 230 
 231         if (currentOSRWithLocks) {
 232             OsrWithLocksCount.increment(debug);
 233             try (DebugCloseable context = osrStart.withNodeSourcePosition()) {
 234                 for (int i = osrState.monitorIdCount() - 1; i >= 0; --i) {
 235                     MonitorIdNode id = osrState.monitorIdAt(i);
 236                     ValueNode lockedObject = osrState.lockAt(i);
 237                     OSRMonitorEnterNode osrMonitorEnter = graph.add(new OSRMonitorEnterNode(lockedObject, id));
 238                     for (Node usage : id.usages()) {
 239                         if (usage instanceof AccessMonitorNode) {
 240                             AccessMonitorNode access = (AccessMonitorNode) usage;
 241                             access.setObject(lockedObject);
 242                         }
 243                     }
 244                     FixedNode oldNext = osrStart.next();
 245                     oldNext.replaceAtPredecessor(null);
 246                     osrMonitorEnter.setNext(oldNext);
 247                     osrStart.setNext(osrMonitorEnter);
 248                 }
 249             }
 250 
 251             debug.dump(DebugContext.DETAILED_LEVEL, graph, "After inserting OSR monitor enters");
 252             /*
 253              * Ensure balanced monitorenter - monitorexit
 254              *
 255              * Ensure that there is no monitor exit without a monitor enter in the graph. If there
 256              * is one this can only be done by bytecode as we have the monitor enter before the OSR
 257              * loop but the exit in a path of the loop that must be under a condition, else it will
 258              * throw an IllegalStateException anyway in the 2.iteration
 259              */
 260             for (MonitorExitNode exit : graph.getNodes(MonitorExitNode.TYPE)) {
 261                 MonitorIdNode id = exit.getMonitorId();
 262                 if (id.usages().filter(MonitorEnterNode.class).count() != 1) {
 263                     throw new PermanentBailoutException("Unbalanced monitor enter-exit in OSR compilation with locks. Object is locked before the loop but released inside the loop.");
 264                 }
 265             }
 266         }
 267         debug.dump(DebugContext.DETAILED_LEVEL, graph, "OnStackReplacement result");
 268         new DeadCodeEliminationPhase(Required).apply(graph);
 269         /*
 270          * There must not be any parameter nodes left after OSR compilation.
 271          */
 272         assert graph.getNodes(ParameterNode.TYPE).count() == 0 : "OSR Compilation contains references to parameters.";
 273     }
 274 
 275     private static EntryMarkerNode getEntryMarker(StructuredGraph graph) {
 276         NodeIterable<EntryMarkerNode> osrNodes = graph.getNodes(EntryMarkerNode.TYPE);
 277         EntryMarkerNode osr = osrNodes.first();
 278         if (osr == null) {
 279             throw new PermanentBailoutException("No OnStackReplacementNode generated");
 280         }
 281         if (osrNodes.count() > 1) {
 282             throw new GraalError("Multiple OnStackReplacementNodes generated");
 283         }
 284         if (osr.stateAfter().stackSize() != 0) {
 285             throw new PermanentBailoutException("OSR with stack entries not supported: %s", osr.stateAfter().toString(Verbosity.Debugger));
 286         }
 287         return osr;
 288     }
 289 
 290     private static LoopBeginNode osrLoop(EntryMarkerNode osr) {
 291         // Check that there is an OSR loop for the OSR begin
 292         LoopsData loops = new LoopsData(osr.graph());
 293         Loop<Block> l = loops.getCFG().getNodeToBlock().get(osr).getLoop();
 294         if (l == null) {
 295             return null;
 296         }
 297         return (LoopBeginNode) l.getHeader().getBeginNode();
 298     }
 299 
 300     private static boolean osrWithLocks(EntryMarkerNode osr) {
 301         return osr.stateAfter().locksSize() != 0;
 302     }
 303 
 304     @Override
 305     public float codeSizeIncrease() {
 306         return 5.0f;
 307     }
 308 
 309     private static class OSRLocalSpeculationReason implements SpeculationReason {
 310         private int bci;
 311         private Stamp speculatedStamp;
 312         private int localIndex;
 313 
 314         OSRLocalSpeculationReason(int bci, Stamp speculatedStamp, int localIndex) {
 315             this.bci = bci;
 316             this.speculatedStamp = speculatedStamp;
 317             this.localIndex = localIndex;
 318         }
 319 
 320         @Override
 321         public boolean equals(Object obj) {
 322             if (obj instanceof OSRLocalSpeculationReason) {
 323                 OSRLocalSpeculationReason that = (OSRLocalSpeculationReason) obj;
 324                 return this.bci == that.bci && this.speculatedStamp.equals(that.speculatedStamp) && this.localIndex == that.localIndex;
 325             }
 326             return false;
 327         }
 328 
 329         @Override
 330         public int hashCode() {
 331             return (bci << 16) ^ speculatedStamp.hashCode() ^ localIndex;
 332         }
 333     }
 334 }