1 /*
   2  * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 
  25 package org.graalvm.compiler.core.test;
  26 
  27 import static java.lang.reflect.Modifier.isStatic;
  28 import static jdk.vm.ci.runtime.JVMCICompiler.INVOCATION_ENTRY_BCI;
  29 import static org.graalvm.compiler.nodes.ConstantNode.getConstantNodes;
  30 import static org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin.InlineInfo.DO_NOT_INLINE_NO_EXCEPTION;
  31 import static org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin.InlineInfo.DO_NOT_INLINE_WITH_EXCEPTION;
  32 
  33 import java.lang.annotation.ElementType;
  34 import java.lang.annotation.Retention;
  35 import java.lang.annotation.RetentionPolicy;
  36 import java.lang.annotation.Target;
  37 import java.lang.reflect.Constructor;
  38 import java.lang.reflect.Executable;
  39 import java.lang.reflect.InvocationTargetException;
  40 import java.lang.reflect.Method;
  41 import java.util.ArrayList;
  42 import java.util.Arrays;
  43 import java.util.Collection;
  44 import java.util.Collections;
  45 import java.util.EnumMap;
  46 import java.util.List;
  47 import java.util.ListIterator;
  48 import java.util.Map;
  49 import java.util.Set;
  50 import java.util.concurrent.ConcurrentHashMap;
  51 import java.util.function.Supplier;
  52 
  53 import org.graalvm.compiler.api.directives.GraalDirectives;
  54 import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
  55 import org.graalvm.compiler.api.test.Graal;
  56 import org.graalvm.compiler.code.CompilationResult;
  57 import org.graalvm.compiler.core.CompilationPrinter;
  58 import org.graalvm.compiler.core.GraalCompiler;
  59 import org.graalvm.compiler.core.GraalCompiler.Request;
  60 import org.graalvm.compiler.core.common.CompilationIdentifier;
  61 import org.graalvm.compiler.core.common.type.StampFactory;
  62 import org.graalvm.compiler.core.target.Backend;
  63 import org.graalvm.compiler.debug.DebugContext;
  64 import org.graalvm.compiler.debug.DebugDumpHandler;
  65 import org.graalvm.compiler.debug.DebugDumpScope;
  66 import org.graalvm.compiler.debug.DebugHandlersFactory;
  67 import org.graalvm.compiler.debug.GraalError;
  68 import org.graalvm.compiler.debug.TTY;
  69 import org.graalvm.compiler.graph.Node;
  70 import org.graalvm.compiler.graph.NodeClass;
  71 import org.graalvm.compiler.graph.NodeMap;
  72 import org.graalvm.compiler.java.BytecodeParser;
  73 import org.graalvm.compiler.java.ComputeLoopFrequenciesClosure;
  74 import org.graalvm.compiler.java.GraphBuilderPhase;
  75 import org.graalvm.compiler.lir.asm.CompilationResultBuilderFactory;
  76 import org.graalvm.compiler.lir.phases.LIRSuites;
  77 import org.graalvm.compiler.nodeinfo.NodeInfo;
  78 import org.graalvm.compiler.nodeinfo.NodeSize;
  79 import org.graalvm.compiler.nodeinfo.Verbosity;
  80 import org.graalvm.compiler.nodes.BreakpointNode;
  81 import org.graalvm.compiler.nodes.Cancellable;
  82 import org.graalvm.compiler.nodes.ConstantNode;
  83 import org.graalvm.compiler.nodes.FixedWithNextNode;
  84 import org.graalvm.compiler.nodes.FrameState;
  85 import org.graalvm.compiler.nodes.FullInfopointNode;
  86 import org.graalvm.compiler.nodes.Invoke;
  87 import org.graalvm.compiler.nodes.InvokeNode;
  88 import org.graalvm.compiler.nodes.InvokeWithExceptionNode;
  89 import org.graalvm.compiler.nodes.ParameterNode;
  90 import org.graalvm.compiler.nodes.ProxyNode;
  91 import org.graalvm.compiler.nodes.ReturnNode;
  92 import org.graalvm.compiler.nodes.StructuredGraph;
  93 import org.graalvm.compiler.nodes.StructuredGraph.AllowAssumptions;
  94 import org.graalvm.compiler.nodes.StructuredGraph.Builder;
  95 import org.graalvm.compiler.nodes.StructuredGraph.ScheduleResult;
  96 import org.graalvm.compiler.nodes.ValueNode;
  97 import org.graalvm.compiler.nodes.cfg.Block;
  98 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
  99 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration.Plugins;
 100 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
 101 import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin;
 102 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin;
 103 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
 104 import org.graalvm.compiler.nodes.java.AccessFieldNode;
 105 import org.graalvm.compiler.nodes.spi.LoweringProvider;
 106 import org.graalvm.compiler.nodes.spi.Replacements;
 107 import org.graalvm.compiler.nodes.virtual.VirtualObjectNode;
 108 import org.graalvm.compiler.options.OptionValues;
 109 import org.graalvm.compiler.phases.BasePhase;
 110 import org.graalvm.compiler.phases.OptimisticOptimizations;
 111 import org.graalvm.compiler.phases.Phase;
 112 import org.graalvm.compiler.phases.PhaseSuite;
 113 import org.graalvm.compiler.phases.common.CanonicalizerPhase;
 114 import org.graalvm.compiler.loop.phases.ConvertDeoptimizeToGuardPhase;
 115 import org.graalvm.compiler.phases.common.inlining.InliningPhase;
 116 import org.graalvm.compiler.phases.common.inlining.info.InlineInfo;
 117 import org.graalvm.compiler.phases.common.inlining.policy.GreedyInliningPolicy;
 118 import org.graalvm.compiler.phases.schedule.SchedulePhase;
 119 import org.graalvm.compiler.phases.schedule.SchedulePhase.SchedulingStrategy;
 120 import org.graalvm.compiler.phases.tiers.HighTierContext;
 121 import org.graalvm.compiler.phases.tiers.MidTierContext;
 122 import org.graalvm.compiler.phases.tiers.Suites;
 123 import org.graalvm.compiler.phases.tiers.TargetProvider;
 124 import org.graalvm.compiler.phases.util.Providers;
 125 import org.graalvm.compiler.printer.GraalDebugHandlersFactory;
 126 import org.graalvm.compiler.runtime.RuntimeProvider;
 127 import org.graalvm.compiler.serviceprovider.JavaVersionUtil;
 128 import org.graalvm.compiler.test.AddExports;
 129 import org.graalvm.compiler.test.GraalTest;
 130 import org.graalvm.compiler.test.JLModule;
 131 import org.junit.After;
 132 import org.junit.Assert;
 133 import org.junit.Test;
 134 import org.junit.internal.AssumptionViolatedException;
 135 
 136 import jdk.vm.ci.code.Architecture;
 137 import jdk.vm.ci.code.BailoutException;
 138 import jdk.vm.ci.code.CodeCacheProvider;
 139 import jdk.vm.ci.code.InstalledCode;
 140 import jdk.vm.ci.code.TargetDescription;
 141 import jdk.vm.ci.meta.Assumptions.Assumption;
 142 import jdk.vm.ci.meta.ConstantReflectionProvider;
 143 import jdk.vm.ci.meta.DeoptimizationReason;
 144 import jdk.vm.ci.meta.JavaConstant;
 145 import jdk.vm.ci.meta.JavaKind;
 146 import jdk.vm.ci.meta.JavaType;
 147 import jdk.vm.ci.meta.MetaAccessProvider;
 148 import jdk.vm.ci.meta.ProfilingInfo;
 149 import jdk.vm.ci.meta.ResolvedJavaMethod;
 150 import jdk.vm.ci.meta.ResolvedJavaType;
 151 import jdk.vm.ci.meta.SpeculationLog;
 152 
 153 /**
 154  * Base class for compiler unit tests.
 155  * <p>
 156  * White box tests for compiler transformations use this pattern:
 157  * <ol>
 158  * <li>Create a graph by {@linkplain #parseEager parsing} a method.</li>
 159  * <li>Manually modify the graph (e.g. replace a parameter node with a constant).</li>
 160  * <li>Apply a transformation to the graph.</li>
 161  * <li>Assert that the transformed graph is equal to an expected graph.</li>
 162  * </ol>
 163  * <p>
 164  * See {@link InvokeHintsTest} as an example of a white box test.
 165  * <p>
 166  * Black box tests use the {@link #test(String, Object...)} or
 167  * {@link #testN(int, String, Object...)} to execute some method in the interpreter and compare its
 168  * result against that produced by a Graal compiled version of the method.
 169  * <p>
 170  * These tests will be run by the {@code mx unittest} command.
 171  */
 172 @AddExports({"java.base/jdk.internal.org.objectweb.asm", "java.base/jdk.internal.org.objectweb.asm.tree"})
 173 public abstract class GraalCompilerTest extends GraalTest {
 174 
 175     /**
 176      * Gets the initial option values provided by the Graal runtime. These are option values
 177      * typically parsed from the command line.
 178      */
 179     public static OptionValues getInitialOptions() {
 180         return Graal.getRequiredCapability(OptionValues.class);
 181     }
 182 
 183     private static final int BAILOUT_RETRY_LIMIT = 1;
 184     private final Providers providers;
 185     private final Backend backend;
 186 
 187     /**
 188      * Representative class for the {@code java.base} module.
 189      */
 190     public static final Class<?> JAVA_BASE = Class.class;
 191 
 192     /**
 193      * Exports the package named {@code packageName} declared in {@code moduleMember}'s module to
 194      * this object's module. This must be called before accessing packages that are no longer public
 195      * as of JDK 9.
 196      */
 197     protected final void exportPackage(Class<?> moduleMember, String packageName) {
 198         if (JavaVersionUtil.JAVA_SPEC > 8) {
 199             JLModule.exportPackageTo(moduleMember, packageName, getClass());
 200         }
 201     }
 202 
 203     /**
 204      * Denotes a test method that must be inlined by the {@link BytecodeParser}.
 205      */
 206     @Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
 207     @Retention(RetentionPolicy.RUNTIME)
 208     public @interface BytecodeParserForceInline {
 209     }
 210 
 211     /**
 212      * Denotes a test method that must never be inlined by the {@link BytecodeParser}.
 213      */
 214     @Retention(RetentionPolicy.RUNTIME)
 215     @Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
 216     public @interface BytecodeParserNeverInline {
 217         /**
 218          * Specifies if the call should be implemented with {@link InvokeWithExceptionNode} instead
 219          * of {@link InvokeNode}.
 220          */
 221         boolean invokeWithException() default false;
 222     }
 223 
 224     /**
 225      * Can be overridden by unit tests to verify properties of the graph.
 226      *
 227      * @param graph the graph at the end of HighTier
 228      * @throws AssertionError if the verification fails
 229      */
 230     protected void checkHighTierGraph(StructuredGraph graph) {
 231     }
 232 
 233     /**
 234      * Can be overridden by unit tests to verify properties of the graph.
 235      *
 236      * @param graph the graph at the end of MidTier
 237      * @throws AssertionError if the verification fails
 238      */
 239     protected void checkMidTierGraph(StructuredGraph graph) {
 240     }
 241 
 242     /**
 243      * Can be overridden by unit tests to verify properties of the graph.
 244      *
 245      * @param graph the graph at the end of LowTier
 246      * @throws AssertionError if the verification fails
 247      */
 248     protected void checkLowTierGraph(StructuredGraph graph) {
 249     }
 250 
 251     protected static void breakpoint() {
 252     }
 253 
 254     @SuppressWarnings("unused")
 255     protected static void breakpoint(int arg0) {
 256     }
 257 
 258     protected static void shouldBeOptimizedAway() {
 259     }
 260 
 261     protected Suites createSuites(OptionValues opts) {
 262         Suites ret = backend.getSuites().getDefaultSuites(opts).copy();
 263         ListIterator<BasePhase<? super HighTierContext>> iter = ret.getHighTier().findPhase(ConvertDeoptimizeToGuardPhase.class, true);
 264         if (iter == null) {
 265             /*
 266              * in the economy configuration, we don't have the ConvertDeoptimizeToGuard phase, so we
 267              * just select the first CanonicalizerPhase in HighTier
 268              */
 269             iter = ret.getHighTier().findPhase(CanonicalizerPhase.class);
 270         }
 271         iter.add(new Phase() {
 272 
 273             @Override
 274             protected void run(StructuredGraph graph) {
 275                 ComputeLoopFrequenciesClosure.compute(graph);
 276             }
 277 
 278             @Override
 279             public float codeSizeIncrease() {
 280                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 281             }
 282 
 283             @Override
 284             protected CharSequence getName() {
 285                 return "ComputeLoopFrequenciesPhase";
 286             }
 287         });
 288         ret.getHighTier().appendPhase(new Phase() {
 289 
 290             @Override
 291             protected void run(StructuredGraph graph) {
 292                 checkHighTierGraph(graph);
 293             }
 294 
 295             @Override
 296             public float codeSizeIncrease() {
 297                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 298             }
 299 
 300             @Override
 301             protected CharSequence getName() {
 302                 return "CheckGraphPhase";
 303             }
 304         });
 305         ret.getMidTier().appendPhase(new Phase() {
 306 
 307             @Override
 308             protected void run(StructuredGraph graph) {
 309                 checkMidTierGraph(graph);
 310             }
 311 
 312             @Override
 313             public float codeSizeIncrease() {
 314                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 315             }
 316 
 317             @Override
 318             protected CharSequence getName() {
 319                 return "CheckGraphPhase";
 320             }
 321         });
 322         ret.getLowTier().appendPhase(new Phase() {
 323 
 324             @Override
 325             protected void run(StructuredGraph graph) {
 326                 checkLowTierGraph(graph);
 327             }
 328 
 329             @Override
 330             public float codeSizeIncrease() {
 331                 return NodeSize.IGNORE_SIZE_CONTRACT_FACTOR;
 332             }
 333 
 334             @Override
 335             protected CharSequence getName() {
 336                 return "CheckGraphPhase";
 337             }
 338         });
 339         return ret;
 340     }
 341 
 342     protected LIRSuites createLIRSuites(OptionValues opts) {
 343         LIRSuites ret = backend.getSuites().getDefaultLIRSuites(opts).copy();
 344         return ret;
 345     }
 346 
 347     public GraalCompilerTest() {
 348         this.backend = Graal.getRequiredCapability(RuntimeProvider.class).getHostBackend();
 349         this.providers = getBackend().getProviders();
 350     }
 351 
 352     /**
 353      * Set up a test for a non-default backend. The test should check (via {@link #getBackend()} )
 354      * whether the desired backend is available.
 355      *
 356      * @param arch the name of the desired backend architecture
 357      */
 358     public GraalCompilerTest(Class<? extends Architecture> arch) {
 359         RuntimeProvider runtime = Graal.getRequiredCapability(RuntimeProvider.class);
 360         Backend b = runtime.getBackend(arch);
 361         if (b != null) {
 362             this.backend = b;
 363         } else {
 364             // Fall back to the default/host backend
 365             this.backend = runtime.getHostBackend();
 366         }
 367         this.providers = backend.getProviders();
 368     }
 369 
 370     /**
 371      * Set up a test for a non-default backend.
 372      *
 373      * @param backend the desired backend
 374      */
 375     public GraalCompilerTest(Backend backend) {
 376         this.backend = backend;
 377         this.providers = backend.getProviders();
 378     }
 379 
 380     @Override
 381     @After
 382     public void afterTest() {
 383         if (invocationPluginExtensions != null) {
 384             synchronized (this) {
 385                 if (invocationPluginExtensions != null) {
 386                     extendedInvocationPlugins.removeTestPlugins(invocationPluginExtensions);
 387                     extendedInvocationPlugins = null;
 388                     invocationPluginExtensions = null;
 389                 }
 390             }
 391         }
 392         super.afterTest();
 393     }
 394 
 395     /**
 396      * Gets a {@link DebugContext} object corresponding to {@code options}, creating a new one if
 397      * none currently exists. Debug contexts created by this method will have their
 398      * {@link DebugDumpHandler}s closed in {@link #afterTest()}.
 399      */
 400     protected DebugContext getDebugContext() {
 401         return getDebugContext(getInitialOptions(), null, null);
 402     }
 403 
 404     @Override
 405     protected Collection<DebugHandlersFactory> getDebugHandlersFactories() {
 406         return Collections.singletonList(new GraalDebugHandlersFactory(getSnippetReflection()));
 407     }
 408 
 409     protected void assertEquals(StructuredGraph expected, StructuredGraph graph) {
 410         assertEquals(expected, graph, false, true);
 411     }
 412 
 413     protected int countUnusedConstants(StructuredGraph graph) {
 414         int total = 0;
 415         for (ConstantNode node : getConstantNodes(graph)) {
 416             if (node.hasNoUsages()) {
 417                 total++;
 418             }
 419         }
 420         return total;
 421     }
 422 
 423     protected int getNodeCountExcludingUnusedConstants(StructuredGraph graph) {
 424         return graph.getNodeCount() - countUnusedConstants(graph);
 425     }
 426 
 427     protected void assertEquals(StructuredGraph expected, StructuredGraph graph, boolean excludeVirtual, boolean checkConstants) {
 428         String expectedString = getCanonicalGraphString(expected, excludeVirtual, checkConstants);
 429         String actualString = getCanonicalGraphString(graph, excludeVirtual, checkConstants);
 430         String mismatchString = compareGraphStrings(expected, expectedString, graph, actualString);
 431 
 432         if (!excludeVirtual && getNodeCountExcludingUnusedConstants(expected) != getNodeCountExcludingUnusedConstants(graph)) {
 433             expected.getDebug().dump(DebugContext.BASIC_LEVEL, expected, "Node count not matching - expected");
 434             graph.getDebug().dump(DebugContext.BASIC_LEVEL, graph, "Node count not matching - actual");
 435             Assert.fail("Graphs do not have the same number of nodes: " + expected.getNodeCount() + " vs. " + graph.getNodeCount() + "\n" + mismatchString);
 436         }
 437         if (!expectedString.equals(actualString)) {
 438             expected.getDebug().dump(DebugContext.BASIC_LEVEL, expected, "mismatching graphs - expected");
 439             graph.getDebug().dump(DebugContext.BASIC_LEVEL, graph, "mismatching graphs - actual");
 440             Assert.fail(mismatchString);
 441         }
 442     }
 443 
 444     private static String compareGraphStrings(StructuredGraph expectedGraph, String expectedString, StructuredGraph actualGraph, String actualString) {
 445         if (!expectedString.equals(actualString)) {
 446             String[] expectedLines = expectedString.split("\n");
 447             String[] actualLines = actualString.split("\n");
 448             int diffIndex = -1;
 449             int limit = Math.min(actualLines.length, expectedLines.length);
 450             String marker = " <<<";
 451             for (int i = 0; i < limit; i++) {
 452                 if (!expectedLines[i].equals(actualLines[i])) {
 453                     diffIndex = i;
 454                     break;
 455                 }
 456             }
 457             if (diffIndex == -1) {
 458                 // Prefix is the same so add some space after the prefix
 459                 diffIndex = limit;
 460                 if (actualLines.length == limit) {
 461                     actualLines = Arrays.copyOf(actualLines, limit + 1);
 462                     actualLines[diffIndex] = "";
 463                 } else {
 464                     assert expectedLines.length == limit;
 465                     expectedLines = Arrays.copyOf(expectedLines, limit + 1);
 466                     expectedLines[diffIndex] = "";
 467                 }
 468             }
 469             // Place a marker next to the first line that differs
 470             expectedLines[diffIndex] = expectedLines[diffIndex] + marker;
 471             actualLines[diffIndex] = actualLines[diffIndex] + marker;
 472             String ediff = String.join("\n", expectedLines);
 473             String adiff = String.join("\n", actualLines);
 474             return "mismatch in graphs:\n========= expected (" + expectedGraph + ") =========\n" + ediff + "\n\n========= actual (" + actualGraph + ") =========\n" + adiff;
 475         } else {
 476             return "mismatch in graphs";
 477         }
 478     }
 479 
 480     protected void assertOptimizedAway(StructuredGraph g) {
 481         Assert.assertEquals(0, g.getNodes().filter(NotOptimizedNode.class).count());
 482     }
 483 
 484     protected void assertConstantReturn(StructuredGraph graph, int value) {
 485         String graphString = getCanonicalGraphString(graph, false, true);
 486         Assert.assertEquals("unexpected number of ReturnNodes: " + graphString, graph.getNodes(ReturnNode.TYPE).count(), 1);
 487         ValueNode result = graph.getNodes(ReturnNode.TYPE).first().result();
 488         Assert.assertTrue("unexpected ReturnNode result node: " + graphString, result.isConstant());
 489         Assert.assertEquals("unexpected ReturnNode result kind: " + graphString, result.asJavaConstant().getJavaKind(), JavaKind.Int);
 490         Assert.assertEquals("unexpected ReturnNode result: " + graphString, result.asJavaConstant().asInt(), value);
 491     }
 492 
 493     protected static String getCanonicalGraphString(StructuredGraph graph, boolean excludeVirtual, boolean checkConstants) {
 494         SchedulePhase schedule = new SchedulePhase(SchedulingStrategy.EARLIEST);
 495         schedule.apply(graph);
 496         ScheduleResult scheduleResult = graph.getLastSchedule();
 497 
 498         NodeMap<Integer> canonicalId = graph.createNodeMap();
 499         int nextId = 0;
 500 
 501         List<String> constantsLines = new ArrayList<>();
 502 
 503         StringBuilder result = new StringBuilder();
 504         for (Block block : scheduleResult.getCFG().getBlocks()) {
 505             result.append("Block ").append(block).append(' ');
 506             if (block == scheduleResult.getCFG().getStartBlock()) {
 507                 result.append("* ");
 508             }
 509             result.append("-> ");
 510             for (Block succ : block.getSuccessors()) {
 511                 result.append(succ).append(' ');
 512             }
 513             result.append('\n');
 514             for (Node node : scheduleResult.getBlockToNodesMap().get(block)) {
 515                 if (node instanceof ValueNode && node.isAlive()) {
 516                     if (!excludeVirtual || !(node instanceof VirtualObjectNode || node instanceof ProxyNode || node instanceof FullInfopointNode || node instanceof ParameterNode)) {
 517                         if (node instanceof ConstantNode) {
 518                             String name = checkConstants ? node.toString(Verbosity.Name) : node.getClass().getSimpleName();
 519                             if (excludeVirtual) {
 520                                 constantsLines.add(name);
 521                             } else {
 522                                 constantsLines.add(name + "    (" + filteredUsageCount(node) + ")");
 523                             }
 524                         } else {
 525                             int id;
 526                             if (canonicalId.get(node) != null) {
 527                                 id = canonicalId.get(node);
 528                             } else {
 529                                 id = nextId++;
 530                                 canonicalId.set(node, id);
 531                             }
 532                             String name = node.getClass().getSimpleName();
 533                             result.append("  ").append(id).append('|').append(name);
 534                             if (node instanceof AccessFieldNode) {
 535                                 result.append('#');
 536                                 result.append(((AccessFieldNode) node).field());
 537                             }
 538                             if (!excludeVirtual) {
 539                                 result.append("    (");
 540                                 result.append(filteredUsageCount(node));
 541                                 result.append(')');
 542                             }
 543                             result.append('\n');
 544                         }
 545                     }
 546                 }
 547             }
 548         }
 549 
 550         StringBuilder constantsLinesResult = new StringBuilder();
 551         constantsLinesResult.append(constantsLines.size()).append(" constants:\n");
 552         Collections.sort(constantsLines);
 553         for (String s : constantsLines) {
 554             constantsLinesResult.append(s);
 555             constantsLinesResult.append('\n');
 556         }
 557 
 558         return constantsLinesResult.toString() + result.toString();
 559     }
 560 
 561     /**
 562      * @return usage count excluding {@link FrameState} usages
 563      */
 564     private static int filteredUsageCount(Node node) {
 565         return node.usages().filter(n -> !(n instanceof FrameState)).count();
 566     }
 567 
 568     /**
 569      * @param graph
 570      * @return a scheduled textual dump of {@code graph} .
 571      */
 572     protected static String getScheduledGraphString(StructuredGraph graph) {
 573         SchedulePhase schedule = new SchedulePhase(SchedulingStrategy.EARLIEST_WITH_GUARD_ORDER);
 574         schedule.apply(graph);
 575         ScheduleResult scheduleResult = graph.getLastSchedule();
 576 
 577         StringBuilder result = new StringBuilder();
 578         Block[] blocks = scheduleResult.getCFG().getBlocks();
 579         for (Block block : blocks) {
 580             result.append("Block ").append(block).append(' ');
 581             if (block == scheduleResult.getCFG().getStartBlock()) {
 582                 result.append("* ");
 583             }
 584             result.append("-> ");
 585             for (Block succ : block.getSuccessors()) {
 586                 result.append(succ).append(' ');
 587             }
 588             result.append('\n');
 589             for (Node node : scheduleResult.getBlockToNodesMap().get(block)) {
 590                 result.append(String.format("%1S\n", node));
 591             }
 592         }
 593         return result.toString();
 594     }
 595 
 596     protected Backend getBackend() {
 597         return backend;
 598     }
 599 
 600     protected final Providers getProviders() {
 601         return providers;
 602     }
 603 
 604     protected HighTierContext getDefaultHighTierContext() {
 605         return new HighTierContext(getProviders(), getDefaultGraphBuilderSuite(), getOptimisticOptimizations());
 606     }
 607 
 608     protected MidTierContext getDefaultMidTierContext() {
 609         return new MidTierContext(getProviders(), getTargetProvider(), getOptimisticOptimizations(), null);
 610     }
 611 
 612     protected SnippetReflectionProvider getSnippetReflection() {
 613         return Graal.getRequiredCapability(SnippetReflectionProvider.class);
 614     }
 615 
 616     protected TargetDescription getTarget() {
 617         return getTargetProvider().getTarget();
 618     }
 619 
 620     protected TargetProvider getTargetProvider() {
 621         return getBackend();
 622     }
 623 
 624     protected CodeCacheProvider getCodeCache() {
 625         return getProviders().getCodeCache();
 626     }
 627 
 628     protected ConstantReflectionProvider getConstantReflection() {
 629         return getProviders().getConstantReflection();
 630     }
 631 
 632     protected MetaAccessProvider getMetaAccess() {
 633         return getProviders().getMetaAccess();
 634     }
 635 
 636     protected LoweringProvider getLowerer() {
 637         return getProviders().getLowerer();
 638     }
 639 
 640     protected final BasePhase<HighTierContext> createInliningPhase() {
 641         return createInliningPhase(new CanonicalizerPhase());
 642     }
 643 
 644     protected BasePhase<HighTierContext> createInliningPhase(CanonicalizerPhase canonicalizer) {
 645         return createInliningPhase(null, canonicalizer);
 646     }
 647 
 648     static class GreedyTestInliningPolicy extends GreedyInliningPolicy {
 649         GreedyTestInliningPolicy(Map<Invoke, Double> hints) {
 650             super(hints);
 651         }
 652 
 653         @Override
 654         protected int previousLowLevelGraphSize(InlineInfo info) {
 655             // Ignore previous compiles for tests
 656             return 0;
 657         }
 658     }
 659 
 660     protected BasePhase<HighTierContext> createInliningPhase(Map<Invoke, Double> hints, CanonicalizerPhase canonicalizer) {
 661         return new InliningPhase(new GreedyTestInliningPolicy(hints), canonicalizer);
 662     }
 663 
 664     protected CompilationIdentifier getCompilationId(ResolvedJavaMethod method) {
 665         return getBackend().getCompilationIdentifier(method);
 666     }
 667 
 668     protected CompilationIdentifier getOrCreateCompilationId(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) {
 669         if (graph != null) {
 670             return graph.compilationId();
 671         }
 672         return getCompilationId(installedCodeOwner);
 673     }
 674 
 675     protected void testN(int n, final String name, final Object... args) {
 676         final List<Throwable> errors = new ArrayList<>(n);
 677         Thread[] threads = new Thread[n];
 678         for (int i = 0; i < n; i++) {
 679             Thread t = new Thread(i + ":" + name) {
 680 
 681                 @Override
 682                 public void run() {
 683                     try {
 684                         test(name, args);
 685                     } catch (Throwable e) {
 686                         errors.add(e);
 687                     }
 688                 }
 689             };
 690             threads[i] = t;
 691             t.start();
 692         }
 693         for (int i = 0; i < n; i++) {
 694             try {
 695                 threads[i].join();
 696             } catch (InterruptedException e) {
 697                 errors.add(e);
 698             }
 699         }
 700         if (!errors.isEmpty()) {
 701             throw new MultiCauseAssertionError(errors.size() + " failures", errors.toArray(new Throwable[errors.size()]));
 702         }
 703     }
 704 
 705     protected Object referenceInvoke(ResolvedJavaMethod method, Object receiver, Object... args)
 706                     throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
 707         return invoke(method, receiver, args);
 708     }
 709 
 710     public static class Result {
 711 
 712         public final Object returnValue;
 713         public final Throwable exception;
 714 
 715         public Result(Object returnValue, Throwable exception) {
 716             this.returnValue = returnValue;
 717             this.exception = exception;
 718         }
 719 
 720         @Override
 721         public String toString() {
 722             return exception == null ? returnValue == null ? "null" : returnValue.toString() : "!" + exception;
 723         }
 724     }
 725 
 726     /**
 727      * Called before a test is executed.
 728      */
 729     protected void before(@SuppressWarnings("unused") ResolvedJavaMethod method) {
 730     }
 731 
 732     /**
 733      * Called after a test is executed.
 734      */
 735     protected void after() {
 736     }
 737 
 738     protected Result executeExpected(ResolvedJavaMethod method, Object receiver, Object... args) {
 739         before(method);
 740         try {
 741             // This gives us both the expected return value as well as ensuring that the method to
 742             // be compiled is fully resolved
 743             return new Result(referenceInvoke(method, receiver, args), null);
 744         } catch (InvocationTargetException e) {
 745             return new Result(null, e.getTargetException());
 746         } catch (Exception e) {
 747             throw new RuntimeException(e);
 748         } finally {
 749             after();
 750         }
 751     }
 752 
 753     protected Result executeActual(ResolvedJavaMethod method, Object receiver, Object... args) {
 754         return executeActual(getInitialOptions(), method, receiver, args);
 755     }
 756 
 757     protected Result executeActual(OptionValues options, ResolvedJavaMethod method, Object receiver, Object... args) {
 758         before(method);
 759         Object[] executeArgs = argsWithReceiver(receiver, args);
 760 
 761         checkArgs(method, executeArgs);
 762 
 763         InstalledCode compiledMethod = getCode(method, options);
 764         try {
 765             return new Result(compiledMethod.executeVarargs(executeArgs), null);
 766         } catch (Throwable e) {
 767             return new Result(null, e);
 768         } finally {
 769             after();
 770         }
 771     }
 772 
 773     protected void checkArgs(ResolvedJavaMethod method, Object[] args) {
 774         JavaType[] sig = method.toParameterTypes();
 775         Assert.assertEquals(sig.length, args.length);
 776         for (int i = 0; i < args.length; i++) {
 777             JavaType javaType = sig[i];
 778             JavaKind kind = javaType.getJavaKind();
 779             Object arg = args[i];
 780             if (kind == JavaKind.Object) {
 781                 if (arg != null && javaType instanceof ResolvedJavaType) {
 782                     ResolvedJavaType resolvedJavaType = (ResolvedJavaType) javaType;
 783                     Assert.assertTrue(resolvedJavaType + " from " + getMetaAccess().lookupJavaType(arg.getClass()), resolvedJavaType.isAssignableFrom(getMetaAccess().lookupJavaType(arg.getClass())));
 784                 }
 785             } else {
 786                 Assert.assertNotNull(arg);
 787                 Assert.assertEquals(kind.toBoxedJavaClass(), arg.getClass());
 788             }
 789         }
 790     }
 791 
 792     /**
 793      * Prepends a non-null receiver argument to a given list or args.
 794      *
 795      * @param receiver the receiver argument to prepend if it is non-null
 796      */
 797     protected Object[] argsWithReceiver(Object receiver, Object... args) {
 798         Object[] executeArgs;
 799         if (receiver == null) {
 800             executeArgs = args;
 801         } else {
 802             executeArgs = new Object[args.length + 1];
 803             executeArgs[0] = receiver;
 804             for (int i = 0; i < args.length; i++) {
 805                 executeArgs[i + 1] = args[i];
 806             }
 807         }
 808         return applyArgSuppliers(executeArgs);
 809     }
 810 
 811     protected final Result test(String name, Object... args) {
 812         return test(getInitialOptions(), name, args);
 813     }
 814 
 815     protected final Result test(OptionValues options, String name, Object... args) {
 816         try {
 817             ResolvedJavaMethod method = getResolvedJavaMethod(name);
 818             Object receiver = method.isStatic() ? null : this;
 819             return test(options, method, receiver, args);
 820         } catch (AssumptionViolatedException e) {
 821             // Suppress so that subsequent calls to this method within the
 822             // same Junit @Test annotated method can proceed.
 823             return null;
 824         }
 825     }
 826 
 827     /**
 828      * Type denoting a lambda that supplies a fresh value each time it is called. This is useful
 829      * when supplying an argument to {@link GraalCompilerTest#test(String, Object...)} where the
 830      * test modifies the state of the argument (e.g., updates a field).
 831      */
 832     @FunctionalInterface
 833     public interface ArgSupplier extends Supplier<Object> {
 834     }
 835 
 836     /**
 837      * Convenience method for using an {@link ArgSupplier} lambda in a varargs list.
 838      */
 839     public static Object supply(ArgSupplier supplier) {
 840         return supplier;
 841     }
 842 
 843     protected Result test(ResolvedJavaMethod method, Object receiver, Object... args) {
 844         return test(getInitialOptions(), method, receiver, args);
 845     }
 846 
 847     protected Result test(OptionValues options, ResolvedJavaMethod method, Object receiver, Object... args) {
 848         Result expect = executeExpected(method, receiver, args);
 849         if (getCodeCache() != null) {
 850             testAgainstExpected(options, method, expect, receiver, args);
 851         }
 852         return expect;
 853     }
 854 
 855     /**
 856      * Process a given set of arguments, converting any {@link ArgSupplier} argument to the argument
 857      * it supplies.
 858      */
 859     protected Object[] applyArgSuppliers(Object... args) {
 860         Object[] res = args;
 861         for (int i = 0; i < args.length; i++) {
 862             if (args[i] instanceof ArgSupplier) {
 863                 if (res == args) {
 864                     res = args.clone();
 865                 }
 866                 res[i] = ((ArgSupplier) args[i]).get();
 867             }
 868         }
 869         return res;
 870     }
 871 
 872     protected final void testAgainstExpected(ResolvedJavaMethod method, Result expect, Object receiver, Object... args) {
 873         testAgainstExpected(getInitialOptions(), method, expect, Collections.<DeoptimizationReason> emptySet(), receiver, args);
 874     }
 875 
 876     protected void testAgainstExpected(ResolvedJavaMethod method, Result expect, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) {
 877         testAgainstExpected(getInitialOptions(), method, expect, shouldNotDeopt, receiver, args);
 878     }
 879 
 880     protected final void testAgainstExpected(OptionValues options, ResolvedJavaMethod method, Result expect, Object receiver, Object... args) {
 881         testAgainstExpected(options, method, expect, Collections.<DeoptimizationReason> emptySet(), receiver, args);
 882     }
 883 
 884     protected void testAgainstExpected(OptionValues options, ResolvedJavaMethod method, Result expect, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) {
 885         Result actual = executeActualCheckDeopt(options, method, shouldNotDeopt, receiver, args);
 886         assertEquals(expect, actual);
 887     }
 888 
 889     protected Result executeActualCheckDeopt(OptionValues options, ResolvedJavaMethod method, Set<DeoptimizationReason> shouldNotDeopt, Object receiver, Object... args) {
 890         Map<DeoptimizationReason, Integer> deoptCounts = new EnumMap<>(DeoptimizationReason.class);
 891         ProfilingInfo profile = method.getProfilingInfo();
 892         for (DeoptimizationReason reason : shouldNotDeopt) {
 893             deoptCounts.put(reason, profile.getDeoptimizationCount(reason));
 894         }
 895         Result actual = executeActual(options, method, receiver, args);
 896         profile = method.getProfilingInfo(); // profile can change after execution
 897         for (DeoptimizationReason reason : shouldNotDeopt) {
 898             Assert.assertEquals("wrong number of deopt counts for " + reason, (int) deoptCounts.get(reason), profile.getDeoptimizationCount(reason));
 899         }
 900         return actual;
 901     }
 902 
 903     private static final List<Class<?>> C2_OMIT_STACK_TRACE_IN_FAST_THROW_EXCEPTIONS = Arrays.asList(
 904                     ArithmeticException.class,
 905                     ArrayIndexOutOfBoundsException.class,
 906                     ArrayStoreException.class,
 907                     ClassCastException.class,
 908                     NullPointerException.class);
 909 
 910     protected void assertEquals(Result expect, Result actual) {
 911         if (expect.exception != null) {
 912             Assert.assertTrue("expected " + expect.exception, actual.exception != null);
 913             Assert.assertEquals("Exception class", expect.exception.getClass(), actual.exception.getClass());
 914             // C2 can optimize out the stack trace and message in some cases
 915             if (expect.exception.getMessage() != null || !C2_OMIT_STACK_TRACE_IN_FAST_THROW_EXCEPTIONS.contains(expect.exception.getClass())) {
 916                 Assert.assertEquals("Exception message", expect.exception.getMessage(), actual.exception.getMessage());
 917             }
 918         } else {
 919             if (actual.exception != null) {
 920                 throw new AssertionError("expected " + expect.returnValue + " but got an exception", actual.exception);
 921             }
 922             assertDeepEquals(expect.returnValue, actual.returnValue);
 923         }
 924     }
 925 
 926     private Map<ResolvedJavaMethod, InstalledCode> cache = new ConcurrentHashMap<>();
 927 
 928     /**
 929      * Gets installed code for a given method, compiling it first if necessary. The graph is parsed
 930      * {@link #parseEager eagerly}.
 931      */
 932     protected final InstalledCode getCode(ResolvedJavaMethod method) {
 933         return getCode(method, null, false, false, getInitialOptions());
 934     }
 935 
 936     protected final InstalledCode getCode(ResolvedJavaMethod method, OptionValues options) {
 937         return getCode(method, null, false, false, options);
 938     }
 939 
 940     /**
 941      * Gets installed code for a given method, compiling it first if necessary.
 942      *
 943      * @param installedCodeOwner the method the compiled code will be associated with when installed
 944      * @param graph the graph to be compiled. If null, a graph will be obtained from
 945      *            {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}.
 946      */
 947     protected final InstalledCode getCode(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) {
 948         return getCode(installedCodeOwner, graph, false, false, graph == null ? getInitialOptions() : graph.getOptions());
 949     }
 950 
 951     /**
 952      * Gets installed code for a given method and graph, compiling it first if necessary.
 953      *
 954      * @param installedCodeOwner the method the compiled code will be associated with when installed
 955      * @param graph the graph to be compiled. If null, a graph will be obtained from
 956      *            {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}.
 957      * @param forceCompile specifies whether to ignore any previous code cached for the (method,
 958      *            key) pair
 959      */
 960     protected final InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile) {
 961         return getCode(installedCodeOwner, graph, forceCompile, false, graph == null ? getInitialOptions() : graph.getOptions());
 962     }
 963 
 964     /**
 965      * Gets installed code for a given method and graph, compiling it first if necessary.
 966      *
 967      * @param installedCodeOwner the method the compiled code will be associated with when installed
 968      * @param graph the graph to be compiled. If null, a graph will be obtained from
 969      *            {@code installedCodeOwner} via {@link #parseForCompile(ResolvedJavaMethod)}.
 970      * @param forceCompile specifies whether to ignore any previous code cached for the (method,
 971      *            key) pair
 972      * @param installAsDefault specifies whether to install as the default implementation
 973      * @param options the options that will be used in {@link #parseForCompile(ResolvedJavaMethod)}
 974      */
 975     @SuppressWarnings("try")
 976     protected InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile, boolean installAsDefault, OptionValues options) {
 977         boolean useCache = !forceCompile && getArgumentToBind() == null;
 978         if (useCache && graph == null) {
 979             InstalledCode cached = cache.get(installedCodeOwner);
 980             if (cached != null) {
 981                 if (cached.isValid()) {
 982                     return cached;
 983                 }
 984             }
 985         }
 986         // loop for retrying compilation
 987         for (int retry = 0; retry <= BAILOUT_RETRY_LIMIT; retry++) {
 988             final CompilationIdentifier id = getOrCreateCompilationId(installedCodeOwner, graph);
 989 
 990             InstalledCode installedCode = null;
 991             StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner, id, options) : graph;
 992             DebugContext debug = graphToCompile.getDebug();
 993 
 994             try (AllocSpy spy = AllocSpy.open(installedCodeOwner); DebugContext.Scope ds = debug.scope("Compiling", new DebugDumpScope(id.toString(CompilationIdentifier.Verbosity.ID), true))) {
 995                 CompilationPrinter printer = CompilationPrinter.begin(options, id, installedCodeOwner, INVOCATION_ENTRY_BCI);
 996                 CompilationResult compResult = compile(installedCodeOwner, graphToCompile, new CompilationResult(graphToCompile.compilationId()), id, options);
 997                 printer.finish(compResult);
 998 
 999                 try (DebugContext.Scope s = debug.scope("CodeInstall", getCodeCache(), installedCodeOwner, compResult);
1000                                 DebugContext.Activation a = debug.activate()) {
1001                     try {
1002                         if (installAsDefault) {
1003                             installedCode = addDefaultMethod(debug, installedCodeOwner, compResult);
1004                         } else {
1005                             installedCode = addMethod(debug, installedCodeOwner, compResult);
1006                         }
1007                         if (installedCode == null) {
1008                             throw new GraalError("Could not install code for " + installedCodeOwner.format("%H.%n(%p)"));
1009                         }
1010                     } catch (BailoutException e) {
1011                         if (retry < BAILOUT_RETRY_LIMIT && graph == null && !e.isPermanent()) {
1012                             // retry (if there is no predefined graph)
1013                             TTY.println(String.format("Restart compilation %s (%s) due to a non-permanent bailout!", installedCodeOwner, id));
1014                             continue;
1015                         }
1016                         throw e;
1017                     }
1018                 } catch (Throwable e) {
1019                     throw debug.handle(e);
1020                 }
1021             } catch (Throwable e) {
1022                 throw debug.handle(e);
1023             }
1024 
1025             if (useCache) {
1026                 cache.put(installedCodeOwner, installedCode);
1027             }
1028             return installedCode;
1029         }
1030         throw GraalError.shouldNotReachHere();
1031     }
1032 
1033     /**
1034      * Used to produce a graph for a method about to be compiled by
1035      * {@link #compile(ResolvedJavaMethod, StructuredGraph)} if the second parameter to that method
1036      * is null.
1037      *
1038      * The default implementation in {@link GraalCompilerTest} is to call {@link #parseEager}.
1039      */
1040     protected StructuredGraph parseForCompile(ResolvedJavaMethod method, OptionValues options) {
1041         return parseEager(method, AllowAssumptions.YES, getCompilationId(method), options);
1042     }
1043 
1044     protected final StructuredGraph parseForCompile(ResolvedJavaMethod method, DebugContext debug) {
1045         return parseEager(method, AllowAssumptions.YES, debug);
1046     }
1047 
1048     protected final StructuredGraph parseForCompile(ResolvedJavaMethod method) {
1049         return parseEager(method, AllowAssumptions.YES, getCompilationId(method), getInitialOptions());
1050     }
1051 
1052     protected StructuredGraph parseForCompile(ResolvedJavaMethod method, CompilationIdentifier compilationId, OptionValues options) {
1053         return parseEager(method, AllowAssumptions.YES, compilationId, options);
1054     }
1055 
1056     /**
1057      * Compiles a given method.
1058      *
1059      * @param installedCodeOwner the method the compiled code will be associated with when installed
1060      * @param graph the graph to be compiled for {@code installedCodeOwner}. If null, a graph will
1061      *            be obtained from {@code installedCodeOwner} via
1062      *            {@link #parseForCompile(ResolvedJavaMethod)}.
1063      */
1064     protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph) {
1065         OptionValues options = graph == null ? getInitialOptions() : graph.getOptions();
1066         CompilationIdentifier compilationId = getOrCreateCompilationId(installedCodeOwner, graph);
1067         return compile(installedCodeOwner, graph, new CompilationResult(compilationId), compilationId, options);
1068     }
1069 
1070     protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, CompilationIdentifier compilationId) {
1071         OptionValues options = graph == null ? getInitialOptions() : graph.getOptions();
1072         return compile(installedCodeOwner, graph, new CompilationResult(compilationId), compilationId, options);
1073     }
1074 
1075     protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, OptionValues options) {
1076         assert graph == null || graph.getOptions() == options;
1077         CompilationIdentifier compilationId = getOrCreateCompilationId(installedCodeOwner, graph);
1078         return compile(installedCodeOwner, graph, new CompilationResult(compilationId), compilationId, options);
1079     }
1080 
1081     protected OptimisticOptimizations getOptimisticOptimizations() {
1082         return OptimisticOptimizations.ALL;
1083     }
1084 
1085     /**
1086      * Compiles a given method.
1087      *
1088      * @param installedCodeOwner the method the compiled code will be associated with when installed
1089      * @param graph the graph to be compiled for {@code installedCodeOwner}. If null, a graph will
1090      *            be obtained from {@code installedCodeOwner} via
1091      *            {@link #parseForCompile(ResolvedJavaMethod)}.
1092      * @param compilationId
1093      */
1094     @SuppressWarnings("try")
1095     protected CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, CompilationResult compilationResult, CompilationIdentifier compilationId, OptionValues options) {
1096         StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner, compilationId, options) : graph;
1097         lastCompiledGraph = graphToCompile;
1098         DebugContext debug = graphToCompile.getDebug();
1099         try (DebugContext.Scope s = debug.scope("Compile", graphToCompile)) {
1100             assert options != null;
1101             Request<CompilationResult> request = new Request<>(graphToCompile, installedCodeOwner, getProviders(), getBackend(), getDefaultGraphBuilderSuite(), getOptimisticOptimizations(),
1102                             graphToCompile.getProfilingInfo(), createSuites(options), createLIRSuites(options), compilationResult, CompilationResultBuilderFactory.Default, true);
1103             return GraalCompiler.compile(request);
1104         } catch (Throwable e) {
1105             throw debug.handle(e);
1106         }
1107     }
1108 
1109     protected StructuredGraph getFinalGraph(String method) {
1110         return getFinalGraph(getResolvedJavaMethod(method));
1111     }
1112 
1113     protected StructuredGraph getFinalGraph(ResolvedJavaMethod method) {
1114         StructuredGraph graph = parseForCompile(method);
1115         applyFrontEnd(graph);
1116         return graph;
1117     }
1118 
1119     @SuppressWarnings("try")
1120     protected void applyFrontEnd(StructuredGraph graph) {
1121         DebugContext debug = graph.getDebug();
1122         try (DebugContext.Scope s = debug.scope("FrontEnd", graph)) {
1123             GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), getOptimisticOptimizations(), graph.getProfilingInfo(), createSuites(graph.getOptions()));
1124         } catch (Throwable e) {
1125             throw debug.handle(e);
1126         }
1127     }
1128 
1129     protected StructuredGraph lastCompiledGraph;
1130 
1131     protected SpeculationLog getSpeculationLog() {
1132         return null;
1133     }
1134 
1135     protected InstalledCode addMethod(DebugContext debug, final ResolvedJavaMethod method, final CompilationResult compilationResult) {
1136         return backend.addInstalledCode(debug, method, null, compilationResult);
1137     }
1138 
1139     protected InstalledCode addDefaultMethod(DebugContext debug, final ResolvedJavaMethod method, final CompilationResult compilationResult) {
1140         return backend.createDefaultInstalledCode(debug, method, compilationResult);
1141     }
1142 
1143     private final Map<ResolvedJavaMethod, Executable> methodMap = new ConcurrentHashMap<>();
1144 
1145     /**
1146      * Converts a reflection {@link Method} to a {@link ResolvedJavaMethod}.
1147      */
1148     protected ResolvedJavaMethod asResolvedJavaMethod(Executable method) {
1149         ResolvedJavaMethod javaMethod = getMetaAccess().lookupJavaMethod(method);
1150         methodMap.put(javaMethod, method);
1151         return javaMethod;
1152     }
1153 
1154     protected ResolvedJavaMethod getResolvedJavaMethod(String methodName) {
1155         return asResolvedJavaMethod(getMethod(methodName));
1156     }
1157 
1158     protected ResolvedJavaMethod getResolvedJavaMethod(Class<?> clazz, String methodName) {
1159         return asResolvedJavaMethod(getMethod(clazz, methodName));
1160     }
1161 
1162     protected ResolvedJavaMethod getResolvedJavaMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
1163         return asResolvedJavaMethod(getMethod(clazz, methodName, parameterTypes));
1164     }
1165 
1166     /**
1167      * Gets the reflection {@link Method} from which a given {@link ResolvedJavaMethod} was created
1168      * or null if {@code javaMethod} does not correspond to a reflection method.
1169      */
1170     protected Executable lookupMethod(ResolvedJavaMethod javaMethod) {
1171         return methodMap.get(javaMethod);
1172     }
1173 
1174     @SuppressWarnings("deprecation")
1175     protected Object invoke(ResolvedJavaMethod javaMethod, Object receiver, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
1176         Executable method = lookupMethod(javaMethod);
1177         Assert.assertTrue(method != null);
1178         if (!method.isAccessible()) {
1179             method.setAccessible(true);
1180         }
1181         if (method instanceof Method) {
1182             return ((Method) method).invoke(receiver, applyArgSuppliers(args));
1183         }
1184         assert receiver == null : "no receiver for constructor invokes";
1185         return ((Constructor<?>) method).newInstance(applyArgSuppliers(args));
1186     }
1187 
1188     /**
1189      * Parses a Java method in {@linkplain GraphBuilderConfiguration#getDefault default} mode to
1190      * produce a graph.
1191      *
1192      * @param methodName the name of the method in {@code this.getClass()} to be parsed
1193      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1194      */
1195     protected final StructuredGraph parseProfiled(String methodName, AllowAssumptions allowAssumptions) {
1196         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1197         return parse(builder(method, allowAssumptions), getDefaultGraphBuilderSuite());
1198     }
1199 
1200     /**
1201      * Parses a Java method in {@linkplain GraphBuilderConfiguration#getDefault default} mode to
1202      * produce a graph.
1203      *
1204      * @param method the method to be parsed
1205      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1206      */
1207     protected final StructuredGraph parseProfiled(ResolvedJavaMethod method, AllowAssumptions allowAssumptions) {
1208         return parse(builder(method, allowAssumptions), getDefaultGraphBuilderSuite());
1209     }
1210 
1211     /**
1212      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1213      * set to true to produce a graph.
1214      *
1215      * @param methodName the name of the method in {@code this.getClass()} to be parsed
1216      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1217      */
1218     protected final StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions) {
1219         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1220         return parse(builder(method, allowAssumptions), getEagerGraphBuilderSuite());
1221     }
1222 
1223     /**
1224      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1225      * set to true to produce a graph.
1226      *
1227      * @param methodName the name of the method in {@code this.getClass()} to be parsed
1228      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1229      * @param options the option values to be used when compiling the graph
1230      */
1231     protected final StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions, OptionValues options) {
1232         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1233         return parse(builder(method, allowAssumptions, options), getEagerGraphBuilderSuite());
1234     }
1235 
1236     protected final StructuredGraph parseEager(String methodName, AllowAssumptions allowAssumptions, DebugContext debug) {
1237         ResolvedJavaMethod method = getResolvedJavaMethod(methodName);
1238         return parse(builder(method, allowAssumptions, debug), getEagerGraphBuilderSuite());
1239     }
1240 
1241     /**
1242      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1243      * set to true to produce a graph.
1244      *
1245      * @param method the method to be parsed
1246      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1247      */
1248     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions) {
1249         return parse(builder(method, allowAssumptions), getEagerGraphBuilderSuite());
1250     }
1251 
1252     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, DebugContext debug) {
1253         return parse(builder(method, allowAssumptions, debug), getEagerGraphBuilderSuite());
1254     }
1255 
1256     /**
1257      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1258      * set to true to produce a graph.
1259      *
1260      * @param method the method to be parsed
1261      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1262      * @param options the option values to be used when compiling the graph
1263      */
1264     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, OptionValues options) {
1265         return parse(builder(method, allowAssumptions, options), getEagerGraphBuilderSuite());
1266     }
1267 
1268     /**
1269      * Parses a Java method with {@linkplain GraphBuilderConfiguration#withEagerResolving(boolean)}
1270      * set to true to produce a graph.
1271      *
1272      * @param method the method to be parsed
1273      * @param allowAssumptions specifies if {@link Assumption}s can be made compiling the graph
1274      * @param compilationId the compilation identifier to be associated with the graph
1275      * @param options the option values to be used when compiling the graph
1276      */
1277     protected final StructuredGraph parseEager(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, CompilationIdentifier compilationId, OptionValues options) {
1278         return parse(builder(method, allowAssumptions, compilationId, options), getEagerGraphBuilderSuite());
1279     }
1280 
1281     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, DebugContext debug) {
1282         OptionValues options = debug.getOptions();
1283         return new Builder(options, debug, allowAssumptions).method(method).compilationId(getCompilationId(method));
1284     }
1285 
1286     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions) {
1287         OptionValues options = getInitialOptions();
1288         return new Builder(options, getDebugContext(options, null, method), allowAssumptions).method(method).compilationId(getCompilationId(method));
1289     }
1290 
1291     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, CompilationIdentifier compilationId, OptionValues options) {
1292         return new Builder(options, getDebugContext(options, compilationId.toString(CompilationIdentifier.Verbosity.ID), method), allowAssumptions).method(method).compilationId(compilationId);
1293     }
1294 
1295     protected final Builder builder(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, OptionValues options) {
1296         return new Builder(options, getDebugContext(options, null, method), allowAssumptions).method(method).compilationId(getCompilationId(method));
1297     }
1298 
1299     protected PhaseSuite<HighTierContext> getDebugGraphBuilderSuite() {
1300         return getCustomGraphBuilderSuite(GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withFullInfopoints(true));
1301     }
1302 
1303     @SuppressWarnings("try")
1304     protected StructuredGraph parse(StructuredGraph.Builder builder, PhaseSuite<HighTierContext> graphBuilderSuite) {
1305         ResolvedJavaMethod javaMethod = builder.getMethod();
1306         builder.speculationLog(getSpeculationLog());
1307         if (builder.getCancellable() == null) {
1308             builder.cancellable(getCancellable(javaMethod));
1309         }
1310         assert javaMethod.getAnnotation(Test.class) == null : "shouldn't parse method with @Test annotation: " + javaMethod;
1311         StructuredGraph graph = builder.build();
1312         DebugContext debug = graph.getDebug();
1313         try (DebugContext.Scope ds = debug.scope("Parsing", javaMethod, graph)) {
1314             graphBuilderSuite.apply(graph, getDefaultHighTierContext());
1315             Object[] args = getArgumentToBind();
1316             if (args != null) {
1317                 bindArguments(graph, args);
1318             }
1319             return graph;
1320         } catch (Throwable e) {
1321             throw debug.handle(e);
1322         }
1323     }
1324 
1325     protected void bindArguments(StructuredGraph graph, Object[] argsToBind) {
1326         ResolvedJavaMethod m = graph.method();
1327         Object receiver = isStatic(m.getModifiers()) ? null : this;
1328         Object[] args = argsWithReceiver(receiver, argsToBind);
1329         JavaType[] parameterTypes = m.toParameterTypes();
1330         assert parameterTypes.length == args.length;
1331         for (ParameterNode param : graph.getNodes(ParameterNode.TYPE)) {
1332             JavaConstant c = getSnippetReflection().forBoxed(parameterTypes[param.index()].getJavaKind(), args[param.index()]);
1333             ConstantNode replacement = ConstantNode.forConstant(c, getMetaAccess(), graph);
1334             param.replaceAtUsages(replacement);
1335         }
1336     }
1337 
1338     protected Object[] getArgumentToBind() {
1339         return null;
1340     }
1341 
1342     protected PhaseSuite<HighTierContext> getEagerGraphBuilderSuite() {
1343         return getCustomGraphBuilderSuite(GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withEagerResolving(true).withUnresolvedIsError(true));
1344     }
1345 
1346     /**
1347      * Gets the cancellable that should be associated with a graph being created by any of the
1348      * {@code parse...()} methods.
1349      *
1350      * @param method the method being parsed into a graph
1351      */
1352     protected Cancellable getCancellable(ResolvedJavaMethod method) {
1353         return null;
1354     }
1355 
1356     protected Plugins getDefaultGraphBuilderPlugins() {
1357         PhaseSuite<HighTierContext> suite = backend.getSuites().getDefaultGraphBuilderSuite();
1358         Plugins defaultPlugins = ((GraphBuilderPhase) suite.findPhase(GraphBuilderPhase.class).previous()).getGraphBuilderConfig().getPlugins();
1359         // defensive copying
1360         return new Plugins(defaultPlugins);
1361     }
1362 
1363     protected PhaseSuite<HighTierContext> getDefaultGraphBuilderSuite() {
1364         // defensive copying
1365         return backend.getSuites().getDefaultGraphBuilderSuite().copy();
1366     }
1367 
1368     /**
1369      * Registers extra invocation plugins for this test. The extra plugins are removed in the
1370      * {@link #afterTest()} method.
1371      *
1372      * Subclasses overriding this method should always call the same method on the super class in
1373      * case it wants to register plugins.
1374      *
1375      * @param invocationPlugins
1376      */
1377     protected void registerInvocationPlugins(InvocationPlugins invocationPlugins) {
1378         invocationPlugins.register(new InvocationPlugin() {
1379             @Override
1380             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
1381                 b.add(new BreakpointNode());
1382                 return true;
1383             }
1384         }, GraalCompilerTest.class, "breakpoint");
1385         invocationPlugins.register(new InvocationPlugin() {
1386             @Override
1387             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver, ValueNode arg0) {
1388                 b.add(new BreakpointNode(arg0));
1389                 return true;
1390             }
1391         }, GraalCompilerTest.class, "breakpoint", int.class);
1392         invocationPlugins.register(new InvocationPlugin() {
1393             @Override
1394             public boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, Receiver receiver) {
1395                 b.add(new NotOptimizedNode());
1396                 return true;
1397             }
1398         }, GraalCompilerTest.class, "shouldBeOptimizedAway");
1399     }
1400 
1401     /**
1402      * The {@link #testN(int, String, Object...)} method means multiple threads trying to initialize
1403      * this field.
1404      */
1405     private volatile InvocationPlugins invocationPluginExtensions;
1406 
1407     private InvocationPlugins extendedInvocationPlugins;
1408 
1409     protected PhaseSuite<HighTierContext> getCustomGraphBuilderSuite(GraphBuilderConfiguration gbConf) {
1410         PhaseSuite<HighTierContext> suite = getDefaultGraphBuilderSuite();
1411         ListIterator<BasePhase<? super HighTierContext>> iterator = suite.findPhase(GraphBuilderPhase.class);
1412         initializeInvocationPluginExtensions();
1413         GraphBuilderConfiguration gbConfCopy = editGraphBuilderConfiguration(gbConf.copy());
1414         iterator.remove();
1415         iterator.add(new GraphBuilderPhase(gbConfCopy));
1416         return suite;
1417     }
1418 
1419     private void initializeInvocationPluginExtensions() {
1420         if (invocationPluginExtensions == null) {
1421             synchronized (this) {
1422                 if (invocationPluginExtensions == null) {
1423                     InvocationPlugins invocationPlugins = new InvocationPlugins();
1424                     registerInvocationPlugins(invocationPlugins);
1425                     extendedInvocationPlugins = getReplacements().getGraphBuilderPlugins().getInvocationPlugins();
1426                     extendedInvocationPlugins.addTestPlugins(invocationPlugins, null);
1427                     invocationPluginExtensions = invocationPlugins;
1428                 }
1429             }
1430         }
1431     }
1432 
1433     protected GraphBuilderConfiguration editGraphBuilderConfiguration(GraphBuilderConfiguration conf) {
1434         conf.getPlugins().prependInlineInvokePlugin(new InlineInvokePlugin() {
1435 
1436             @Override
1437             public InlineInfo shouldInlineInvoke(GraphBuilderContext b, ResolvedJavaMethod method, ValueNode[] args) {
1438                 BytecodeParserNeverInline neverInline = method.getAnnotation(BytecodeParserNeverInline.class);
1439                 if (neverInline != null) {
1440                     return neverInline.invokeWithException() ? DO_NOT_INLINE_WITH_EXCEPTION : DO_NOT_INLINE_NO_EXCEPTION;
1441                 }
1442                 if (method.getAnnotation(BytecodeParserForceInline.class) != null) {
1443                     return InlineInfo.createStandardInlineInfo(method);
1444                 }
1445                 return bytecodeParserShouldInlineInvoke(b, method, args);
1446             }
1447         });
1448         return conf;
1449     }
1450 
1451     /**
1452      * Supplements {@link BytecodeParserForceInline} and {@link BytecodeParserNeverInline} in terms
1453      * of allowing a test to influence the inlining decision made during bytecode parsing.
1454      *
1455      * @see InlineInvokePlugin#shouldInlineInvoke(GraphBuilderContext, ResolvedJavaMethod,
1456      *      ValueNode[])
1457      */
1458     @SuppressWarnings("unused")
1459     protected InlineInvokePlugin.InlineInfo bytecodeParserShouldInlineInvoke(GraphBuilderContext b, ResolvedJavaMethod method, ValueNode[] args) {
1460         return null;
1461     }
1462 
1463     @NodeInfo
1464     public static class NotOptimizedNode extends FixedWithNextNode {
1465         private static final NodeClass<NotOptimizedNode> TYPE = NodeClass.create(NotOptimizedNode.class);
1466 
1467         protected NotOptimizedNode() {
1468             super(TYPE, StampFactory.forVoid());
1469         }
1470 
1471     }
1472 
1473     protected Replacements getReplacements() {
1474         return getProviders().getReplacements();
1475     }
1476 
1477     /**
1478      * Inject a probability for a branch condition into the profiling information of this test case.
1479      *
1480      * @param p the probability that cond is true
1481      * @param cond the condition of the branch
1482      * @return cond
1483      */
1484     protected static boolean branchProbability(double p, boolean cond) {
1485         return GraalDirectives.injectBranchProbability(p, cond);
1486     }
1487 
1488     /**
1489      * Inject an iteration count for a loop condition into the profiling information of this test
1490      * case.
1491      *
1492      * @param i the iteration count of the loop
1493      * @param cond the condition of the loop
1494      * @return cond
1495      */
1496     protected static boolean iterationCount(double i, boolean cond) {
1497         return GraalDirectives.injectIterationCount(i, cond);
1498     }
1499 
1500     /**
1501      * Test if the current test runs on the given platform. The name must match the name given in
1502      * the {@link Architecture#getName()}.
1503      *
1504      * @param name The name to test
1505      * @return true if we run on the architecture given by name
1506      */
1507     protected boolean isArchitecture(String name) {
1508         return name.equals(backend.getTarget().arch.getName());
1509     }
1510 }