204
|
1 import unittest, os
|
173
|
2 import c3, ppci, ir, x86, transform
|
204
|
3
|
|
4 class ConstantFolderTestCase(unittest.TestCase):
|
|
5 def setUp(self):
|
|
6 self.b = ir.Builder()
|
|
7 self.cf = transform.ConstantFolder()
|
|
8
|
|
9 def testBuilder(self):
|
|
10 m = ir.Module('test')
|
|
11 self.b.setModule(m)
|
|
12 f = self.b.newFunction('test')
|
|
13 self.b.setFunction(f)
|
|
14 bb = self.b.newBB()
|
|
15 self.b.setBB(bb)
|
|
16 v1 = self.b.newTmp('t')
|
|
17 v2 = self.b.newTmp('t')
|
|
18 v3 = self.b.newTmp('t')
|
|
19 self.b.addIns(ir.ImmLoad(v1, 5))
|
|
20 self.b.addIns(ir.ImmLoad(v2, 7))
|
|
21 self.b.addIns(ir.BinaryOperator(v3, '+', v1, v2))
|
|
22 self.assertEqual(3, len(m.Instructions))
|
|
23 self.cf.run(m)
|
|
24 self.assertEqual(3, len(m.Instructions))
|
|
25 self.assertIsInstance(m.Instructions[-1], ir.ImmLoad)
|
|
26 self.assertEqual(12, m.Instructions[-1].value)
|
|
27
|
171
|
28
|
|
29 testsrc = """
|
|
30 package test2;
|
|
31
|
175
|
32 function void tesssst(int henkie)
|
171
|
33 {
|
175
|
34 var int a, b, cee;
|
171
|
35 a = 2 * 33 - 12;
|
|
36 b = a * 2 + 13;
|
|
37 a = b + a;
|
175
|
38 cee = a;
|
171
|
39 if (a > b and b *3 - a+8*b== 3*6-b)
|
|
40 {
|
|
41 var int x = a;
|
|
42 x = b * 2 - a;
|
175
|
43 a = x * x * add2(x, 22 - a);
|
171
|
44 }
|
|
45 else
|
|
46 {
|
175
|
47 a = b + a + add2(a, b);
|
171
|
48 }
|
|
49 var int y;
|
|
50 y = a - b * 53;
|
|
51 }
|
|
52
|
172
|
53 function int add2(int x, int y)
|
|
54 {
|
|
55 var int res;
|
174
|
56 res = x + y + 2 - 7 + 2;
|
175
|
57 //if (y < 2)
|
|
58 //{
|
|
59 // return y - 33;
|
|
60 //}
|
|
61
|
177
|
62 res = res + (x + 2 * y) + (x + 2 * y) + (2*8) + (2*8);
|
|
63
|
174
|
64 if (x > 13)
|
|
65 {
|
176
|
66 while (y > 1337)
|
|
67 {
|
|
68 res = res + 2;
|
|
69 y = y - 12;
|
|
70 }
|
174
|
71 }
|
172
|
72 return res;
|
|
73 }
|
|
74
|
171
|
75 """
|
|
76
|
|
77 if __name__ == '__main__':
|
204
|
78 unittest.main()
|
|
79 sys.exit()
|
171
|
80 diag = ppci.DiagnosticsManager()
|
|
81 builder = c3.Builder(diag)
|
180
|
82 cgenx86 = x86.X86CodeGenSimple(diag)
|
171
|
83 ir = builder.build(testsrc)
|
172
|
84 diag.printErrors(testsrc)
|
173
|
85 #ir.dump()
|
|
86 cf = transform.ConstantFolder()
|
|
87 dcd = transform.DeadCodeDeleter()
|
175
|
88 m2r = transform.Mem2RegPromotor()
|
177
|
89 clr = transform.CleanPass()
|
171
|
90 ir.check()
|
173
|
91 cf.run(ir)
|
175
|
92 dcd.run(ir)
|
177
|
93 clr.run(ir)
|
175
|
94 m2r.run(ir)
|
|
95 #ir.dump()
|
176
|
96
|
|
97 # Dump a graphiz file:
|
|
98 with open('graaf.gv', 'w') as f:
|
|
99 ir.dumpgv(f)
|
|
100 os.system('dot -Tpdf -ograaf.pdf graaf.gv')
|
|
101
|
171
|
102 asm = cgenx86.genBin(ir)
|
175
|
103 #for a in asm:
|
|
104 # print(a)
|
171
|
105 with open('out.asm', 'w') as f:
|
|
106 f.write('BITS 64\n')
|
|
107 for a in asm:
|
|
108 f.write(str(a) + '\n')
|
180
|
109 print(a)
|
|
110
|