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