1 //===---- ADT/SCCIterator.h - Strongly Connected Comp. Iter. ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This builds on the llvm/ADT/GraphTraits.h file to find the strongly
12 /// connected components (SCCs) of a graph in O(N+E) time using Tarjan's DFS
15 /// The SCC iterator has the important property that if a node in SCC S1 has an
16 /// edge to a node in SCC S2, then it visits S1 *after* S2.
18 /// To visit S1 *before* S2, use the scc_iterator on the Inverse graph. (NOTE:
19 /// This requires some simple wrappers and is not supported yet.)
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_ADT_SCCITERATOR_H
24 #define LLVM_ADT_SCCITERATOR_H
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/GraphTraits.h"
32 /// \brief Enumerate the SCCs of a directed graph in reverse topological order
35 /// This is implemented using Tarjan's DFS algorithm using an internal stack to
36 /// build up a vector of nodes in a particular SCC. Note that it is a forward
37 /// iterator and thus you cannot backtrack or re-visit nodes.
38 template <class GraphT, class GT = GraphTraits<GraphT> >
40 : public std::iterator<std::forward_iterator_tag,
41 std::vector<typename GT::NodeType>, ptrdiff_t> {
42 typedef typename GT::NodeType NodeType;
43 typedef typename GT::ChildIteratorType ChildItTy;
44 typedef std::vector<NodeType *> SccTy;
45 typedef std::iterator<std::forward_iterator_tag,
46 std::vector<typename GT::NodeType>, ptrdiff_t> super;
47 typedef typename super::reference reference;
48 typedef typename super::pointer pointer;
50 // Element of VisitStack during DFS.
52 NodeType *Node; ///< The current node pointer.
53 ChildItTy NextChild; ///< The next child, modified inplace during DFS.
54 unsigned MinVisited; ///< Minimum uplink value of all children of Node.
56 StackElement(NodeType *Node, const ChildItTy &Child, unsigned Min)
57 : Node(Node), NextChild(Child), MinVisited(Min) {}
59 bool operator==(const StackElement &Other) const {
60 return Node == Other.Node &&
61 NextChild == Other.NextChild &&
62 MinVisited == Other.MinVisited;
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.
70 DenseMap<NodeType *, unsigned> nodeVisitNumbers;
72 // Stack holding nodes of the SCC.
73 std::vector<NodeType *> SCCNodeStack;
75 // The current SCC, retrieved using operator*().
79 // DFS stack, Used to maintain the ordering. The top contains the current
80 // node, the next child to visit, and the minimum uplink value of all child
81 std::vector<StackElement> VisitStack;
83 // A single "visit" within the non-recursive DFS traversal.
84 void DFSVisitOne(NodeType *N) {
86 nodeVisitNumbers[N] = visitNum;
87 SCCNodeStack.push_back(N);
88 VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
89 #if 0 // Enable if needed when debugging.
90 dbgs() << "TarjanSCC: Node " << N <<
91 " : visitNum = " << visitNum << "\n";
95 // The stack-based DFS traversal; defined below.
96 void DFSVisitChildren() {
97 assert(!VisitStack.empty());
98 while (VisitStack.back().NextChild !=
99 GT::child_end(VisitStack.back().Node)) {
100 // TOS has at least one more child so continue DFS
101 NodeType *childN = *VisitStack.back().NextChild++;
102 typename DenseMap<NodeType *, unsigned>::iterator Visited =
103 nodeVisitNumbers.find(childN);
104 if (Visited == nodeVisitNumbers.end()) {
105 // this node has never been seen.
110 unsigned childNum = Visited->second;
111 if (VisitStack.back().MinVisited > childNum)
112 VisitStack.back().MinVisited = childNum;
116 // Compute the next SCC using the DFS traversal.
118 CurrentSCC.clear(); // Prepare to compute the next SCC
119 while (!VisitStack.empty()) {
122 // Pop the leaf on top of the VisitStack.
123 NodeType *visitingN = VisitStack.back().Node;
124 unsigned minVisitNum = VisitStack.back().MinVisited;
125 assert(VisitStack.back().NextChild == GT::child_end(visitingN));
126 VisitStack.pop_back();
128 // Propagate MinVisitNum to parent so we can detect the SCC starting node.
129 if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
130 VisitStack.back().MinVisited = minVisitNum;
132 #if 0 // Enable if needed when debugging.
133 dbgs() << "TarjanSCC: Popped node " << visitingN <<
134 " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
135 nodeVisitNumbers[visitingN] << "\n";
138 if (minVisitNum != nodeVisitNumbers[visitingN])
141 // A full SCC is on the SCCNodeStack! It includes all nodes below
142 // visitingN on the stack. Copy those nodes to CurrentSCC,
143 // reset their minVisit values, and return (this suspends
144 // the DFS traversal till the next ++).
146 CurrentSCC.push_back(SCCNodeStack.back());
147 SCCNodeStack.pop_back();
148 nodeVisitNumbers[CurrentSCC.back()] = ~0U;
149 } while (CurrentSCC.back() != visitingN);
154 inline scc_iterator(NodeType *entryN) : visitNum(0) {
159 // End is when the DFS stack is empty.
160 inline scc_iterator() {}
163 static inline scc_iterator begin(const GraphT &G) {
164 return scc_iterator(GT::getEntryNode(G));
166 static inline scc_iterator end(const GraphT &) { return scc_iterator(); }
168 /// \brief Direct loop termination test which is more efficient than
169 /// comparison with \c end().
170 inline bool isAtEnd() const {
171 assert(!CurrentSCC.empty() || VisitStack.empty());
172 return CurrentSCC.empty();
175 inline bool operator==(const scc_iterator &x) const {
176 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
178 inline bool operator!=(const scc_iterator &x) const { return !operator==(x); }
180 inline scc_iterator &operator++() {
184 inline scc_iterator operator++(int) {
185 scc_iterator tmp = *this;
190 inline const SccTy &operator*() const {
191 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
194 inline SccTy &operator*() {
195 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
199 /// \brief Test if the current SCC has a loop.
201 /// If the SCC has more than one node, this is trivially true. If not, it may
202 /// still contain a loop if the node has an edge back to itself.
203 bool hasLoop() const {
204 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
205 if (CurrentSCC.size() > 1)
207 NodeType *N = CurrentSCC.front();
208 for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
215 /// This informs the \c scc_iterator that the specified \c Old node
216 /// has been deleted, and \c New is to be used in its place.
217 void ReplaceNode(NodeType *Old, NodeType *New) {
218 assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
219 nodeVisitNumbers[New] = nodeVisitNumbers[Old];
220 nodeVisitNumbers.erase(Old);
224 /// \brief Construct the begin iterator for a deduced graph type T.
225 template <class T> scc_iterator<T> scc_begin(const T &G) {
226 return scc_iterator<T>::begin(G);
229 /// \brief Construct the end iterator for a deduced graph type T.
230 template <class T> scc_iterator<T> scc_end(const T &G) {
231 return scc_iterator<T>::end(G);
234 /// \brief Construct the begin iterator for a deduced graph type T's Inverse<T>.
235 template <class T> scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
236 return scc_iterator<Inverse<T> >::begin(G);
239 /// \brief Construct the end iterator for a deduced graph type T's Inverse<T>.
240 template <class T> scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
241 return scc_iterator<Inverse<T> >::end(G);
244 } // End llvm namespace