* Cleanups
[oota-llvm.git] / include / llvm / ADT / SCCIterator.h
1 //===-- Support/TarjanSCCIterator.h - Tarjan SCC iterator -------*- C++ -*-===//
2 //
3 // This builds on the Support/GraphTraits.h file to find the strongly 
4 // connected components (SCCs) of a graph in O(N+E) time using
5 // Tarjan's DFS algorithm.
6 //
7 // The SCC iterator has the important property that if a node in SCC S1
8 // has an edge to a node in SCC S2, then it visits S1 *after* S2.
9 // 
10 // To visit S1 *before* S2, use the TarjanSCCIterator on the Inverse graph.
11 // (NOTE: This requires some simple wrappers and is not supported yet.)
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef SUPPORT_TARJANSCCITERATOR_H
16 #define SUPPORT_TARJANSCCITERATOR_H
17
18 #include "Support/GraphTraits.h"
19 #include "Support/iterator"
20 #include <vector>
21 #include <map>
22
23 //--------------------------------------------------------------------------
24 // class SCC - A simple representation of an SCC in a generic Graph.
25 //--------------------------------------------------------------------------
26
27 template<class GraphT, class GT = GraphTraits<GraphT> >
28 struct SCC : public std::vector<typename GT::NodeType*> {
29
30   typedef typename GT::NodeType NodeType;
31   typedef typename GT::ChildIteratorType ChildItTy;
32
33   typedef std::vector<typename GT::NodeType*> super;
34   typedef typename super::iterator               iterator;
35   typedef typename super::const_iterator         const_iterator;
36   typedef typename super::reverse_iterator       reverse_iterator;
37   typedef typename super::const_reverse_iterator const_reverse_iterator;
38
39   // HasLoop() -- Test if this SCC has a loop.  If it has more than one
40   // node, this is trivially true.  If not, it may still contain a loop
41   // if the node has an edge back to itself.
42   bool HasLoop() const {
43     if (size() > 1) return true;
44     NodeType* N = front();
45     for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
46       if (*CI == N)
47         return true;
48     return false;
49   }
50 };
51
52 //--------------------------------------------------------------------------
53 // class TarjanSCC_iterator: Enumerate the SCCs of a directed graph, in
54 // reverse topological order of the SCC DAG.
55 //--------------------------------------------------------------------------
56
57 template<class GraphT, class GT = GraphTraits<GraphT> >
58 class TarjanSCC_iterator : public forward_iterator<SCC<GraphT, GT>, ptrdiff_t> {
59   typedef SCC<GraphT, GT> SccTy;
60   typedef forward_iterator<SccTy, ptrdiff_t> super;
61   typedef typename super::reference reference;
62   typedef typename super::pointer pointer;
63   typedef typename GT::NodeType          NodeType;
64   typedef typename GT::ChildIteratorType ChildItTy;
65
66   // The visit counters used to detect when a complete SCC is on the stack.
67   // visitNum is the global counter.
68   // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
69   unsigned visitNum;
70   std::map<NodeType *, unsigned> nodeVisitNumbers;
71
72   // SCCNodeStack - Stack holding nodes of the SCC.
73   std::vector<NodeType *> SCCNodeStack;
74
75   // CurrentSCC - The current SCC, retrieved using operator*().
76   SccTy CurrentSCC;
77
78   // VisitStack - Used to maintain the ordering.  Top = current block
79   // First element is basic block pointer, second is the 'next child' to visit
80   std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
81
82   // MinVistNumStack - Stack holding the "min" values for each node in the DFS.
83   // This is used to track the minimum uplink values for all children of
84   // the corresponding node on the VisitStack.
85   std::vector<unsigned> MinVisitNumStack;
86
87   // A single "visit" within the non-recursive DFS traversal.
88   void DFSVisitOne(NodeType* N) {
89     ++visitNum;                         // Global counter for the visit order
90     nodeVisitNumbers[N] = visitNum;
91     SCCNodeStack.push_back(N);
92     MinVisitNumStack.push_back(visitNum);
93     VisitStack.push_back(make_pair(N, GT::child_begin(N)));
94     //DEBUG(std::cerr << "TarjanSCC: Node " << N <<
95     //      " : visitNum = " << visitNum << "\n");
96   }
97
98   // The stack-based DFS traversal; defined below.
99   void DFSVisitChildren() {
100     assert(!VisitStack.empty());
101     while (VisitStack.back().second != GT::child_end(VisitStack.back().first))
102       { // TOS has at least one more child so continue DFS
103         NodeType *childN = *VisitStack.back().second++;
104         if (nodeVisitNumbers.find(childN) == nodeVisitNumbers.end())
105           { // this node has never been seen
106             DFSVisitOne(childN);
107           }
108         else
109           {
110             unsigned childNum = nodeVisitNumbers[childN];
111             if (MinVisitNumStack.back() > childNum)
112               MinVisitNumStack.back() = childNum;
113           }
114       }
115   }
116
117   // Compute the next SCC using the DFS traversal.
118   void GetNextSCC() {
119     assert(VisitStack.size() == MinVisitNumStack.size());
120     CurrentSCC.clear();                 // Prepare to compute the next SCC
121     while (! VisitStack.empty())
122       {
123         DFSVisitChildren();
124
125         assert(VisitStack.back().second ==
126                GT::child_end(VisitStack.back().first));
127         NodeType* visitingN = VisitStack.back().first;
128         unsigned minVisitNum = MinVisitNumStack.back();
129         VisitStack.pop_back();
130         MinVisitNumStack.pop_back();
131         if (! MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
132           MinVisitNumStack.back() = minVisitNum;
133
134         //DEBUG(std::cerr << "TarjanSCC: Popped node " << visitingN <<
135         //      " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
136         //      nodeVisitNumbers[visitingN] << "\n");
137
138         if (minVisitNum == nodeVisitNumbers[visitingN])
139           { // A full SCC is on the SCCNodeStack!  It includes all nodes below
140             // visitingN on the stack.  Copy those nodes to CurrentSCC,
141             // reset their minVisit values, and return (this suspends
142             // the DFS traversal till the next ++).
143             do {
144               CurrentSCC.push_back(SCCNodeStack.back());
145               SCCNodeStack.pop_back();
146               nodeVisitNumbers[CurrentSCC.back()] = ~0UL; 
147             } while (CurrentSCC.back() != visitingN);
148             return;
149           }
150       }
151   }
152
153   inline TarjanSCC_iterator(NodeType *entryN) : visitNum(0) {
154     DFSVisitOne(entryN);
155     GetNextSCC();
156   }
157   inline TarjanSCC_iterator() { /* End is when DFS stack is empty */ }
158
159 public:
160   typedef TarjanSCC_iterator<GraphT, GT> _Self;
161
162   // Provide static "constructors"...
163   static inline _Self begin(GraphT& G) { return _Self(GT::getEntryNode(G)); }
164   static inline _Self end  (GraphT& G) { return _Self(); }
165
166   // Direct loop termination test (I.fini() is more efficient than I == end())
167   inline bool fini() const {
168     assert(!CurrentSCC.empty() || VisitStack.empty());
169     return CurrentSCC.empty();
170   }
171
172   inline bool operator==(const _Self& x) const { 
173     return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
174   }
175   inline bool operator!=(const _Self& x) const { return !operator==(x); }
176
177   // Iterator traversal: forward iteration only
178   inline _Self& operator++() {          // Preincrement
179     GetNextSCC();
180     return *this; 
181   }
182   inline _Self operator++(int) {        // Postincrement
183     _Self tmp = *this; ++*this; return tmp; 
184   }
185
186   // Retrieve a reference to the current SCC
187   inline const SccTy &operator*() const { 
188     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
189     return CurrentSCC;
190   }
191   inline SccTy &operator*() { 
192     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
193     return CurrentSCC;
194   }
195 };
196
197
198 // Global constructor for the Tarjan SCC iterator.
199 template <class T>
200 TarjanSCC_iterator<T> tarj_begin(T G) {
201   return TarjanSCC_iterator<T>::begin(G);
202 }
203
204 template <class T>
205 TarjanSCC_iterator<T> tarj_end(T G) {
206   return TarjanSCC_iterator<T>::end(G);
207 }
208
209 #endif