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.DebugContext;
  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.ResolvedJavaMethod;
  47 
  48 /**
  49  * <p>
  50  * Represents a feasible concrete target for inlining, whose graph has been copied already and thus
  51  * can be modified without affecting the original (usually cached) version.
  52  * </p>
  53  *
  54  * <p>
  55  * Instances of this class don't make sense in isolation but as part of an
  56  * {@link org.graalvm.compiler.phases.common.inlining.info.InlineInfo InlineInfo}.
  57  * </p>
  58  *
  59  * @see org.graalvm.compiler.phases.common.inlining.walker.InliningData#moveForward()
  60  * @see org.graalvm.compiler.phases.common.inlining.walker.CallsiteHolderExplorable
  61  */
  62 public class InlineableGraph implements Inlineable {
  63 
  64     private final StructuredGraph graph;
  65 
  66     private FixedNodeProbabilityCache probabilites = new FixedNodeProbabilityCache();
  67 
  68     public InlineableGraph(final ResolvedJavaMethod method, final Invoke invoke, final HighTierContext context, CanonicalizerPhase canonicalizer) {
  69         StructuredGraph original = getOriginalGraph(method, context, canonicalizer, invoke.asNode().graph(), invoke.bci());
  70         // TODO copying the graph is only necessary if it is modified or if it contains any invokes
  71         this.graph = (StructuredGraph) original.copy(invoke.asNode().getDebug());
  72         specializeGraphToArguments(invoke, context, canonicalizer);
  73     }
  74 
  75     /**
  76      * This method looks up in a cache the graph for the argument, if not found bytecode is parsed.
  77      * The graph thus obtained is returned, ie the caller is responsible for cloning before
  78      * modification.
  79      */
  80     private static StructuredGraph getOriginalGraph(final ResolvedJavaMethod method, final HighTierContext context, CanonicalizerPhase canonicalizer, StructuredGraph caller, int callerBci) {
  81         StructuredGraph result = InliningUtil.getIntrinsicGraph(context.getReplacements(), method, callerBci);
  82         if (result != null) {
  83             return result;
  84         }
  85         return parseBytecodes(method, context, canonicalizer, caller);
  86     }
  87 
  88     /**
  89      * @return true iff one or more parameters <code>newGraph</code> were specialized to account for
  90      *         a constant argument, or an argument with a more specific stamp.
  91      */
  92     @SuppressWarnings("try")
  93     private boolean specializeGraphToArguments(final Invoke invoke, final HighTierContext context, CanonicalizerPhase canonicalizer) {
  94         DebugContext debug = graph.getDebug();
  95         try (DebugContext.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                     ConstantNode constant = (ConstantNode) arg;
 162                     parameterUsages = trackParameterUsages(param, parameterUsages);
 163                     // collect param usages before replacing the param
 164                     param.replaceAtUsagesAndDelete(graph.unique(
 165                                     ConstantNode.forConstant(arg.stamp(), constant.getValue(), constant.getStableDimension(), constant.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         DebugContext debug = caller.getDebug();
 197         StructuredGraph newGraph = new StructuredGraph.Builder(caller.getOptions(), debug, AllowAssumptions.ifNonNull(caller.getAssumptions())).method(method).build();
 198         try (DebugContext.Scope s = debug.scope("InlineGraph", newGraph)) {
 199             if (!caller.isUnsafeAccessTrackingEnabled()) {
 200                 newGraph.disableUnsafeAccessTracking();
 201             }
 202             if (context.getGraphBuilderSuite() != null) {
 203                 context.getGraphBuilderSuite().apply(newGraph, context);
 204             }
 205             assert newGraph.start().next() != null : "graph needs to be populated by the GraphBuilderSuite " + method + ", " + method.canBeInlined();
 206 
 207             new DeadCodeEliminationPhase(Optional).apply(newGraph);
 208 
 209             canonicalizer.apply(newGraph, context);
 210 
 211             return newGraph;
 212         } catch (Throwable e) {
 213             throw debug.handle(e);
 214         }
 215     }
 216 
 217     @Override
 218     public int getNodeCount() {
 219         return InliningUtil.getNodeCount(graph);
 220     }
 221 
 222     @Override
 223     public Iterable<Invoke> getInvokes() {
 224         return graph.getInvokes();
 225     }
 226 
 227     @Override
 228     public double getProbability(Invoke invoke) {
 229         return probabilites.applyAsDouble(invoke.asNode());
 230     }
 231 
 232     public StructuredGraph getGraph() {
 233         return graph;
 234     }
 235 }
--- EOF ---