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