import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class TestLateMHClonedCallNode {
    private static int field;

    public static void main(String[] args) throws Throwable {
        for (int i = 0; i < 20_000; i++) {
//            test1(true);
//            test1(false);
            test2(true);
            test2(false);
        }
    }

    private static int test1(boolean flag) throws Throwable {
        return inlined1(flag);
    }

    private static int inlined1(boolean flag) throws Throwable {
        MethodHandle mh = mh1;
        for (int i = 0; i < 3; ++i) {
            if (i > 1) {
                mh = mh2;
            }
        }
        int res = 0;
        for (int i = 0; i < 2; i++) {
            if (!flag) {
                field = 42;
            }
            res += (int) mh.invokeExact();
        }
        return res;
    }

    private static int test2(boolean flag) throws Throwable {
        int res = (int)unknownMh.invokeExact();
        return inlined2(flag);
    }

    private static int inlined2(boolean flag) throws Throwable {
        MethodHandle mh = mh1;
        for (int i = 0; i < 3; ++i) {
            if (i > 1) {
                mh = mh2;
            }
        }
        int res = 0;
        for (int i = 0; i < 2; i++) {
            if (!flag) {
                field = 42;
            }
            res += (int) mh.invokeExact();
        }
        return res;
    }

    static final MethodHandle mh1;
    static final MethodHandle mh2;
    static MethodHandle unknownMh;

    static {
        try {
            MethodHandles.Lookup lookup = MethodHandles.lookup();
            mh1 = lookup.findStatic(TestLateMHClonedCallNode.class, "method1", MethodType.methodType(int.class));
            mh2 = lookup.findStatic(TestLateMHClonedCallNode.class, "method2", MethodType.methodType(int.class));
            unknownMh = mh1;
        } catch (NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("Method handle lookup failed");
        }
    }

    static int method1() { return 0; }
    static int method2() { return 42; }
}
