1 /*
   2  * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug 8030976 8059226
  27  * @library /testlibrary /test/lib /
  28  * @modules java.base/jdk.internal.org.objectweb.asm
  29  *          java.base/jdk.internal.misc
  30  *          java.compiler
  31  *          java.management
  32  *          jdk.jvmstat/sun.jvmstat.monitor
  33  * @build TestUnstableIfTrap jdk.test.lib.* compiler.testlibrary.uncommontrap.Verifier
  34  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
  35  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
  36  * @run main/othervm -Xbatch -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
  37  *                   -XX:+WhiteBoxAPI -XX:+LogCompilation
  38  *                   -XX:CompileCommand=compileonly,UnstableIfExecutable.test
  39  *                   -XX:LogFile=always_taken_not_fired.xml
  40  *                   TestUnstableIfTrap ALWAYS_TAKEN false
  41  * @run main/othervm -Xbatch -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
  42  *                   -XX:+WhiteBoxAPI -XX:+LogCompilation
  43  *                   -XX:CompileCommand=compileonly,UnstableIfExecutable.test
  44  *                   -XX:LogFile=always_taken_fired.xml
  45  *                   TestUnstableIfTrap ALWAYS_TAKEN true
  46  * @run main/othervm -Xbatch -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
  47  *                   -XX:+WhiteBoxAPI -XX:+LogCompilation
  48  *                   -XX:CompileCommand=compileonly,UnstableIfExecutable.test
  49  *                   -XX:LogFile=never_taken_not_fired.xml
  50  *                   TestUnstableIfTrap NEVER_TAKEN false
  51  * @run main/othervm -Xbatch -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
  52  *                   -XX:+WhiteBoxAPI -XX:+LogCompilation
  53  *                   -XX:CompileCommand=compileonly,UnstableIfExecutable.test
  54  *                   -XX:LogFile=never_taken_fired.xml
  55  *                   TestUnstableIfTrap NEVER_TAKEN true
  56  * @run driver compiler.testlibrary.uncommontrap.Verifier always_taken_not_fired.xml
  57  *                                                        always_taken_fired.xml
  58  *                                                        never_taken_not_fired.xml
  59  *                                                        never_taken_fired.xml
  60  */
  61 
  62 import java.io.File;
  63 import java.io.FileWriter;
  64 import java.io.IOException;
  65 import java.lang.reflect.Method;
  66 import java.util.Properties;
  67 
  68 import jdk.test.lib.ByteCodeLoader;
  69 import jdk.test.lib.Platform;
  70 import jdk.internal.org.objectweb.asm.ClassVisitor;
  71 import jdk.internal.org.objectweb.asm.ClassWriter;
  72 import jdk.internal.org.objectweb.asm.Label;
  73 import jdk.internal.org.objectweb.asm.MethodVisitor;
  74 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  75 
  76 import sun.hotspot.WhiteBox;
  77 import compiler.testlibrary.uncommontrap.Verifier;
  78 
  79 public class TestUnstableIfTrap {
  80     private static final WhiteBox WB = WhiteBox.getWhiteBox();
  81     private static final String CLASS_NAME = "UnstableIfExecutable";
  82     private static final String METHOD_NAME = "test";
  83     private static final String FIELD_NAME = "field";
  84     private static final int ITERATIONS = 1_000_000;
  85     // There is no dependency on particular class file version, so it could be
  86     // set to any version (if you're updating this test for Java 42).
  87     private static final int CLASS_FILE_VERSION = 49;
  88     private static final int MAX_TIER = 4;
  89     // This test aimed to verify that uncommon trap with reason "unstable_if"
  90     // is emitted when method that contain control-flow divergence such that
  91     // one of two branches is never taken (and other one is taken always).
  92     // C2 will made a decision whether or not the branch was ever taken
  93     // depending on method's profile.
  94     // If profile was collected for a few method's invocations, then C2 will not
  95     // trust in branches' probabilities and the tested trap won't be emitted.
  96     // In fact, a method has to be invoked at least 40 time at the day when this
  97     // comment was written (see Parse::dynamic_branch_prediction for an actual
  98     // value). It would be to implementation dependent to use "40" as
  99     // a threshold value in the test, so in order to improve test's robustness
 100     // the threshold value is 1000: if the tested method was compiled by C2
 101     // before it was invoked 1000 times, then we won't verify that trap was
 102     // emitted and fired.
 103     private static final int MIN_INVOCATIONS_BEFORE_C2_COMPILATION = 1000;
 104     /**
 105      * Description of test case parameters and uncommon trap that will
 106      * be emitted during tested method compilation.
 107      */
 108     private static enum TestCaseName {
 109         ALWAYS_TAKEN(false, "taken always"),
 110         NEVER_TAKEN(true, "taken never");
 111         TestCaseName(boolean predicate, String comment) {
 112             this.predicate = predicate;
 113             this.comment = comment;
 114         }
 115 
 116         public final boolean predicate;
 117         public final String name = "unstable_if";
 118         public final String comment;
 119     }
 120 
 121     public static void main(String args[]) {
 122         if (args.length != 2) {
 123             throw new Error("Expected two arguments: test case name and a "
 124                     + "boolean determining if uncommon trap should be fired.");
 125         }
 126         test(TestCaseName.valueOf(args[0]), Boolean.valueOf(args[1]));
 127     }
 128 
 129     private static void test(TestCaseName testCase, boolean shouldBeFired) {
 130         Method testMethod;
 131         Label unstableIfLocation = new Label();
 132         boolean shouldBeEmitted;
 133         boolean compiledToEarly = false;
 134 
 135         try {
 136             Class testClass = ByteCodeLoader.load(CLASS_NAME,
 137                     generateTest(unstableIfLocation));
 138             testMethod = testClass.getDeclaredMethod(METHOD_NAME,
 139                     boolean.class);
 140             for (int i = 0; i < ITERATIONS; i++) {
 141                 testMethod.invoke(null, testCase.predicate);
 142                 if (i < MIN_INVOCATIONS_BEFORE_C2_COMPILATION
 143                         && isMethodCompiledByC2(testMethod)) {
 144                     compiledToEarly = true;
 145                     // There is no sense in further invocations: we already
 146                     // decided to avoid verification.
 147                     break;
 148                 }
 149             }
 150             // We're checking that trap should be emitted (i.e. it was compiled
 151             // by C2) before the trap is fired, because otherwise the nmethod
 152             // will be deoptimized and isMethodCompiledByC2 will return false.
 153             shouldBeEmitted = isMethodCompiledByC2(testMethod)
 154                     && !compiledToEarly;
 155             if (shouldBeFired) {
 156                 testMethod.invoke(null, !testCase.predicate);
 157             }
 158         } catch (ReflectiveOperationException e) {
 159             throw new Error("Test case should be generated, loaded and executed"
 160                     + " without any issues.", e);
 161         }
 162 
 163         shouldBeFired &= shouldBeEmitted;
 164 
 165         Properties properties = new Properties();
 166         properties.setProperty(Verifier.VERIFICATION_SHOULD_BE_SKIPPED,
 167                 Boolean.toString(compiledToEarly));
 168         properties.setProperty(Verifier.UNCOMMON_TRAP_SHOULD_EMITTED,
 169                 Boolean.toString(shouldBeEmitted));
 170         properties.setProperty(Verifier.UNCOMMON_TRAP_SHOULD_FIRED,
 171                 Boolean.toString(shouldBeFired));
 172         properties.setProperty(Verifier.UNCOMMON_TRAP_NAME, testCase.name);
 173         properties.setProperty(Verifier.UNCOMMON_TRAP_COMMENT,
 174                 testCase.comment);
 175         properties.setProperty(Verifier.UNCOMMON_TRAP_BCI,
 176                 Integer.toString(unstableIfLocation.getOffset()));
 177 
 178         properties.list(System.out);
 179 
 180         File f = new File(WB.getStringVMFlag("LogFile") +
 181                 Verifier.PROPERTIES_FILE_SUFFIX);
 182         try (FileWriter wr = new FileWriter(f)) {
 183             properties.store(wr, "");
 184         } catch (IOException e) {
 185             throw new Error("Unable to store test properties.", e);
 186         }
 187     }
 188 
 189     private static boolean isMethodCompiledByC2(Method m) {
 190         boolean isTiered = WB.getBooleanVMFlag("TieredCompilation");
 191         boolean isMethodCompiled = WB.isMethodCompiled(m);
 192         boolean isMethodCompiledAtMaxTier
 193                 = WB.getMethodCompilationLevel(m) == MAX_TIER;
 194 
 195         return Platform.isServer() && isMethodCompiled
 196                 && (!isTiered || isMethodCompiledAtMaxTier);
 197     }
 198 
 199     /**
 200      * Generates class with name {@code CLASS_NAME}, which will contain a
 201      * static method {@code METHOD_NAME}:
 202      *
 203      * <pre>{@code
 204      * public abstract class UnstableIfExecutable {
 205      *   private static int field = 0;
 206      *
 207      *   public static void test(boolean alwaysTrue) {
 208      *     if (alwaysTrue) {
 209      *       field++;
 210      *     } else {
 211      *       field--;
 212      *     }
 213      *   }
 214      * }
 215      * }</pre>
 216      *
 217      * @return generated bytecode.
 218      */
 219     private static byte[] generateTest(Label unstableIfLocation) {
 220         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
 221 
 222         cw.visit(CLASS_FILE_VERSION, ACC_PUBLIC | ACC_ABSTRACT, CLASS_NAME,
 223                 null, "java/lang/Object", null);
 224 
 225         cw.visitField(ACC_PUBLIC | ACC_STATIC | ACC_VOLATILE, FIELD_NAME,
 226                 "I", null, Integer.valueOf(0));
 227 
 228         generateTestMethod(cw, unstableIfLocation);
 229 
 230         return cw.toByteArray();
 231     }
 232 
 233     private static void generateTestMethod(ClassVisitor cv,
 234             Label unstableIfLocation) {
 235         MethodVisitor mv = cv.visitMethod(ACC_PUBLIC | ACC_STATIC, METHOD_NAME,
 236                 "(Z)V", null, null);
 237         mv.visitCode();
 238 
 239         Label end = new Label();
 240         Label falseBranch = new Label();
 241 
 242         // push "field" field's value and 1 to stack
 243         mv.visitFieldInsn(GETSTATIC, CLASS_NAME, FIELD_NAME, "I");
 244         mv.visitInsn(ICONST_1);
 245         // load argument's value
 246         mv.visitVarInsn(ILOAD, 0); // alwaysTrue
 247         // here is our unstable if
 248         mv.visitLabel(unstableIfLocation);
 249         mv.visitJumpInsn(IFEQ, falseBranch);
 250         // increment on "true"
 251         mv.visitInsn(IADD);
 252         mv.visitJumpInsn(GOTO, end);
 253         // decrement on "false"
 254         mv.visitLabel(falseBranch);
 255         mv.visitInsn(ISUB);
 256         mv.visitLabel(end);
 257         // bye bye
 258         mv.visitInsn(RETURN);
 259 
 260         mv.visitMaxs(0, 0);
 261         mv.visitEnd();
 262     }
 263 }
 264