9273cbedb58f98f011c933e42895920a59d2ab6a
[oota-llvm.git] / include / llvm / ADT / SCCIterator.h
1 //===---- ADT/SCCIterator.h - Strongly Connected Comp. Iter. ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
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
13 /// algorithm.
14 ///
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.
17 ///
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.)
20 ///
21 //===----------------------------------------------------------------------===//
22
23 #ifndef LLVM_ADT_SCCITERATOR_H
24 #define LLVM_ADT_SCCITERATOR_H
25
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/GraphTraits.h"
28 #include <vector>
29
30 namespace llvm {
31
32 /// \brief Enumerate the SCCs of a directed graph in reverse topological order
33 /// of the SCC DAG.
34 ///
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> >
39 class scc_iterator
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;
49
50   // Element of VisitStack during DFS.
51   struct StackElement {
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.
55
56     StackElement(NodeType *Node, const ChildItTy &Child, unsigned Min)
57       : Node(Node), NextChild(Child), MinVisited(Min) {}
58
59     bool operator==(const StackElement &Other) const {
60       return Node == Other.Node &&
61              NextChild == Other.NextChild &&
62              MinVisited == Other.MinVisited;
63     }
64   };
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   DenseMap<NodeType *, unsigned> nodeVisitNumbers;
71
72   // Stack holding nodes of the SCC.
73   std::vector<NodeType *> SCCNodeStack;
74
75   // The current SCC, retrieved using operator*().
76   SccTy CurrentSCC;
77
78
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;
82
83   // A single "visit" within the non-recursive DFS traversal.
84   void DFSVisitOne(NodeType *N);
85
86   // The stack-based DFS traversal; defined below.
87   void DFSVisitChildren();
88
89   // Compute the next SCC using the DFS traversal.
90   void GetNextSCC();
91
92   scc_iterator(NodeType *entryN) : visitNum(0) {
93     DFSVisitOne(entryN);
94     GetNextSCC();
95   }
96
97   // End is when the DFS stack is empty.
98   scc_iterator() {}
99
100 public:
101   static scc_iterator begin(const GraphT &G) {
102     return scc_iterator(GT::getEntryNode(G));
103   }
104   static scc_iterator end(const GraphT &) { return scc_iterator(); }
105
106   /// \brief Direct loop termination test which is more efficient than
107   /// comparison with \c end().
108   bool isAtEnd() const {
109     assert(!CurrentSCC.empty() || VisitStack.empty());
110     return CurrentSCC.empty();
111   }
112
113   bool operator==(const scc_iterator &x) const {
114     return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
115   }
116   bool operator!=(const scc_iterator &x) const { return !operator==(x); }
117
118   scc_iterator &operator++() {
119     GetNextSCC();
120     return *this;
121   }
122   scc_iterator operator++(int) {
123     scc_iterator tmp = *this;
124     ++*this;
125     return tmp;
126   }
127
128   const SccTy &operator*() const {
129     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
130     return CurrentSCC;
131   }
132   SccTy &operator*() {
133     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
134     return CurrentSCC;
135   }
136
137   /// \brief Test if the current SCC has a loop.
138   ///
139   /// If the SCC has more than one node, this is trivially true.  If not, it may
140   /// still contain a loop if the node has an edge back to itself.
141   bool hasLoop() const;
142
143   /// This informs the \c scc_iterator that the specified \c Old node
144   /// has been deleted, and \c New is to be used in its place.
145   void ReplaceNode(NodeType *Old, NodeType *New) {
146     assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
147     nodeVisitNumbers[New] = nodeVisitNumbers[Old];
148     nodeVisitNumbers.erase(Old);
149   }
150 };
151
152 template <class GraphT, class GT>
153 void scc_iterator<GraphT, GT>::DFSVisitOne(NodeType *N) {
154   ++visitNum;
155   nodeVisitNumbers[N] = visitNum;
156   SCCNodeStack.push_back(N);
157   VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
158 #if 0 // Enable if needed when debugging.
159   dbgs() << "TarjanSCC: Node " << N <<
160         " : visitNum = " << visitNum << "\n";
161 #endif
162 }
163
164 template <class GraphT, class GT>
165 void scc_iterator<GraphT, GT>::DFSVisitChildren() {
166   assert(!VisitStack.empty());
167   while (VisitStack.back().NextChild != GT::child_end(VisitStack.back().Node)) {
168     // TOS has at least one more child so continue DFS
169     NodeType *childN = *VisitStack.back().NextChild++;
170     typename DenseMap<NodeType *, unsigned>::iterator Visited =
171         nodeVisitNumbers.find(childN);
172     if (Visited == nodeVisitNumbers.end()) {
173       // this node has never been seen.
174       DFSVisitOne(childN);
175       continue;
176     }
177
178     unsigned childNum = Visited->second;
179     if (VisitStack.back().MinVisited > childNum)
180       VisitStack.back().MinVisited = childNum;
181   }
182 }
183
184 template <class GraphT, class GT> void scc_iterator<GraphT, GT>::GetNextSCC() {
185   CurrentSCC.clear(); // Prepare to compute the next SCC
186   while (!VisitStack.empty()) {
187     DFSVisitChildren();
188
189     // Pop the leaf on top of the VisitStack.
190     NodeType *visitingN = VisitStack.back().Node;
191     unsigned minVisitNum = VisitStack.back().MinVisited;
192     assert(VisitStack.back().NextChild == GT::child_end(visitingN));
193     VisitStack.pop_back();
194
195     // Propagate MinVisitNum to parent so we can detect the SCC starting node.
196     if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
197       VisitStack.back().MinVisited = minVisitNum;
198
199 #if 0 // Enable if needed when debugging.
200     dbgs() << "TarjanSCC: Popped node " << visitingN <<
201           " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
202           nodeVisitNumbers[visitingN] << "\n";
203 #endif
204
205     if (minVisitNum != nodeVisitNumbers[visitingN])
206       continue;
207
208     // A full SCC is on the SCCNodeStack!  It includes all nodes below
209     // visitingN on the stack.  Copy those nodes to CurrentSCC,
210     // reset their minVisit values, and return (this suspends
211     // the DFS traversal till the next ++).
212     do {
213       CurrentSCC.push_back(SCCNodeStack.back());
214       SCCNodeStack.pop_back();
215       nodeVisitNumbers[CurrentSCC.back()] = ~0U;
216     } while (CurrentSCC.back() != visitingN);
217     return;
218   }
219 }
220
221 template <class GraphT, class GT>
222 bool scc_iterator<GraphT, GT>::hasLoop() const {
223     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
224     if (CurrentSCC.size() > 1)
225       return true;
226     NodeType *N = CurrentSCC.front();
227     for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
228          ++CI)
229       if (*CI == N)
230         return true;
231     return false;
232   }
233
234 /// \brief Construct the begin iterator for a deduced graph type T.
235 template <class T> scc_iterator<T> scc_begin(const T &G) {
236   return scc_iterator<T>::begin(G);
237 }
238
239 /// \brief Construct the end iterator for a deduced graph type T.
240 template <class T> scc_iterator<T> scc_end(const T &G) {
241   return scc_iterator<T>::end(G);
242 }
243
244 /// \brief Construct the begin iterator for a deduced graph type T's Inverse<T>.
245 template <class T> scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
246   return scc_iterator<Inverse<T> >::begin(G);
247 }
248
249 /// \brief Construct the end iterator for a deduced graph type T's Inverse<T>.
250 template <class T> scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
251   return scc_iterator<Inverse<T> >::end(G);
252 }
253
254 } // End llvm namespace
255
256 #endif