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