1 //===-- Support/TarjanSCCIterator.h - Tarjan SCC iterator -------*- C++ -*-===//
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.
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.
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.)
13 //===----------------------------------------------------------------------===//
15 #ifndef SUPPORT_TARJANSCCITERATOR_H
16 #define SUPPORT_TARJANSCCITERATOR_H
18 #include "Support/GraphTraits.h"
19 #include "Support/iterator"
23 //===----------------------------------------------------------------------===//
25 /// TarjanSCC_iterator - Enumerate the SCCs of a directed graph, in
26 /// reverse topological order of the SCC DAG.
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;
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.
42 std::map<NodeType *, unsigned> nodeVisitNumbers;
44 // SCCNodeStack - Stack holding nodes of the SCC.
45 std::vector<NodeType *> SCCNodeStack;
47 // CurrentSCC - The current SCC, retrieved using operator*().
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;
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;
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");
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
82 unsigned childNum = nodeVisitNumbers[childN];
83 if (MinVisitNumStack.back() > childNum)
84 MinVisitNumStack.back() = childNum;
89 // Compute the next SCC using the DFS traversal.
91 assert(VisitStack.size() == MinVisitNumStack.size());
92 CurrentSCC.clear(); // Prepare to compute the next SCC
93 while (! VisitStack.empty())
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;
106 //DEBUG(std::cerr << "TarjanSCC: Popped node " << visitingN <<
107 // " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
108 // nodeVisitNumbers[visitingN] << "\n");
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 ++).
116 CurrentSCC.push_back(SCCNodeStack.back());
117 SCCNodeStack.pop_back();
118 nodeVisitNumbers[CurrentSCC.back()] = ~0UL;
119 } while (CurrentSCC.back() != visitingN);
125 inline TarjanSCC_iterator(NodeType *entryN) : visitNum(0) {
129 inline TarjanSCC_iterator() { /* End is when DFS stack is empty */ }
132 typedef TarjanSCC_iterator<GraphT, GT> _Self;
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(); }
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();
144 inline bool operator==(const _Self& x) const {
145 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
147 inline bool operator!=(const _Self& x) const { return !operator==(x); }
149 // Iterator traversal: forward iteration only
150 inline _Self& operator++() { // Preincrement
154 inline _Self operator++(int) { // Postincrement
155 _Self tmp = *this; ++*this; return tmp;
158 // Retrieve a reference to the current SCC
159 inline const SccTy &operator*() const {
160 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
163 inline SccTy &operator*() {
164 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
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)
183 // Global constructor for the Tarjan SCC iterator.
185 TarjanSCC_iterator<T> tarj_begin(T G) {
186 return TarjanSCC_iterator<T>::begin(G);
190 TarjanSCC_iterator<T> tarj_end(T G) {
191 return TarjanSCC_iterator<T>::end(G);