157
|
1 # IR-Structures:
|
171
|
2 from .instruction import *
|
|
3 from .basicblock import BasicBlock
|
157
|
4
|
155
|
5 class Module:
|
170
|
6 """ Main container for a piece of code. """
|
155
|
7 def __init__(self, name):
|
|
8 self.name = name
|
172
|
9 self.funcs = []
|
205
|
10 self.variables = []
|
|
11
|
158
|
12 def __repr__(self):
|
170
|
13 return 'IR-module [{0}]'.format(self.name)
|
205
|
14
|
155
|
15 def getInstructions(self):
|
171
|
16 ins = []
|
172
|
17 for bb in self.BasicBlocks:
|
171
|
18 ins += bb.Instructions
|
|
19 return ins
|
155
|
20 Instructions = property(getInstructions)
|
205
|
21
|
171
|
22 def getBBs(self):
|
172
|
23 bbs = []
|
|
24 for f in self.Functions:
|
|
25 bbs += f.BasicBlocks
|
|
26 return bbs
|
205
|
27
|
171
|
28 BasicBlocks = property(getBBs)
|
172
|
29 def addFunc(self, f):
|
|
30 self.funcs.append(f)
|
205
|
31 addFunction = addFunc
|
|
32
|
|
33 def addVariable(self, v):
|
|
34 self.variables.append(v)
|
|
35
|
|
36 def getVariables(self):
|
|
37 return self.variables
|
|
38 Variables = property(getVariables)
|
|
39
|
|
40 def getFunctions(self):
|
172
|
41 return self.funcs
|
205
|
42 Functions = property(getFunctions)
|
|
43
|
170
|
44 def dump(self):
|
|
45 print(self)
|
205
|
46 for v in self.Variables:
|
|
47 print(' ', v)
|
172
|
48 for fn in self.Functions:
|
|
49 print(fn)
|
|
50 for bb in fn.BasicBlocks:
|
|
51 print(' ', bb)
|
|
52 for ins in bb.Instructions:
|
|
53 print(' ', ins)
|
205
|
54
|
171
|
55 def dumpgv(self, outf):
|
|
56 outf.write('digraph G \n{\n')
|
173
|
57 for f in self.Functions:
|
174
|
58 outf.write('{0} [label="{1}" shape=box3d]\n'.format(id(f), f))
|
173
|
59 for bb in f.BasicBlocks:
|
|
60 contents = str(bb) + '\n'
|
|
61 contents += '\n'.join([str(i) for i in bb.Instructions])
|
174
|
62 outf.write('{0} [shape=note label="{1}"];\n'.format(id(bb), contents))
|
173
|
63 for successor in bb.Successors:
|
|
64 outf.write('"{0}" -> "{1}"\n'.format(id(bb), id(successor)))
|
177
|
65 # Draw dags if any:
|
|
66 if hasattr(bb, 'dag'):
|
|
67 outf.write('{0} -> {1}\n'.format(id(bb), id(bb.dag)))
|
|
68 bb.dag.dumpgv(outf)
|
|
69
|
173
|
70 outf.write('"{0}" -> "{1}" [label="entry"]\n'.format(id(f), id(f.entry)))
|
171
|
71 outf.write('}\n')
|
155
|
72
|
171
|
73 # Analysis functions:
|
|
74 def check(self):
|
|
75 """ Perform sanity check on module """
|
|
76 for i in self.Instructions:
|
|
77 for t in i.defs:
|
|
78 assert type(t) is Value, "def must be Value, not {0}".format(type(t))
|
|
79 for t in i.uses:
|
174
|
80 assert type(t) is Use, "use must be Value, not {0}".format(type(t))
|
171
|
81
|