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