1 /*
   2  * Copyright (c) 2017, 2019, 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 package compiler.valhalla.valuetypes;
  25 
  26 import compiler.whitebox.CompilerWhiteBoxTest;
  27 import jdk.test.lib.Asserts;
  28 import jdk.test.lib.management.InputArguments;
  29 import jdk.test.lib.Platform;
  30 import jdk.test.lib.process.ProcessTools;
  31 import jdk.test.lib.process.OutputAnalyzer;
  32 import jdk.test.lib.Utils;
  33 import sun.hotspot.WhiteBox;
  34 
  35 import java.lang.annotation.Retention;
  36 import java.lang.annotation.RetentionPolicy;
  37 import java.lang.annotation.Repeatable;
  38 import java.lang.invoke.*;
  39 import java.lang.reflect.Method;
  40 import java.util.ArrayList;
  41 import java.util.Arrays;
  42 import java.util.Hashtable;
  43 import java.util.LinkedHashMap;
  44 import java.util.List;
  45 import java.util.Map;
  46 import java.util.regex.Matcher;
  47 import java.util.regex.Pattern;
  48 import java.util.TreeMap;
  49 
  50 // Mark method as test
  51 @Retention(RetentionPolicy.RUNTIME)
  52 @Repeatable(Tests.class)
  53 @interface Test {
  54     // Regular expression used to match forbidden IR nodes
  55     // in the C2 IR emitted for this test.
  56     String failOn() default "";
  57     // Regular expressions used to match and count IR nodes.
  58     String[] match() default { };
  59     int[] matchCount() default { };
  60     int compLevel() default ValueTypeTest.COMP_LEVEL_ANY;
  61     int valid() default ValueTypeTest.AllFlags;
  62 }
  63 
  64 @Retention(RetentionPolicy.RUNTIME)
  65 @interface Tests {
  66     Test[] value();
  67 }
  68 
  69 // Force method inlining during compilation
  70 @Retention(RetentionPolicy.RUNTIME)
  71 @interface ForceInline { }
  72 
  73 // Prevent method inlining during compilation
  74 @Retention(RetentionPolicy.RUNTIME)
  75 @interface DontInline { }
  76 
  77 // Prevent method compilation
  78 @Retention(RetentionPolicy.RUNTIME)
  79 @interface DontCompile { }
  80 
  81 // Force method compilation
  82 @Retention(RetentionPolicy.RUNTIME)
  83 @interface ForceCompile {
  84     int compLevel() default ValueTypeTest.COMP_LEVEL_ANY;
  85 }
  86 
  87 // Number of warmup iterations
  88 @Retention(RetentionPolicy.RUNTIME)
  89 @interface Warmup {
  90     int value();
  91 }
  92 
  93 public abstract class ValueTypeTest {
  94     // Run "jtreg -Dtest.c1=true" to enable experimental C1 testing. This forces all
  95     // compilable methods to be compiled with C1, regardless of the @Test(compLevel=?) setting.
  96     static final boolean TEST_C1 = Boolean.getBoolean("test.c1");
  97 
  98     // Should we execute tests that assume (ValueType[] <: Object[])?
  99     static final boolean ENABLE_VALUE_ARRAY_COVARIANCE = Boolean.getBoolean("ValueArrayCovariance");
 100 
 101     // Random test values
 102     public static final int  rI = Utils.getRandomInstance().nextInt() % 1000;
 103     public static final long rL = Utils.getRandomInstance().nextLong() % 1000;
 104 
 105     // User defined settings
 106     protected static final boolean XCOMP = Platform.isComp();
 107     private static final boolean PRINT_GRAPH = true;
 108     private static final boolean PRINT_TIMES = Boolean.parseBoolean(System.getProperty("PrintTimes", "false"));
 109     private static       boolean VERIFY_IR = Boolean.parseBoolean(System.getProperty("VerifyIR", "true")) && !TEST_C1 && !XCOMP;
 110     private static final boolean VERIFY_VM = Boolean.parseBoolean(System.getProperty("VerifyVM", "false"));
 111     private static final String SCENARIOS = System.getProperty("Scenarios", "");
 112     private static final String TESTLIST = System.getProperty("Testlist", "");
 113     private static final String EXCLUDELIST = System.getProperty("Exclude", "");
 114     private static final int WARMUP = Integer.parseInt(System.getProperty("Warmup", "251"));
 115     private static final boolean DUMP_REPLAY = Boolean.parseBoolean(System.getProperty("DumpReplay", "false"));
 116 
 117     // Pre-defined settings
 118     private static final String[] defaultFlags = {
 119         "-XX:-BackgroundCompilation", "-XX:CICompilerCount=1",
 120         "-XX:CompileCommand=quiet",
 121         "-XX:CompileCommand=compileonly,java.lang.invoke.*::*",
 122         "-XX:CompileCommand=compileonly,java.lang.Long::sum",
 123         "-XX:CompileCommand=compileonly,java.lang.Object::<init>",
 124         "-XX:CompileCommand=inline,compiler.valhalla.valuetypes.MyValue*::<init>",
 125         "-XX:CompileCommand=compileonly,compiler.valhalla.valuetypes.*::*"};
 126     private static final String[] printFlags = {
 127         "-XX:+PrintCompilation", "-XX:+PrintIdeal", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintOptoAssembly"};
 128     private static final String[] verifyFlags = {
 129         "-XX:+VerifyOops", "-XX:+VerifyStack", "-XX:+VerifyLastFrame", "-XX:+VerifyBeforeGC", "-XX:+VerifyAfterGC",
 130         "-XX:+VerifyDuringGC", "-XX:+VerifyAdapterSharing"};
 131 
 132     protected static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
 133     protected static final int ValueTypePassFieldsAsArgsOn = 0x1;
 134     protected static final int ValueTypePassFieldsAsArgsOff = 0x2;
 135     protected static final int ValueTypeArrayFlattenOn = 0x4;
 136     protected static final int ValueTypeArrayFlattenOff = 0x8;
 137     protected static final int ValueTypeReturnedAsFieldsOn = 0x10;
 138     protected static final int ValueTypeReturnedAsFieldsOff = 0x20;
 139     protected static final int AlwaysIncrementalInlineOn = 0x40;
 140     protected static final int AlwaysIncrementalInlineOff = 0x80;
 141     static final int AllFlags = ValueTypePassFieldsAsArgsOn | ValueTypePassFieldsAsArgsOff | ValueTypeArrayFlattenOn | ValueTypeArrayFlattenOff | ValueTypeReturnedAsFieldsOn;
 142     protected static final boolean ValueTypePassFieldsAsArgs = (Boolean)WHITE_BOX.getVMFlag("ValueTypePassFieldsAsArgs");
 143     protected static final boolean ValueTypeArrayFlatten = (WHITE_BOX.getIntxVMFlag("ValueArrayElemMaxFlatSize") == -1); // FIXME - fix this if default of ValueArrayElemMaxFlatSize is changed
 144     protected static final boolean ValueTypeReturnedAsFields = (Boolean)WHITE_BOX.getVMFlag("ValueTypeReturnedAsFields");
 145     protected static final boolean AlwaysIncrementalInline = (Boolean)WHITE_BOX.getVMFlag("AlwaysIncrementalInline");
 146     protected static final long TieredStopAtLevel = (Long)WHITE_BOX.getVMFlag("TieredStopAtLevel");
 147     protected static final int COMP_LEVEL_ANY               = -2;
 148     protected static final int COMP_LEVEL_ALL               = -2;
 149     protected static final int COMP_LEVEL_AOT               = -1;
 150     protected static final int COMP_LEVEL_NONE              =  0;
 151     protected static final int COMP_LEVEL_SIMPLE            =  1;     // C1
 152     protected static final int COMP_LEVEL_LIMITED_PROFILE   =  2;     // C1, invocation & backedge counters
 153     protected static final int COMP_LEVEL_FULL_PROFILE      =  3;     // C1, invocation & backedge counters + mdo
 154     protected static final int COMP_LEVEL_FULL_OPTIMIZATION =  4;     // C2 or JVMCI
 155 
 156     protected static final Hashtable<String, Method> tests = new Hashtable<String, Method>();
 157     protected static final boolean USE_COMPILER = WHITE_BOX.getBooleanVMFlag("UseCompiler");
 158     protected static final boolean PRINT_IDEAL  = WHITE_BOX.getBooleanVMFlag("PrintIdeal");
 159 
 160     // Regular expressions used to match nodes in the PrintIdeal output
 161     protected static final String START = "(\\d+\\t(.*";
 162     protected static final String MID = ".*)+\\t===.*";
 163     protected static final String END = ")|";
 164     protected static final String ALLOC  = "(.*precise klass compiler/valhalla/valuetypes/MyValue.*\\R(.*(nop|spill).*\\R)*.*_new_instance_Java" + END;
 165     protected static final String ALLOCA = "(.*precise klass \\[Lcompiler/valhalla/valuetypes/MyValue.*\\R(.*(nop|spill).*\\R)*.*_new_array_Java" + END;
 166     protected static final String LOAD   = START + "Load(B|S|I|L|F|D|P|N)" + MID + "@compiler/valhalla/valuetypes/MyValue.*" + END;
 167     protected static final String LOADK  = START + "LoadK" + MID + END;
 168     protected static final String STORE  = START + "Store(B|C|S|I|L|F|D|P|N)" + MID + "@compiler/valhalla/valuetypes/MyValue.*" + END;
 169     protected static final String LOOP   = START + "Loop" + MID + "" + END;
 170     protected static final String TRAP   = START + "CallStaticJava" + MID + "uncommon_trap.*(unstable_if|predicate)" + END;
 171     protected static final String RETURN = START + "Return" + MID + "returns" + END;
 172     protected static final String LINKTOSTATIC = START + "CallStaticJava" + MID + "linkToStatic" + END;
 173     protected static final String NPE = START + "CallStaticJava" + MID + "null_check" + END;
 174     protected static final String CALL = START + "CallStaticJava" + MID + END;
 175     protected static final String STOREVALUETYPEFIELDS = START + "CallStaticJava" + MID + "store_value_type_fields" + END;
 176     protected static final String SCOBJ = "(.*# ScObj.*" + END;
 177 
 178     public static String[] concat(String prefix[], String... extra) {
 179         ArrayList<String> list = new ArrayList<String>();
 180         if (prefix != null) {
 181             for (String s : prefix) {
 182                 list.add(s);
 183             }
 184         }
 185         if (extra != null) {
 186             for (String s : extra) {
 187                 list.add(s);
 188             }
 189         }
 190 
 191         return list.toArray(new String[list.size()]);
 192     }
 193 
 194     /**
 195      * Override getNumScenarios and getVMParameters if you want to run with more than
 196      * the 5 built-in scenarios
 197      */
 198     public int getNumScenarios() {
 199         if (TEST_C1) {
 200             return 1;
 201         } else {
 202             return 6;
 203         }
 204     }
 205 
 206     /**
 207      * VM paramaters for the 5 built-in test scenarios. If your test needs to append
 208      * extra parameters for (some of) these scenarios, override getExtraVMParameters().
 209      */
 210     public String[] getVMParameters(int scenario) {
 211         if (TEST_C1) {
 212             return new String[] {
 213                 "-XX:+EnableValhallaC1",
 214                 "-XX:TieredStopAtLevel=1",
 215                 "-XX:-ValueTypePassFieldsAsArgs",
 216                 "-XX:-ValueTypeReturnedAsFields"
 217             };
 218         }
 219 
 220         switch (scenario) {
 221         case 0: return new String[] {
 222                 "-XX:+AlwaysIncrementalInline",
 223                 "-XX:ValueArrayElemMaxFlatOops=-1",
 224                 "-XX:ValueArrayElemMaxFlatSize=-1",
 225                 "-XX:ValueFieldMaxFlatSize=-1",
 226                 "-XX:+ValueTypePassFieldsAsArgs",
 227                 "-XX:+ValueTypeReturnedAsFields"};
 228         case 1: return new String[] {
 229                 "-XX:-UseCompressedOops",
 230                 "-XX:ValueArrayElemMaxFlatOops=-1",
 231                 "-XX:ValueArrayElemMaxFlatSize=-1",
 232                 "-XX:ValueFieldMaxFlatSize=-1",
 233                 "-XX:-ValueTypePassFieldsAsArgs",
 234                 "-XX:-ValueTypeReturnedAsFields"};
 235         case 2: return new String[] {
 236                 "-DVerifyIR=false",
 237                 "-XX:-UseCompressedOops",
 238                 "-XX:ValueArrayElemMaxFlatOops=0",
 239                 "-XX:ValueArrayElemMaxFlatSize=0",
 240                 "-XX:ValueFieldMaxFlatSize=0",
 241                 "-XX:+ValueTypePassFieldsAsArgs",
 242                 "-XX:+ValueTypeReturnedAsFields",
 243                 "-XX:+StressValueTypeReturnedAsFields"};
 244         case 3: return new String[] {
 245                 "-DVerifyIR=false",
 246                 "-XX:+AlwaysIncrementalInline",
 247                 "-XX:-ValueTypePassFieldsAsArgs",
 248                 "-XX:-ValueTypeReturnedAsFields"};
 249         case 4: return new String[] {
 250                 "-DVerifyIR=false",
 251                 "-XX:ValueArrayElemMaxFlatOops=-1",
 252                 "-XX:ValueArrayElemMaxFlatSize=-1",
 253                 "-XX:ValueFieldMaxFlatSize=0",
 254                 "-XX:+ValueTypePassFieldsAsArgs",
 255                 "-XX:-ValueTypeReturnedAsFields"};
 256         case 5: return new String[] {
 257                 "-XX:+AlwaysIncrementalInline",
 258                 "-XX:ValueArrayElemMaxFlatOops=-1",
 259                 "-XX:ValueArrayElemMaxFlatSize=-1",
 260                 "-XX:ValueFieldMaxFlatSize=-1",
 261                 "-XX:-ValueTypePassFieldsAsArgs",
 262                 "-XX:-ValueTypeReturnedAsFields"};
 263         }
 264 
 265         return null;
 266     }
 267 
 268     /**
 269      * Override this method to provide extra parameters for selected scenarios
 270      */
 271     public String[] getExtraVMParameters(int scenario) {
 272         return null;
 273     }
 274 
 275     public static void main(String[] args) throws Throwable {
 276         if (args.length != 1) {
 277             throw new RuntimeException("Usage: @run main/othervm/timeout=120 -Xbootclasspath/a:." +
 278                                        " -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions" +
 279                                        " -XX:+UnlockExperimentalVMOptions -XX:+WhiteBoxAPI -XX:+EnableValhalla" +
 280                                        " compiler.valhalla.valuetypes.ValueTypeTest <YourTestMainClass>");
 281         }
 282         String testMainClassName = args[0];
 283         Class testMainClass = Class.forName(testMainClassName);
 284         ValueTypeTest test = (ValueTypeTest)testMainClass.newInstance();
 285         List<String> scenarios = null;
 286         if (!SCENARIOS.isEmpty()) {
 287            scenarios = Arrays.asList(SCENARIOS.split(","));
 288         }
 289         for (int i=0; i<test.getNumScenarios(); i++) {
 290             if (scenarios == null || scenarios.contains(Integer.toString(i))) {
 291                 System.out.println("Scenario #" + i + " -------- ");
 292                 String[] cmds = InputArguments.getVmInputArgs();
 293                 cmds = concat(cmds, test.getVMParameters(i));
 294                 cmds = concat(cmds, test.getExtraVMParameters(i));
 295                 cmds = concat(cmds, testMainClassName);
 296 
 297                 OutputAnalyzer oa = ProcessTools.executeTestJvm(cmds);
 298                 String output = oa.getOutput();
 299                 oa.shouldHaveExitValue(0);
 300                 System.out.println(output);
 301             } else {
 302                 System.out.println("Scenario #" + i + " is skipped due to -Dscenarios=" + SCENARIOS);
 303             }
 304         }
 305     }
 306 
 307     // To exclude test cases, use -DExclude=<case1>,<case2>,...
 308     // Each case can be just the method name, or can be <class>.<method>. The latter form is useful
 309     // when you are running several tests at the same time.
 310     //
 311     // jtreg -DExclude=test12 TestArrays.java
 312     // jtreg -DExclude=test34 TestLWorld.java
 313     // -- or --
 314     // jtreg -DExclude=TestArrays.test12,TestLWorld.test34 TestArrays.java TestLWorld.java
 315     //
 316     private List<String> buildExcludeList() {
 317         List<String> exclude = null;
 318         String classPrefix = getClass().getSimpleName() + ".";
 319         if (!EXCLUDELIST.isEmpty()) {
 320             exclude = new ArrayList(Arrays.asList(EXCLUDELIST.split(",")));
 321             for (int i = exclude.size() - 1; i >= 0; i--) {
 322                 String ex = exclude.get(i);
 323                 if (ex.indexOf(".") > 0) {
 324                     if (ex.startsWith(classPrefix)) {
 325                         ex = ex.substring(classPrefix.length());
 326                         exclude.set(i, ex);
 327                     } else {
 328                         exclude.remove(i);
 329                     }
 330                 }
 331             }
 332         }
 333         return exclude;
 334     }
 335 
 336     protected ValueTypeTest() {
 337         List<String> list = null;
 338         if (!TESTLIST.isEmpty()) {
 339            list = Arrays.asList(TESTLIST.split(","));
 340         }
 341         List<String> exclude = buildExcludeList();
 342 
 343         // Gather all test methods and put them in Hashtable
 344         for (Method m : getClass().getDeclaredMethods()) {
 345             Test[] annos = m.getAnnotationsByType(Test.class);
 346             if (annos.length != 0 &&
 347                 ((list == null || list.contains(m.getName())) && (exclude == null || !exclude.contains(m.getName())))) {
 348                 tests.put(getClass().getSimpleName() + "::" + m.getName(), m);
 349             }
 350         }
 351     }
 352 
 353     protected void run(String[] args, Class<?>... classes) throws Throwable {
 354         if (args.length == 0) {
 355             // Spawn a new VM instance
 356             execute_vm();
 357         } else {
 358             // Execute tests in the VM spawned by the above code.
 359             Asserts.assertTrue(args.length == 1 && args[0].equals("run"), "must be");
 360             run(classes);
 361         }
 362     }
 363 
 364     private void execute_vm() throws Throwable {
 365         Asserts.assertFalse(tests.isEmpty(), "no tests to execute");
 366         String[] vmInputArgs = InputArguments.getVmInputArgs();
 367         for (String arg : vmInputArgs) {
 368             if (arg.startsWith("-XX:CompileThreshold")) {
 369                 // Disable IR verification if non-default CompileThreshold is set
 370                 VERIFY_IR = false;
 371             }
 372             if (arg.startsWith("-XX:+EnableValhallaC1")) {
 373                 // Disable IR verification if C1 is used (FIXME!)
 374                 VERIFY_IR = false;
 375             }
 376         }
 377         // Each VM is launched with flags in this order, so the later ones can override the earlier one:
 378         //     defaultFlags
 379         //     VERIFY_IR/VERIFY_VM flags specified below
 380         //     vmInputArgs, which consists of:
 381         //        @run options
 382         //        getVMParameters()
 383         //        getExtraVMParameters()
 384         String cmds[] = defaultFlags;
 385         if (VERIFY_IR) {
 386             // Add print flags for IR verification
 387             cmds = concat(cmds, printFlags);
 388             // Always trap for exception throwing to not confuse IR verification
 389             cmds = concat(cmds, "-XX:-OmitStackTraceInFastThrow");
 390         }
 391         if (VERIFY_VM) {
 392             cmds = concat(cmds, verifyFlags);
 393         }
 394         cmds = concat(cmds, vmInputArgs);
 395 
 396         // Run tests in own process and verify output
 397         cmds = concat(cmds, getClass().getName(), "run");
 398         OutputAnalyzer oa = ProcessTools.executeTestJvm(cmds);
 399         // If ideal graph printing is enabled/supported, verify output
 400         String output = oa.getOutput();
 401         oa.shouldHaveExitValue(0);
 402         if (VERIFY_IR) {
 403             if (output.contains("PrintIdeal enabled")) {
 404                 parseOutput(output);
 405             } else {
 406                 System.out.println(output);
 407                 System.out.println("WARNING: IR verification failed! Running with -Xint, -Xcomp or release build?");
 408             }
 409         }
 410     }
 411 
 412     private void parseOutput(String output) throws Exception {
 413         Pattern comp_re = Pattern.compile("\\n\\s+\\d+\\s+\\d+\\s+(%| )(s| )(!| )b(n| )\\s+\\S+\\.(?<name>[^.]+::\\S+)\\s+(?<osr>@ \\d+\\s+)?[(]\\d+ bytes[)]\\n");
 414         Matcher m = comp_re.matcher(output);
 415         Map<String,String> compilations = new LinkedHashMap<>();
 416         int prev = 0;
 417         String methodName = null;
 418         while (m.find()) {
 419             if (prev == 0) {
 420                 // Print header
 421                 System.out.print(output.substring(0, m.start()+1));
 422             } else if (methodName != null) {
 423                 compilations.put(methodName, output.substring(prev, m.start()+1));
 424             }
 425             if (m.group("osr") != null) {
 426                 methodName = null;
 427             } else {
 428                 methodName = m.group("name");
 429             }
 430             prev = m.end();
 431         }
 432         if (prev == 0) {
 433             // Print header
 434             System.out.print(output);
 435         } else if (methodName != null) {
 436             compilations.put(methodName, output.substring(prev));
 437         }
 438         // Iterate over compilation output
 439         for (String testName : compilations.keySet()) {
 440             Method test = tests.get(testName);
 441             if (test == null) {
 442                 // Skip helper methods
 443                 continue;
 444             }
 445             String graph = compilations.get(testName);
 446             if (PRINT_GRAPH) {
 447                 System.out.println("\nGraph for " + testName + "\n" + graph);
 448             }
 449             // Parse graph using regular expressions to determine if it contains forbidden nodes
 450             Test[] annos = test.getAnnotationsByType(Test.class);
 451             Test anno = null;
 452             for (Test a : annos) {
 453                 if ((a.valid() & ValueTypePassFieldsAsArgsOn) != 0 && ValueTypePassFieldsAsArgs) {
 454                     assert anno == null;
 455                     anno = a;
 456                 } else if ((a.valid() & ValueTypePassFieldsAsArgsOff) != 0 && !ValueTypePassFieldsAsArgs) {
 457                     assert anno == null;
 458                     anno = a;
 459                 } else if ((a.valid() & ValueTypeArrayFlattenOn) != 0 && ValueTypeArrayFlatten) {
 460                     assert anno == null;
 461                     anno = a;
 462                 } else if ((a.valid() & ValueTypeArrayFlattenOff) != 0 && !ValueTypeArrayFlatten) {
 463                     assert anno == null;
 464                     anno = a;
 465                 } else if ((a.valid() & ValueTypeReturnedAsFieldsOn) != 0 && ValueTypeReturnedAsFields) {
 466                     assert anno == null;
 467                     anno = a;
 468                 } else if ((a.valid() & ValueTypeReturnedAsFieldsOff) != 0 && !ValueTypeReturnedAsFields) {
 469                     assert anno == null;
 470                     anno = a;
 471                 } else if ((a.valid() & AlwaysIncrementalInlineOn) != 0 && AlwaysIncrementalInline) {
 472                     assert anno == null;
 473                     anno = a;
 474                 } else if ((a.valid() & AlwaysIncrementalInlineOff) != 0 && !AlwaysIncrementalInline) {
 475                     assert anno == null;
 476                     anno = a;
 477                 }
 478             }
 479             assert anno != null;
 480             String regexFail = anno.failOn();
 481             if (!regexFail.isEmpty()) {
 482                 Pattern pattern = Pattern.compile(regexFail.substring(0, regexFail.length()-1));
 483                 Matcher matcher = pattern.matcher(graph);
 484                 boolean found = matcher.find();
 485                 Asserts.assertFalse(found, "Graph for '" + testName + "' contains forbidden node:\n" + (found ? matcher.group() : ""));
 486             }
 487             String[] regexMatch = anno.match();
 488             int[] matchCount = anno.matchCount();
 489             for (int i = 0; i < regexMatch.length; ++i) {
 490                 Pattern pattern = Pattern.compile(regexMatch[i].substring(0, regexMatch[i].length()-1));
 491                 Matcher matcher = pattern.matcher(graph);
 492                 int count = 0;
 493                 String nodes = "";
 494                 while (matcher.find()) {
 495                     count++;
 496                     nodes += matcher.group() + "\n";
 497                 }
 498                 if (matchCount[i] < 0) {
 499                     Asserts.assertLTE(Math.abs(matchCount[i]), count, "Graph for '" + testName + "' contains different number of match nodes:\n" + nodes);
 500                 } else {
 501                     Asserts.assertEQ(matchCount[i], count, "Graph for '" + testName + "' contains different number of match nodes:\n" + nodes);
 502                 }
 503             }
 504             tests.remove(testName);
 505             System.out.println(testName + " passed");
 506         }
 507         // Check if all tests were compiled
 508         if (tests.size() != 0) {
 509             for (String name : tests.keySet()) {
 510                 System.out.println("Test '" + name + "' not compiled!");
 511             }
 512             throw new RuntimeException("Not all tests were compiled");
 513         }
 514     }
 515 
 516     private void setup(Class<?> clazz) {
 517         if (XCOMP) {
 518             // Don't control compilation if -Xcomp is enabled
 519             return;
 520         }
 521         if (DUMP_REPLAY) {
 522             // Generate replay compilation files
 523             String directive = "[{ match: \"*.*\", DumpReplay: true }]";
 524             if (WHITE_BOX.addCompilerDirective(directive) != 1) {
 525                 throw new RuntimeException("Failed to add compiler directive");
 526             }
 527         }
 528 
 529         Method[] methods = clazz.getDeclaredMethods();
 530         for (Method m : methods) {
 531             if (m.isAnnotationPresent(Test.class)) {
 532                 // Don't inline tests
 533                 WHITE_BOX.testSetDontInlineMethod(m, true);
 534             }
 535             if (m.isAnnotationPresent(DontCompile.class)) {
 536                 WHITE_BOX.makeMethodNotCompilable(m, COMP_LEVEL_ANY, true);
 537                 WHITE_BOX.makeMethodNotCompilable(m, COMP_LEVEL_ANY, false);
 538                 WHITE_BOX.testSetDontInlineMethod(m, true);
 539             } else if (m.isAnnotationPresent(ForceCompile.class)) {
 540                 int compLevel = getCompLevel(m.getAnnotation(ForceCompile.class));
 541                 WHITE_BOX.enqueueMethodForCompilation(m, compLevel);
 542             }
 543             if (m.isAnnotationPresent(ForceInline.class)) {
 544                 WHITE_BOX.testSetForceInlineMethod(m, true);
 545             } else if (m.isAnnotationPresent(DontInline.class)) {
 546                 WHITE_BOX.testSetDontInlineMethod(m, true);
 547             }
 548         }
 549 
 550         // Compile class initializers
 551         int compLevel = getCompLevel(null);
 552         WHITE_BOX.enqueueInitializerForCompilation(clazz, compLevel);
 553     }
 554 
 555     private void run(Class<?>... classes) throws Exception {
 556         if (USE_COMPILER && PRINT_IDEAL && !XCOMP) {
 557             System.out.println("PrintIdeal enabled");
 558         }
 559         System.out.format("rI = %d, rL = %d\n", rI, rL);
 560 
 561         setup(getClass());
 562         for (Class<?> clazz : classes) {
 563             setup(clazz);
 564         }
 565 
 566         // Execute tests
 567         TreeMap<Long, String> durations = PRINT_TIMES ? new TreeMap<Long, String>() : null;
 568         for (Method test : tests.values()) {
 569             long startTime = System.nanoTime();
 570             Method verifier = getClass().getMethod(test.getName() + "_verifier", boolean.class);
 571             // Warmup using verifier method
 572             Warmup anno = test.getAnnotation(Warmup.class);
 573             int warmup = anno == null ? WARMUP : anno.value();
 574             for (int i = 0; i < warmup; ++i) {
 575                 verifier.invoke(this, true);
 576             }
 577             int compLevel = getCompLevel(test.getAnnotation(Test.class));
 578             // Trigger compilation
 579             WHITE_BOX.enqueueMethodForCompilation(test, compLevel);
 580             Asserts.assertTrue(!USE_COMPILER || WHITE_BOX.isMethodCompiled(test, false), test + " not compiled");
 581             // Check result
 582             verifier.invoke(this, false);
 583             if (PRINT_TIMES) {
 584                 long endTime = System.nanoTime();
 585                 long duration = (endTime - startTime);
 586                 durations.put(duration, test.getName());
 587             }
 588         }
 589 
 590         // Print execution times
 591         if (PRINT_TIMES) {
 592           System.out.println("\n\nTest execution times:");
 593           for (Map.Entry<Long, String> entry : durations.entrySet()) {
 594               System.out.format("%-10s%15d ns\n", entry.getValue() + ":", entry.getKey());
 595           }
 596         }
 597     }
 598 
 599     // Choose the appropriate compilation level for a method, according to the given annotation.
 600     //
 601     // Currently, if TEST_C1 is true, we always use COMP_LEVEL_SIMPLE. Otherwise, if the
 602     // compLevel is unspecified, the default is COMP_LEVEL_FULL_OPTIMIZATION.
 603     int getCompLevel(Object annotation) {
 604         if (TEST_C1) {
 605             return COMP_LEVEL_SIMPLE;
 606         }
 607         int compLevel;
 608         if (annotation == null) {
 609             compLevel = COMP_LEVEL_ANY;
 610         } else if (annotation instanceof Test) {
 611             compLevel = ((Test)annotation).compLevel();
 612         } else {
 613             compLevel = ((ForceCompile)annotation).compLevel();
 614         }
 615         if (compLevel == COMP_LEVEL_ANY) {
 616             compLevel = COMP_LEVEL_FULL_OPTIMIZATION;
 617         }
 618         if (compLevel > (int)TieredStopAtLevel) {
 619             compLevel = (int)TieredStopAtLevel;
 620         }
 621         return compLevel;
 622     }
 623 }