import java.lang.reflect.*;
import jdk.internal.misc.Unsafe;

/*
java --add-opens java.base/jdk.internal.misc=ALL-UNNAMED --add-exports java.base/jdk.internal.misc=ALL-UNNAMED -Xbatch -XX:CompileCommand=quiet -XX:+PrintInlining -XX:TypeProfileLevel=222 -XX:+PrintCompilation -XX:+AlwaysIncrementalInline -XX:+UnlockDiagnosticVMOptions -XX:CompileCommand=compileonly,Test::test* -XX:-TieredCompilation Test.java
*/

public class Test {

    private static Unsafe UNSAFE;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
        } catch (Exception e) {}
    }

    // Delay inlining
    public static int helperSmall(Object array, boolean run) {
        //return run ? UNSAFE.getShortUnaligned(array, 1) : 0; // 147 CheckCastPP : speculative=byte[int:>=0]
        return run ? UNSAFE.getShortUnaligned(array, 1_049_000) : 0; // after warmup CheckCastPP: speculative=byte[int:>=0]
    }

    public static int accessSmallArray(boolean useNull, boolean run) {
        Object array = getSmall(useNull); // 71 CheckCastPP: speculative=byte[int:>=0]
        // Make sure null is only visible after helper method was (incrementally) inlined and argument profile information was used (i.e., CheckCastPP nodes with spec type was added), see GraphKit::record_profiled_arguments_for_speculation/record_profiled_parameters_for_speculation -> GraphKit::record_profile_for_speculation
        return helperSmall(array, run);
    }

    public static Object getSmall(boolean useNull) {
        //return useNull ? null : new byte[10];
        return useNull ? null : new byte[1_050_000];
    }

    public static int test2(boolean run) {
        return accessSmallArray(true, run);
    }

    public static void main(String[] args) {
        // Warmup
        for (int i = 0; i < 5000; i++) {
            accessSmallArray(false, true);
        }

        // Trigger compilation (we can't use -Xcomp because CompilationPolicy::is_mature will return false and we will not use profile info for arguments)
        for (int i = 0; i < 10_000; ++i) {
            test2(false);
        }
    }
}
