1 /*
  2  * Copyright (c) 2021, 2024, 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                     "UseZbb",
143                     "UseRVV",
144                     "Xlog",
145                     "LogCompilation"
146             )
147     );
148 
149     public static final boolean VERBOSE = Boolean.getBoolean("Verbose");
150     public static final boolean TESTLIST = !System.getProperty("Test", "").isEmpty();
151     public static final boolean EXCLUDELIST = !System.getProperty("Exclude", "").isEmpty();
152     private static final boolean REPORT_STDOUT = Boolean.getBoolean("ReportStdout");
153     // Only used for internal testing and should not be used for normal user testing.
154 
155     private static final String RERUN_HINT = """
156                                                #############################################################
157                                                 - To only run the failed tests use -DTest, -DExclude,
158                                                   and/or -DScenarios.
159                                                 - To also get the standard output of the test VM run with
160                                                   -DReportStdout=true or for even more fine-grained logging
161                                                   use -DVerbose=true.
162                                                #############################################################
163                                              """ + System.lineSeparator();
164 
165     private boolean irVerificationPossible = Boolean.parseBoolean(System.getProperty("VerifyIR", "true"));
166     private boolean shouldVerifyIR; // Should we perform IR matching?
167     private static boolean toggleBool;
168 
169     private final Class<?> testClass;
170     private Set<Class<?>> helperClasses;
171     private List<Scenario> scenarios;
172     private Set<Integer> scenarioIndices;
173     private List<String> flags;
174     private int defaultWarmup = -1;
175     private boolean testClassesOnBootClassPath;
176 
177     /*
178      * Public interface methods
179      */
180 
181     /**
182      * Creates an instance acting as a builder to test the class from which this constructor was invoked from.
183      * Use this constructor if you want to use multiple run options (flags, helper classes, scenarios).
184      * Use the associated add methods ({@link #addFlags(String...)}, {@link #addScenarios(Scenario...)},
185      * {@link #addHelperClasses(Class...)}) to set up everything and then start the testing by invoking {@link #start()}.
186      */
187     public TestFramework() {
188         this(StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass());
189     }
190 
191     /**
192      * Creates an instance acting as a builder to test {@code testClass}.
193      * Use this constructor if you want to use multiple run options (flags, helper classes, scenarios).
194      * Use the associated add methods ({@link #addFlags(String...)}, {@link #addScenarios(Scenario...)},
195      * {@link #addHelperClasses(Class...)}) to set up everything and then start the testing by invoking {@link #start()}.
196      *
197      * @param testClass the class to be tested by the framework.
198      * @see #TestFramework()
199      */
200     public TestFramework(Class<?> testClass) {
201         TestRun.check(testClass != null, "Test class cannot be null");
202         this.testClass = testClass;
203         if (VERBOSE) {
204             System.out.println("Test class: " + testClass);
205         }
206     }
207 
208     /**
209      * Tests the class from which this method was invoked from.
210      */
211     public static void run() {
212         StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
213         run(walker.getCallerClass());
214     }
215 
216     /**
217      * Tests {@code testClass}.
218      *
219      * @param testClass the class to be tested by the framework.
220      * @see #run()
221      */
222     public static void run(Class<?> testClass) {
223         TestFramework framework = new TestFramework(testClass);
224         framework.start();
225     }
226 
227     /**
228      * Tests the class from which this method was invoked from. The test VM is called with the specified {@code flags}.
229      * <ul>
230      *     <li><p>The {@code flags} override any set VM or Javaoptions flags by JTreg by default.<p>
231      *            Use {@code -DPreferCommandLineFlags=true} if you want to prefer the JTreg VM and  Javaoptions flags over
232      *            the specified {@code flags} of this method.</li>
233      *     <li><p>If you want to run your entire JTreg test with additional flags, use this method.</li>
234      *     <li><p>If you want to run your entire JTreg test with additional flags but for another test class then the one
235      *            from which this method was called from, use {@link #addFlags(String...)}, use this method.</li>
236      *     <li><p>If you want to run your JTreg test with multiple flag combinations, use
237      *            {@link #addScenarios(Scenario...)}</li>
238      * </ul>
239      *
240      * @param flags VM flags to be used for the test VM.
241      */
242     public static void runWithFlags(String... flags) {
243         StackWalker walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
244         TestFramework framework = new TestFramework(walker.getCallerClass());
245         framework.addFlags(flags);
246         framework.start();
247     }
248 
249     /**
250      * Add VM flags to be used for the test VM. These flags override any VM or Javaoptions set by JTreg by default.<p>
251      * Use {@code -DPreferCommandLineFlags=true} if you want to prefer the VM or Javaoptions over the scenario flags.
252      *
253      * <p>
254      * The testing can be started by invoking {@link #start()}
255      *
256      * @param flags VM options to be applied to the test VM.
257      * @return the same framework instance.
258      */
259     public TestFramework addFlags(String... flags) {
260         TestRun.check(flags != null && Arrays.stream(flags).noneMatch(Objects::isNull), "A flag cannot be null");
261         if (this.flags == null) {
262             this.flags = new ArrayList<>();
263         }
264         this.flags.addAll(Arrays.asList(flags));
265         return this;
266     }
267 
268     /**
269      * Add helper classes that can specify additional compile command annotations ({@link ForceCompile @ForceCompile},
270      * {@link DontCompile @DontCompile}, {@link ForceInline @ForceInline}, {@link DontInline @DontInline}) to be applied
271      * while testing {@code testClass} (also see description of {@link TestFramework}).
272      *
273      * <p>
274      * Duplicates in {@code helperClasses} are ignored. If a class is used by the test class that does not specify any
275      * compile command annotations, you do not need to include it with this method. If no helper class specifies any
276      * compile commands, you do not need to call this method at all.
277      *
278      * <p>
279      * The testing can be started by invoking {@link #start()}.
280      *
281      * @param helperClasses helper classes containing compile command annotations ({@link ForceCompile},
282      *                      {@link DontCompile}, {@link ForceInline}, {@link DontInline}) to be applied
283      *                      while testing {@code testClass} (also see description of {@link TestFramework}).
284      * @return the same framework instance.
285      */
286     public TestFramework addHelperClasses(Class<?>... helperClasses) {
287         TestRun.check(helperClasses != null && Arrays.stream(helperClasses).noneMatch(Objects::isNull),
288                       "A Helper class cannot be null");
289         if (this.helperClasses == null) {
290             this.helperClasses = new HashSet<>();
291         }
292 
293         this.helperClasses.addAll(Arrays.asList(helperClasses));
294         return this;
295     }
296 
297     /**
298      * Add scenarios to be used for the test VM. A test VM is called for each scenario in {@code scenarios} by using the
299      * specified VM flags in the scenario. The scenario flags override any flags set by {@link #addFlags(String...)}
300      * and thus also override any VM or Javaoptions set by JTreg by default.<p>
301      * Use {@code -DPreferCommandLineFlags=true} if you want to prefer the VM and Javaoptions over the scenario flags.
302      *
303      * <p>
304      * The testing can be started by invoking {@link #start()}
305      *
306      * @param scenarios scenarios which specify specific flags for the test VM.
307      * @return the same framework instance.
308      */
309     public TestFramework addScenarios(Scenario... scenarios) {
310         TestFormat.checkAndReport(scenarios != null && Arrays.stream(scenarios).noneMatch(Objects::isNull),
311                                   "A scenario cannot be null");
312         if (this.scenarios == null) {
313             this.scenarios = new ArrayList<>();
314             this.scenarioIndices = new HashSet<>();
315         }
316 
317         for (Scenario scenario : scenarios) {
318             int scenarioIndex = scenario.getIndex();
319             TestFormat.checkNoThrow(scenarioIndices.add(scenarioIndex),
320                              "Cannot define two scenarios with the same index " + scenarioIndex);
321             this.scenarios.add(scenario);
322         }
323         TestFormat.throwIfAnyFailures();
324         return this;
325     }
326 
327     /**
328      * Add test classes to boot classpath. This adds all classes found on path {@link jdk.test.lib.Utils#TEST_CLASSES}
329      * to the boot classpath with "-Xbootclasspath/a". This is useful when trying to run tests in a privileged mode.
330      */
331     public TestFramework addTestClassesToBootClassPath() {
332         this.testClassesOnBootClassPath = true;
333         return this;
334     }
335 
336     /**
337      * Start the testing of the implicitly (by {@link #TestFramework()}) or explicitly (by {@link #TestFramework(Class)})
338      * set test class.
339      */
340     public void start() {
341         if (shouldInstallWhiteBox()) {
342             installWhiteBox();
343         }
344         checkIRRuleCompilePhasesFormat();
345         disableIRVerificationIfNotFeasible();
346 
347         if (scenarios == null) {
348             try {
349                 start(null);
350             } catch (TestVMException e) {
351                 System.err.println(System.lineSeparator() + e.getExceptionInfo() + RERUN_HINT);
352                 throw e;
353             } catch (IRViolationException e) {
354                 System.out.println(e.getCompilations());
355                 System.err.println(System.lineSeparator() + e.getExceptionInfo() + System.lineSeparator() + RERUN_HINT);
356                 throw e;
357             }
358         } else {
359             startWithScenarios();
360         }
361     }
362 
363     private void checkIRRuleCompilePhasesFormat() {
364         for (Method method : testClass.getDeclaredMethods()) {
365             for (IR irAnno : method.getAnnotationsByType(IR.class)) {
366                 TestFormat.checkNoThrow(irAnno.phase().length > 0,
367                                         "@IR rule " + irAnno + " must specify a non-empty list of compile " +
368                                         "phases \"phase\" at " + method);
369             }
370         }
371         TestFormat.throwIfAnyFailures();
372     }
373 
374     /**
375      * Try to load the Whitebox class from the user directory with a custom class loader. If the user has already built the
376      * Whitebox, we can load it. Otherwise, the framework needs to install it.
377      *
378      * @return true if the framework needs to install the Whitebox
379      */
380     private boolean shouldInstallWhiteBox() {
381         try {
382             URL url = Path.of(System.getProperty("user.dir")).toUri().toURL();
383             URLClassLoader userDirClassLoader =
384                     URLClassLoader.newInstance(new URL[] {url}, TestFramework.class.getClassLoader().getParent());
385             Class.forName(WhiteBox.class.getName(), false, userDirClassLoader);
386         } catch (MalformedURLException e) {
387             throw new TestFrameworkException("corrupted user.dir property", e);
388         } catch (ClassNotFoundException e) {
389             // We need to manually install the WhiteBox if we cannot load the WhiteBox class from the user directory.
390             // This happens when the user test does not explicitly install the WhiteBox as part of the test.
391             return true;
392         }
393         return false;
394     }
395 
396     /**
397      * Set a new default warm-up (overriding the framework default of 2000 at
398      * {@link TestVM#WARMUP_ITERATIONS}) to be applied for all tests that do not specify an explicit
399      * warm-up with {@link Warmup @Warmup}.
400      *
401      * @param defaultWarmup a new non-negative default warm-up.
402      * @return the same framework instance.
403      */
404     public TestFramework setDefaultWarmup(int defaultWarmup) {
405         TestFormat.checkAndReport(defaultWarmup >= 0, "Cannot specify a negative default warm-up");
406         this.defaultWarmup = defaultWarmup;
407         return this;
408     }
409 
410     /**
411      * Get the VM output of the test VM. Use {@code -DVerbose=true} to enable more debug information. If scenarios
412      * were run, use {@link Scenario#getTestVMOutput()}.
413      *
414      * @return the last test VM output.
415      */
416     public static String getLastTestVMOutput() {
417         return TestVMProcess.getLastTestVMOutput();
418     }
419 
420     /*
421      * The following methods are only intended to be called from actual @Test methods and not from the main() method of
422      * a JTreg test. Calling these methods from main() results in a linking exception (Whitebox not yet loaded and enabled).
423      */
424 
425     /**
426      * Compile {@code m} at compilation level {@code compLevel}. {@code m} is first enqueued and might not be compiled,
427      * yet, upon returning from this method.
428      *
429      * @param m the method to be compiled.
430      * @param compLevel the (valid) compilation level at which the method should be compiled.
431      * @throws TestRunException if compilation level is {@link CompLevel#SKIP} or {@link CompLevel#WAIT_FOR_COMPILATION}.
432      */
433     public static void compile(Method m, CompLevel compLevel) {
434         TestVM.compile(m, compLevel);
435     }
436 
437     /**
438      * Deoptimize {@code m}.
439      *
440      * @param m the method to be deoptimized.
441      */
442     public static void deoptimize(Method m) {
443         TestVM.deoptimize(m);
444     }
445 
446     /**
447      * Returns a boolean indicating if {@code m} is compiled at any level.
448      *
449      * @param m the method to be checked.
450      * @return {@code true} if {@code m} is compiled at any level;
451      *         {@code false} otherwise.
452      */
453     public static boolean isCompiled(Method m) {
454         return TestVM.isCompiled(m);
455     }
456 
457     /**
458      * Returns a boolean indicating if {@code m} is compiled with C1.
459      *
460      * @param m the method to be checked.
461      * @return {@code true} if {@code m} is compiled with C1;
462      *         {@code false} otherwise.
463      */
464     public static boolean isC1Compiled(Method m) {
465         return TestVM.isC1Compiled(m);
466     }
467 
468     /**
469      * Returns a boolean indicating if {@code m} is compiled with C2.
470      *
471      * @param m the method to be checked.
472      * @return {@code true} if {@code m} is compiled with C2;
473      *         {@code false} otherwise.
474      */
475     public static boolean isC2Compiled(Method m) {
476         return TestVM.isC2Compiled(m);
477     }
478 
479     /**
480      * Returns a boolean indicating if {@code m} is compiled at the specified {@code compLevel}.
481      *
482      * @param m the method to be checked.
483      * @param compLevel the compilation level.
484      * @return {@code true} if {@code m} is compiled at {@code compLevel};
485      *         {@code false} otherwise.
486      */
487     public static boolean isCompiledAtLevel(Method m, CompLevel compLevel) {
488         return TestVM.isCompiledAtLevel(m, compLevel);
489     }
490 
491     /**
492      * Checks if {@code m} is compiled at any level.
493      *
494      * @param m the method to be checked.
495      * @throws TestRunException if {@code m} is not compiled at any level.
496      */
497     public static void assertCompiled(Method m) {
498         TestVM.assertCompiled(m);
499     }
500 
501     /**
502      * Checks if {@code m} is not compiled at any level.
503      *
504      * @param m the method to be checked.
505      * @throws TestRunException if {@code m} is compiled at any level.
506      */
507     public static void assertNotCompiled(Method m) {
508         TestVM.assertNotCompiled(m);
509     }
510 
511     /**
512      * Verifies that {@code m} is compiled with C1.
513      *
514      * @param m the method to be verified.
515      * @throws TestRunException if {@code m} is not compiled with C1.
516      */
517     public static void assertCompiledByC1(Method m) {
518         TestVM.assertCompiledByC1(m);
519     }
520 
521     /**
522      * Verifies that {@code m} is compiled with C2.
523      *
524      * @param m the method to be checked.
525      * @throws TestRunException if {@code m} is not compiled with C2.
526      */
527     public static void assertCompiledByC2(Method m) {
528         TestVM.assertCompiledByC2(m);
529     }
530 
531     /**
532      * Verifies that {@code m} is compiled at the specified {@code compLevel}.
533      *
534      * @param m the method to be checked.
535      * @param compLevel the compilation level.
536      * @throws TestRunException if {@code m} is not compiled at {@code compLevel}.
537      */
538     public static void assertCompiledAtLevel(Method m, CompLevel compLevel) {
539         TestVM.assertCompiledAtLevel(m, compLevel);
540     }
541 
542     /**
543      * Verifies that {@code m} was deoptimized after being C1 compiled.
544      *
545      * @param m the method to be checked.
546      * @throws TestRunException if {@code m} is was not deoptimized after being C1 compiled.
547      */
548     public static void assertDeoptimizedByC1(Method m) {
549         TestVM.assertDeoptimizedByC1(m);
550     }
551 
552     /**
553      * Verifies that {@code m} was deoptimized after being C2 compiled.
554      *
555      * @param m the method to be checked.
556      * @throws TestRunException if {@code m} is was not deoptimized after being C2 compiled.
557      */
558     public static void assertDeoptimizedByC2(Method m) {
559         TestVM.assertDeoptimizedByC2(m);
560     }
561 
562     /**
563      * Checks if deopt of {@code m} is stable at the specified {@code compLevel}.
564      *
565      * @param m the method to be checked.
566      * @param compLevel the compilation level.
567      * @return {@code true} if deopt of {@code m} is stable at {@code compLevel};
568      *         {@code false} otherwise.
569      */
570     public static boolean isStableDeopt(Method m, CompLevel compLevel) {
571         return TestVM.isStableDeopt(m, compLevel);
572     }
573 
574     /**
575      * Returns a different boolean each time this method is invoked (switching between {@code false} and {@code true}).
576      * The very first invocation returns {@code false}. Note that this method could be used by different tests and
577      * thus the first invocation for a test could be {@code true} or {@code false} depending on how many times
578      * other tests have already invoked this method.
579      *
580      * @return an inverted boolean of the result of the last invocation of this method.
581      */
582     public static boolean toggleBoolean() {
583         toggleBool = !toggleBool;
584         return toggleBool;
585     }
586 
587     /*
588      * End of public interface methods
589      */
590 
591     /**
592      * Used to move Whitebox class to the right folder in the JTreg test
593      */
594     private void installWhiteBox() {
595         try {
596             ClassFileInstaller.main(WhiteBox.class.getName());
597         } catch (Exception e) {
598             throw new Error("failed to install whitebox classes", e);
599         }
600     }
601 
602     /**
603      * Disable IR verification completely in certain cases.
604      */
605     private void disableIRVerificationIfNotFeasible() {
606         if (irVerificationPossible) {
607             irVerificationPossible = Platform.isDebugBuild() && !Platform.isInt() && !Platform.isComp();
608             if (!irVerificationPossible) {
609                 System.out.println("IR verification disabled due to not running a debug build (required for PrintIdeal" +
610                                    "and PrintOptoAssembly), running with -Xint, or -Xcomp (use warm-up of 0 instead)");
611                 return;
612             }
613 
614             irVerificationPossible = hasIRAnnotations();
615             if (!irVerificationPossible) {
616                 System.out.println("IR verification disabled due to test " + testClass + " not specifying any @IR annotations");
617                 return;
618             }
619 
620             // No IR verification is done if additional non-whitelisted JTreg VM or Javaoptions flag is specified.
621             irVerificationPossible = onlyWhitelistedJTregVMAndJavaOptsFlags();
622             if (!irVerificationPossible) {
623                 System.out.println("IR verification disabled due to using non-whitelisted JTreg VM or Javaoptions flag(s)."
624                                    + System.lineSeparator());
625             }
626         }
627     }
628 
629     /**
630      * For scenarios: Run the tests with the scenario settings and collect all exceptions to be able to run all
631      * scenarios without prematurely throwing an exception. Format violations, however, are wrong for all scenarios
632      * and thus is reported immediately on the first scenario execution.
633      */
634     private void startWithScenarios() {
635         Map<Scenario, Exception> exceptionMap = new TreeMap<>(Comparator.comparingInt(Scenario::getIndex));
636         for (Scenario scenario : scenarios) {
637             try {
638                 start(scenario);
639             } catch (TestFormatException e) {
640                 // Test format violation is wrong for all the scenarios. Only report once.
641                 throw e;
642             } catch (Exception e) {
643                 exceptionMap.put(scenario, e);
644             }
645         }
646         if (!exceptionMap.isEmpty()) {
647             reportScenarioFailures(exceptionMap);
648         }
649     }
650 
651     private void reportScenarioFailures(Map<Scenario, Exception> exceptionMap) {
652         String failedScenarios = "The following scenarios have failed: #"
653                                  + exceptionMap.keySet().stream()
654                                                .map(s -> String.valueOf(s.getIndex()))
655                                                .collect(Collectors.joining(", #"));
656         StringBuilder builder = new StringBuilder(failedScenarios);
657         builder.append(System.lineSeparator()).append(System.lineSeparator());
658         for (Map.Entry<Scenario, Exception> entry : exceptionMap.entrySet()) {
659             Exception e = entry.getValue();
660             Scenario scenario = entry.getKey();
661             String errorMsg = "";
662             if (scenario != null) {
663                 errorMsg = getScenarioTitleAndFlags(scenario);
664             }
665             if (e instanceof IRViolationException irException) {
666                 // For IR violations, only show the actual violations and not the (uninteresting) stack trace.
667                 if (scenario != null) {
668                     System.out.println("Scenario #" + scenario.getIndex());
669                 }
670                 System.out.println(irException.getCompilations());
671                 builder.append(errorMsg).append(System.lineSeparator()).append(irException.getExceptionInfo());
672             } else if (e instanceof TestVMException testVMException) {
673                 builder.append(errorMsg).append(System.lineSeparator()).append(testVMException.getExceptionInfo());
674             } else {
675                 // Print stack trace otherwise
676                 StringWriter errors = new StringWriter();
677                 e.printStackTrace(new PrintWriter(errors));
678                 builder.append(errors);
679             }
680             builder.append(System.lineSeparator());
681         }
682         System.err.println(builder);
683         if (!VERBOSE && !REPORT_STDOUT && !TESTLIST && !EXCLUDELIST) {
684             // Provide a hint to the user how to get additional output/debugging information.
685             System.err.println(RERUN_HINT);
686         }
687         throw new TestRunException(failedScenarios + ". Please check stderr for more information.");
688     }
689 
690     private static String getScenarioTitleAndFlags(Scenario scenario) {
691         StringBuilder builder = new StringBuilder();
692         String title = "Scenario #" + scenario.getIndex();
693         builder.append(title).append(System.lineSeparator()).append("=".repeat(title.length()))
694                .append(System.lineSeparator());
695         builder.append("Scenario flags: [").append(String.join(", ", scenario.getFlags())).append("]")
696                .append(System.lineSeparator());
697         return builder.toString();
698     }
699 
700     /**
701      * Execute a separate "flag" VM with White Box access to determine all test VM flags. The flag VM sends an encoding of
702      * all required flags for the test VM to the driver VM over a socket. Once the flag VM exits, this driver VM parses the
703      * test VM flags, which also determine if IR matching should be done, and then starts the test VM to execute all tests.
704      */
705     private void start(Scenario scenario) {
706         if (scenario != null && !scenario.isEnabled()) {
707             System.out.println("Disabled scenario #" + scenario.getIndex() + "! This scenario is not present in set flag " +
708                                "-DScenarios and is therefore not executed.");
709             return;
710         }
711         shouldVerifyIR = irVerificationPossible;
712         try {
713             // Use TestFramework flags and scenario flags for new VMs.
714             List<String> additionalFlags = new ArrayList<>();
715             if (flags != null) {
716                 additionalFlags.addAll(flags);
717             }
718             if (scenario != null) {
719                 List<String> scenarioFlags = scenario.getFlags();
720                 String scenarioFlagsString = scenarioFlags.isEmpty() ? "" : " - [" + String.join(", ", scenarioFlags) + "]";
721                 System.out.println("Scenario #" + scenario.getIndex() + scenarioFlagsString + ":");
722                 additionalFlags.addAll(scenarioFlags);
723             }
724             String frameworkAndScenarioFlags = additionalFlags.isEmpty() ?
725                     "" : " - [" + String.join(", ", additionalFlags) + "]";
726 
727             if (shouldVerifyIR) {
728                 // Only need to use flag VM if an IR verification is possibly done.
729                 System.out.println("Run Flag VM:");
730                 FlagVMProcess flagVMProcess = new FlagVMProcess(testClass, additionalFlags);
731                 shouldVerifyIR = flagVMProcess.shouldVerifyIR();
732                 if (shouldVerifyIR) {
733                     // Add more flags for the test VM which are required to do IR verification.
734                     additionalFlags.addAll(flagVMProcess.getTestVMFlags());
735                 } // else: Flag VM found a reason to not do IR verification.
736             } else {
737                 System.out.println("Skip Flag VM due to not performing IR verification.");
738             }
739 
740             System.out.println("Run Test VM" + frameworkAndScenarioFlags + ":");
741             runTestVM(additionalFlags);
742         } finally {
743             if (scenario != null) {
744                 scenario.setTestVMOutput(TestVMProcess.getLastTestVMOutput());
745             }
746             System.out.println();
747         }
748     }
749 
750     private boolean hasIRAnnotations() {
751         return Arrays.stream(testClass.getDeclaredMethods()).anyMatch(m -> m.getAnnotationsByType(IR.class).length > 0);
752     }
753 
754     private boolean onlyWhitelistedJTregVMAndJavaOptsFlags() {
755         List<String> flags = Arrays.stream(Utils.getTestJavaOpts())
756                                    .map(s -> s.replaceFirst("-XX:[+|-]?|-(?=[^D|^e])", ""))
757                                    .collect(Collectors.toList());
758         for (String flag : flags) {
759             // Property flags (prefix -D), -ea and -esa are whitelisted.
760             if (!flag.startsWith("-D") && !flag.startsWith("-e") && JTREG_WHITELIST_FLAGS.stream().noneMatch(flag::contains)) {
761                 // Found VM flag that is not whitelisted
762                 return false;
763             }
764         }
765         return true;
766     }
767 
768     private void runTestVM(List<String> additionalFlags) {
769         TestVMProcess testVMProcess = new TestVMProcess(additionalFlags, testClass, helperClasses, defaultWarmup,
770                                                         testClassesOnBootClassPath);
771         if (shouldVerifyIR) {
772             try {
773                 TestClassParser testClassParser = new TestClassParser(testClass);
774                 Matchable testClassMatchable = testClassParser.parse(testVMProcess.getHotspotPidFileName(),
775                                                                      testVMProcess.getIrEncoding());
776                 IRMatcher matcher = new IRMatcher(testClassMatchable);
777                 matcher.match();
778             } catch (IRViolationException e) {
779                 e.addCommandLine(testVMProcess.getCommandLine());
780                 throw e;
781             }
782         } else {
783             System.out.println("IR verification disabled either due to no @IR annotations, through explicitly setting " +
784                                "-DVerify=false, due to not running a debug build, using a non-whitelisted JTreg VM or " +
785                                "Javaopts flag like -Xint, or running the test VM with other VM flags added by user code " +
786                                "that make the IR verification impossible (e.g. -XX:-UseCompile, " +
787                                "-XX:TieredStopAtLevel=[1,2,3], etc.).");
788         }
789     }
790 
791     public static void check(boolean test, String failureMessage) {
792         if (!test) {
793             throw new TestFrameworkException(failureMessage);
794         }
795     }
796 }