7b31c331b4e7815a532f8c360d5c24de1951af33
[packages/hoopl.git] / src / Compiler / Hoopl / Util.hs
1 {-# LANGUAGE GADTs, ScopedTypeVariables, FlexibleInstances, RankNTypes #-}
2
3 module Compiler.Hoopl.Util
4 ( gUnitOO, gUnitOC, gUnitCO, gUnitCC
5 , catGraphNodeOC, catGraphNodeOO
6 , catNodeCOGraph, catNodeOOGraph
7 , graphMapBlocks
8 , blockMapNodes, blockMapNodes3
9 , blockGraph
10 , postorder_dfs, postorder_dfs_from, postorder_dfs_from_except
11 , preorder_dfs, preorder_dfs_from_except
12 , labelsDefined, labelsUsed, externalEntryLabels
13 , LabelsPtr(..)
14 )
15 where
16
17 import Control.Monad
18
19 import Compiler.Hoopl.Collections
20 import Compiler.Hoopl.Graph
21 import Compiler.Hoopl.Label
22
23
24 ----------------------------------------------------------------
25
26 gUnitOO :: block n O O -> Graph' block n O O
27 gUnitOC :: block n O C -> Graph' block n O C
28 gUnitCO :: block n C O -> Graph' block n C O
29 gUnitCC :: Edges (block n) => block n C C -> Graph' block n C C
30 gUnitOO b = GUnit b
31 gUnitOC b = GMany (JustO b) emptyBody NothingO
32 gUnitCO b = GMany NothingO emptyBody (JustO b)
33 gUnitCC b = GMany NothingO (addBlock b $ emptyBody) NothingO
34
35
36 catGraphNodeOO :: Graph n e O -> n O O -> Graph n e O
37 catGraphNodeOC :: Edges n => Graph n e O -> n O C -> Graph n e C
38 catNodeOOGraph :: n O O -> Graph n O x -> Graph n O x
39 catNodeCOGraph :: Edges n => n C O -> Graph n O x -> Graph n C x
40
41 catGraphNodeOO GNil n = gUnitOO $ BMiddle n
42 catGraphNodeOO (GUnit b) n = gUnitOO $ b `BCat` BMiddle n
43 catGraphNodeOO (GMany e body (JustO x)) n = GMany e body (JustO $ x `BHead` n)
44
45 catGraphNodeOC GNil n = gUnitOC $ BLast n
46 catGraphNodeOC (GUnit b) n = gUnitOC $ addToLeft b $ BLast n
47 where addToLeft :: Block n O O -> Block n O C -> Block n O C
48 addToLeft (BMiddle m) g = m `BTail` g
49 addToLeft (b1 `BCat` b2) g = addToLeft b1 $ addToLeft b2 g
50 catGraphNodeOC (GMany e body (JustO x)) n = GMany e body' NothingO
51 where body' = addBlock (x `BClosed` BLast n) body
52
53 catNodeOOGraph n GNil = gUnitOO $ BMiddle n
54 catNodeOOGraph n (GUnit b) = gUnitOO $ BMiddle n `BCat` b
55 catNodeOOGraph n (GMany (JustO e) body x) = GMany (JustO $ n `BTail` e) body x
56
57 catNodeCOGraph n GNil = gUnitCO $ BFirst n
58 catNodeCOGraph n (GUnit b) = gUnitCO $ addToRight (BFirst n) b
59 where addToRight :: Block n C O -> Block n O O -> Block n C O
60 addToRight g (BMiddle m) = g `BHead` m
61 addToRight g (b1 `BCat` b2) = addToRight (addToRight g b1) b2
62 catNodeCOGraph n (GMany (JustO e) body x) = GMany NothingO body' x
63 where body' = addBlock (BFirst n `BClosed` e) body
64
65
66
67
68
69 blockGraph :: Edges n => Block n e x -> Graph n e x
70 blockGraph b@(BFirst {}) = gUnitCO b
71 blockGraph b@(BMiddle {}) = gUnitOO b
72 blockGraph b@(BLast {}) = gUnitOC b
73 blockGraph b@(BCat {}) = gUnitOO b
74 blockGraph b@(BHead {}) = gUnitCO b
75 blockGraph b@(BTail {}) = gUnitOC b
76 blockGraph b@(BClosed {}) = gUnitCC b
77
78
79 -- | Function 'graphMapBlocks' enables a change of representation of blocks,
80 -- nodes, or both. It lifts a polymorphic block transform into a polymorphic
81 -- graph transform. When the block representation stabilizes, a similar
82 -- function should be provided for blocks.
83 graphMapBlocks :: forall block n block' n' e x .
84 (forall e x . block n e x -> block' n' e x)
85 -> (Graph' block n e x -> Graph' block' n' e x)
86 bodyMapBlocks :: forall block n block' n' .
87 (block n C C -> block' n' C C)
88 -> (Body' block n -> Body' block' n')
89
90 graphMapBlocks f = map
91 where map :: Graph' block n e x -> Graph' block' n' e x
92 map GNil = GNil
93 map (GUnit b) = GUnit (f b)
94 map (GMany e b x) = GMany (fmap f e) (bodyMapBlocks f b) (fmap f x)
95
96 bodyMapBlocks f (Body body) = Body $ mapMap f body
97
98 -- | Function 'blockMapNodes' enables a change of nodes in a block.
99 blockMapNodes3 :: ( n C O -> n C O
100 , n O O -> n O O
101 , n O C -> n O C)
102 -> Block n e x -> Block n e x
103 blockMapNodes3 (f, _, _) (BFirst n) = BFirst (f n)
104 blockMapNodes3 (_, m, _) (BMiddle n) = BMiddle (m n)
105 blockMapNodes3 (_, _, l) (BLast n) = BLast (l n)
106 blockMapNodes3 fs (BCat x y) = BCat (blockMapNodes3 fs x) (blockMapNodes3 fs y)
107 blockMapNodes3 fs@(_, m, _) (BHead x n) = BHead (blockMapNodes3 fs x) (m n)
108 blockMapNodes3 fs@(_, m, _) (BTail n x) = BTail (m n) (blockMapNodes3 fs x)
109 blockMapNodes3 fs (BClosed x y) = BClosed (blockMapNodes3 fs x) (blockMapNodes3 fs y)
110
111 blockMapNodes :: (forall e x. n e x -> n e x)
112 -> Block n e x -> Block n e x
113 blockMapNodes f = blockMapNodes3 (f, f, f)
114
115 ----------------------------------------------------------------
116
117 class LabelsPtr l where
118 targetLabels :: l -> [Label]
119
120 instance Edges n => LabelsPtr (n e C) where
121 targetLabels n = successors n
122
123 instance LabelsPtr Label where
124 targetLabels l = [l]
125
126 instance LabelsPtr LabelSet where
127 targetLabels = setElems
128
129 instance LabelsPtr l => LabelsPtr [l] where
130 targetLabels = concatMap targetLabels
131
132
133 -- | Traversal: 'postorder_dfs' returns a list of blocks reachable
134 -- from the entry of enterable graph. The entry and exit are *not* included.
135 -- The list has the following property:
136 --
137 -- Say a "back reference" exists if one of a block's
138 -- control-flow successors precedes it in the output list
139 --
140 -- Then there are as few back references as possible
141 --
142 -- The output is suitable for use in
143 -- a forward dataflow problem. For a backward problem, simply reverse
144 -- the list. ('postorder_dfs' is sufficiently tricky to implement that
145 -- one doesn't want to try and maintain both forward and backward
146 -- versions.)
147
148 postorder_dfs :: Edges (block n) => Graph' block n O x -> [block n C C]
149 preorder_dfs :: Edges (block n) => Graph' block n O x -> [block n C C]
150
151 -- | This is the most important traversal over this data structure. It drops
152 -- unreachable code and puts blocks in an order that is good for solving forward
153 -- dataflow problems quickly. The reverse order is good for solving backward
154 -- dataflow problems quickly. The forward order is also reasonably good for
155 -- emitting instructions, except that it will not usually exploit Forrest
156 -- Baskett's trick of eliminating the unconditional branch from a loop. For
157 -- that you would need a more serious analysis, probably based on dominators, to
158 -- identify loop headers.
159 --
160 -- The ubiquity of 'postorder_dfs' is one reason for the ubiquity of the 'LGraph'
161 -- representation, when for most purposes the plain 'Graph' representation is
162 -- more mathematically elegant (but results in more complicated code).
163 --
164 -- Here's an easy way to go wrong! Consider
165 -- @
166 -- A -> [B,C]
167 -- B -> D
168 -- C -> D
169 -- @
170 -- Then ordinary dfs would give [A,B,D,C] which has a back ref from C to D.
171 -- Better to get [A,B,C,D]
172
173
174 graphDfs :: (Edges (block n))
175 => (LabelMap (block n C C) -> block n O C -> LabelSet -> [block n C C])
176 -> (Graph' block n O x -> [block n C C])
177 graphDfs _ (GNil) = []
178 graphDfs _ (GUnit{}) = []
179 graphDfs order (GMany (JustO entry) (Body body) _) = order body entry setEmpty
180
181 postorder_dfs = graphDfs postorder_dfs_from_except
182 preorder_dfs = graphDfs preorder_dfs_from_except
183
184 postorder_dfs_from_except :: forall block e . (Edges block, LabelsPtr e)
185 => LabelMap (block C C) -> e -> LabelSet -> [block C C]
186 postorder_dfs_from_except blocks b visited =
187 vchildren (get_children b) (\acc _visited -> acc) [] visited
188 where
189 vnode :: block C C -> ([block C C] -> LabelSet -> a) -> [block C C] -> LabelSet -> a
190 vnode block cont acc visited =
191 if setMember id visited then
192 cont acc visited
193 else
194 let cont' acc visited = cont (block:acc) visited in
195 vchildren (get_children block) cont' acc (setInsert id visited)
196 where id = entryLabel block
197 vchildren bs cont acc visited = next bs acc visited
198 where next children acc visited =
199 case children of [] -> cont acc visited
200 (b:bs) -> vnode b (next bs) acc visited
201 get_children block = foldr add_id [] $ targetLabels block
202 add_id id rst = case lookupFact id blocks of
203 Just b -> b : rst
204 Nothing -> rst
205
206 postorder_dfs_from
207 :: (Edges block, LabelsPtr b) => LabelMap (block C C) -> b -> [block C C]
208 postorder_dfs_from blocks b = postorder_dfs_from_except blocks b setEmpty
209
210
211 ----------------------------------------------------------------
212
213 data VM a = VM { unVM :: LabelSet -> (a, LabelSet) }
214 marked :: Label -> VM Bool
215 mark :: Label -> VM ()
216 instance Monad VM where
217 return a = VM $ \visited -> (a, visited)
218 m >>= k = VM $ \visited -> let (a, v') = unVM m visited in unVM (k a) v'
219 marked l = VM $ \v -> (setMember l v, v)
220 mark l = VM $ \v -> ((), setInsert l v)
221
222 preorder_dfs_from_except :: forall block e . (Edges block, LabelsPtr e)
223 => LabelMap (block C C) -> e -> LabelSet -> [block C C]
224 preorder_dfs_from_except blocks b visited =
225 (fst $ unVM (children (get_children b)) visited) []
226 where children [] = return id
227 children (b:bs) = liftM2 (.) (visit b) (children bs)
228 visit :: block C C -> VM (HL (block C C))
229 visit b = do already <- marked (entryLabel b)
230 if already then return id
231 else do mark (entryLabel b)
232 bs <- children $ get_children b
233 return $ b `cons` bs
234 get_children block = foldr add_id [] $ targetLabels block
235 add_id id rst = case lookupFact id blocks of
236 Just b -> b : rst
237 Nothing -> rst
238
239 type HL a = [a] -> [a] -- Hughes list (constant-time concatenation)
240 cons :: a -> HL a -> HL a
241 cons a as tail = a : as tail
242
243 ----------------------------------------------------------------
244
245 labelsDefined :: forall block n e x . Edges (block n) => Graph' block n e x -> LabelSet
246 labelsDefined GNil = setEmpty
247 labelsDefined (GUnit{}) = setEmpty
248 labelsDefined (GMany _ body x) = foldBodyBlocks addEntry body $ exitLabel x
249 where addEntry block labels = setInsert (entryLabel block) labels
250 exitLabel :: MaybeO x (block n C O) -> LabelSet
251 exitLabel NothingO = setEmpty
252 exitLabel (JustO b) = setFromList [entryLabel b]
253
254 labelsUsed :: forall block n e x. Edges (block n) => Graph' block n e x -> LabelSet
255 labelsUsed GNil = setEmpty
256 labelsUsed (GUnit{}) = setEmpty
257 labelsUsed (GMany e body _) = foldBodyBlocks addTargets body $ entryTargets e
258 where addTargets block labels = setInsertList (successors block) labels
259 entryTargets :: MaybeO e (block n O C) -> LabelSet
260 entryTargets NothingO = setEmpty
261 entryTargets (JustO b) = addTargets b setEmpty
262
263 foldBodyBlocks :: (block n C C -> a -> a) -> Body' block n -> a -> a
264 foldBodyBlocks f (Body body) z = mapFold f z body
265
266 externalEntryLabels :: Edges (block n) => Body' block n -> LabelSet
267 externalEntryLabels body = defined `setDifference` used
268 where defined = labelsDefined g
269 used = labelsUsed g
270 g = GMany NothingO body NothingO