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)
|
|
16 def binop_to_tree(e):
|
|
17 names = {'+':'ADDI32', '-':'SUBI32', '|':'ORI32', '<<':'SHLI32',
|
|
18 '*':'MULI32'}
|
|
19 op = names[e.operation]
|
|
20 return Tree(op, makeTree(e.a), makeTree(e.b))
|
|
21
|
|
22 @register(ir.Temp)
|
|
23 def temp_to_tree(e):
|
|
24 t = Tree('REGI32')
|
|
25 t.value = e
|
|
26 return t
|
|
27
|
|
28 @register(ir.Const)
|
|
29 def const_to_tree(e):
|
354
|
30 if type(e.value) is bytes:
|
|
31 t = Tree('CONSTDATA')
|
|
32 t.value = e.value
|
|
33 return t
|
|
34 elif type(e.value) is int:
|
|
35 t = Tree('CONSTI32')
|
|
36 t.value = e.value
|
|
37 return t
|
|
38 else:
|
|
39 raise Exception('{} not implemented'.format(type(e.value)))
|
322
|
40
|
|
41 @register(ir.Mem)
|
|
42 def mem_to_tree(e):
|
|
43 return Tree('MEMI32', makeTree(e.e))
|
|
44
|
354
|
45 @register(ir.Addr)
|
|
46 def mem_to_tree(e):
|
|
47 return Tree('ADR', makeTree(e.e))
|
|
48
|
322
|
49 @register(ir.Call)
|
|
50 def call_to_tree(e):
|
323
|
51 t = Tree('CALL')
|
|
52 t.value = e
|
|
53 return t
|
322
|
54
|
|
55 def makeTree(ir_node):
|
|
56 """ Transform an ir node into a tree usable for matching """
|
|
57 return f_map[type(ir_node)](ir_node)
|