comparison python/mem2reg.py @ 253:74c6a20302d5

Added better logging
author Windel Bouwman
date Wed, 31 Jul 2013 17:57:03 +0200
parents
children 444b9df2ed99
comparison
equal deleted inserted replaced
252:c4370696ccc7 253:74c6a20302d5
1 import logging
2 from transform import FunctionPass
3 from ir import *
4
5 def isAllocPromotable(allocinst):
6 # Check if alloc value is only used by load and store operations.
7 assert type(allocinst) is Alloc
8 return all(type(use) in [Load,Store] for use in allocinst.value.used_by)
9
10 class Mem2RegPromotor(FunctionPass):
11 def promoteSingleBlock(self, ai):
12 v = ai.value
13 bb = ai.Block
14
15 # Replace all loads with the value:
16 loads = [i for i in v.used_by if isinstance(i, Load)]
17 stores = [i for i in v.used_by if isinstance(i, Store)]
18 stores.sort(key=lambda s: s.Position)
19 stores.reverse()
20
21 for load in loads:
22 idx = load.Position
23 # Search upwards:
24 for store in stores:
25 if store.Position < load.Position:
26 break
27 for use_ins in load.value.used_by:
28 use_ins.replaceValue(load.value, store.value)
29 assert not load.value.Used
30 logging.debug('replaced {} with {}'.format(load, store.value))
31 bb.removeInstruction(load)
32
33 # Remove store instructions:
34 for store in stores:
35 sv = store.value
36 logging.debug('removing {}'.format(store))
37 bb.removeInstruction(store)
38 #assert sv.Used
39
40 # Remove alloca instruction:
41 assert not ai.value.Used, ai.value.used_by
42 bb.removeInstruction(ai)
43
44 def promote(self, ai):
45 # Find load operations and replace them with assignments
46 v = ai.value
47 if len(ai.value.UsedInBlocks) == 1:
48 self.promoteSingleBlock(ai)
49 return
50
51 loads = [i for i in v.used_by if isinstance(i, Load)]
52 stores = [i for i in v.used_by if isinstance(i, Store)]
53
54 # Each store instruction can be removed (later).
55 # Instead of storing the value, we use it
56 # where the load would have been!
57 replMap = {}
58 for store in stores:
59 replMap[store] = store.value
60
61 # for each load, track back what the defining store
62 # was.
63 for load in loads:
64 pass
65
66 def onFunction(self, f):
67 for bb in f.BasicBlocks:
68 allocs = [i for i in bb.Instructions if isinstance(i, Alloc)]
69 for i in allocs:
70 if isAllocPromotable(i):
71 self.promote(i)
72