1 /*
   2  * Copyright (c) 2015, 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 
  24 
  25 package org.graalvm.compiler.replacements;
  26 
  27 import static org.graalvm.compiler.debug.GraalError.unimplemented;
  28 import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_IGNORED;
  29 import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_IGNORED;
  30 
  31 import java.net.URI;
  32 import java.util.ArrayList;
  33 import java.util.Arrays;
  34 import java.util.Formatter;
  35 import java.util.HashMap;
  36 import java.util.List;
  37 import java.util.Map;
  38 
  39 import jdk.internal.vm.compiler.collections.EconomicMap;
  40 import jdk.internal.vm.compiler.collections.Equivalence;
  41 import org.graalvm.compiler.api.replacements.Fold;
  42 import org.graalvm.compiler.bytecode.Bytecode;
  43 import org.graalvm.compiler.bytecode.BytecodeProvider;
  44 import org.graalvm.compiler.bytecode.ResolvedJavaMethodBytecode;
  45 import org.graalvm.compiler.core.common.PermanentBailoutException;
  46 import org.graalvm.compiler.core.common.cfg.CFGVerifier;
  47 import org.graalvm.compiler.core.common.spi.ConstantFieldProvider;
  48 import org.graalvm.compiler.core.common.type.Stamp;
  49 import org.graalvm.compiler.core.common.type.StampFactory;
  50 import org.graalvm.compiler.core.common.type.StampPair;
  51 import org.graalvm.compiler.debug.DebugCloseable;
  52 import org.graalvm.compiler.debug.DebugContext;
  53 import org.graalvm.compiler.debug.GraalError;
  54 import org.graalvm.compiler.graph.Node;
  55 import org.graalvm.compiler.graph.Node.NodeIntrinsic;
  56 import org.graalvm.compiler.graph.NodeClass;
  57 import org.graalvm.compiler.graph.NodeSourcePosition;
  58 import org.graalvm.compiler.graph.SourceLanguagePosition;
  59 import org.graalvm.compiler.graph.SourceLanguagePositionProvider;
  60 import org.graalvm.compiler.graph.spi.Canonicalizable;
  61 import org.graalvm.compiler.java.GraphBuilderPhase;
  62 import org.graalvm.compiler.nodeinfo.NodeInfo;
  63 import org.graalvm.compiler.nodes.AbstractBeginNode;
  64 import org.graalvm.compiler.nodes.AbstractMergeNode;
  65 import org.graalvm.compiler.nodes.CallTargetNode;
  66 import org.graalvm.compiler.nodes.CallTargetNode.InvokeKind;
  67 import org.graalvm.compiler.nodes.ControlSinkNode;
  68 import org.graalvm.compiler.nodes.DeoptimizeNode;
  69 import org.graalvm.compiler.nodes.EncodedGraph;
  70 import org.graalvm.compiler.nodes.FixedNode;
  71 import org.graalvm.compiler.nodes.FixedWithNextNode;
  72 import org.graalvm.compiler.nodes.FrameState;
  73 import org.graalvm.compiler.nodes.IfNode;
  74 import org.graalvm.compiler.nodes.Invoke;
  75 import org.graalvm.compiler.nodes.InvokeWithExceptionNode;
  76 import org.graalvm.compiler.nodes.MergeNode;
  77 import org.graalvm.compiler.nodes.NodeView;
  78 import org.graalvm.compiler.nodes.ParameterNode;
  79 import org.graalvm.compiler.nodes.ReturnNode;
  80 import org.graalvm.compiler.nodes.SimplifyingGraphDecoder;
  81 import org.graalvm.compiler.nodes.StateSplit;
  82 import org.graalvm.compiler.nodes.StructuredGraph;
  83 import org.graalvm.compiler.nodes.UnwindNode;
  84 import org.graalvm.compiler.nodes.ValueNode;
  85 import org.graalvm.compiler.nodes.cfg.ControlFlowGraph;
  86 import org.graalvm.compiler.nodes.extended.ForeignCallNode;
  87 import org.graalvm.compiler.nodes.extended.IntegerSwitchNode;
  88 import org.graalvm.compiler.nodes.graphbuilderconf.GeneratedInvocationPlugin;
  89 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
  90 import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin;
  91 import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin.InlineInfo;
  92 import org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext;
  93 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin;
  94 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
  95 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.InvocationPluginReceiver;
  96 import org.graalvm.compiler.nodes.graphbuilderconf.LoopExplosionPlugin;
  97 import org.graalvm.compiler.nodes.graphbuilderconf.LoopExplosionPlugin.LoopExplosionKind;
  98 import org.graalvm.compiler.nodes.graphbuilderconf.NodePlugin;
  99 import org.graalvm.compiler.nodes.graphbuilderconf.ParameterPlugin;
 100 import org.graalvm.compiler.nodes.java.LoadFieldNode;
 101 import org.graalvm.compiler.nodes.java.LoadIndexedNode;
 102 import org.graalvm.compiler.nodes.java.MethodCallTargetNode;
 103 import org.graalvm.compiler.nodes.java.MonitorIdNode;
 104 import org.graalvm.compiler.nodes.java.NewArrayNode;
 105 import org.graalvm.compiler.nodes.java.NewInstanceNode;
 106 import org.graalvm.compiler.nodes.java.NewMultiArrayNode;
 107 import org.graalvm.compiler.nodes.java.StoreFieldNode;
 108 import org.graalvm.compiler.nodes.java.StoreIndexedNode;
 109 import org.graalvm.compiler.nodes.spi.StampProvider;
 110 import org.graalvm.compiler.nodes.type.StampTool;
 111 import org.graalvm.compiler.nodes.util.GraphUtil;
 112 import org.graalvm.compiler.options.Option;
 113 import org.graalvm.compiler.options.OptionKey;
 114 import org.graalvm.compiler.options.OptionType;
 115 import org.graalvm.compiler.options.OptionValues;
 116 import org.graalvm.compiler.phases.common.inlining.InliningUtil;
 117 
 118 import jdk.vm.ci.code.Architecture;
 119 import jdk.vm.ci.code.BailoutException;
 120 import jdk.vm.ci.code.BytecodeFrame;
 121 import jdk.vm.ci.meta.Assumptions;
 122 import jdk.vm.ci.meta.ConstantReflectionProvider;
 123 import jdk.vm.ci.meta.DeoptimizationAction;
 124 import jdk.vm.ci.meta.DeoptimizationReason;
 125 import jdk.vm.ci.meta.JavaConstant;
 126 import jdk.vm.ci.meta.JavaKind;
 127 import jdk.vm.ci.meta.JavaType;
 128 import jdk.vm.ci.meta.MetaAccessProvider;
 129 import jdk.vm.ci.meta.ResolvedJavaField;
 130 import jdk.vm.ci.meta.ResolvedJavaMethod;
 131 import jdk.vm.ci.meta.ResolvedJavaType;
 132 
 133 /**
 134  * A graph decoder that performs partial evaluation, i.e., that performs method inlining and
 135  * canonicalization/simplification of nodes during decoding.
 136  *
 137  * Inlining and loop explosion are configured via the plugin mechanism also used by the
 138  * {@link GraphBuilderPhase}. However, not all callback methods defined in
 139  * {@link GraphBuilderContext} are available since decoding is more limited than graph building.
 140  *
 141  * The standard {@link Canonicalizable#canonical node canonicalization} interface is used to
 142  * canonicalize nodes during decoding. Additionally, {@link IfNode branches} and
 143  * {@link IntegerSwitchNode switches} with constant conditions are simplified.
 144  */
 145 public abstract class PEGraphDecoder extends SimplifyingGraphDecoder {
 146 
 147     private static final Object CACHED_NULL_VALUE = new Object();
 148 
 149     public static class Options {
 150         @Option(help = "Maximum inlining depth during partial evaluation before reporting an infinite recursion")//
 151         public static final OptionKey<Integer> InliningDepthError = new OptionKey<>(1000);
 152 
 153         @Option(help = "Max number of loop explosions per method.", type = OptionType.Debug)//
 154         public static final OptionKey<Integer> MaximumLoopExplosionCount = new OptionKey<>(10000);
 155 
 156         @Option(help = "Do not bail out but throw an exception on failed loop explosion.", type = OptionType.Debug)//
 157         public static final OptionKey<Boolean> FailedLoopExplosionIsFatal = new OptionKey<>(false);
 158     }
 159 
 160     protected class PEMethodScope extends MethodScope {
 161         /** The state of the caller method. Only non-null during method inlining. */
 162         protected final PEMethodScope caller;
 163         protected final ResolvedJavaMethod method;
 164         protected final InvokeData invokeData;
 165         protected final int inliningDepth;
 166 
 167         protected final ValueNode[] arguments;
 168         private SourceLanguagePosition sourceLanguagePosition = UnresolvedSourceLanguagePosition.INSTANCE;
 169 
 170         protected FrameState outerState;
 171         protected FrameState exceptionState;
 172         protected ExceptionPlaceholderNode exceptionPlaceholderNode;
 173         protected NodeSourcePosition callerBytecodePosition;
 174 
 175         protected PEMethodScope(StructuredGraph targetGraph, PEMethodScope caller, LoopScope callerLoopScope, EncodedGraph encodedGraph, ResolvedJavaMethod method, InvokeData invokeData,
 176                         int inliningDepth, LoopExplosionPlugin loopExplosionPlugin, ValueNode[] arguments) {
 177             super(callerLoopScope, targetGraph, encodedGraph, loopExplosionKind(method, loopExplosionPlugin));
 178 
 179             this.caller = caller;
 180             this.method = method;
 181             this.invokeData = invokeData;
 182             this.inliningDepth = inliningDepth;
 183             this.arguments = arguments;
 184         }
 185 
 186         @Override
 187         public boolean isInlinedMethod() {
 188             return caller != null;
 189         }
 190 
 191         @Override
 192         public NodeSourcePosition getCallerBytecodePosition(NodeSourcePosition position) {
 193             if (caller == null) {
 194                 return position;
 195             }
 196             if (callerBytecodePosition == null) {
 197                 NodeSourcePosition invokePosition = invokeData.invoke.asNode().getNodeSourcePosition();
 198                 if (invokePosition == null) {
 199                     assert position == null : "should only happen when tracking is disabled";
 200                     return null;
 201                 }
 202                 callerBytecodePosition = invokePosition;
 203             }
 204             if (position != null) {
 205                 return position.addCaller(caller.resolveSourceLanguagePosition(), callerBytecodePosition);
 206             }
 207             final SourceLanguagePosition pos = caller.resolveSourceLanguagePosition();
 208             if (pos != null && callerBytecodePosition != null) {
 209                 return new NodeSourcePosition(pos, callerBytecodePosition.getCaller(), callerBytecodePosition.getMethod(), callerBytecodePosition.getBCI());
 210             }
 211             return callerBytecodePosition;
 212         }
 213 
 214         private SourceLanguagePosition resolveSourceLanguagePosition() {
 215             SourceLanguagePosition res = sourceLanguagePosition;
 216             if (res == UnresolvedSourceLanguagePosition.INSTANCE) {
 217                 res = null;
 218                 if (arguments != null && method.hasReceiver() && arguments.length > 0 && arguments[0].isJavaConstant()) {
 219                     JavaConstant constantArgument = arguments[0].asJavaConstant();
 220                     res = sourceLanguagePositionProvider.getPosition(constantArgument);
 221                 }
 222                 sourceLanguagePosition = res;
 223             }
 224             return res;
 225         }
 226     }
 227 
 228     private static final class UnresolvedSourceLanguagePosition implements SourceLanguagePosition {
 229         static final SourceLanguagePosition INSTANCE = new UnresolvedSourceLanguagePosition();
 230 
 231         @Override
 232         public String toShortString() {
 233             throw new IllegalStateException(getClass().getSimpleName() + " should not be reachable.");
 234         }
 235 
 236         @Override
 237         public int getOffsetEnd() {
 238             throw new IllegalStateException(getClass().getSimpleName() + " should not be reachable.");
 239         }
 240 
 241         @Override
 242         public int getOffsetStart() {
 243             throw new IllegalStateException(getClass().getSimpleName() + " should not be reachable.");
 244         }
 245 
 246         @Override
 247         public int getLineNumber() {
 248             throw new IllegalStateException(getClass().getSimpleName() + " should not be reachable.");
 249         }
 250 
 251         @Override
 252         public URI getURI() {
 253             throw new IllegalStateException(getClass().getSimpleName() + " should not be reachable.");
 254         }
 255 
 256         @Override
 257         public String getLanguage() {
 258             throw new IllegalStateException(getClass().getSimpleName() + " should not be reachable.");
 259         }
 260     }
 261 
 262     protected class PENonAppendGraphBuilderContext implements GraphBuilderContext {
 263         protected final PEMethodScope methodScope;
 264         protected final Invoke invoke;
 265 
 266         @Override
 267         public ExternalInliningContext getExternalInliningContext() {
 268             return new ExternalInliningContext() {
 269                 @Override
 270                 public int getInlinedDepth() {
 271                     int count = 0;
 272                     PEGraphDecoder.PEMethodScope scope = methodScope;
 273                     while (scope != null) {
 274                         if (scope.method.equals(callInlinedMethod)) {
 275                             count++;
 276                         }
 277                         scope = scope.caller;
 278                     }
 279                     return count;
 280                 }
 281             };
 282         }
 283 
 284         public PENonAppendGraphBuilderContext(PEMethodScope methodScope, Invoke invoke) {
 285             this.methodScope = methodScope;
 286             this.invoke = invoke;
 287         }
 288 
 289         /**
 290          * {@link Fold} and {@link NodeIntrinsic} can be deferred during parsing/decoding. Only by
 291          * the end of {@linkplain SnippetTemplate#instantiate Snippet instantiation} do they need to
 292          * have been processed.
 293          *
 294          * This is how SVM handles snippets. They are parsed with plugins disabled and then encoded
 295          * and stored in the image. When the snippet is needed at runtime the graph is decoded and
 296          * the plugins are run during the decoding process. If they aren't handled at this point
 297          * then they will never be handled.
 298          */
 299         @Override
 300         public boolean canDeferPlugin(GeneratedInvocationPlugin plugin) {
 301             return plugin.getSource().equals(Fold.class) || plugin.getSource().equals(Node.NodeIntrinsic.class);
 302         }
 303 
 304         @Override
 305         public BailoutException bailout(String string) {
 306             BailoutException bailout = new PermanentBailoutException(string);
 307             throw GraphUtil.createBailoutException(string, bailout, GraphUtil.approxSourceStackTraceElement(methodScope.getCallerBytecodePosition()));
 308         }
 309 
 310         @Override
 311         public StampProvider getStampProvider() {
 312             return stampProvider;
 313         }
 314 
 315         @Override
 316         public MetaAccessProvider getMetaAccess() {
 317             return metaAccess;
 318         }
 319 
 320         @Override
 321         public ConstantReflectionProvider getConstantReflection() {
 322             return constantReflection;
 323         }
 324 
 325         @Override
 326         public ConstantFieldProvider getConstantFieldProvider() {
 327             return constantFieldProvider;
 328         }
 329 
 330         @Override
 331         public StructuredGraph getGraph() {
 332             return graph;
 333         }
 334 
 335         @Override
 336         public int getDepth() {
 337             return methodScope.inliningDepth;
 338         }
 339 
 340         @Override
 341         public IntrinsicContext getIntrinsic() {
 342             return null;
 343         }
 344 
 345         @Override
 346         public <T extends ValueNode> T append(T value) {
 347             throw unimplemented();
 348         }
 349 
 350         @Override
 351         public void push(JavaKind kind, ValueNode value) {
 352             throw unimplemented();
 353         }
 354 
 355         @Override
 356         public void handleReplacedInvoke(InvokeKind invokeKind, ResolvedJavaMethod targetMethod, ValueNode[] args, boolean inlineEverything) {
 357             throw unimplemented();
 358         }
 359 
 360         @Override
 361         public void handleReplacedInvoke(CallTargetNode callTarget, JavaKind resultType) {
 362             throw unimplemented();
 363         }
 364 
 365         @Override
 366         public boolean intrinsify(BytecodeProvider bytecodeProvider, ResolvedJavaMethod targetMethod, ResolvedJavaMethod substitute, InvocationPlugin.Receiver receiver, ValueNode[] args) {
 367             return false;
 368         }
 369 
 370         @Override
 371         public void setStateAfter(StateSplit stateSplit) {
 372             throw unimplemented();
 373         }
 374 
 375         @Override
 376         public GraphBuilderContext getParent() {
 377             throw unimplemented();
 378         }
 379 
 380         @Override
 381         public Bytecode getCode() {
 382             throw unimplemented();
 383         }
 384 
 385         @Override
 386         public ResolvedJavaMethod getMethod() {
 387             throw unimplemented();
 388         }
 389 
 390         @Override
 391         public int bci() {
 392             return invoke.bci();
 393         }
 394 
 395         @Override
 396         public InvokeKind getInvokeKind() {
 397             throw unimplemented();
 398         }
 399 
 400         @Override
 401         public JavaType getInvokeReturnType() {
 402             throw unimplemented();
 403         }
 404 
 405         @Override
 406         public String toString() {
 407             Formatter fmt = new Formatter();
 408             PEMethodScope scope = this.methodScope;
 409             fmt.format("%s", new ResolvedJavaMethodBytecode(scope.method).asStackTraceElement(invoke.bci()));
 410             NodeSourcePosition callers = scope.getCallerBytecodePosition();
 411             if (callers != null) {
 412                 fmt.format("%n%s", callers);
 413             }
 414             return fmt.toString();
 415         }
 416     }
 417 
 418     protected class PEAppendGraphBuilderContext extends PENonAppendGraphBuilderContext {
 419         protected FixedWithNextNode lastInstr;
 420         protected ValueNode pushedNode;
 421         protected boolean invokeConsumed;
 422 
 423         public PEAppendGraphBuilderContext(PEMethodScope inlineScope, FixedWithNextNode lastInstr) {
 424             super(inlineScope, inlineScope.invokeData != null ? inlineScope.invokeData.invoke : null);
 425             this.lastInstr = lastInstr;
 426         }
 427 
 428         @Override
 429         public void push(JavaKind kind, ValueNode value) {
 430             if (pushedNode != null) {
 431                 throw unimplemented("Only one push is supported");
 432             }
 433             pushedNode = value;
 434         }
 435 
 436         @Override
 437         public void setStateAfter(StateSplit stateSplit) {
 438             Node stateAfter = decodeFloatingNode(methodScope.caller, methodScope.callerLoopScope, methodScope.invokeData.stateAfterOrderId);
 439             getGraph().add(stateAfter);
 440             FrameState fs = (FrameState) handleFloatingNodeAfterAdd(methodScope.caller, methodScope.callerLoopScope, stateAfter);
 441             stateSplit.setStateAfter(fs);
 442         }
 443 
 444         @SuppressWarnings("try")
 445         @Override
 446         public <T extends ValueNode> T append(T v) {
 447             if (v.graph() != null) {
 448                 return v;
 449             }
 450             try (DebugCloseable position = withNodeSoucePosition()) {
 451                 T added = getGraph().addOrUniqueWithInputs(v);
 452                 if (added == v) {
 453                     updateLastInstruction(v);
 454                 }
 455                 return added;
 456             }
 457         }
 458 
 459         private DebugCloseable withNodeSoucePosition() {
 460             if (getGraph().trackNodeSourcePosition()) {
 461                 NodeSourcePosition callerBytecodePosition = methodScope.getCallerBytecodePosition();
 462                 if (callerBytecodePosition != null) {
 463                     return getGraph().withNodeSourcePosition(callerBytecodePosition);
 464                 }
 465             }
 466             return null;
 467         }
 468 
 469         private <T extends ValueNode> void updateLastInstruction(T v) {
 470             if (v instanceof FixedNode) {
 471                 FixedNode fixedNode = (FixedNode) v;
 472                 if (lastInstr != null) {
 473                     lastInstr.setNext(fixedNode);
 474                 }
 475                 if (fixedNode instanceof FixedWithNextNode) {
 476                     FixedWithNextNode fixedWithNextNode = (FixedWithNextNode) fixedNode;
 477                     assert fixedWithNextNode.next() == null : "cannot append instruction to instruction which isn't end";
 478                     lastInstr = fixedWithNextNode;
 479                 } else {
 480                     lastInstr = null;
 481                 }
 482             }
 483         }
 484 
 485         @Override
 486         public void handleReplacedInvoke(CallTargetNode callTarget, JavaKind resultType) {
 487             if (invokeConsumed) {
 488                 throw unimplemented("handleReplacedInvoke can be called only once");
 489             }
 490             invokeConsumed = true;
 491 
 492             appendInvoke(methodScope.caller, methodScope.callerLoopScope, methodScope.invokeData, callTarget);
 493             updateLastInstruction(invoke.asNode());
 494         }
 495     }
 496 
 497     @NodeInfo(cycles = CYCLES_IGNORED, size = SIZE_IGNORED)
 498     static class ExceptionPlaceholderNode extends ValueNode {
 499         public static final NodeClass<ExceptionPlaceholderNode> TYPE = NodeClass.create(ExceptionPlaceholderNode.class);
 500 
 501         protected ExceptionPlaceholderNode() {
 502             super(TYPE, StampFactory.object());
 503         }
 504     }
 505 
 506     protected static class SpecialCallTargetCacheKey {
 507         private final InvokeKind invokeKind;
 508         private final ResolvedJavaMethod targetMethod;
 509         private final ResolvedJavaType contextType;
 510         private final Stamp receiverStamp;
 511 
 512         public SpecialCallTargetCacheKey(InvokeKind invokeKind, ResolvedJavaMethod targetMethod, ResolvedJavaType contextType, Stamp receiverStamp) {
 513             this.invokeKind = invokeKind;
 514             this.targetMethod = targetMethod;
 515             this.contextType = contextType;
 516             this.receiverStamp = receiverStamp;
 517         }
 518 
 519         @Override
 520         public int hashCode() {
 521             return invokeKind.hashCode() ^ targetMethod.hashCode() ^ contextType.hashCode() ^ receiverStamp.hashCode();
 522         }
 523 
 524         @Override
 525         public boolean equals(Object obj) {
 526             if (obj instanceof SpecialCallTargetCacheKey) {
 527                 SpecialCallTargetCacheKey key = (SpecialCallTargetCacheKey) obj;
 528                 return key.invokeKind.equals(this.invokeKind) && key.targetMethod.equals(this.targetMethod) && key.contextType.equals(this.contextType) && key.receiverStamp.equals(this.receiverStamp);
 529             }
 530             return false;
 531         }
 532     }
 533 
 534     private final LoopExplosionPlugin loopExplosionPlugin;
 535     private final InvocationPlugins invocationPlugins;
 536     private final InlineInvokePlugin[] inlineInvokePlugins;
 537     private final ParameterPlugin parameterPlugin;
 538     private final NodePlugin[] nodePlugins;
 539     private final EconomicMap<SpecialCallTargetCacheKey, Object> specialCallTargetCache;
 540     private final EconomicMap<ResolvedJavaMethod, Object> invocationPluginCache;
 541     private final ResolvedJavaMethod callInlinedMethod;
 542     protected final SourceLanguagePositionProvider sourceLanguagePositionProvider;
 543 
 544     public PEGraphDecoder(Architecture architecture, StructuredGraph graph, MetaAccessProvider metaAccess, ConstantReflectionProvider constantReflection, ConstantFieldProvider constantFieldProvider,
 545                     StampProvider stampProvider, LoopExplosionPlugin loopExplosionPlugin, InvocationPlugins invocationPlugins, InlineInvokePlugin[] inlineInvokePlugins,
 546                     ParameterPlugin parameterPlugin,
 547                     NodePlugin[] nodePlugins, ResolvedJavaMethod callInlinedMethod, SourceLanguagePositionProvider sourceLanguagePositionProvider) {
 548         super(architecture, graph, metaAccess, constantReflection, constantFieldProvider, stampProvider, true);
 549         this.loopExplosionPlugin = loopExplosionPlugin;
 550         this.invocationPlugins = invocationPlugins;
 551         this.inlineInvokePlugins = inlineInvokePlugins;
 552         this.parameterPlugin = parameterPlugin;
 553         this.nodePlugins = nodePlugins;
 554         this.specialCallTargetCache = EconomicMap.create(Equivalence.DEFAULT);
 555         this.invocationPluginCache = EconomicMap.create(Equivalence.DEFAULT);
 556         this.callInlinedMethod = callInlinedMethod;
 557         this.sourceLanguagePositionProvider = sourceLanguagePositionProvider;
 558     }
 559 
 560     protected static LoopExplosionKind loopExplosionKind(ResolvedJavaMethod method, LoopExplosionPlugin loopExplosionPlugin) {
 561         if (loopExplosionPlugin == null) {
 562             return LoopExplosionKind.NONE;
 563         } else {
 564             return loopExplosionPlugin.loopExplosionKind(method);
 565         }
 566     }
 567 
 568     public void decode(ResolvedJavaMethod method, boolean isSubstitution, boolean trackNodeSourcePosition) {
 569         PEMethodScope methodScope = new PEMethodScope(graph, null, null, lookupEncodedGraph(method, null, null, isSubstitution, trackNodeSourcePosition), method, null, 0, loopExplosionPlugin, null);
 570         decode(createInitialLoopScope(methodScope, null));
 571         cleanupGraph(methodScope);
 572 
 573         debug.dump(DebugContext.VERBOSE_LEVEL, graph, "After graph cleanup");
 574         assert graph.verify();
 575 
 576         try {
 577             /* Check that the control flow graph can be computed, to catch problems early. */
 578             assert CFGVerifier.verify(ControlFlowGraph.compute(graph, true, true, true, true));
 579         } catch (Throwable ex) {
 580             throw GraalError.shouldNotReachHere("Control flow graph not valid after partial evaluation");
 581         }
 582     }
 583 
 584     @Override
 585     protected void cleanupGraph(MethodScope methodScope) {
 586         super.cleanupGraph(methodScope);
 587 
 588         for (FrameState frameState : graph.getNodes(FrameState.TYPE)) {
 589             if (frameState.bci == BytecodeFrame.UNWIND_BCI) {
 590                 /*
 591                  * handleMissingAfterExceptionFrameState is called during graph decoding from
 592                  * InliningUtil.processFrameState - but during graph decoding it does not do
 593                  * anything because the usages of the frameState are not available yet. So we need
 594                  * to call it again.
 595                  */
 596                 PEMethodScope peMethodScope = (PEMethodScope) methodScope;
 597                 Invoke invoke = peMethodScope.invokeData != null ? peMethodScope.invokeData.invoke : null;
 598                 InliningUtil.handleMissingAfterExceptionFrameState(frameState, invoke, null, true);
 599 
 600                 /*
 601                  * The frameState must be gone now, because it is not a valid deoptimization point.
 602                  */
 603                 assert frameState.isDeleted();
 604             }
 605         }
 606     }
 607 
 608     @Override
 609     protected void checkLoopExplosionIteration(MethodScope s, LoopScope loopScope) {
 610         PEMethodScope methodScope = (PEMethodScope) s;
 611 
 612         if (loopScope.loopIteration > Options.MaximumLoopExplosionCount.getValue(options)) {
 613             throw tooManyLoopExplosionIterations(methodScope, options);
 614         }
 615     }
 616 
 617     private static RuntimeException tooManyLoopExplosionIterations(PEMethodScope methodScope, OptionValues options) {
 618         String message = "too many loop explosion iterations - does the explosion not terminate for method " + methodScope.method + "?";
 619         RuntimeException bailout = Options.FailedLoopExplosionIsFatal.getValue(options) ? new RuntimeException(message) : new PermanentBailoutException(message);
 620         throw GraphUtil.createBailoutException(message, bailout, GraphUtil.approxSourceStackTraceElement(methodScope.getCallerBytecodePosition()));
 621     }
 622 
 623     @Override
 624     protected LoopScope handleInvoke(MethodScope s, LoopScope loopScope, InvokeData invokeData) {
 625         PEMethodScope methodScope = (PEMethodScope) s;
 626 
 627         /*
 628          * Decode the call target, but do not add it to the graph yet. This avoids adding usages for
 629          * all the arguments, which are expensive to remove again when we can inline the method.
 630          */
 631         assert invokeData.invoke.callTarget() == null : "callTarget edge is ignored during decoding of Invoke";
 632         CallTargetNode callTarget = (CallTargetNode) decodeFloatingNode(methodScope, loopScope, invokeData.callTargetOrderId);
 633         if (callTarget instanceof MethodCallTargetNode) {
 634             MethodCallTargetNode methodCall = (MethodCallTargetNode) callTarget;
 635             if (methodCall.invokeKind().hasReceiver()) {
 636                 invokeData.constantReceiver = methodCall.arguments().get(0).asJavaConstant();
 637                 NodeSourcePosition invokePosition = invokeData.invoke.asNode().getNodeSourcePosition();
 638                 if (invokeData.constantReceiver != null && invokePosition != null) {
 639                     // new NodeSourcePosition(invokeData.constantReceiver,
 640                     // invokePosition.getCaller(), invokePosition.getMethod(),
 641                     // invokePosition.getBCI());
 642                 }
 643             }
 644             LoopScope inlineLoopScope = trySimplifyInvoke(methodScope, loopScope, invokeData, (MethodCallTargetNode) callTarget);
 645             if (inlineLoopScope != null) {
 646                 return inlineLoopScope;
 647             }
 648         }
 649 
 650         /* We know that we need an invoke, so now we can add the call target to the graph. */
 651         graph.add(callTarget);
 652         registerNode(loopScope, invokeData.callTargetOrderId, callTarget, false, false);
 653         return super.handleInvoke(methodScope, loopScope, invokeData);
 654     }
 655 
 656     protected LoopScope trySimplifyInvoke(PEMethodScope methodScope, LoopScope loopScope, InvokeData invokeData, MethodCallTargetNode callTarget) {
 657         // attempt to devirtualize the call
 658         ResolvedJavaMethod specialCallTarget = getSpecialCallTarget(invokeData, callTarget);
 659         if (specialCallTarget != null) {
 660             callTarget.setTargetMethod(specialCallTarget);
 661             callTarget.setInvokeKind(InvokeKind.Special);
 662         }
 663 
 664         if (tryInvocationPlugin(methodScope, loopScope, invokeData, callTarget)) {
 665             /*
 666              * The invocation plugin handled the call, so decoding continues in the calling method.
 667              */
 668             return loopScope;
 669         }
 670         LoopScope inlineLoopScope = tryInline(methodScope, loopScope, invokeData, callTarget);
 671         if (inlineLoopScope != null) {
 672             /*
 673              * We can inline the call, so decoding continues in the inlined method.
 674              */
 675             return inlineLoopScope;
 676         }
 677 
 678         for (InlineInvokePlugin plugin : inlineInvokePlugins) {
 679             plugin.notifyNotInlined(new PENonAppendGraphBuilderContext(methodScope, invokeData.invoke), callTarget.targetMethod(), invokeData.invoke);
 680         }
 681         return null;
 682     }
 683 
 684     private ResolvedJavaMethod getSpecialCallTarget(InvokeData invokeData, MethodCallTargetNode callTarget) {
 685         if (callTarget.invokeKind().isDirect()) {
 686             return null;
 687         }
 688 
 689         // check for trivial cases (e.g. final methods, nonvirtual methods)
 690         if (callTarget.targetMethod().canBeStaticallyBound()) {
 691             return callTarget.targetMethod();
 692         }
 693 
 694         SpecialCallTargetCacheKey key = new SpecialCallTargetCacheKey(callTarget.invokeKind(), callTarget.targetMethod(), invokeData.contextType, callTarget.receiver().stamp(NodeView.DEFAULT));
 695         Object specialCallTarget = specialCallTargetCache.get(key);
 696         if (specialCallTarget == null) {
 697             specialCallTarget = MethodCallTargetNode.devirtualizeCall(key.invokeKind, key.targetMethod, key.contextType, graph.getAssumptions(),
 698                             key.receiverStamp);
 699             if (specialCallTarget == null) {
 700                 specialCallTarget = CACHED_NULL_VALUE;
 701             }
 702             specialCallTargetCache.put(key, specialCallTarget);
 703         }
 704 
 705         return specialCallTarget == CACHED_NULL_VALUE ? null : (ResolvedJavaMethod) specialCallTarget;
 706     }
 707 
 708     protected boolean tryInvocationPlugin(PEMethodScope methodScope, LoopScope loopScope, InvokeData invokeData, MethodCallTargetNode callTarget) {
 709         if (invocationPlugins == null || invocationPlugins.isEmpty()) {
 710             return false;
 711         }
 712 
 713         Invoke invoke = invokeData.invoke;
 714 
 715         ResolvedJavaMethod targetMethod = callTarget.targetMethod();
 716         InvocationPlugin invocationPlugin = getInvocationPlugin(targetMethod);
 717         if (invocationPlugin == null) {
 718             return false;
 719         }
 720 
 721         ValueNode[] arguments = callTarget.arguments().toArray(new ValueNode[0]);
 722         FixedWithNextNode invokePredecessor = (FixedWithNextNode) invoke.asNode().predecessor();
 723 
 724         /*
 725          * Remove invoke from graph so that invocation plugin can append nodes to the predecessor.
 726          */
 727         invoke.asNode().replaceAtPredecessor(null);
 728 
 729         PEMethodScope inlineScope = new PEMethodScope(graph, methodScope, loopScope, null, targetMethod, invokeData, methodScope.inliningDepth + 1, loopExplosionPlugin, arguments);
 730         PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(inlineScope, invokePredecessor);
 731         InvocationPluginReceiver invocationPluginReceiver = new InvocationPluginReceiver(graphBuilderContext);
 732 
 733         if (invocationPlugin.execute(graphBuilderContext, targetMethod, invocationPluginReceiver.init(targetMethod, arguments), arguments)) {
 734 
 735             if (graphBuilderContext.invokeConsumed) {
 736                 /* Nothing to do. */
 737             } else if (graphBuilderContext.lastInstr != null) {
 738                 registerNode(loopScope, invokeData.invokeOrderId, graphBuilderContext.pushedNode, true, true);
 739                 invoke.asNode().replaceAtUsages(graphBuilderContext.pushedNode);
 740                 graphBuilderContext.lastInstr.setNext(nodeAfterInvoke(methodScope, loopScope, invokeData, AbstractBeginNode.prevBegin(graphBuilderContext.lastInstr)));
 741                 deleteInvoke(invoke);
 742             } else {
 743                 assert graphBuilderContext.pushedNode == null : "Why push a node when the invoke does not return anyway?";
 744                 invoke.asNode().replaceAtUsages(null);
 745                 deleteInvoke(invoke);
 746             }
 747             return true;
 748 
 749         } else {
 750             /* Intrinsification failed, restore original state: invoke is in Graph. */
 751             invokePredecessor.setNext(invoke.asNode());
 752             return false;
 753         }
 754     }
 755 
 756     private InvocationPlugin getInvocationPlugin(ResolvedJavaMethod targetMethod) {
 757         Object invocationPlugin = invocationPluginCache.get(targetMethod);
 758         if (invocationPlugin == null) {
 759             invocationPlugin = invocationPlugins.lookupInvocation(targetMethod);
 760             if (invocationPlugin == null) {
 761                 invocationPlugin = CACHED_NULL_VALUE;
 762             }
 763             invocationPluginCache.put(targetMethod, invocationPlugin);
 764         }
 765 
 766         return invocationPlugin == CACHED_NULL_VALUE ? null : (InvocationPlugin) invocationPlugin;
 767     }
 768 
 769     protected LoopScope tryInline(PEMethodScope methodScope, LoopScope loopScope, InvokeData invokeData, MethodCallTargetNode callTarget) {
 770         if (!callTarget.invokeKind().isDirect()) {
 771             return null;
 772         }
 773 
 774         ResolvedJavaMethod targetMethod = callTarget.targetMethod();
 775         if (targetMethod.hasNeverInlineDirective()) {
 776             return null;
 777         }
 778 
 779         ValueNode[] arguments = callTarget.arguments().toArray(new ValueNode[0]);
 780         GraphBuilderContext graphBuilderContext = new PENonAppendGraphBuilderContext(methodScope, invokeData.invoke);
 781 
 782         for (InlineInvokePlugin plugin : inlineInvokePlugins) {
 783             InlineInfo inlineInfo = plugin.shouldInlineInvoke(graphBuilderContext, targetMethod, arguments);
 784             if (inlineInfo != null) {
 785                 if (inlineInfo.getMethodToInline() == null) {
 786                     return null;
 787                 } else {
 788                     return doInline(methodScope, loopScope, invokeData, inlineInfo, arguments);
 789                 }
 790             }
 791         }
 792         return null;
 793     }
 794 
 795     protected LoopScope doInline(PEMethodScope methodScope, LoopScope loopScope, InvokeData invokeData, InlineInfo inlineInfo, ValueNode[] arguments) {
 796         if (!invokeData.invoke.useForInlining()) {
 797             return null;
 798         }
 799         ResolvedJavaMethod inlineMethod = inlineInfo.getMethodToInline();
 800         ResolvedJavaMethod originalMethod = inlineInfo.getOriginalMethod();
 801         boolean isSubstitution = originalMethod != null && !originalMethod.equals(inlineMethod);
 802         EncodedGraph graphToInline = lookupEncodedGraph(inlineMethod, originalMethod, inlineInfo.getIntrinsicBytecodeProvider(), isSubstitution, graph.trackNodeSourcePosition());
 803         if (graphToInline == null) {
 804             return null;
 805         }
 806 
 807         assert !graph.trackNodeSourcePosition() || graphToInline.trackNodeSourcePosition() : graph + " " + graphToInline;
 808         if (methodScope.inliningDepth > Options.InliningDepthError.getValue(options)) {
 809             throw tooDeepInlining(methodScope);
 810         }
 811 
 812         for (InlineInvokePlugin plugin : inlineInvokePlugins) {
 813             plugin.notifyBeforeInline(inlineMethod);
 814         }
 815 
 816         Invoke invoke = invokeData.invoke;
 817         FixedNode invokeNode = invoke.asNode();
 818         FixedWithNextNode predecessor = (FixedWithNextNode) invokeNode.predecessor();
 819         invokeNode.replaceAtPredecessor(null);
 820 
 821         PEMethodScope inlineScope = new PEMethodScope(graph, methodScope, loopScope, graphToInline, inlineMethod, invokeData, methodScope.inliningDepth + 1,
 822                         loopExplosionPlugin, arguments);
 823 
 824         if (!inlineMethod.isStatic()) {
 825             if (StampTool.isPointerAlwaysNull(arguments[0])) {
 826                 /*
 827                  * The receiver is null, so we can unconditionally throw a NullPointerException
 828                  * instead of performing any inlining.
 829                  */
 830                 DeoptimizeNode deoptimizeNode = graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateReprofile, DeoptimizationReason.NullCheckException));
 831                 predecessor.setNext(deoptimizeNode);
 832                 finishInlining(inlineScope);
 833                 /* Continue decoding in the caller. */
 834                 return loopScope;
 835 
 836             } else if (!StampTool.isPointerNonNull(arguments[0])) {
 837                 /* The receiver might be null, so we need to insert a null check. */
 838                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(inlineScope, predecessor);
 839                 arguments[0] = graphBuilderContext.nullCheckedValue(arguments[0]);
 840                 predecessor = graphBuilderContext.lastInstr;
 841             }
 842         }
 843 
 844         LoopScope inlineLoopScope = createInitialLoopScope(inlineScope, predecessor);
 845 
 846         /*
 847          * The GraphEncoder assigns parameters a nodeId immediately after the fixed nodes.
 848          * Initializing createdNodes here avoid decoding and immediately replacing the
 849          * ParameterNodes.
 850          */
 851         int firstArgumentNodeId = inlineScope.maxFixedNodeOrderId + 1;
 852         for (int i = 0; i < arguments.length; i++) {
 853             inlineLoopScope.createdNodes[firstArgumentNodeId + i] = arguments[i];
 854         }
 855 
 856         // Copy assumptions from inlinee to caller
 857         Assumptions assumptions = graph.getAssumptions();
 858         Assumptions inlinedAssumptions = graphToInline.getAssumptions();
 859         if (assumptions != null) {
 860             if (inlinedAssumptions != null) {
 861                 assumptions.record(inlinedAssumptions);
 862             }
 863         } else {
 864             assert inlinedAssumptions == null : String.format("cannot inline graph (%s) which makes assumptions into a graph (%s) that doesn't", inlineMethod, graph);
 865         }
 866 
 867         // Copy inlined methods from inlinee to caller
 868         List<ResolvedJavaMethod> inlinedMethods = graphToInline.getInlinedMethods();
 869         if (inlinedMethods != null) {
 870             for (ResolvedJavaMethod other : inlinedMethods) {
 871                 graph.recordMethod(other);
 872             }
 873         }
 874 
 875         if (graphToInline.getFields() != null) {
 876             for (ResolvedJavaField field : graphToInline.getFields()) {
 877                 graph.recordField(field);
 878             }
 879         }
 880         if (graphToInline.hasUnsafeAccess()) {
 881             graph.markUnsafeAccess();
 882         }
 883 
 884         /*
 885          * Do the actual inlining by returning the initial loop scope for the inlined method scope.
 886          */
 887         return inlineLoopScope;
 888     }
 889 
 890     @Override
 891     protected void finishInlining(MethodScope is) {
 892         PEMethodScope inlineScope = (PEMethodScope) is;
 893         ResolvedJavaMethod inlineMethod = inlineScope.method;
 894         PEMethodScope methodScope = inlineScope.caller;
 895         LoopScope loopScope = inlineScope.callerLoopScope;
 896         InvokeData invokeData = inlineScope.invokeData;
 897         Invoke invoke = invokeData.invoke;
 898         FixedNode invokeNode = invoke.asNode();
 899 
 900         ValueNode exceptionValue = null;
 901         int returnNodeCount = 0;
 902         int unwindNodeCount = 0;
 903         List<ControlSinkNode> returnAndUnwindNodes = inlineScope.returnAndUnwindNodes;
 904         for (int i = 0; i < returnAndUnwindNodes.size(); i++) {
 905             FixedNode fixedNode = returnAndUnwindNodes.get(i);
 906             if (fixedNode instanceof ReturnNode) {
 907                 returnNodeCount++;
 908             } else if (fixedNode.isAlive()) {
 909                 assert fixedNode instanceof UnwindNode;
 910                 unwindNodeCount++;
 911             }
 912         }
 913 
 914         if (unwindNodeCount > 0) {
 915             FixedNode unwindReplacement;
 916             if (invoke instanceof InvokeWithExceptionNode) {
 917                 /* Decoding continues for the exception handler. */
 918                 unwindReplacement = makeStubNode(methodScope, loopScope, invokeData.exceptionNextOrderId);
 919             } else {
 920                 /* No exception handler available, so the only thing we can do is deoptimize. */
 921                 unwindReplacement = graph.add(new DeoptimizeNode(DeoptimizationAction.InvalidateRecompile, DeoptimizationReason.NotCompiledExceptionHandler));
 922             }
 923 
 924             if (unwindNodeCount == 1) {
 925                 /* Only one UnwindNode, we can use the exception directly. */
 926                 UnwindNode unwindNode = getSingleMatchingNode(returnAndUnwindNodes, returnNodeCount > 0, UnwindNode.class);
 927                 exceptionValue = unwindNode.exception();
 928                 unwindNode.replaceAndDelete(unwindReplacement);
 929 
 930             } else {
 931                 /*
 932                  * More than one UnwindNode. This can happen with the loop explosion strategy
 933                  * FULL_EXPLODE_UNTIL_RETURN, where we keep exploding after the loop and therefore
 934                  * also explode exception paths. Merge the exception in a similar way as multiple
 935                  * return values.
 936                  */
 937                 MergeNode unwindMergeNode = graph.add(new MergeNode());
 938                 exceptionValue = InliningUtil.mergeValueProducers(unwindMergeNode, getMatchingNodes(returnAndUnwindNodes, returnNodeCount > 0, UnwindNode.class, unwindNodeCount),
 939                                 null, unwindNode -> unwindNode.exception());
 940                 unwindMergeNode.setNext(unwindReplacement);
 941 
 942                 ensureExceptionStateDecoded(inlineScope);
 943                 unwindMergeNode.setStateAfter(inlineScope.exceptionState.duplicateModified(JavaKind.Object, JavaKind.Object, exceptionValue));
 944             }
 945         }
 946 
 947         assert invoke.next() == null;
 948         assert !(invoke instanceof InvokeWithExceptionNode) || ((InvokeWithExceptionNode) invoke).exceptionEdge() == null;
 949 
 950         ValueNode returnValue;
 951         if (returnNodeCount == 0) {
 952             returnValue = null;
 953         } else if (returnNodeCount == 1) {
 954             ReturnNode returnNode = getSingleMatchingNode(returnAndUnwindNodes, unwindNodeCount > 0, ReturnNode.class);
 955             returnValue = returnNode.result();
 956             FixedNode n = nodeAfterInvoke(methodScope, loopScope, invokeData, AbstractBeginNode.prevBegin(returnNode));
 957             returnNode.replaceAndDelete(n);
 958         } else {
 959             AbstractMergeNode merge = graph.add(new MergeNode());
 960             merge.setStateAfter((FrameState) ensureNodeCreated(methodScope, loopScope, invokeData.stateAfterOrderId));
 961             returnValue = InliningUtil.mergeReturns(merge, getMatchingNodes(returnAndUnwindNodes, unwindNodeCount > 0, ReturnNode.class, returnNodeCount));
 962             FixedNode n = nodeAfterInvoke(methodScope, loopScope, invokeData, merge);
 963             merge.setNext(n);
 964         }
 965         invokeNode.replaceAtUsages(returnValue);
 966 
 967         /*
 968          * Usage the handles that we have on the return value and the exception to update the
 969          * orderId->Node table.
 970          */
 971         registerNode(loopScope, invokeData.invokeOrderId, returnValue, true, true);
 972         if (invoke instanceof InvokeWithExceptionNode) {
 973             registerNode(loopScope, invokeData.exceptionOrderId, exceptionValue, true, true);
 974         }
 975         if (inlineScope.exceptionPlaceholderNode != null) {
 976             inlineScope.exceptionPlaceholderNode.replaceAtUsagesAndDelete(exceptionValue);
 977         }
 978         deleteInvoke(invoke);
 979 
 980         for (InlineInvokePlugin plugin : inlineInvokePlugins) {
 981             plugin.notifyAfterInline(inlineMethod);
 982         }
 983     }
 984 
 985     @SuppressWarnings("unchecked")
 986     private static <T> T getSingleMatchingNode(List<ControlSinkNode> returnAndUnwindNodes, boolean hasNonMatchingEntries, Class<T> clazz) {
 987         if (!hasNonMatchingEntries) {
 988             assert returnAndUnwindNodes.size() == 1;
 989             return (T) returnAndUnwindNodes.get(0);
 990         }
 991 
 992         for (int i = 0; i < returnAndUnwindNodes.size(); i++) {
 993             ControlSinkNode node = returnAndUnwindNodes.get(i);
 994             if (clazz.isInstance(node)) {
 995                 return (T) node;
 996             }
 997         }
 998         throw GraalError.shouldNotReachHere();
 999     }
1000 
1001     @SuppressWarnings("unchecked")
1002     private static <T> List<T> getMatchingNodes(List<ControlSinkNode> returnAndUnwindNodes, boolean hasNonMatchingEntries, Class<T> clazz, int resultCount) {
1003         if (!hasNonMatchingEntries) {
1004             return (List<T>) returnAndUnwindNodes;
1005         }
1006 
1007         List<T> result = new ArrayList<>(resultCount);
1008         for (int i = 0; i < returnAndUnwindNodes.size(); i++) {
1009             ControlSinkNode node = returnAndUnwindNodes.get(i);
1010             if (clazz.isInstance(node)) {
1011                 result.add((T) node);
1012             }
1013         }
1014         assert result.size() == resultCount;
1015         return result;
1016     }
1017 
1018     private static RuntimeException tooDeepInlining(PEMethodScope methodScope) {
1019         HashMap<ResolvedJavaMethod, Integer> methodCounts = new HashMap<>();
1020         for (PEMethodScope cur = methodScope; cur != null; cur = cur.caller) {
1021             Integer oldCount = methodCounts.get(cur.method);
1022             methodCounts.put(cur.method, oldCount == null ? 1 : oldCount + 1);
1023         }
1024 
1025         List<Map.Entry<ResolvedJavaMethod, Integer>> methods = new ArrayList<>(methodCounts.entrySet());
1026         methods.sort((e1, e2) -> -Integer.compare(e1.getValue(), e2.getValue()));
1027 
1028         StringBuilder msg = new StringBuilder("Too deep inlining, probably caused by recursive inlining.").append(System.lineSeparator()).append("== Inlined methods ordered by inlining frequency:");
1029         for (Map.Entry<ResolvedJavaMethod, Integer> entry : methods) {
1030             msg.append(System.lineSeparator()).append(entry.getKey().format("%H.%n(%p) [")).append(entry.getValue()).append("]");
1031         }
1032         msg.append(System.lineSeparator()).append("== Complete stack trace of inlined methods:");
1033         int lastBci = 0;
1034         for (PEMethodScope cur = methodScope; cur != null; cur = cur.caller) {
1035             msg.append(System.lineSeparator()).append(cur.method.asStackTraceElement(lastBci));
1036             if (cur.invokeData != null) {
1037                 lastBci = cur.invokeData.invoke.bci();
1038             } else {
1039                 lastBci = 0;
1040             }
1041         }
1042 
1043         throw new PermanentBailoutException(msg.toString());
1044     }
1045 
1046     public FixedNode nodeAfterInvoke(PEMethodScope methodScope, LoopScope loopScope, InvokeData invokeData, AbstractBeginNode lastBlock) {
1047         assert lastBlock.isAlive();
1048         FixedNode n;
1049         if (invokeData.invoke instanceof InvokeWithExceptionNode) {
1050             registerNode(loopScope, invokeData.nextOrderId, lastBlock, false, false);
1051             n = makeStubNode(methodScope, loopScope, invokeData.nextNextOrderId);
1052         } else {
1053             n = makeStubNode(methodScope, loopScope, invokeData.nextOrderId);
1054         }
1055         return n;
1056     }
1057 
1058     private static void deleteInvoke(Invoke invoke) {
1059         /*
1060          * Clean up unused nodes. We cannot just call killCFG on the invoke node because that can
1061          * kill too much: nodes that are decoded later can use values that appear unused by now.
1062          */
1063         FrameState frameState = invoke.stateAfter();
1064         invoke.asNode().safeDelete();
1065         assert invoke.callTarget() == null : "must not have been added to the graph yet";
1066         if (frameState != null && frameState.hasNoUsages()) {
1067             frameState.safeDelete();
1068         }
1069     }
1070 
1071     protected abstract EncodedGraph lookupEncodedGraph(ResolvedJavaMethod method, ResolvedJavaMethod originalMethod, BytecodeProvider intrinsicBytecodeProvider, boolean isSubstitution,
1072                     boolean trackNodeSourcePosition);
1073 
1074     @Override
1075     protected void handleFixedNode(MethodScope s, LoopScope loopScope, int nodeOrderId, FixedNode node) {
1076         PEMethodScope methodScope = (PEMethodScope) s;
1077 
1078         if (node instanceof ForeignCallNode) {
1079             ForeignCallNode foreignCall = (ForeignCallNode) node;
1080             if (foreignCall.getBci() == BytecodeFrame.UNKNOWN_BCI && methodScope.invokeData != null) {
1081                 foreignCall.setBci(methodScope.invokeData.invoke.bci());
1082             }
1083         }
1084 
1085         super.handleFixedNode(methodScope, loopScope, nodeOrderId, node);
1086     }
1087 
1088     @SuppressWarnings("try")
1089     @Override
1090     protected Node canonicalizeFixedNode(MethodScope s, Node node) {
1091         PEMethodScope methodScope = (PEMethodScope) s;
1092 
1093         Node replacedNode = node;
1094         if (nodePlugins != null && nodePlugins.length > 0) {
1095             if (node instanceof LoadFieldNode) {
1096                 LoadFieldNode loadFieldNode = (LoadFieldNode) node;
1097                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, loadFieldNode);
1098                 ResolvedJavaField field = loadFieldNode.field();
1099                 if (loadFieldNode.isStatic()) {
1100                     for (NodePlugin nodePlugin : nodePlugins) {
1101                         if (nodePlugin.handleLoadStaticField(graphBuilderContext, field)) {
1102                             replacedNode = graphBuilderContext.pushedNode;
1103                             break;
1104                         }
1105                     }
1106                 } else {
1107                     ValueNode object = loadFieldNode.object();
1108                     for (NodePlugin nodePlugin : nodePlugins) {
1109                         if (nodePlugin.handleLoadField(graphBuilderContext, object, field)) {
1110                             replacedNode = graphBuilderContext.pushedNode;
1111                             break;
1112                         }
1113                     }
1114                 }
1115             } else if (node instanceof StoreFieldNode) {
1116                 StoreFieldNode storeFieldNode = (StoreFieldNode) node;
1117                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, storeFieldNode);
1118                 ResolvedJavaField field = storeFieldNode.field();
1119                 if (storeFieldNode.isStatic()) {
1120                     ValueNode value = storeFieldNode.value();
1121                     for (NodePlugin nodePlugin : nodePlugins) {
1122                         if (nodePlugin.handleStoreStaticField(graphBuilderContext, field, value)) {
1123                             replacedNode = graphBuilderContext.pushedNode;
1124                             break;
1125                         }
1126                     }
1127                 } else {
1128                     ValueNode object = storeFieldNode.object();
1129                     ValueNode value = storeFieldNode.value();
1130                     for (NodePlugin nodePlugin : nodePlugins) {
1131                         if (nodePlugin.handleStoreField(graphBuilderContext, object, field, value)) {
1132                             replacedNode = graphBuilderContext.pushedNode;
1133                             break;
1134                         }
1135                     }
1136                 }
1137             } else if (node instanceof LoadIndexedNode) {
1138                 LoadIndexedNode loadIndexedNode = (LoadIndexedNode) node;
1139                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, loadIndexedNode);
1140                 ValueNode array = loadIndexedNode.array();
1141                 ValueNode index = loadIndexedNode.index();
1142                 for (NodePlugin nodePlugin : nodePlugins) {
1143                     if (nodePlugin.handleLoadIndexed(graphBuilderContext, array, index, loadIndexedNode.getBoundsCheck(), loadIndexedNode.elementKind())) {
1144                         replacedNode = graphBuilderContext.pushedNode;
1145                         break;
1146                     }
1147                 }
1148             } else if (node instanceof StoreIndexedNode) {
1149                 StoreIndexedNode storeIndexedNode = (StoreIndexedNode) node;
1150                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, storeIndexedNode);
1151                 ValueNode array = storeIndexedNode.array();
1152                 ValueNode index = storeIndexedNode.index();
1153                 ValueNode value = storeIndexedNode.value();
1154                 for (NodePlugin nodePlugin : nodePlugins) {
1155                     if (nodePlugin.handleStoreIndexed(graphBuilderContext, array, index, storeIndexedNode.getBoundsCheck(), storeIndexedNode.getStoreCheck(), storeIndexedNode.elementKind(), value)) {
1156                         replacedNode = graphBuilderContext.pushedNode;
1157                         break;
1158                     }
1159                 }
1160             } else if (node instanceof NewInstanceNode) {
1161                 NewInstanceNode newInstanceNode = (NewInstanceNode) node;
1162                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, newInstanceNode);
1163                 ResolvedJavaType type = newInstanceNode.instanceClass();
1164                 for (NodePlugin nodePlugin : nodePlugins) {
1165                     if (nodePlugin.handleNewInstance(graphBuilderContext, type)) {
1166                         replacedNode = graphBuilderContext.pushedNode;
1167                         break;
1168                     }
1169                 }
1170             } else if (node instanceof NewArrayNode) {
1171                 NewArrayNode newArrayNode = (NewArrayNode) node;
1172                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, newArrayNode);
1173                 ResolvedJavaType elementType = newArrayNode.elementType();
1174                 ValueNode length = newArrayNode.length();
1175                 for (NodePlugin nodePlugin : nodePlugins) {
1176                     if (nodePlugin.handleNewArray(graphBuilderContext, elementType, length)) {
1177                         replacedNode = graphBuilderContext.pushedNode;
1178                         break;
1179                     }
1180                 }
1181             } else if (node instanceof NewMultiArrayNode) {
1182                 NewMultiArrayNode newArrayNode = (NewMultiArrayNode) node;
1183                 PEAppendGraphBuilderContext graphBuilderContext = new PEAppendGraphBuilderContext(methodScope, newArrayNode);
1184                 ResolvedJavaType elementType = newArrayNode.type();
1185                 ValueNode[] dimensions = newArrayNode.dimensions().toArray(new ValueNode[0]);
1186                 for (NodePlugin nodePlugin : nodePlugins) {
1187                     if (nodePlugin.handleNewMultiArray(graphBuilderContext, elementType, dimensions)) {
1188                         replacedNode = graphBuilderContext.pushedNode;
1189                         break;
1190                     }
1191                 }
1192             }
1193         }
1194 
1195         return super.canonicalizeFixedNode(methodScope, replacedNode);
1196     }
1197 
1198     @Override
1199     protected Node handleFloatingNodeBeforeAdd(MethodScope s, LoopScope loopScope, Node n) {
1200         PEMethodScope methodScope = (PEMethodScope) s;
1201 
1202         Node node = n;
1203         if (node instanceof ParameterNode) {
1204             ParameterNode param = (ParameterNode) node;
1205             if (methodScope.isInlinedMethod()) {
1206                 throw GraalError.shouldNotReachHere("Parameter nodes are already registered when the inlined scope is created");
1207 
1208             } else if (parameterPlugin != null) {
1209                 assert !methodScope.isInlinedMethod();
1210                 GraphBuilderContext graphBuilderContext = new PENonAppendGraphBuilderContext(methodScope, null);
1211                 Node result = parameterPlugin.interceptParameter(graphBuilderContext, param.index(),
1212                                 StampPair.create(param.stamp(NodeView.DEFAULT), param.uncheckedStamp()));
1213                 if (result != null) {
1214                     return result;
1215                 }
1216             }
1217             node = param.copyWithInputs();
1218         }
1219 
1220         return super.handleFloatingNodeBeforeAdd(methodScope, loopScope, node);
1221     }
1222 
1223     protected void ensureOuterStateDecoded(PEMethodScope methodScope) {
1224         if (methodScope.outerState == null && methodScope.caller != null) {
1225             FrameState stateAtReturn = methodScope.invokeData.invoke.stateAfter();
1226             if (stateAtReturn == null) {
1227                 stateAtReturn = (FrameState) decodeFloatingNode(methodScope.caller, methodScope.callerLoopScope, methodScope.invokeData.stateAfterOrderId);
1228             }
1229 
1230             JavaKind invokeReturnKind = methodScope.invokeData.invoke.asNode().getStackKind();
1231             FrameState outerState = stateAtReturn.duplicateModified(graph, methodScope.invokeData.invoke.bci(), stateAtReturn.rethrowException(), true, invokeReturnKind, null, null);
1232 
1233             /*
1234              * When the encoded graph has methods inlining, we can already have a proper caller
1235              * state. If not, we set the caller state here.
1236              */
1237             if (outerState.outerFrameState() == null && methodScope.caller != null) {
1238                 ensureOuterStateDecoded(methodScope.caller);
1239                 outerState.setOuterFrameState(methodScope.caller.outerState);
1240             }
1241             methodScope.outerState = outerState;
1242         }
1243     }
1244 
1245     protected void ensureStateAfterDecoded(PEMethodScope methodScope) {
1246         if (methodScope.invokeData.invoke.stateAfter() == null) {
1247             methodScope.invokeData.invoke.setStateAfter((FrameState) ensureNodeCreated(methodScope.caller, methodScope.callerLoopScope, methodScope.invokeData.stateAfterOrderId));
1248         }
1249     }
1250 
1251     protected void ensureExceptionStateDecoded(PEMethodScope methodScope) {
1252         if (methodScope.exceptionState == null && methodScope.caller != null && methodScope.invokeData.invoke instanceof InvokeWithExceptionNode) {
1253             ensureStateAfterDecoded(methodScope);
1254 
1255             assert methodScope.exceptionPlaceholderNode == null;
1256             methodScope.exceptionPlaceholderNode = graph.add(new ExceptionPlaceholderNode());
1257             registerNode(methodScope.callerLoopScope, methodScope.invokeData.exceptionOrderId, methodScope.exceptionPlaceholderNode, false, false);
1258             FrameState exceptionState = (FrameState) ensureNodeCreated(methodScope.caller, methodScope.callerLoopScope, methodScope.invokeData.exceptionStateOrderId);
1259 
1260             if (exceptionState.outerFrameState() == null && methodScope.caller != null) {
1261                 ensureOuterStateDecoded(methodScope.caller);
1262                 exceptionState.setOuterFrameState(methodScope.caller.outerState);
1263             }
1264             methodScope.exceptionState = exceptionState;
1265         }
1266     }
1267 
1268     @Override
1269     protected Node handleFloatingNodeAfterAdd(MethodScope s, LoopScope loopScope, Node node) {
1270         PEMethodScope methodScope = (PEMethodScope) s;
1271 
1272         if (methodScope.isInlinedMethod()) {
1273             if (node instanceof FrameState) {
1274                 FrameState frameState = (FrameState) node;
1275 
1276                 ensureOuterStateDecoded(methodScope);
1277                 if (frameState.bci < 0) {
1278                     ensureExceptionStateDecoded(methodScope);
1279                 }
1280                 List<ValueNode> invokeArgsList = null;
1281                 if (frameState.bci == BytecodeFrame.BEFORE_BCI) {
1282                     /*
1283                      * We know that the argument list is only used in this case, so avoid the List
1284                      * allocation for "normal" bcis.
1285                      */
1286                     invokeArgsList = Arrays.asList(methodScope.arguments);
1287                 }
1288                 return InliningUtil.processFrameState(frameState, methodScope.invokeData.invoke, null, methodScope.method, methodScope.exceptionState, methodScope.outerState, true,
1289                                 methodScope.method, invokeArgsList);
1290 
1291             } else if (node instanceof MonitorIdNode) {
1292                 ensureOuterStateDecoded(methodScope);
1293                 InliningUtil.processMonitorId(methodScope.outerState, (MonitorIdNode) node);
1294                 return node;
1295             }
1296         }
1297 
1298         return node;
1299     }
1300 }