1544c7b93386c90f15fd4ae646a73bbe99ea8215
[ghc-hetmet.git] / ghc / compiler / utils / Digraph.lhs
1 \begin{code}
2 module Digraph(
3
4         -- At present the only one with a "nice" external interface
5         stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
6
7         Graph, Vertex, 
8         graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
9
10         Tree(..), Forest,
11         showTree, showForest,
12
13         dfs, dff,
14         topSort,
15         components,
16         scc,
17         back, cross, forward,
18         reachable, path,
19         bcc
20
21     ) where
22
23 # include "HsVersions.h"
24
25 ------------------------------------------------------------------------------
26 -- A version of the graph algorithms described in:
27 -- 
28 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
29 --   by David King and John Launchbury
30 -- 
31 -- Also included is some additional code for printing tree structures ...
32 ------------------------------------------------------------------------------
33
34
35 #define ARR_ELT         (COMMA)
36
37 import Util     ( sortLt )
38
39 -- Extensions
40 import ST
41
42 -- std interfaces
43 import Maybe
44 import Array
45 import List
46 import Outputable
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52 %*      External interface
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 data SCC vertex = AcyclicSCC vertex
58                 | CyclicSCC  [vertex]
59
60 flattenSCCs :: [SCC a] -> [a]
61 flattenSCCs = concatMap flattenSCC
62
63 flattenSCC (AcyclicSCC v) = [v]
64 flattenSCC (CyclicSCC vs) = vs
65
66 instance Outputable a => Outputable (SCC a) where
67    ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
68    ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
69 \end{code}
70
71 \begin{code}
72 stronglyConnComp
73         :: Ord key
74         => [(node, key, [key])]         -- The graph; its ok for the
75                                         -- out-list to contain keys which arent
76                                         -- a vertex key, they are ignored
77         -> [SCC node]
78
79 stronglyConnComp edges
80   = map get_node (stronglyConnCompR edges)
81   where
82     get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
83     get_node (CyclicSCC triples)     = CyclicSCC [n | (n,_,_) <- triples]
84
85 -- The "R" interface is used when you expect to apply SCC to
86 -- the (some of) the result of SCC, so you dont want to lose the dependency info
87 stronglyConnCompR
88         :: Ord key
89         => [(node, key, [key])]         -- The graph; its ok for the
90                                         -- out-list to contain keys which arent
91                                         -- a vertex key, they are ignored
92         -> [SCC (node, key, [key])]
93
94 stronglyConnCompR [] = []  -- added to avoid creating empty array in graphFromEdges -- SOF
95 stronglyConnCompR edges
96   = map decode forest
97   where
98     (graph, vertex_fn) = graphFromEdges edges
99     forest             = scc graph
100     decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
101                        | otherwise         = AcyclicSCC (vertex_fn v)
102     decode other = CyclicSCC (dec other [])
103                  where
104                    dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
105     mentions_itself v = v `elem` (graph ! v)
106 \end{code}
107
108 %************************************************************************
109 %*                                                                      *
110 %*      Graphs
111 %*                                                                      *
112 %************************************************************************
113
114
115 \begin{code}
116 type Vertex  = Int
117 type Table a = Array Vertex a
118 type Graph   = Table [Vertex]
119 type Bounds  = (Vertex, Vertex)
120 type Edge    = (Vertex, Vertex)
121 \end{code}
122
123 \begin{code}
124 vertices :: Graph -> [Vertex]
125 vertices  = indices
126
127 edges    :: Graph -> [Edge]
128 edges g   = [ (v, w) | v <- vertices g, w <- g!v ]
129
130 mapT    :: (Vertex -> a -> b) -> Table a -> Table b
131 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
132
133 buildG :: Bounds -> [Edge] -> Graph
134 buildG bounds edges = accumArray (flip (:)) [] bounds edges
135
136 transposeG  :: Graph -> Graph
137 transposeG g = buildG (bounds g) (reverseE g)
138
139 reverseE    :: Graph -> [Edge]
140 reverseE g   = [ (w, v) | (v, w) <- edges g ]
141
142 outdegree :: Graph -> Table Int
143 outdegree  = mapT numEdges
144              where numEdges v ws = length ws
145
146 indegree :: Graph -> Table Int
147 indegree  = outdegree . transposeG
148 \end{code}
149
150
151 \begin{code}
152 graphFromEdges
153         :: Ord key
154         => [(node, key, [key])]
155         -> (Graph, Vertex -> (node, key, [key]))
156 graphFromEdges edges
157   = (graph, \v -> vertex_map ! v)
158   where
159     max_v           = length edges - 1
160     bounds          = (0,max_v) :: (Vertex, Vertex)
161     sorted_edges    = sortLt lt edges
162     edges1          = zipWith (,) [0..] sorted_edges
163
164     graph           = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_,    _, ks) <- edges1]
165     key_map         = array bounds [(,) v k                        | (,) v (_,    k, _ ) <- edges1]
166     vertex_map      = array bounds edges1
167
168     (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
169
170     -- key_vertex :: key -> Maybe Vertex
171     --  returns Nothing for non-interesting vertices
172     key_vertex k   = find 0 max_v 
173                    where
174                      find a b | a > b 
175                               = Nothing
176                      find a b = case compare k (key_map ! mid) of
177                                    LT -> find a (mid-1)
178                                    EQ -> Just mid
179                                    GT -> find (mid+1) b
180                               where
181                                 mid = (a + b) `div` 2
182 \end{code}
183
184 %************************************************************************
185 %*                                                                      *
186 %*      Trees and forests
187 %*                                                                      *
188 %************************************************************************
189
190 \begin{code}
191 data Tree a   = Node a (Forest a)
192 type Forest a = [Tree a]
193
194 mapTree              :: (a -> b) -> (Tree a -> Tree b)
195 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
196 \end{code}
197
198 \begin{code}
199 instance Show a => Show (Tree a) where
200   showsPrec p t s = showTree t ++ s
201
202 showTree :: Show a => Tree a -> String
203 showTree  = drawTree . mapTree show
204
205 showForest :: Show a => Forest a -> String
206 showForest  = unlines . map showTree
207
208 drawTree        :: Tree String -> String
209 drawTree         = unlines . draw
210
211 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
212  where this          = s1 ++ x ++ " "
213
214        space n       = take n (repeat ' ')
215
216        stLoop []     = [""]
217        stLoop [t]    = grp s2 "  " (draw t)
218        stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
219
220        rsLoop [t]    = grp s5 "  " (draw t)
221        rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
222
223        grp fst rst   = zipWith (++) (fst:repeat rst)
224
225        [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
226 \end{code}
227
228
229 %************************************************************************
230 %*                                                                      *
231 %*      Depth first search
232 %*                                                                      *
233 %************************************************************************
234
235 \begin{code}
236 type Set s    = STArray s Vertex Bool
237
238 mkEmpty      :: Bounds -> ST s (Set s)
239 mkEmpty bnds  = newSTArray bnds False
240
241 contains     :: Set s -> Vertex -> ST s Bool
242 contains m v  = readSTArray m v
243
244 include      :: Set s -> Vertex -> ST s ()
245 include m v   = writeSTArray m v True
246 \end{code}
247
248 \begin{code}
249 dff          :: Graph -> Forest Vertex
250 dff g         = dfs g (vertices g)
251
252 dfs          :: Graph -> [Vertex] -> Forest Vertex
253 dfs g vs      = prune (bounds g) (map (generate g) vs)
254
255 generate     :: Graph -> Vertex -> Tree Vertex
256 generate g v  = Node v (map (generate g) (g!v))
257
258 prune        :: Bounds -> Forest Vertex -> Forest Vertex
259 prune bnds ts = runST (mkEmpty bnds  >>= \m ->
260                        chop m ts)
261
262 chop         :: Set s -> Forest Vertex -> ST s (Forest Vertex)
263 chop m []     = return []
264 chop m (Node v ts : us)
265               = contains m v >>= \visited ->
266                 if visited then
267                   chop m us
268                 else
269                   include m v >>= \_  ->
270                   chop m ts   >>= \as ->
271                   chop m us   >>= \bs ->
272                   return (Node v as : bs)
273 \end{code}
274
275
276 %************************************************************************
277 %*                                                                      *
278 %*      Algorithms
279 %*                                                                      *
280 %************************************************************************
281
282 ------------------------------------------------------------
283 -- Algorithm 1: depth first search numbering
284 ------------------------------------------------------------
285
286 \begin{code}
287 --preorder            :: Tree a -> [a]
288 preorder (Node a ts) = a : preorderF ts
289
290 preorderF           :: Forest a -> [a]
291 preorderF ts         = concat (map preorder ts)
292
293 preOrd :: Graph -> [Vertex]
294 preOrd  = preorderF . dff
295
296 tabulate        :: Bounds -> [Vertex] -> Table Int
297 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
298
299 preArr          :: Bounds -> Forest Vertex -> Table Int
300 preArr bnds      = tabulate bnds . preorderF
301 \end{code}
302
303
304 ------------------------------------------------------------
305 -- Algorithm 2: topological sorting
306 ------------------------------------------------------------
307
308 \begin{code}
309 --postorder :: Tree a -> [a]
310 postorder (Node a ts) = postorderF ts ++ [a]
311
312 postorderF   :: Forest a -> [a]
313 postorderF ts = concat (map postorder ts)
314
315 postOrd      :: Graph -> [Vertex]
316 postOrd       = postorderF . dff
317
318 topSort      :: Graph -> [Vertex]
319 topSort       = reverse . postOrd
320 \end{code}
321
322
323 ------------------------------------------------------------
324 -- Algorithm 3: connected components
325 ------------------------------------------------------------
326
327 \begin{code}
328 components   :: Graph -> Forest Vertex
329 components    = dff . undirected
330
331 undirected   :: Graph -> Graph
332 undirected g  = buildG (bounds g) (edges g ++ reverseE g)
333 \end{code}
334
335
336 -- Algorithm 4: strongly connected components
337
338 \begin{code}
339 scc  :: Graph -> Forest Vertex
340 scc g = dfs g (reverse (postOrd (transposeG g)))
341 \end{code}
342
343
344 ------------------------------------------------------------
345 -- Algorithm 5: Classifying edges
346 ------------------------------------------------------------
347
348 \begin{code}
349 tree              :: Bounds -> Forest Vertex -> Graph
350 tree bnds ts       = buildG bnds (concat (map flat ts))
351                    where
352                      flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
353                                         concat (map flat ts)
354
355 back              :: Graph -> Table Int -> Graph
356 back g post        = mapT select g
357  where select v ws = [ w | w <- ws, post!v < post!w ]
358
359 cross             :: Graph -> Table Int -> Table Int -> Graph
360 cross g pre post   = mapT select g
361  where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
362
363 forward           :: Graph -> Graph -> Table Int -> Graph
364 forward g tree pre = mapT select g
365  where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
366 \end{code}
367
368
369 ------------------------------------------------------------
370 -- Algorithm 6: Finding reachable vertices
371 ------------------------------------------------------------
372
373 \begin{code}
374 reachable    :: Graph -> Vertex -> [Vertex]
375 reachable g v = preorderF (dfs g [v])
376
377 path         :: Graph -> Vertex -> Vertex -> Bool
378 path g v w    = w `elem` (reachable g v)
379 \end{code}
380
381
382 ------------------------------------------------------------
383 -- Algorithm 7: Biconnected components
384 ------------------------------------------------------------
385
386 \begin{code}
387 bcc :: Graph -> Forest [Vertex]
388 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
389  where forest = dff g
390        dnum   = preArr (bounds g) forest
391
392 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
393 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
394  where us = map (do_label g dnum) ts
395        lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
396                      ++ [lu | Node (u,du,lu) xs <- us])
397
398 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
399 bicomps (Node (v,dv,lv) ts)
400       = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
401
402 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
403 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
404  where collected = map collect ts
405        vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
406        cs = concat [ if lw<dv then us else [Node (v:ws) us]
407                         | (lw, Node ws us) <- collected ]
408 \end{code}
409