173
|
1 from ir import *
|
|
2 # Standard passes:
|
|
3
|
|
4 class FunctionPass:
|
|
5 def run(self, ir):
|
|
6 """ Main entry point for the pass """
|
|
7 for f in ir.Functions:
|
|
8 self.onFunction(f)
|
|
9 def onFunction(self, f):
|
|
10 """ Override this virtual method """
|
|
11 raise NotImplementedError()
|
|
12
|
|
13 class BasicBlockPass(FunctionPass):
|
|
14 def onFunction(self, f):
|
|
15 for bb in f.BasicBlocks:
|
|
16 self.onBasicBlock(bb)
|
|
17 def onBasicBlock(self, bb):
|
|
18 """ Override this virtual method """
|
|
19 raise NotImplementedError()
|
|
20
|
|
21 class InstructionPass(BasicBlockPass):
|
|
22 def onBasicBlock(self, bb):
|
|
23 for ins in bb.Instructions:
|
|
24 self.onInstruction(ins)
|
|
25 def onInstruction(self, ins):
|
|
26 """ Override this virtual method """
|
|
27 raise NotImplementedError()
|
|
28
|
|
29 # Usefull transforms:
|
|
30 class ConstantFolder(InstructionPass):
|
|
31 def onInstruction(self, i):
|
|
32 if type(i) is ImmLoad:
|
|
33 i.target.constval = i.value
|
|
34 print(type(i.value), i.value)
|
|
35 elif type(i) is BinaryOperator:
|
|
36 a = i.value1
|
|
37 b = i.value2
|
|
38 if hasattr(a, 'constval') and hasattr(b,'constval'):
|
|
39 op = i.operation
|
|
40 if op == '+':
|
|
41 i2 = ImmLoad(i.result, a.constval + b.constval)
|
|
42 print(i2)
|
|
43 i.Parent.replaceInstruction(i, i2)
|
|
44 elif op == '*':
|
|
45 i2 = ImmLoad(i.result, a.constval * b.constval)
|
|
46 print(i2)
|
|
47 i.Parent.replaceInstruction(i, i2)
|
|
48 elif op == '-':
|
|
49 i2 = ImmLoad(i.result, a.constval - b.constval)
|
|
50 print(i2)
|
|
51 i.Parent.replaceInstruction(i, i2)
|
|
52
|
|
53 class DeadCodeDeleter(InstructionPass):
|
|
54 def onInstruction(self, ins):
|
|
55 print(ins, ins.Users)
|
|
56 if not ins.defs in ins.live_out:
|
|
57 ins.Parent.removeInstruction(ins)
|
|
58
|