322
|
1 from tree import Tree
|
|
2 from . import ir
|
|
3
|
323
|
4 """ Create a tree from ir code. """
|
|
5
|
322
|
6 f_map = {} # Mapping from types to tree creation functions
|
|
7
|
|
8 def register(tp):
|
|
9 """ Register a function for type tp """
|
|
10 def reg_f(f):
|
|
11 f_map[tp] = f
|
|
12 return f
|
|
13 return reg_f
|
|
14
|
|
15 @register(ir.Binop)
|
394
|
16 @register(ir.Add)
|
322
|
17 def binop_to_tree(e):
|
|
18 names = {'+':'ADDI32', '-':'SUBI32', '|':'ORI32', '<<':'SHLI32',
|
356
|
19 '*':'MULI32', '&':'ANDI32', '>>':'SHRI32'}
|
322
|
20 op = names[e.operation]
|
|
21 return Tree(op, makeTree(e.a), makeTree(e.b))
|
|
22
|
|
23 @register(ir.Temp)
|
|
24 def temp_to_tree(e):
|
|
25 t = Tree('REGI32')
|
|
26 t.value = e
|
|
27 return t
|
|
28
|
364
|
29 @register(ir.GlobalVariable)
|
|
30 def global_address_to_tree(e):
|
|
31 t = Tree('GLOBALADDRESS')
|
|
32 t.value = ir.label_name(e)
|
|
33 return t
|
|
34
|
322
|
35 @register(ir.Const)
|
|
36 def const_to_tree(e):
|
354
|
37 if type(e.value) is bytes:
|
|
38 t = Tree('CONSTDATA')
|
|
39 t.value = e.value
|
|
40 return t
|
|
41 elif type(e.value) is int:
|
|
42 t = Tree('CONSTI32')
|
|
43 t.value = e.value
|
|
44 return t
|
|
45 else:
|
|
46 raise Exception('{} not implemented'.format(type(e.value)))
|
322
|
47
|
|
48 @register(ir.Mem)
|
|
49 def mem_to_tree(e):
|
|
50 return Tree('MEMI32', makeTree(e.e))
|
|
51
|
354
|
52 @register(ir.Addr)
|
|
53 def mem_to_tree(e):
|
|
54 return Tree('ADR', makeTree(e.e))
|
|
55
|
322
|
56 @register(ir.Call)
|
|
57 def call_to_tree(e):
|
323
|
58 t = Tree('CALL')
|
|
59 t.value = e
|
|
60 return t
|
322
|
61
|
|
62 def makeTree(ir_node):
|
|
63 """ Transform an ir node into a tree usable for matching """
|
|
64 return f_map[type(ir_node)](ir_node)
|