1 /*
   2  * Copyright (c) 2012, 2016, 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 org.graalvm.compiler.phases.common.inlining.info.elem;
  24 
  25 import static org.graalvm.compiler.phases.common.DeadCodeEliminationPhase.Optionality.Optional;
  26 
  27 import java.util.ArrayList;
  28 import java.util.List;
  29 
  30 import org.graalvm.compiler.core.common.type.Stamp;
  31 import org.graalvm.compiler.debug.Debug;
  32 import org.graalvm.compiler.graph.Node;
  33 import org.graalvm.compiler.graph.NodeInputList;
  34 import org.graalvm.compiler.nodes.ConstantNode;
  35 import org.graalvm.compiler.nodes.Invoke;
  36 import org.graalvm.compiler.nodes.ParameterNode;
  37 import org.graalvm.compiler.nodes.StructuredGraph;
  38 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
  39 import org.graalvm.compiler.nodes.ValueNode;
  40 import org.graalvm.compiler.phases.common.CanonicalizerPhase;
  41 import org.graalvm.compiler.phases.common.DeadCodeEliminationPhase;
  42 import org.graalvm.compiler.phases.common.inlining.InliningUtil;
  43 import org.graalvm.compiler.phases.graph.FixedNodeProbabilityCache;
  44 import org.graalvm.compiler.phases.tiers.HighTierContext;
  45 
  46 import jdk.vm.ci.meta.Constant;
  47 import jdk.vm.ci.meta.ResolvedJavaMethod;
  48 
  49 /**
  50  * <p>
  51  * Represents a feasible concrete target for inlining, whose graph has been copied already and thus
  52  * can be modified without affecting the original (usually cached) version.
  53  * </p>
  54  *
  55  * <p>
  56  * Instances of this class don't make sense in isolation but as part of an
  57  * {@link org.graalvm.compiler.phases.common.inlining.info.InlineInfo InlineInfo}.
  58  * </p>
  59  *
  60  * @see org.graalvm.compiler.phases.common.inlining.walker.InliningData#moveForward()
  61  * @see org.graalvm.compiler.phases.common.inlining.walker.CallsiteHolderExplorable
  62  */
  63 public class InlineableGraph implements Inlineable {
  64 
  65     private final StructuredGraph graph;
  66 
  67     private FixedNodeProbabilityCache probabilites = new FixedNodeProbabilityCache();
  68 
  69     public InlineableGraph(final ResolvedJavaMethod method, final Invoke invoke, final HighTierContext context, CanonicalizerPhase canonicalizer) {
  70         StructuredGraph original = getOriginalGraph(method, context, canonicalizer, invoke.asNode().graph(), invoke.bci());
  71         // TODO copying the graph is only necessary if it is modified or if it contains any invokes
  72         this.graph = (StructuredGraph) original.copy();
  73         specializeGraphToArguments(invoke, context, canonicalizer);
  74     }
  75 
  76     /**
  77      * This method looks up in a cache the graph for the argument, if not found bytecode is parsed.
  78      * The graph thus obtained is returned, ie the caller is responsible for cloning before
  79      * modification.
  80      */
  81     private static StructuredGraph getOriginalGraph(final ResolvedJavaMethod method, final HighTierContext context, CanonicalizerPhase canonicalizer, StructuredGraph caller, int callerBci) {
  82         StructuredGraph result = InliningUtil.getIntrinsicGraph(context.getReplacements(), method, callerBci);
  83         if (result != null) {
  84             return result;
  85         }
  86         return parseBytecodes(method, context, canonicalizer, caller);
  87     }
  88 
  89     /**
  90      * @return true iff one or more parameters <code>newGraph</code> were specialized to account for
  91      *         a constant argument, or an argument with a more specific stamp.
  92      */
  93     @SuppressWarnings("try")
  94     private boolean specializeGraphToArguments(final Invoke invoke, final HighTierContext context, CanonicalizerPhase canonicalizer) {
  95         try (Debug.Scope s = Debug.scope("InlineGraph", graph)) {
  96 
  97             ArrayList<Node> parameterUsages = replaceParamsWithMoreInformativeArguments(invoke, context);
  98             if (parameterUsages != null) {
  99                 assert !parameterUsages.isEmpty() : "The caller didn't have more information about arguments after all";
 100                 canonicalizer.applyIncremental(graph, context, parameterUsages);
 101                 return true;
 102             } else {
 103                 // TODO (chaeubl): if args are not more concrete, inlining should be avoided
 104                 // in most cases or we could at least use the previous graph size + invoke
 105                 // probability to check the inlining
 106                 return false;
 107             }
 108 
 109         } catch (Throwable e) {
 110             throw Debug.handle(e);
 111         }
 112     }
 113 
 114     private static boolean isArgMoreInformativeThanParam(ValueNode arg, ParameterNode param) {
 115         return arg.isConstant() || canStampBeImproved(arg, param);
 116     }
 117 
 118     private static boolean canStampBeImproved(ValueNode arg, ParameterNode param) {
 119         return improvedStamp(arg, param) != null;
 120     }
 121 
 122     private static Stamp improvedStamp(ValueNode arg, ParameterNode param) {
 123         Stamp joinedStamp = param.stamp().join(arg.stamp());
 124         if (joinedStamp == null || joinedStamp.equals(param.stamp())) {
 125             return null;
 126         }
 127         return joinedStamp;
 128     }
 129 
 130     /**
 131      * This method detects:
 132      * <ul>
 133      * <li>constants among the arguments to the <code>invoke</code></li>
 134      * <li>arguments with more precise type than that declared by the corresponding parameter</li>
 135      * </ul>
 136      *
 137      * <p>
 138      * The corresponding parameters are updated to reflect the above information. Before doing so,
 139      * their usages are added to <code>parameterUsages</code> for later incremental
 140      * canonicalization.
 141      * </p>
 142      *
 143      * @return null if no incremental canonicalization is need, a list of nodes for such
 144      *         canonicalization otherwise.
 145      */
 146     private ArrayList<Node> replaceParamsWithMoreInformativeArguments(final Invoke invoke, final HighTierContext context) {
 147         NodeInputList<ValueNode> args = invoke.callTarget().arguments();
 148         ArrayList<Node> parameterUsages = null;
 149         List<ParameterNode> params = graph.getNodes(ParameterNode.TYPE).snapshot();
 150         assert params.size() <= args.size();
 151         /*
 152          * param-nodes that aren't used (eg, as a result of canonicalization) don't occur in
 153          * `params`. Thus, in general, the sizes of `params` and `args` don't always match. Still,
 154          * it's always possible to pair a param-node with its corresponding arg-node using
 155          * param.index() as index into `args`.
 156          */
 157         for (ParameterNode param : params) {
 158             if (param.usages().isNotEmpty()) {
 159                 ValueNode arg = args.get(param.index());
 160                 if (arg.isConstant()) {
 161                     Constant constant = arg.asConstant();
 162                     parameterUsages = trackParameterUsages(param, parameterUsages);
 163                     // collect param usages before replacing the param
 164                     param.replaceAtUsagesAndDelete(graph.unique(
 165                                     ConstantNode.forConstant(arg.stamp(), constant, ((ConstantNode) arg).getStableDimension(), ((ConstantNode) arg).isDefaultStable(), context.getMetaAccess())));
 166                     // param-node gone, leaving a gap in the sequence given by param.index()
 167                 } else {
 168                     Stamp impro = improvedStamp(arg, param);
 169                     if (impro != null) {
 170                         param.setStamp(impro);
 171                         parameterUsages = trackParameterUsages(param, parameterUsages);
 172                     } else {
 173                         assert !isArgMoreInformativeThanParam(arg, param);
 174                     }
 175                 }
 176             }
 177         }
 178         assert (parameterUsages == null) || (!parameterUsages.isEmpty());
 179         return parameterUsages;
 180     }
 181 
 182     private static ArrayList<Node> trackParameterUsages(ParameterNode param, ArrayList<Node> parameterUsages) {
 183         ArrayList<Node> result = (parameterUsages == null) ? new ArrayList<>() : parameterUsages;
 184         param.usages().snapshotTo(result);
 185         return result;
 186     }
 187 
 188     /**
 189      * This method builds the IR nodes for the given <code>method</code> and canonicalizes them.
 190      * Provided profiling info is mature, the resulting graph is cached. The caller is responsible
 191      * for cloning before modification.
 192      * </p>
 193      */
 194     @SuppressWarnings("try")
 195     private static StructuredGraph parseBytecodes(ResolvedJavaMethod method, HighTierContext context, CanonicalizerPhase canonicalizer, StructuredGraph caller) {
 196         StructuredGraph newGraph = new StructuredGraph.Builder(caller.getOptions(), AllowAssumptions.ifNonNull(caller.getAssumptions())).method(method).build();
 197         try (Debug.Scope s = Debug.scope("InlineGraph", newGraph)) {
 198             if (!caller.isUnsafeAccessTrackingEnabled()) {
 199                 newGraph.disableUnsafeAccessTracking();
 200             }
 201             if (context.getGraphBuilderSuite() != null) {
 202                 context.getGraphBuilderSuite().apply(newGraph, context);
 203             }
 204             assert newGraph.start().next() != null : "graph needs to be populated by the GraphBuilderSuite " + method + ", " + method.canBeInlined();
 205 
 206             new DeadCodeEliminationPhase(Optional).apply(newGraph);
 207 
 208             canonicalizer.apply(newGraph, context);
 209 
 210             return newGraph;
 211         } catch (Throwable e) {
 212             throw Debug.handle(e);
 213         }
 214     }
 215 
 216     @Override
 217     public int getNodeCount() {
 218         return InliningUtil.getNodeCount(graph);
 219     }
 220 
 221     @Override
 222     public Iterable<Invoke> getInvokes() {
 223         return graph.getInvokes();
 224     }
 225 
 226     @Override
 227     public double getProbability(Invoke invoke) {
 228         return probabilites.applyAsDouble(invoke.asNode());
 229     }
 230 
 231     public StructuredGraph getGraph() {
 232         return graph;
 233     }
 234 }