1 /*
   2  * Copyright (c) 2011, 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 package com.oracle.graal.phases.common;
  24 
  25 import static com.oracle.graal.phases.GraalOptions.*;
  26 import static com.oracle.graal.phases.common.InliningPhase.Options.*;
  27 
  28 import java.util.*;
  29 import java.util.concurrent.*;
  30 
  31 import com.oracle.graal.api.code.*;
  32 import com.oracle.graal.api.meta.*;
  33 import com.oracle.graal.debug.*;
  34 import com.oracle.graal.graph.*;
  35 import com.oracle.graal.nodes.*;
  36 import com.oracle.graal.nodes.java.*;
  37 import com.oracle.graal.nodes.spi.*;
  38 import com.oracle.graal.nodes.type.*;
  39 import com.oracle.graal.nodes.util.*;
  40 import com.oracle.graal.options.*;
  41 import com.oracle.graal.phases.*;
  42 import com.oracle.graal.phases.PhasePlan.PhasePosition;
  43 import com.oracle.graal.phases.common.CanonicalizerPhase.CustomCanonicalizer;
  44 import com.oracle.graal.phases.common.InliningUtil.InlineInfo;
  45 import com.oracle.graal.phases.common.InliningUtil.Inlineable;
  46 import com.oracle.graal.phases.common.InliningUtil.InlineableMacroNode;
  47 import com.oracle.graal.phases.common.InliningUtil.InlineableGraph;
  48 import com.oracle.graal.phases.common.InliningUtil.InliningPolicy;
  49 import com.oracle.graal.phases.graph.*;
  50 
  51 public class InliningPhase extends Phase {
  52 
  53     static class Options {
  54 
  55         // @formatter:off
  56         @Option(help = "Unconditionally inline intrinsics")
  57         public static final OptionValue<Boolean> AlwaysInlineIntrinsics = new OptionValue<>(false);
  58         // @formatter:on
  59     }
  60 
  61     private final PhasePlan plan;
  62     private final MetaAccessProvider runtime;
  63     private final Assumptions compilationAssumptions;
  64     private final Replacements replacements;
  65     private final GraphCache cache;
  66     private final InliningPolicy inliningPolicy;
  67     private final OptimisticOptimizations optimisticOpts;
  68 
  69     private CustomCanonicalizer customCanonicalizer;
  70     private int inliningCount;
  71     private int maxMethodPerInlining = Integer.MAX_VALUE;
  72 
  73     // Metrics
  74     private static final DebugMetric metricInliningPerformed = Debug.metric("InliningPerformed");
  75     private static final DebugMetric metricInliningConsidered = Debug.metric("InliningConsidered");
  76     private static final DebugMetric metricInliningStoppedByMaxDesiredSize = Debug.metric("InliningStoppedByMaxDesiredSize");
  77     private static final DebugMetric metricInliningRuns = Debug.metric("Runs");
  78 
  79     public InliningPhase(MetaAccessProvider runtime, Map<Invoke, Double> hints, Replacements replacements, Assumptions assumptions, GraphCache cache, PhasePlan plan,
  80                     OptimisticOptimizations optimisticOpts) {
  81         this(runtime, replacements, assumptions, cache, plan, optimisticOpts, hints);
  82     }
  83 
  84     private InliningPhase(MetaAccessProvider runtime, Replacements replacements, Assumptions assumptions, GraphCache cache, PhasePlan plan, OptimisticOptimizations optimisticOpts,
  85                     Map<Invoke, Double> hints) {
  86         this.runtime = runtime;
  87         this.replacements = replacements;
  88         this.compilationAssumptions = assumptions;
  89         this.cache = cache;
  90         this.plan = plan;
  91         this.inliningPolicy = new GreedyInliningPolicy(replacements, hints);
  92         this.optimisticOpts = optimisticOpts;
  93     }
  94 
  95     public InliningPhase(MetaAccessProvider runtime, Replacements replacements, Assumptions assumptions, GraphCache cache, PhasePlan plan, OptimisticOptimizations optimisticOpts, InliningPolicy policy) {
  96         this.runtime = runtime;
  97         this.replacements = replacements;
  98         this.compilationAssumptions = assumptions;
  99         this.cache = cache;
 100         this.plan = plan;
 101         this.inliningPolicy = policy;
 102         this.optimisticOpts = optimisticOpts;
 103     }
 104 
 105     public void setCustomCanonicalizer(CustomCanonicalizer customCanonicalizer) {
 106         this.customCanonicalizer = customCanonicalizer;
 107     }
 108 
 109     public void setMaxMethodsPerInlining(int max) {
 110         maxMethodPerInlining = max;
 111     }
 112 
 113     public int getInliningCount() {
 114         return inliningCount;
 115     }
 116 
 117     public static void storeStatisticsAfterLowTier(StructuredGraph graph) {
 118         ResolvedJavaMethod method = graph.method();
 119         if (method != null) {
 120             CompiledMethodInfo info = compiledMethodInfo(graph.method());
 121             info.setLowLevelNodeCount(graph.getNodeCount());
 122         }
 123     }
 124 
 125     @Override
 126     protected void run(final StructuredGraph graph) {
 127         final InliningData data = new InliningData(graph, compilationAssumptions);
 128 
 129         while (data.hasUnprocessedGraphs()) {
 130             final MethodInvocation currentInvocation = data.currentInvocation();
 131             GraphInfo graphInfo = data.currentGraph();
 132             if (!currentInvocation.isRoot() && !inliningPolicy.isWorthInlining(currentInvocation.callee(), data.inliningDepth(), currentInvocation.probability(), currentInvocation.relevance(), false)) {
 133                 int remainingGraphs = currentInvocation.totalGraphs() - currentInvocation.processedGraphs();
 134                 assert remainingGraphs > 0;
 135                 data.popGraphs(remainingGraphs);
 136                 data.popInvocation();
 137             } else if (graphInfo.hasRemainingInvokes() && inliningPolicy.continueInlining(graphInfo.graph())) {
 138                 processNextInvoke(data, graphInfo);
 139             } else {
 140                 data.popGraph();
 141                 if (!currentInvocation.isRoot()) {
 142                     assert currentInvocation.callee().invoke().asNode().isAlive();
 143                     currentInvocation.incrementProcessedGraphs();
 144                     if (currentInvocation.processedGraphs() == currentInvocation.totalGraphs()) {
 145                         data.popInvocation();
 146                         final MethodInvocation parentInvoke = data.currentInvocation();
 147                         Debug.scope("Inlining", data.inliningContext(), new Runnable() {
 148 
 149                             @Override
 150                             public void run() {
 151                                 tryToInline(data.currentGraph(), currentInvocation, parentInvoke, data.inliningDepth() + 1);
 152                             }
 153                         });
 154 
 155                     }
 156                 }
 157             }
 158         }
 159 
 160         assert data.inliningDepth() == 0;
 161         assert data.graphCount() == 0;
 162     }
 163 
 164     /**
 165      * Process the next invoke and enqueue all its graphs for processing.
 166      */
 167     private void processNextInvoke(InliningData data, GraphInfo graphInfo) {
 168         Invoke invoke = graphInfo.popInvoke();
 169         MethodInvocation callerInvocation = data.currentInvocation();
 170         Assumptions parentAssumptions = callerInvocation.assumptions();
 171         InlineInfo info = InliningUtil.getInlineInfo(data, invoke, maxMethodPerInlining, replacements, parentAssumptions, optimisticOpts);
 172 
 173         if (info != null) {
 174             double invokeProbability = graphInfo.invokeProbability(invoke);
 175             double invokeRelevance = graphInfo.invokeRelevance(invoke);
 176             MethodInvocation calleeInvocation = data.pushInvocation(info, parentAssumptions, invokeProbability, invokeRelevance);
 177 
 178             for (int i = 0; i < info.numberOfMethods(); i++) {
 179                 Inlineable elem = getInlineableElement(info.methodAt(i), info.invoke(), calleeInvocation.assumptions());
 180                 info.setInlinableElement(i, elem);
 181                 if (elem instanceof InlineableGraph) {
 182                     data.pushGraph(((InlineableGraph) elem).getGraph(), invokeProbability * info.probabilityAt(i), invokeRelevance * info.relevanceAt(i));
 183                 } else {
 184                     assert elem instanceof InlineableMacroNode;
 185                     data.pushDummyGraph();
 186                 }
 187             }
 188         }
 189     }
 190 
 191     private void tryToInline(GraphInfo callerGraphInfo, MethodInvocation calleeInfo, MethodInvocation parentInvocation, int inliningDepth) {
 192         InlineInfo callee = calleeInfo.callee();
 193         Assumptions callerAssumptions = parentInvocation.assumptions();
 194 
 195         if (inliningPolicy.isWorthInlining(callee, inliningDepth, calleeInfo.probability(), calleeInfo.relevance(), true)) {
 196             doInline(callerGraphInfo, calleeInfo, callerAssumptions);
 197         } else if (optimisticOpts.devirtualizeInvokes()) {
 198             callee.tryToDevirtualizeInvoke(runtime, callerAssumptions);
 199         }
 200         metricInliningConsidered.increment();
 201     }
 202 
 203     private void doInline(GraphInfo callerGraphInfo, MethodInvocation calleeInfo, Assumptions callerAssumptions) {
 204         StructuredGraph callerGraph = callerGraphInfo.graph();
 205         int markBeforeInlining = callerGraph.getMark();
 206         InlineInfo callee = calleeInfo.callee();
 207         try {
 208             List<Node> invokeUsages = callee.invoke().asNode().usages().snapshot();
 209             callee.inline(runtime, callerAssumptions, replacements);
 210             callerAssumptions.record(calleeInfo.assumptions());
 211             metricInliningRuns.increment();
 212             Debug.dump(callerGraph, "after %s", callee);
 213 
 214             if (OptCanonicalizer.getValue()) {
 215                 int markBeforeCanonicalization = callerGraph.getMark();
 216                 new CanonicalizerPhase.Instance(runtime, callerAssumptions, !AOTCompilation.getValue(), invokeUsages, markBeforeInlining, customCanonicalizer).apply(callerGraph);
 217 
 218                 // process invokes that are possibly created during canonicalization
 219                 for (Node newNode : callerGraph.getNewNodes(markBeforeCanonicalization)) {
 220                     if (newNode instanceof Invoke) {
 221                         callerGraphInfo.pushInvoke((Invoke) newNode);
 222                     }
 223                 }
 224             }
 225 
 226             callerGraphInfo.computeProbabilities();
 227 
 228             inliningCount++;
 229             metricInliningPerformed.increment();
 230         } catch (BailoutException bailout) {
 231             throw bailout;
 232         } catch (AssertionError | RuntimeException e) {
 233             throw new GraalInternalError(e).addContext(callee.toString());
 234         } catch (GraalInternalError e) {
 235             throw e.addContext(callee.toString());
 236         }
 237     }
 238 
 239     private Inlineable getInlineableElement(final ResolvedJavaMethod method, Invoke invoke, Assumptions assumptions) {
 240         Class<? extends FixedWithNextNode> macroNodeClass = InliningUtil.getMacroNodeClass(replacements, method);
 241         if (macroNodeClass != null) {
 242             return new InlineableMacroNode(macroNodeClass);
 243         } else {
 244             return new InlineableGraph(buildGraph(method, invoke, assumptions));
 245         }
 246     }
 247 
 248     private StructuredGraph buildGraph(final ResolvedJavaMethod method, final Invoke invoke, final Assumptions assumptions) {
 249         final StructuredGraph newGraph;
 250         final boolean parseBytecodes;
 251 
 252         // TODO (chaeubl): copying the graph is only necessary if it is modified or if it contains
 253         // any invokes
 254         StructuredGraph intrinsicGraph = InliningUtil.getIntrinsicGraph(replacements, method);
 255         if (intrinsicGraph != null) {
 256             newGraph = intrinsicGraph.copy();
 257             parseBytecodes = false;
 258         } else {
 259             StructuredGraph cachedGraph = getCachedGraph(method);
 260             if (cachedGraph != null) {
 261                 newGraph = cachedGraph.copy();
 262                 parseBytecodes = false;
 263             } else {
 264                 newGraph = new StructuredGraph(method);
 265                 parseBytecodes = true;
 266             }
 267         }
 268 
 269         return Debug.scope("InlineGraph", newGraph, new Callable<StructuredGraph>() {
 270 
 271             @Override
 272             public StructuredGraph call() throws Exception {
 273                 if (parseBytecodes) {
 274                     parseBytecodes(newGraph, assumptions);
 275                 }
 276 
 277                 boolean callerHasMoreInformationAboutArguments = false;
 278                 NodeInputList<ValueNode> args = invoke.callTarget().arguments();
 279                 for (LocalNode localNode : newGraph.getNodes(LocalNode.class).snapshot()) {
 280                     ValueNode arg = args.get(localNode.index());
 281                     if (arg.isConstant()) {
 282                         Constant constant = arg.asConstant();
 283                         newGraph.replaceFloating(localNode, ConstantNode.forConstant(constant, runtime, newGraph));
 284                         callerHasMoreInformationAboutArguments = true;
 285                     } else {
 286                         Stamp joinedStamp = localNode.stamp().join(arg.stamp());
 287                         if (joinedStamp != null && !joinedStamp.equals(localNode.stamp())) {
 288                             localNode.setStamp(joinedStamp);
 289                             callerHasMoreInformationAboutArguments = true;
 290                         }
 291                     }
 292                 }
 293 
 294                 if (!callerHasMoreInformationAboutArguments) {
 295                     // TODO (chaeubl): if args are not more concrete, inlining should be avoided
 296                     // in most cases or we could at least use the previous graph size + invoke
 297                     // probability to check the inlining
 298                 }
 299 
 300                 if (OptCanonicalizer.getValue()) {
 301                     new CanonicalizerPhase.Instance(runtime, assumptions, !AOTCompilation.getValue()).apply(newGraph);
 302                 }
 303 
 304                 return newGraph;
 305             }
 306         });
 307     }
 308 
 309     private StructuredGraph getCachedGraph(ResolvedJavaMethod method) {
 310         if (CacheGraphs.getValue() && cache != null) {
 311             StructuredGraph cachedGraph = cache.get(method);
 312             if (cachedGraph != null) {
 313                 return cachedGraph;
 314             }
 315         }
 316         return null;
 317     }
 318 
 319     private StructuredGraph parseBytecodes(StructuredGraph newGraph, Assumptions assumptions) {
 320         boolean hasMatureProfilingInfo = newGraph.method().getProfilingInfo().isMature();
 321 
 322         if (plan != null) {
 323             plan.runPhases(PhasePosition.AFTER_PARSING, newGraph);
 324         }
 325         assert newGraph.start().next() != null : "graph needs to be populated during PhasePosition.AFTER_PARSING";
 326 
 327         new DeadCodeEliminationPhase().apply(newGraph);
 328 
 329         if (OptCanonicalizer.getValue()) {
 330             new CanonicalizerPhase.Instance(runtime, assumptions, !AOTCompilation.getValue()).apply(newGraph);
 331         }
 332 
 333         if (CacheGraphs.getValue() && cache != null) {
 334             cache.put(newGraph.copy(), hasMatureProfilingInfo);
 335         }
 336         return newGraph;
 337     }
 338 
 339     private static synchronized CompiledMethodInfo compiledMethodInfo(ResolvedJavaMethod m) {
 340         CompiledMethodInfo info = (CompiledMethodInfo) m.getCompilerStorage().get(CompiledMethodInfo.class);
 341         if (info == null) {
 342             info = new CompiledMethodInfo();
 343             m.getCompilerStorage().put(CompiledMethodInfo.class, info);
 344         }
 345         return info;
 346     }
 347 
 348     private abstract static class AbstractInliningPolicy implements InliningPolicy {
 349 
 350         protected final Replacements replacements;
 351         protected final Map<Invoke, Double> hints;
 352 
 353         public AbstractInliningPolicy(Replacements replacements, Map<Invoke, Double> hints) {
 354             this.replacements = replacements;
 355             this.hints = hints;
 356         }
 357 
 358         protected double computeMaximumSize(double relevance, int configuredMaximum) {
 359             double inlineRatio = Math.min(RelevanceCapForInlining.getValue(), relevance);
 360             return configuredMaximum * inlineRatio;
 361         }
 362 
 363         protected double getInliningBonus(InlineInfo info) {
 364             if (hints != null && hints.containsKey(info.invoke())) {
 365                 return hints.get(info.invoke());
 366             }
 367             return 1;
 368         }
 369 
 370         protected boolean isIntrinsic(InlineInfo info) {
 371             if (AlwaysInlineIntrinsics.getValue()) {
 372                 return onlyIntrinsics(info);
 373             } else {
 374                 return onlyForcedIntrinsics(info);
 375             }
 376         }
 377 
 378         private boolean onlyIntrinsics(InlineInfo info) {
 379             for (int i = 0; i < info.numberOfMethods(); i++) {
 380                 if (!InliningUtil.canIntrinsify(replacements, info.methodAt(i))) {
 381                     return false;
 382                 }
 383             }
 384             return true;
 385         }
 386 
 387         private boolean onlyForcedIntrinsics(InlineInfo info) {
 388             for (int i = 0; i < info.numberOfMethods(); i++) {
 389                 if (!InliningUtil.canIntrinsify(replacements, info.methodAt(i))) {
 390                     return false;
 391                 }
 392                 if (!replacements.isForcedSubstitution(info.methodAt(i))) {
 393                     return false;
 394                 }
 395             }
 396             return true;
 397         }
 398 
 399         protected static int previousLowLevelGraphSize(InlineInfo info) {
 400             int size = 0;
 401             for (int i = 0; i < info.numberOfMethods(); i++) {
 402                 size += compiledMethodInfo(info.methodAt(i)).lowLevelNodeCount();
 403             }
 404             return size;
 405         }
 406 
 407         protected static int determineNodeCount(InlineInfo info) {
 408             int nodes = 0;
 409             for (int i = 0; i < info.numberOfMethods(); i++) {
 410                 Inlineable elem = info.inlineableElementAt(i);
 411                 if (elem != null) {
 412                     nodes += elem.getNodeCount();
 413                 }
 414             }
 415             return nodes;
 416         }
 417 
 418         protected static double determineInvokeProbability(InlineInfo info) {
 419             double invokeProbability = 0;
 420             for (int i = 0; i < info.numberOfMethods(); i++) {
 421                 Inlineable callee = info.inlineableElementAt(i);
 422                 Iterable<Invoke> invokes = callee.getInvokes();
 423                 if (invokes.iterator().hasNext()) {
 424                     NodesToDoubles nodeProbabilities = new ComputeProbabilityClosure(((InlineableGraph) callee).getGraph()).apply();
 425                     for (Invoke invoke : invokes) {
 426                         invokeProbability += nodeProbabilities.get(invoke.asNode());
 427                     }
 428                 }
 429             }
 430             return invokeProbability;
 431         }
 432     }
 433 
 434     private static final class GreedyInliningPolicy extends AbstractInliningPolicy {
 435 
 436         public GreedyInliningPolicy(Replacements replacements, Map<Invoke, Double> hints) {
 437             super(replacements, hints);
 438         }
 439 
 440         public boolean continueInlining(StructuredGraph currentGraph) {
 441             if (currentGraph.getNodeCount() >= MaximumDesiredSize.getValue()) {
 442                 InliningUtil.logInliningDecision("inlining is cut off by MaximumDesiredSize");
 443                 metricInliningStoppedByMaxDesiredSize.increment();
 444                 return false;
 445             }
 446             return true;
 447         }
 448 
 449         @Override
 450         public boolean isWorthInlining(InlineInfo info, int inliningDepth, double probability, double relevance, boolean fullyProcessed) {
 451             if (isIntrinsic(info)) {
 452                 return InliningUtil.logInlinedMethod(info, inliningDepth, fullyProcessed, "intrinsic");
 453             }
 454 
 455             double inliningBonus = getInliningBonus(info);
 456             int nodes = determineNodeCount(info);
 457             int lowLevelGraphSize = previousLowLevelGraphSize(info);
 458 
 459             if (SmallCompiledLowLevelGraphSize.getValue() > 0 && lowLevelGraphSize > SmallCompiledLowLevelGraphSize.getValue() * inliningBonus) {
 460                 return InliningUtil.logNotInlinedMethod(info, inliningDepth, "too large previous low-level graph (low-level-nodes: %d, relevance=%f, probability=%f, bonus=%f, nodes=%d)",
 461                                 lowLevelGraphSize, relevance, probability, inliningBonus, nodes);
 462             }
 463 
 464             if (nodes < TrivialInliningSize.getValue() * inliningBonus) {
 465                 return InliningUtil.logInlinedMethod(info, inliningDepth, fullyProcessed, "trivial (relevance=%f, probability=%f, bonus=%f, nodes=%d)", relevance, probability, inliningBonus, nodes);
 466             }
 467 
 468             /*
 469              * TODO (chaeubl): invoked methods that are on important paths but not yet compiled ->
 470              * will be compiled anyways and it is likely that we are the only caller... might be
 471              * useful to inline those methods but increases bootstrap time (maybe those methods are
 472              * also getting queued in the compilation queue concurrently)
 473              */
 474             double invokes = determineInvokeProbability(info);
 475             if (LimitInlinedInvokes.getValue() > 0 && fullyProcessed && invokes > LimitInlinedInvokes.getValue() * inliningBonus) {
 476                 return InliningUtil.logNotInlinedMethod(info, inliningDepth, "callee invoke probability is too high (invokeP=%f, relevance=%f, probability=%f, bonus=%f, nodes=%d)", invokes,
 477                                 relevance, probability, inliningBonus, nodes);
 478             }
 479 
 480             double maximumNodes = computeMaximumSize(relevance, (int) (MaximumInliningSize.getValue() * inliningBonus));
 481             if (nodes <= maximumNodes) {
 482                 return InliningUtil.logInlinedMethod(info, inliningDepth, fullyProcessed, "relevance-based (relevance=%f, probability=%f, bonus=%f, nodes=%d <= %f)", relevance, probability,
 483                                 inliningBonus, nodes, maximumNodes);
 484             }
 485 
 486             return InliningUtil.logNotInlinedMethod(info, inliningDepth, "relevance-based (relevance=%f, probability=%f, bonus=%f, nodes=%d > %f)", relevance, probability, inliningBonus, nodes,
 487                             maximumNodes);
 488         }
 489     }
 490 
 491     public static final class InlineEverythingPolicy implements InliningPolicy {
 492 
 493         public boolean continueInlining(StructuredGraph graph) {
 494             if (graph.getNodeCount() >= MaximumDesiredSize.getValue()) {
 495                 throw new BailoutException("Inline all calls failed. The resulting graph is too large.");
 496             }
 497             return true;
 498         }
 499 
 500         public boolean isWorthInlining(InlineInfo info, int inliningDepth, double probability, double relevance, boolean fullyProcessed) {
 501             return true;
 502         }
 503     }
 504 
 505     private static class InliningIterator {
 506 
 507         private final FixedNode start;
 508         private final Deque<FixedNode> nodeQueue;
 509         private final NodeBitMap queuedNodes;
 510 
 511         public InliningIterator(FixedNode start, NodeBitMap visitedFixedNodes) {
 512             this.start = start;
 513             this.nodeQueue = new ArrayDeque<>();
 514             this.queuedNodes = visitedFixedNodes;
 515             assert start.isAlive();
 516         }
 517 
 518         public LinkedList<Invoke> apply() {
 519             LinkedList<Invoke> invokes = new LinkedList<>();
 520             FixedNode current;
 521             forcedQueue(start);
 522 
 523             while ((current = nextQueuedNode()) != null) {
 524                 assert current.isAlive();
 525 
 526                 if (current instanceof Invoke) {
 527                     if (current != start) {
 528                         invokes.addLast((Invoke) current);
 529                     }
 530                     queueSuccessors(current);
 531                 } else if (current instanceof LoopBeginNode) {
 532                     queueSuccessors(current);
 533                 } else if (current instanceof LoopEndNode) {
 534                     // nothing todo
 535                 } else if (current instanceof MergeNode) {
 536                     queueSuccessors(current);
 537                 } else if (current instanceof FixedWithNextNode) {
 538                     queueSuccessors(current);
 539                 } else if (current instanceof EndNode) {
 540                     queueMerge((EndNode) current);
 541                 } else if (current instanceof ControlSinkNode) {
 542                     // nothing todo
 543                 } else if (current instanceof ControlSplitNode) {
 544                     queueSuccessors(current);
 545                 } else {
 546                     assert false : current;
 547                 }
 548             }
 549 
 550             return invokes;
 551         }
 552 
 553         private void queueSuccessors(FixedNode x) {
 554             for (Node node : x.successors()) {
 555                 queue(node);
 556             }
 557         }
 558 
 559         private void queue(Node node) {
 560             if (node != null && !queuedNodes.isMarked(node)) {
 561                 forcedQueue(node);
 562             }
 563         }
 564 
 565         private void forcedQueue(Node node) {
 566             queuedNodes.mark(node);
 567             nodeQueue.addFirst((FixedNode) node);
 568         }
 569 
 570         private FixedNode nextQueuedNode() {
 571             if (nodeQueue.isEmpty()) {
 572                 return null;
 573             }
 574 
 575             FixedNode result = nodeQueue.removeFirst();
 576             assert queuedNodes.isMarked(result);
 577             return result;
 578         }
 579 
 580         private void queueMerge(AbstractEndNode end) {
 581             MergeNode merge = end.merge();
 582             if (!queuedNodes.isMarked(merge) && visitedAllEnds(merge)) {
 583                 queuedNodes.mark(merge);
 584                 nodeQueue.add(merge);
 585             }
 586         }
 587 
 588         private boolean visitedAllEnds(MergeNode merge) {
 589             for (int i = 0; i < merge.forwardEndCount(); i++) {
 590                 if (!queuedNodes.isMarked(merge.forwardEndAt(i))) {
 591                     return false;
 592                 }
 593             }
 594             return true;
 595         }
 596     }
 597 
 598     /**
 599      * Holds the data for building the callee graphs recursively: graphs and invocations (each
 600      * invocation can have multiple graphs).
 601      */
 602     static class InliningData {
 603 
 604         private static final GraphInfo DummyGraphInfo = new GraphInfo(null, new LinkedList<Invoke>(), 1.0, 1.0);
 605 
 606         /**
 607          * Call hierarchy from outer most call (i.e., compilation unit) to inner most callee.
 608          */
 609         private final ArrayDeque<GraphInfo> graphQueue;
 610         private final ArrayDeque<MethodInvocation> invocationQueue;
 611 
 612         private int maxGraphs;
 613 
 614         public InliningData(StructuredGraph rootGraph, Assumptions rootAssumptions) {
 615             this.graphQueue = new ArrayDeque<>();
 616             this.invocationQueue = new ArrayDeque<>();
 617             this.maxGraphs = 1;
 618 
 619             invocationQueue.push(new MethodInvocation(null, rootAssumptions, 1.0, 1.0));
 620             pushGraph(rootGraph, 1.0, 1.0);
 621         }
 622 
 623         public int graphCount() {
 624             return graphQueue.size();
 625         }
 626 
 627         public void pushGraph(StructuredGraph graph, double probability, double relevance) {
 628             assert !contains(graph);
 629             NodeBitMap visitedFixedNodes = graph.createNodeBitMap();
 630             LinkedList<Invoke> invokes = new InliningIterator(graph.start(), visitedFixedNodes).apply();
 631             assert invokes.size() == count(graph.getInvokes());
 632             graphQueue.push(new GraphInfo(graph, invokes, probability, relevance));
 633             assert graphQueue.size() <= maxGraphs;
 634         }
 635 
 636         public void pushDummyGraph() {
 637             graphQueue.push(DummyGraphInfo);
 638         }
 639 
 640         public boolean hasUnprocessedGraphs() {
 641             return !graphQueue.isEmpty();
 642         }
 643 
 644         public GraphInfo currentGraph() {
 645             return graphQueue.peek();
 646         }
 647 
 648         public void popGraph() {
 649             graphQueue.pop();
 650             assert graphQueue.size() <= maxGraphs;
 651         }
 652 
 653         public void popGraphs(int count) {
 654             assert count >= 0;
 655             for (int i = 0; i < count; i++) {
 656                 graphQueue.pop();
 657             }
 658         }
 659 
 660         /**
 661          * Gets the call hierarchy of this inling from outer most call to inner most callee.
 662          */
 663         public Object[] inliningContext() {
 664             Object[] result = new Object[graphQueue.size()];
 665             int i = 0;
 666             for (GraphInfo g : graphQueue) {
 667                 result[i++] = g.graph.method();
 668             }
 669             return result;
 670         }
 671 
 672         public MethodInvocation currentInvocation() {
 673             return invocationQueue.peek();
 674         }
 675 
 676         public MethodInvocation pushInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
 677             MethodInvocation methodInvocation = new MethodInvocation(info, new Assumptions(assumptions.useOptimisticAssumptions()), probability, relevance);
 678             invocationQueue.push(methodInvocation);
 679             maxGraphs += info.numberOfMethods();
 680             assert graphQueue.size() <= maxGraphs;
 681             return methodInvocation;
 682         }
 683 
 684         public void popInvocation() {
 685             maxGraphs -= invocationQueue.peek().callee.numberOfMethods();
 686             assert graphQueue.size() <= maxGraphs;
 687             invocationQueue.pop();
 688         }
 689 
 690         public int countRecursiveInlining(ResolvedJavaMethod method) {
 691             int count = 0;
 692             for (GraphInfo graphInfo : graphQueue) {
 693                 if (method.equals(graphInfo.method())) {
 694                     count++;
 695                 }
 696             }
 697             return count;
 698         }
 699 
 700         public int inliningDepth() {
 701             assert invocationQueue.size() > 0;
 702             return invocationQueue.size() - 1;
 703         }
 704 
 705         @Override
 706         public String toString() {
 707             StringBuilder result = new StringBuilder("Invocations: ");
 708 
 709             for (MethodInvocation invocation : invocationQueue) {
 710                 if (invocation.callee() != null) {
 711                     result.append(invocation.callee().numberOfMethods());
 712                     result.append("x ");
 713                     result.append(invocation.callee().invoke());
 714                     result.append("; ");
 715                 }
 716             }
 717 
 718             result.append("\nGraphs: ");
 719             for (GraphInfo graph : graphQueue) {
 720                 result.append(graph.graph());
 721                 result.append("; ");
 722             }
 723 
 724             return result.toString();
 725         }
 726 
 727         private boolean contains(StructuredGraph graph) {
 728             for (GraphInfo info : graphQueue) {
 729                 if (info.graph() == graph) {
 730                     return true;
 731                 }
 732             }
 733             return false;
 734         }
 735 
 736         private static int count(Iterable<Invoke> invokes) {
 737             int count = 0;
 738             Iterator<Invoke> iterator = invokes.iterator();
 739             while (iterator.hasNext()) {
 740                 iterator.next();
 741                 count++;
 742             }
 743             return count;
 744         }
 745     }
 746 
 747     private static class MethodInvocation {
 748 
 749         private final InlineInfo callee;
 750         private final Assumptions assumptions;
 751         private final double probability;
 752         private final double relevance;
 753 
 754         private int processedGraphs;
 755 
 756         public MethodInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
 757             this.callee = info;
 758             this.assumptions = assumptions;
 759             this.probability = probability;
 760             this.relevance = relevance;
 761         }
 762 
 763         public void incrementProcessedGraphs() {
 764             processedGraphs++;
 765             assert processedGraphs <= callee.numberOfMethods();
 766         }
 767 
 768         public int processedGraphs() {
 769             assert processedGraphs <= callee.numberOfMethods();
 770             return processedGraphs;
 771         }
 772 
 773         public int totalGraphs() {
 774             return callee.numberOfMethods();
 775         }
 776 
 777         public InlineInfo callee() {
 778             return callee;
 779         }
 780 
 781         public Assumptions assumptions() {
 782             return assumptions;
 783         }
 784 
 785         public double probability() {
 786             return probability;
 787         }
 788 
 789         public double relevance() {
 790             return relevance;
 791         }
 792 
 793         public boolean isRoot() {
 794             return callee == null;
 795         }
 796 
 797         @Override
 798         public String toString() {
 799             if (isRoot()) {
 800                 return "<root>";
 801             }
 802             CallTargetNode callTarget = callee.invoke().callTarget();
 803             if (callTarget instanceof MethodCallTargetNode) {
 804                 ResolvedJavaMethod calleeMethod = ((MethodCallTargetNode) callTarget).targetMethod();
 805                 return MetaUtil.format("Invoke#%H.%n(%p)", calleeMethod);
 806             } else {
 807                 return "Invoke#" + callTarget.targetName();
 808             }
 809         }
 810     }
 811 
 812     /**
 813      * Information about a graph that will potentially be inlined. This includes tracking the
 814      * invocations in graph that will subject to inlining themselves.
 815      */
 816     private static class GraphInfo {
 817 
 818         private final StructuredGraph graph;
 819         private final LinkedList<Invoke> remainingInvokes;
 820         private final double probability;
 821         private final double relevance;
 822 
 823         private NodesToDoubles nodeProbabilities;
 824         private NodesToDoubles nodeRelevance;
 825 
 826         public GraphInfo(StructuredGraph graph, LinkedList<Invoke> invokes, double probability, double relevance) {
 827             this.graph = graph;
 828             this.remainingInvokes = invokes;
 829             this.probability = probability;
 830             this.relevance = relevance;
 831 
 832             if (graph != null) {
 833                 computeProbabilities();
 834             }
 835         }
 836 
 837         /**
 838          * Gets the method associated with the {@linkplain #graph() graph} represented by this
 839          * object.
 840          */
 841         public ResolvedJavaMethod method() {
 842             return graph.method();
 843         }
 844 
 845         public boolean hasRemainingInvokes() {
 846             return !remainingInvokes.isEmpty();
 847         }
 848 
 849         /**
 850          * The graph about which this object contains inlining information.
 851          */
 852         public StructuredGraph graph() {
 853             return graph;
 854         }
 855 
 856         public Invoke popInvoke() {
 857             return remainingInvokes.removeFirst();
 858         }
 859 
 860         public void pushInvoke(Invoke invoke) {
 861             remainingInvokes.push(invoke);
 862         }
 863 
 864         public void computeProbabilities() {
 865             nodeProbabilities = new ComputeProbabilityClosure(graph).apply();
 866             nodeRelevance = new ComputeInliningRelevanceClosure(graph, nodeProbabilities).apply();
 867         }
 868 
 869         public double invokeProbability(Invoke invoke) {
 870             return probability * nodeProbabilities.get(invoke.asNode());
 871         }
 872 
 873         public double invokeRelevance(Invoke invoke) {
 874             return Math.min(CapInheritedRelevance.getValue(), relevance) * nodeRelevance.get(invoke.asNode());
 875         }
 876 
 877         @Override
 878         public String toString() {
 879             return MetaUtil.format("%H.%n(%p)", method()) + remainingInvokes;
 880         }
 881     }
 882 
 883     private static class CompiledMethodInfo {
 884 
 885         private int lowLevelNodes;
 886 
 887         public CompiledMethodInfo() {
 888         }
 889 
 890         public int lowLevelNodeCount() {
 891             return lowLevelNodes;
 892         }
 893 
 894         public void setLowLevelNodeCount(int lowLevelNodes) {
 895             this.lowLevelNodes = lowLevelNodes;
 896         }
 897 
 898     }
 899 }