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