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