1 /*
2 * Copyright (c) 2024, 2026, 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 * @modules jdk.incubator.code
27 * @run main TestAnfTransform
28 */
29
30 import jdk.incubator.code.Reflect;
31 import jdk.incubator.code.Op;
32 import jdk.incubator.code.CodeTransformer;
33 import jdk.incubator.code.dialect.core.NormalizeBlocksTransformer;
34 import jdk.incubator.code.dialect.core.SSA;
35 import jdk.incubator.code.dialect.core.CoreOp;
36
37 import java.lang.reflect.Method;
38 import java.util.List;
39
40 public class TestAnfTransform {
41
42 @Reflect
43 public static int fibonacci(int v) {
44 if (v == 0) {
45 return 0;
46 } else if (v == 1) {
47 return 1;
48 }
49
50 v = v - 2;
51 int s1, s2, t;
52 s1 = 0;
53 s2 = 1;
54
55 while(v > 0) {
56 t = s1 + s2;
57 s1 = s2;
58 s2 = t;
59 v--;
60 }
61
62 return s1 + s2;
63
64 }
65
66 public static void main(String[] args) {
67
68 testRun("fibonacci", List.of(int.class), 20);
69
70 }
71
72 private static void testRun(String methodName, List<Class<?>> params, Object...args) {
73 try {
74 Class<TestAnfTransform> clazz = TestAnfTransform.class;
75 Method method = clazz.getDeclaredMethod(methodName,params.toArray(new Class[params.size()]));
76 CoreOp.FuncOp f = Op.ofMethod(method).orElseThrow();
77
78 //Ensure we're fully lowered before testing.
79 var fz = f.transform(CodeTransformer.LOWERING_TRANSFORMER);
80 fz = SSA.transform(fz);
81 fz = NormalizeBlocksTransformer.transform(fz);
82
83 System.out.println(fz.toText());
84
85 var res = new AnfTransformer(fz).transform();
86 System.out.println("---------------------");
87 System.out.println(res.toText());
88
89 } catch (NoSuchMethodException e) {
90 throw new RuntimeException(e);
91 }
92 }
93 }