1 /*
  2  * Copyright (c) 2021, 2025, 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.lib.ir_framework;
 25 
 26 import compiler.lib.ir_framework.driver.FlagVMProcess;
 27 import compiler.lib.ir_framework.driver.TestVMException;
 28 import compiler.lib.ir_framework.driver.TestVMProcess;
 29 import compiler.lib.ir_framework.driver.irmatching.IRMatcher;
 30 import compiler.lib.ir_framework.driver.irmatching.IRViolationException;
 31 import compiler.lib.ir_framework.driver.irmatching.Matchable;
 32 import compiler.lib.ir_framework.driver.irmatching.parser.TestClassParser;
 33 import compiler.lib.ir_framework.shared.*;
 34 import compiler.lib.ir_framework.test.TestVM;
 35 import jdk.test.lib.Platform;
 36 import jdk.test.lib.Utils;
 37 import jdk.test.lib.helpers.ClassFileInstaller;
 38 import jdk.test.whitebox.WhiteBox;
 39 
 40 import java.io.PrintWriter;
 41 import java.io.StringWriter;
 42 import java.lang.reflect.Method;
 43 import java.net.MalformedURLException;
 44 import java.net.URL;
 45 import java.net.URLClassLoader;
 46 import java.nio.file.Path;
 47 import java.util.*;
 48 import java.util.stream.Collectors;
 49 
 50 /**
 51  * This class represents the main entry point to the test framework whose main purpose is to perform regex-based checks on
 52  * the C2 IR shape emitted by the VM flags {@code -XX:+PrintIdeal} and {@code -XX:+PrintOptoAssembly}. The framework can
 53  * also be used for other non-IR matching (and non-compiler) tests by providing easy to use annotations for commonly used
 54  * testing patterns and compiler control flags.
 55  * <p>
 56  * The framework offers various annotations to control how your test code should be invoked and being checked. There are
 57  * three kinds of tests depending on how much control is needed over the test invocation:
 58  * <b>Base tests</b> (see {@link Test}), <b>checked tests</b> (see {@link Check}), and <b>custom run tests</b>
 59  * (see {@link Run}). Each type of test needs to define a unique <i>test method</i> that specifies a {@link Test @Test}
 60  * annotation which represents the test code that is eventually executed by the test framework. More information about
 61  * the usage and how to write different tests can be found in {@link Test}, {@link Check}, and {@link Run}.
 62  * <p>
 63  * Each test method can specify an arbitrary number of IR rules. This is done by using {@link IR @IR} annotations which
 64  * can define regex strings that are matched on the output of {@code -XX:+PrintIdeal} and {@code -XX:+PrintOptoAssembly}.
 65  * The matching is done after the test method was (optionally) warmed up and compiled. More information about the usage
 66  * and how to write different IR rules can be found at {@link IR}.
 67  * <p>
 68  * This framework should be used with the following JTreg setup in your Test.java file in package <i>some.package</i>:
 69  * <pre>
 70  * {@literal @}library /test/lib
 71  * {@literal @}run driver some.package.Test
 72  * </pre>
 73  * Note that even though the framework uses the Whitebox API internally, it is not required to build and enabel it in the
 74  * JTreg test if the test itself is not utilizing any Whitebox features directly.
 75  * <p>
 76  * To specify additional flags, use {@link #runWithFlags(String...)}, {@link #addFlags(String...)}, or
 77  * {@link #addScenarios(Scenario...)} where the scenarios can also be used to run different flag combinations
 78  * (instead of specifying multiple JTreg {@code @run} entries).
 79  * <p>
 80  * After annotating your test code with the framework specific annotations, the framework needs to be invoked from the
 81  * {@code main()} method of your JTreg test. There are two ways to do so. The first way is by calling the various
 82  * {@code runXX()} methods of {@link TestFramework}. The second way, which gives more control, is to create a new
 83  * {@code TestFramework} builder object on which {@link #start()} needs to be eventually called to start the testing.
 84  * <p>
 85  * The framework is called from the <i>driver VM</i> in which the JTreg test is initially run by specifying {@code
 86  * @run driver} in the JTreg header. This strips all additionally specified JTreg VM and Javaoptions.
 87  * The framework creates a new <i>flag VM</i> with all these flags added again in order to figure out which flags are
 88  * required to run the tests specified in the test class (e.g. {@code -XX:+PrintIdeal} and {@code -XX:+PrintOptoAssembly}
 89  * for IR matching).
 90  * <p>
 91  * After the flag VM terminates, it starts a new <i>test VM</i> which performs the execution of the specified
 92  * tests in the test class as described in {@link Test}, {@link Check}, and {@link Run}.
 93  * <p>
 94  * In a last step, once the test VM has terminated without exceptions, IR matching is performed if there are any IR
 95  * rules and if no VM flags disable it (e.g. not running with {@code -Xint}, see {@link IR} for more details).
 96  * The IR regex matching is done on the output of {@code -XX:+PrintIdeal} and {@code -XX:+PrintOptoAssembly} by parsing
 97  * the hotspot_pid file of the test VM. Failing IR rules are reported by throwing a {@link IRViolationException}.
 98  *
 99  * @see Test
100  * @see Check
101  * @see Run
102  * @see IR
103  */
104 public class TestFramework {
105     /**
106      * JTreg can define additional VM (-Dtest.vm.opts) and Javaoptions (-Dtest.java.opts) flags. IR verification is only
107      * performed when all these additional JTreg flags (does not include additionally added framework and scenario flags
108      * by user code) are whitelisted.
109      *
110      * <p>
111      * A flag is whitelisted if it is a property flag (starting with -D), -ea, -esa, or if the flag name contains any of
112      * the entries of this list as a substring (partial match).
113      */
114     public static final Set<String> JTREG_WHITELIST_FLAGS = new HashSet<>(
115             Arrays.asList(
116                     // The following substrings are part of more than one VM flag
117                     "RAM",
118                     "Heap",
119                     "Trace",
120                     "Print",
121                     "Verify",
122                     "UseNewCode",
123                     "Xmn",
124                     "Xms",
125                     "Xmx",
126                     "Xss",
127                     // The following substrings are only part of one VM flag (=exact match)
128                     "CreateCoredumpOnCrash",
129                     "IgnoreUnrecognizedVMOptions",
130                     "UnlockDiagnosticVMOptions",
131                     "UnlockExperimentalVMOptions",
132                     "BackgroundCompilation",
133                     "Xbatch",
134                     "TieredCompilation",
135                     "CompileThreshold",
136                     "Xmixed",
137                     "server",
138                     "AlignVector",
139                     "UseAVX",
140                     "UseSSE",
141                     "UseSVE",
142                     "Xlog",
143                     "LogCompilation",
144                     "UseCompactObjectHeaders",
145                     "UseFMA",
146                     "AOTCache",
147                     // Riscv
148                     "UseRVV",
149                     "UseZbb",
150                     "UseZfh",
151                     "UseZicond",
152                     "UseZvbb"
153             )
154     );
155 
156     public static final boolean VERBOSE = Boolean.getBoolean("Verbose");
157     public static final boolean PRINT_RULE_MATCHING_TIME = Boolean.getBoolean("PrintRuleMatchingTime");
158     public static final boolean TESTLIST = !System.getProperty("Test", "").isEmpty();
159     public static final boolean EXCLUDELIST = !System.getProperty("Exclude", "").isEmpty();
160     private static final boolean REPORT_STDOUT = Boolean.getBoolean("ReportStdout");
161     // Only used for internal testing and should not be used for normal user testing.
162 
163     private static final String RERUN_HINT = """
164                                                #############################################################
165                                                 - To only run the failed tests use -DTest, -DExclude,
166                                                   and/or -DScenarios.
167                                                 - To also get the standard output of the test VM run with
168                                                   -DReportStdout=true or for even more fine-grained logging
169                                                   use -DVerbose=true.
170                                                #############################################################
171                                              """ + System.lineSeparator();
172 
173     private boolean irVerificationPossible = Boolean.parseBoolean(System.getProperty("VerifyIR", "true"));
174     private boolean shouldVerifyIR; // Should we perform IR matching?
175     private static boolean toggleBool;
176 
177     private final Class<?> testClass;
178     private Set<Class<?>> helperClasses;
179     private List<Scenario> scenarios;
180     private Set<Integer> scenarioIndices;
181     private List<String> flags;
182     private int defaultWarmup = -1;
183     private boolean testClassesOnBootClassPath;
184     private boolean isAllowNotCompilable = false;
185 
186     /*
187      * Public interface methods
188      */
189 
190     /**
191      * Creates an instance acting as a builder to test the class from which this constructor was invoked from.
192      * Use this constructor if you want to use multiple run options (flags, helper classes, scenarios).
193      * Use the associated add methods ({@link #addFlags(String...)}, {@link #addScenarios(Scenario...)},
194      * {@link #addHelperClasses(Class...)}) to set up everything and then start the testing by invoking {@link #start()}.
195      */
196     public TestFramework() {
197         this(StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass());
198     }
199 
200     /**
201      * Creates an instance acting as a builder to test {@code testClass}.
202      * Use this constructor if you want to use multiple run options (flags, helper classes, scenarios).
203      * Use the associated add methods ({@link #addFlags(String...)}, {@link #addScenarios(Scenario...)},
204      * {@link #addHelperClasses(Class...)}) to set up everything and then start the testing by invoking {@link #start()}.
205      *
206      * @param testClass the class to be tested by the framework.
207      * @see #TestFramework()
208      */
209     public TestFramework(Class<?> testClass) {
210         TestRun.check(testClass != null, "Test class cannot be null");
211         this.testClass = testClass;
212         if (VERBOSE) {
213             System.out.println("Test class: " + testClass);
214         }
215     }
216 
217     /**
218      * Tests the class from which this method was invoked from.
219      */
220     public static void run() {
221         StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
222         run(walker.getCallerClass());
223     }
224 
225     /**
226      * Tests {@code testClass}.
227      *
228      * @param testClass the class to be tested by the framework.
229      * @see #run()
230      */
231     public static void run(Class<?> testClass) {
232         TestFramework framework = new TestFramework(testClass);
233         framework.start();
234     }
235 
236     /**
237      * Tests the class from which this method was invoked from. The test VM is called with the specified {@code flags}.
238      * <ul>
239      *     <li><p>The {@code flags} override any set VM or Javaoptions flags by JTreg by default.<p>
240      *            Use {@code -DPreferCommandLineFlags=true} if you want to prefer the JTreg VM and  Javaoptions flags over
241      *            the specified {@code flags} of this method.</li>
242      *     <li><p>If you want to run your entire JTreg test with additional flags, use this method.</li>
243      *     <li><p>If you want to run your entire JTreg test with additional flags but for another test class then the one
244      *            from which this method was called from, use {@link #addFlags(String...)}, use this method.</li>
245      *     <li><p>If you want to run your JTreg test with multiple flag combinations, use
246      *            {@link #addScenarios(Scenario...)}</li>
247      * </ul>
248      *
249      * @param flags VM flags to be used for the test VM.
250      */
251     public static void runWithFlags(String... flags) {
252         StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
253         TestFramework framework = new TestFramework(walker.getCallerClass());
254         framework.addFlags(flags);
255         framework.start();
256     }
257 
258     /**
259      * Add VM flags to be used for the test VM. These flags override any VM or Javaoptions set by JTreg by default.<p>
260      * Use {@code -DPreferCommandLineFlags=true} if you want to prefer the VM or Javaoptions over the scenario flags.
261      *
262      * <p>
263      * The testing can be started by invoking {@link #start()}
264      *
265      * @param flags VM options to be applied to the test VM.
266      * @return the same framework instance.
267      */
268     public TestFramework addFlags(String... flags) {
269         TestRun.check(flags != null && Arrays.stream(flags).noneMatch(Objects::isNull), "A flag cannot be null");
270         if (this.flags == null) {
271             this.flags = new ArrayList<>();
272         }
273         this.flags.addAll(Arrays.asList(flags));
274         return this;
275     }
276 
277     /**
278      * Add helper classes that can specify additional compile command annotations ({@link ForceCompile @ForceCompile},
279      * {@link DontCompile @DontCompile}, {@link ForceInline @ForceInline}, {@link DontInline @DontInline}) to be applied
280      * while testing {@code testClass} (also see description of {@link TestFramework}).
281      *
282      * <p>
283      * Duplicates in {@code helperClasses} are ignored. If a class is used by the test class that does not specify any
284      * compile command annotations, you do not need to include it with this method. If no helper class specifies any
285      * compile commands, you do not need to call this method at all.
286      *
287      * <p>
288      * The testing can be started by invoking {@link #start()}.
289      *
290      * @param helperClasses helper classes containing compile command annotations ({@link ForceCompile},
291      *                      {@link DontCompile}, {@link ForceInline}, {@link DontInline}) to be applied
292      *                      while testing {@code testClass} (also see description of {@link TestFramework}).
293      * @return the same framework instance.
294      */
295     public TestFramework addHelperClasses(Class<?>... helperClasses) {
296         TestRun.check(helperClasses != null && Arrays.stream(helperClasses).noneMatch(Objects::isNull),
297                       "A Helper class cannot be null");
298         if (this.helperClasses == null) {
299             this.helperClasses = new HashSet<>();
300         }
301 
302         this.helperClasses.addAll(Arrays.asList(helperClasses));
303         return this;
304     }
305 
306     /**
307      * Add scenarios to be used for the test VM. A test VM is called for each scenario in {@code scenarios} by using the
308      * specified VM flags in the scenario. The scenario flags override any flags set by {@link #addFlags(String...)}
309      * and thus also override any VM or Javaoptions set by JTreg by default.<p>
310      * Use {@code -DPreferCommandLineFlags=true} if you want to prefer the VM and Javaoptions over the scenario flags.
311      *
312      * <p>
313      * The testing can be started by invoking {@link #start()}
314      *
315      * @param scenarios scenarios which specify specific flags for the test VM.
316      * @return the same framework instance.
317      */
318     public TestFramework addScenarios(Scenario... scenarios) {
319         TestFormat.checkAndReport(scenarios != null && Arrays.stream(scenarios).noneMatch(Objects::isNull),
320                                   "A scenario cannot be null");
321         if (this.scenarios == null) {
322             this.scenarios = new ArrayList<>();
323             this.scenarioIndices = new HashSet<>();
324         }
325 
326         for (Scenario scenario : scenarios) {
327             int scenarioIndex = scenario.getIndex();
328             TestFormat.checkNoThrow(scenarioIndices.add(scenarioIndex),
329                              "Cannot define two scenarios with the same index " + scenarioIndex);
330             this.scenarios.add(scenario);
331         }
332         TestFormat.throwIfAnyFailures();
333         return this;
334     }
335 
336     /**
337      * Add test classes to boot classpath. This adds all classes found on path {@link jdk.test.lib.Utils#TEST_CLASSES}
338      * to the boot classpath with "-Xbootclasspath/a". This is useful when trying to run tests in a privileged mode.
339      */
340     public TestFramework addTestClassesToBootClassPath() {
341         this.testClassesOnBootClassPath = true;
342         return this;
343     }
344 
345     /**
346      * Start the testing of the implicitly (by {@link #TestFramework()}) or explicitly (by {@link #TestFramework(Class)})
347      * set test class.
348      */
349     public void start() {
350         if (shouldInstallWhiteBox()) {
351             installWhiteBox();
352         }
353         checkIRRuleCompilePhasesFormat();
354         disableIRVerificationIfNotFeasible();
355 
356         if (scenarios == null) {
357             try {
358                 start(null);
359             } catch (TestVMException e) {
360                 System.err.println(System.lineSeparator() + e.getExceptionInfo() + RERUN_HINT);
361                 throw e;
362             } catch (IRViolationException e) {
363                 System.out.println(e.getCompilations());
364                 System.err.println(System.lineSeparator() + e.getExceptionInfo() + System.lineSeparator() + RERUN_HINT);
365                 throw e;
366             }
367         } else {
368             startWithScenarios();
369         }
370     }
371 
372     private void checkIRRuleCompilePhasesFormat() {
373         for (Method method : testClass.getDeclaredMethods()) {
374             for (IR irAnno : method.getAnnotationsByType(IR.class)) {
375                 TestFormat.checkNoThrow(irAnno.phase().length > 0,
376                                         "@IR rule " + irAnno + " must specify a non-empty list of compile " +
377                                         "phases \"phase\" at " + method);
378             }
379         }
380         TestFormat.throwIfAnyFailures();
381     }
382 
383     /**
384      * Try to load the Whitebox class from the user directory with a custom class loader. If the user has already built the
385      * Whitebox, we can load it. Otherwise, the framework needs to install it.
386      *
387      * @return true if the framework needs to install the Whitebox
388      */
389     private boolean shouldInstallWhiteBox() {
390         try {
391             URL url = Path.of(System.getProperty("user.dir")).toUri().toURL();
392             URLClassLoader userDirClassLoader =
393                     URLClassLoader.newInstance(new URL[] {url}, TestFramework.class.getClassLoader().getParent());
394             Class.forName(WhiteBox.class.getName(), false, userDirClassLoader);
395         } catch (MalformedURLException e) {
396             throw new TestFrameworkException("corrupted user.dir property", e);
397         } catch (ClassNotFoundException e) {
398             // We need to manually install the WhiteBox if we cannot load the WhiteBox class from the user directory.
399             // This happens when the user test does not explicitly install the WhiteBox as part of the test.
400             return true;
401         }
402         return false;
403     }
404 
405     /**
406      * Set a new default warm-up (overriding the framework default of 2000 at
407      * {@link TestVM#WARMUP_ITERATIONS}) to be applied for all tests that do not specify an explicit
408      * warm-up with {@link Warmup @Warmup}.
409      *
410      * @param defaultWarmup a new non-negative default warm-up.
411      * @return the same framework instance.
412      */
413     public TestFramework setDefaultWarmup(int defaultWarmup) {
414         TestFormat.checkAndReport(defaultWarmup >= 0, "Cannot specify a negative default warm-up");
415         this.defaultWarmup = defaultWarmup;
416         return this;
417     }
418 
419     /**
420      * In rare cases, methods may not be compilable because of a compilation bailout. By default, this leads to a
421      * test failure. However, if such cases are expected in multiple methods in a test class, this flag can be set to
422      * true, which allows any test to pass even if there is a compilation bailout. If only selected methods are prone
423      * to bail out, it is preferred to use {@link Test#allowNotCompilable()} instead for more fine-grained control.
424      * By setting this flag, any associated {@link IR} rule of a test is only executed if the test method was compiled,
425      * and else it is ignored silently.
426      */
427     public TestFramework allowNotCompilable() {
428         this.isAllowNotCompilable = true;
429         return this;
430     }
431 
432     /**
433      * Get the VM output of the test VM. Use {@code -DVerbose=true} to enable more debug information. If scenarios
434      * were run, use {@link Scenario#getTestVMOutput()}.
435      *
436      * @return the last test VM output.
437      */
438     public static String getLastTestVMOutput() {
439         return TestVMProcess.getLastTestVMOutput();
440     }
441 
442     /*
443      * The following methods are only intended to be called from actual @Test methods and not from the main() method of
444      * a JTreg test. Calling these methods from main() results in a linking exception (Whitebox not yet loaded and enabled).
445      */
446 
447     /**
448      * Compile {@code m} at compilation level {@code compLevel}. {@code m} is first enqueued and might not be compiled,
449      * yet, upon returning from this method.
450      *
451      * @param m the method to be compiled.
452      * @param compLevel the (valid) compilation level at which the method should be compiled.
453      * @throws TestRunException if compilation level is {@link CompLevel#SKIP} or {@link CompLevel#WAIT_FOR_COMPILATION}.
454      */
455     public static void compile(Method m, CompLevel compLevel) {
456         TestVM.compile(m, compLevel);
457     }
458 
459     /**
460      * Deoptimize {@code m}.
461      *
462      * @param m the method to be deoptimized.
463      */
464     public static void deoptimize(Method m) {
465         TestVM.deoptimize(m);
466     }
467 
468     /**
469      * Returns a boolean indicating if {@code m} is compiled at any level.
470      *
471      * @param m the method to be checked.
472      * @return {@code true} if {@code m} is compiled at any level;
473      *         {@code false} otherwise.
474      */
475     public static boolean isCompiled(Method m) {
476         return TestVM.isCompiled(m);
477     }
478 
479     /**
480      * Returns a boolean indicating if {@code m} is compiled with C1.
481      *
482      * @param m the method to be checked.
483      * @return {@code true} if {@code m} is compiled with C1;
484      *         {@code false} otherwise.
485      */
486     public static boolean isC1Compiled(Method m) {
487         return TestVM.isC1Compiled(m);
488     }
489 
490     /**
491      * Returns a boolean indicating if {@code m} is compiled with C2.
492      *
493      * @param m the method to be checked.
494      * @return {@code true} if {@code m} is compiled with C2;
495      *         {@code false} otherwise.
496      */
497     public static boolean isC2Compiled(Method m) {
498         return TestVM.isC2Compiled(m);
499     }
500 
501     /**
502      * Returns a boolean indicating if {@code m} is compiled at the specified {@code compLevel}.
503      *
504      * @param m the method to be checked.
505      * @param compLevel the compilation level.
506      * @return {@code true} if {@code m} is compiled at {@code compLevel};
507      *         {@code false} otherwise.
508      */
509     public static boolean isCompiledAtLevel(Method m, CompLevel compLevel) {
510         return TestVM.isCompiledAtLevel(m, compLevel);
511     }
512 
513     /**
514      * Checks if {@code m} is compiled at any level.
515      *
516      * @param m the method to be checked.
517      * @throws TestRunException if {@code m} is not compiled at any level.
518      */
519     public static void assertCompiled(Method m) {
520         TestVM.assertCompiled(m);
521     }
522 
523     /**
524      * Checks if {@code m} is not compiled at any level.
525      *
526      * @param m the method to be checked.
527      * @throws TestRunException if {@code m} is compiled at any level.
528      */
529     public static void assertNotCompiled(Method m) {
530         TestVM.assertNotCompiled(m);
531     }
532 
533     /**
534      * Verifies that {@code m} is compiled with C1.
535      *
536      * @param m the method to be verified.
537      * @throws TestRunException if {@code m} is not compiled with C1.
538      */
539     public static void assertCompiledByC1(Method m) {
540         TestVM.assertCompiledByC1(m);
541     }
542 
543     /**
544      * Verifies that {@code m} is compiled with C2.
545      *
546      * @param m the method to be checked.
547      * @throws TestRunException if {@code m} is not compiled with C2.
548      */
549     public static void assertCompiledByC2(Method m) {
550         TestVM.assertCompiledByC2(m);
551     }
552 
553     /**
554      * Verifies that {@code m} is compiled at the specified {@code compLevel}.
555      *
556      * @param m the method to be checked.
557      * @param compLevel the compilation level.
558      * @throws TestRunException if {@code m} is not compiled at {@code compLevel}.
559      */
560     public static void assertCompiledAtLevel(Method m, CompLevel compLevel) {
561         TestVM.assertCompiledAtLevel(m, compLevel);
562     }
563 
564     /**
565      * Verifies that {@code m} was deoptimized after being C1 compiled.
566      *
567      * @param m the method to be checked.
568      * @throws TestRunException if {@code m} is was not deoptimized after being C1 compiled.
569      */
570     public static void assertDeoptimizedByC1(Method m) {
571         TestVM.assertDeoptimizedByC1(m);
572     }
573 
574     /**
575      * Verifies that {@code m} was deoptimized after being C2 compiled.
576      *
577      * @param m the method to be checked.
578      * @throws TestRunException if {@code m} is was not deoptimized after being C2 compiled.
579      */
580     public static void assertDeoptimizedByC2(Method m) {
581         TestVM.assertDeoptimizedByC2(m);
582     }
583 
584     /**
585      * Returns a different boolean each time this method is invoked (switching between {@code false} and {@code true}).
586      * The very first invocation returns {@code false}. Note that this method could be used by different tests and
587      * thus the first invocation for a test could be {@code true} or {@code false} depending on how many times
588      * other tests have already invoked this method.
589      *
590      * @return an inverted boolean of the result of the last invocation of this method.
591      */
592     public static boolean toggleBoolean() {
593         toggleBool = !toggleBool;
594         return toggleBool;
595     }
596 
597     /*
598      * End of public interface methods
599      */
600 
601     /**
602      * Used to move Whitebox class to the right folder in the JTreg test
603      */
604     private void installWhiteBox() {
605         try {
606             ClassFileInstaller.main(WhiteBox.class.getName());
607         } catch (Exception e) {
608             throw new Error("failed to install whitebox classes", e);
609         }
610     }
611 
612     /**
613      * Disable IR verification completely in certain cases.
614      */
615     private void disableIRVerificationIfNotFeasible() {
616         if (!irVerificationPossible) {
617             return;
618         }
619 
620         boolean debugTest = Platform.isDebugBuild();
621         boolean intTest = !Platform.isInt();
622         boolean compTest = !Platform.isComp();
623         boolean irTest = hasIRAnnotations();
624         // No IR verification is done if additional non-whitelisted JTreg VM or Javaoptions flag is specified.
625         List<String> nonWhiteListedFlags = anyNonWhitelistedJTregVMAndJavaOptsFlags();
626         boolean nonWhiteListedTest = nonWhiteListedFlags.isEmpty();
627 
628         irVerificationPossible = debugTest && intTest && compTest && irTest && nonWhiteListedTest;
629         if (irVerificationPossible) {
630             return;
631         }
632 
633         System.out.println("IR verification disabled due to the following reason(s):");
634         if (!debugTest) {
635             System.out.println("- Not running a debug build (required for PrintIdeal and PrintOptoAssembly)");
636         }
637         if (!intTest) {
638             System.out.println("- Running with -Xint (no compilations)");
639         }
640         if (!compTest) {
641             System.out.println("- Running with -Xcomp (use warm-up of 0 instead)");
642         }
643         if (!irTest) {
644             System.out.println("- Test " + testClass + " not specifying any @IR annotations");
645         }
646         if (!nonWhiteListedTest) {
647             System.out.println("- Using non-whitelisted JTreg VM or Javaoptions flag(s):");
648             nonWhiteListedFlags.forEach((f) -> System.out.println("  - " + f));
649         }
650 
651         System.out.println("");
652     }
653 
654     /**
655      * For scenarios: Run the tests with the scenario settings and collect all exceptions to be able to run all
656      * scenarios without prematurely throwing an exception. Format violations, however, are wrong for all scenarios
657      * and thus is reported immediately on the first scenario execution.
658      */
659     private void startWithScenarios() {
660         Map<Scenario, Exception> exceptionMap = new TreeMap<>(Comparator.comparingInt(Scenario::getIndex));
661         for (Scenario scenario : scenarios) {
662             try {
663                 start(scenario);
664             } catch (TestFormatException e) {
665                 // Test format violation is wrong for all the scenarios. Only report once.
666                 throw e;
667             } catch (Exception e) {
668                 exceptionMap.put(scenario, e);
669             }
670         }
671         if (!exceptionMap.isEmpty()) {
672             reportScenarioFailures(exceptionMap);
673         }
674     }
675 
676     private void reportScenarioFailures(Map<Scenario, Exception> exceptionMap) {
677         String failedScenarios = "The following scenarios have failed: #"
678                                  + exceptionMap.keySet().stream()
679                                                .map(s -> String.valueOf(s.getIndex()))
680                                                .collect(Collectors.joining(", #"));
681         StringBuilder builder = new StringBuilder(failedScenarios);
682         builder.append(System.lineSeparator()).append(System.lineSeparator());
683         for (Map.Entry<Scenario, Exception> entry : exceptionMap.entrySet()) {
684             Exception e = entry.getValue();
685             Scenario scenario = entry.getKey();
686             String errorMsg = "";
687             if (scenario != null) {
688                 errorMsg = getScenarioTitleAndFlags(scenario);
689             }
690             if (e instanceof IRViolationException irException) {
691                 // For IR violations, only show the actual violations and not the (uninteresting) stack trace.
692                 if (scenario != null) {
693                     System.out.println("Scenario #" + scenario.getIndex());
694                 }
695                 System.out.println(irException.getCompilations());
696                 builder.append(errorMsg).append(System.lineSeparator()).append(irException.getExceptionInfo());
697             } else if (e instanceof TestVMException testVMException) {
698                 builder.append(errorMsg).append(System.lineSeparator()).append(testVMException.getExceptionInfo());
699             } else {
700                 // Print stack trace otherwise
701                 StringWriter errors = new StringWriter();
702                 e.printStackTrace(new PrintWriter(errors));
703                 builder.append(errors);
704             }
705             builder.append(System.lineSeparator());
706         }
707         System.err.println(builder);
708         if (!VERBOSE && !REPORT_STDOUT && !TESTLIST && !EXCLUDELIST) {
709             // Provide a hint to the user how to get additional output/debugging information.
710             System.err.println(RERUN_HINT);
711         }
712         throw new TestRunException(failedScenarios + ". Please check stderr for more information.");
713     }
714 
715     private static String getScenarioTitleAndFlags(Scenario scenario) {
716         StringBuilder builder = new StringBuilder();
717         String title = "Scenario #" + scenario.getIndex();
718         builder.append(title).append(System.lineSeparator()).append("=".repeat(title.length()))
719                .append(System.lineSeparator());
720         builder.append("Scenario flags: [").append(String.join(", ", scenario.getFlags())).append("]")
721                .append(System.lineSeparator());
722         return builder.toString();
723     }
724 
725     /**
726      * Execute a separate "flag" VM with White Box access to determine all test VM flags. The flag VM sends an encoding of
727      * all required flags for the test VM to the driver VM over a socket. Once the flag VM exits, this driver VM parses the
728      * test VM flags, which also determine if IR matching should be done, and then starts the test VM to execute all tests.
729      */
730     private void start(Scenario scenario) {
731         if (scenario != null && !scenario.isEnabled()) {
732             System.out.println("Disabled scenario #" + scenario.getIndex() + "! This scenario is not present in set flag " +
733                                "-DScenarios and is therefore not executed.");
734             return;
735         }
736         shouldVerifyIR = irVerificationPossible;
737         try {
738             // Use TestFramework flags and scenario flags for new VMs.
739             List<String> additionalFlags = new ArrayList<>();
740             if (flags != null) {
741                 additionalFlags.addAll(flags);
742             }
743             if (scenario != null) {
744                 List<String> scenarioFlags = scenario.getFlags();
745                 String scenarioFlagsString = scenarioFlags.isEmpty() ? "" : " - [" + String.join(", ", scenarioFlags) + "]";
746                 System.out.println("Scenario #" + scenario.getIndex() + scenarioFlagsString + ":");
747                 additionalFlags.addAll(scenarioFlags);
748             }
749             String frameworkAndScenarioFlags = additionalFlags.isEmpty() ?
750                     "" : " - [" + String.join(", ", additionalFlags) + "]";
751 
752             if (shouldVerifyIR) {
753                 // Only need to use flag VM if an IR verification is possibly done.
754                 System.out.println("Run Flag VM:");
755                 FlagVMProcess flagVMProcess = new FlagVMProcess(testClass, additionalFlags);
756                 shouldVerifyIR = flagVMProcess.shouldVerifyIR();
757                 if (shouldVerifyIR) {
758                     // Add more flags for the test VM which are required to do IR verification.
759                     additionalFlags.addAll(flagVMProcess.getTestVMFlags());
760                 } // else: Flag VM found a reason to not do IR verification.
761             } else {
762                 System.out.println("Skip Flag VM due to not performing IR verification.");
763             }
764 
765             System.out.println("Run Test VM" + frameworkAndScenarioFlags + ":");
766             runTestVM(additionalFlags);
767         } finally {
768             if (scenario != null) {
769                 scenario.setTestVMOutput(TestVMProcess.getLastTestVMOutput());
770             }
771             System.out.println();
772         }
773     }
774 
775     private boolean hasIRAnnotations() {
776         return Arrays.stream(testClass.getDeclaredMethods()).anyMatch(m -> m.getAnnotationsByType(IR.class).length > 0);
777     }
778 
779     private List<String> anyNonWhitelistedJTregVMAndJavaOptsFlags() {
780         List<String> flags = Arrays.stream(Utils.getTestJavaOpts())
781                                    .map(s -> s.replaceFirst("-XX:[+|-]?|-(?=[^D|^e])", ""))
782                                    .collect(Collectors.toList());
783         List<String> nonWhiteListedFlags = new ArrayList();
784         for (String flag : flags) {
785             // Property flags (prefix -D), -ea and -esa are whitelisted.
786             if (!flag.startsWith("-D") && !flag.startsWith("-e") && JTREG_WHITELIST_FLAGS.stream().noneMatch(flag::contains)) {
787                 // Found VM flag that is not whitelisted
788                 nonWhiteListedFlags.add(flag);
789             }
790         }
791         return nonWhiteListedFlags;
792     }
793 
794     private void runTestVM(List<String> additionalFlags) {
795         TestVMProcess testVMProcess = new TestVMProcess(additionalFlags, testClass, helperClasses, defaultWarmup,
796                                                         isAllowNotCompilable, testClassesOnBootClassPath);
797         if (shouldVerifyIR) {
798             try {
799                 TestClassParser testClassParser = new TestClassParser(testClass, isAllowNotCompilable);
800                 Matchable testClassMatchable = testClassParser.parse(testVMProcess.getHotspotPidFileName(),
801                                                                      testVMProcess.getIrEncoding());
802                 IRMatcher matcher = new IRMatcher(testClassMatchable);
803                 matcher.match();
804             } catch (IRViolationException e) {
805                 e.addCommandLine(testVMProcess.getCommandLine());
806                 throw e;
807             }
808         } else {
809             System.out.println("IR verification disabled either due to no @IR annotations, through explicitly setting " +
810                                "-DVerify=false, due to not running a debug build, using a non-whitelisted JTreg VM or " +
811                                "Javaopts flag like -Xint, or running the test VM with other VM flags added by user code " +
812                                "that make the IR verification impossible (e.g. -XX:-UseCompile, " +
813                                "-XX:TieredStopAtLevel=[1,2,3], etc.).");
814         }
815     }
816 
817     public static void check(boolean test, String failureMessage) {
818         if (!test) {
819             throw new TestFrameworkException(failureMessage);
820         }
821     }
822 }