4732ef5e91fd017092f7e1881f2e1fab981cf9b0
[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                            const std::vector<typename GT::NodeType>,
42                            ptrdiff_t> {
43   typedef typename GT::NodeType NodeType;
44   typedef typename GT::ChildIteratorType ChildItTy;
45   typedef std::vector<NodeType *> SccTy;
46   typedef std::iterator<std::forward_iterator_tag,
47                         const std::vector<typename GT::NodeType>,
48                         ptrdiff_t> super;
49   typedef typename super::reference reference;
50   typedef typename super::pointer pointer;
51
52   /// Element of VisitStack during DFS.
53   struct StackElement {
54     NodeType *Node;       ///< The current node pointer.
55     ChildItTy NextChild;  ///< The next child, modified inplace during DFS.
56     unsigned MinVisited;  ///< Minimum uplink value of all children of Node.
57
58     StackElement(NodeType *Node, const ChildItTy &Child, unsigned Min)
59       : Node(Node), NextChild(Child), MinVisited(Min) {}
60
61     bool operator==(const StackElement &Other) const {
62       return Node == Other.Node &&
63              NextChild == Other.NextChild &&
64              MinVisited == Other.MinVisited;
65     }
66   };
67
68   /// The visit counters used to detect when a complete SCC is on the stack.
69   /// visitNum is the global counter.
70   ///
71   /// nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
72   unsigned visitNum;
73   DenseMap<NodeType *, unsigned> nodeVisitNumbers;
74
75   /// Stack holding nodes of the SCC.
76   std::vector<NodeType *> SCCNodeStack;
77
78   /// The current SCC, retrieved using operator*().
79   SccTy CurrentSCC;
80
81   /// DFS stack, Used to maintain the ordering.  The top contains the current
82   /// node, the next child to visit, and the minimum uplink value of all child
83   std::vector<StackElement> VisitStack;
84
85   /// A single "visit" within the non-recursive DFS traversal.
86   void DFSVisitOne(NodeType *N);
87
88   /// The stack-based DFS traversal; defined below.
89   void DFSVisitChildren();
90
91   /// Compute the next SCC using the DFS traversal.
92   void GetNextSCC();
93
94   scc_iterator(NodeType *entryN) : visitNum(0) {
95     DFSVisitOne(entryN);
96     GetNextSCC();
97   }
98
99   /// End is when the DFS stack is empty.
100   scc_iterator() {}
101
102 public:
103   static scc_iterator begin(const GraphT &G) {
104     return scc_iterator(GT::getEntryNode(G));
105   }
106   static scc_iterator end(const GraphT &) { return scc_iterator(); }
107
108   /// \brief Direct loop termination test which is more efficient than
109   /// comparison with \c end().
110   bool isAtEnd() const {
111     assert(!CurrentSCC.empty() || VisitStack.empty());
112     return CurrentSCC.empty();
113   }
114
115   bool operator==(const scc_iterator &x) const {
116     return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
117   }
118   bool operator!=(const scc_iterator &x) const { return !operator==(x); }
119
120   scc_iterator &operator++() {
121     GetNextSCC();
122     return *this;
123   }
124   scc_iterator operator++(int) {
125     scc_iterator tmp = *this;
126     ++*this;
127     return tmp;
128   }
129
130   const SccTy &operator*() const {
131     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
132     return CurrentSCC;
133   }
134
135   /// \brief Test if the current SCC has a loop.
136   ///
137   /// If the SCC has more than one node, this is trivially true.  If not, it may
138   /// still contain a loop if the node has an edge back to itself.
139   bool hasLoop() const;
140
141   /// This informs the \c scc_iterator that the specified \c Old node
142   /// has been deleted, and \c New is to be used in its place.
143   void ReplaceNode(NodeType *Old, NodeType *New) {
144     assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
145     nodeVisitNumbers[New] = nodeVisitNumbers[Old];
146     nodeVisitNumbers.erase(Old);
147   }
148 };
149
150 template <class GraphT, class GT>
151 void scc_iterator<GraphT, GT>::DFSVisitOne(NodeType *N) {
152   ++visitNum;
153   nodeVisitNumbers[N] = visitNum;
154   SCCNodeStack.push_back(N);
155   VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
156 #if 0 // Enable if needed when debugging.
157   dbgs() << "TarjanSCC: Node " << N <<
158         " : visitNum = " << visitNum << "\n";
159 #endif
160 }
161
162 template <class GraphT, class GT>
163 void scc_iterator<GraphT, GT>::DFSVisitChildren() {
164   assert(!VisitStack.empty());
165   while (VisitStack.back().NextChild != GT::child_end(VisitStack.back().Node)) {
166     // TOS has at least one more child so continue DFS
167     NodeType *childN = *VisitStack.back().NextChild++;
168     typename DenseMap<NodeType *, unsigned>::iterator Visited =
169         nodeVisitNumbers.find(childN);
170     if (Visited == nodeVisitNumbers.end()) {
171       // this node has never been seen.
172       DFSVisitOne(childN);
173       continue;
174     }
175
176     unsigned childNum = Visited->second;
177     if (VisitStack.back().MinVisited > childNum)
178       VisitStack.back().MinVisited = childNum;
179   }
180 }
181
182 template <class GraphT, class GT> void scc_iterator<GraphT, GT>::GetNextSCC() {
183   CurrentSCC.clear(); // Prepare to compute the next SCC
184   while (!VisitStack.empty()) {
185     DFSVisitChildren();
186
187     // Pop the leaf on top of the VisitStack.
188     NodeType *visitingN = VisitStack.back().Node;
189     unsigned minVisitNum = VisitStack.back().MinVisited;
190     assert(VisitStack.back().NextChild == GT::child_end(visitingN));
191     VisitStack.pop_back();
192
193     // Propagate MinVisitNum to parent so we can detect the SCC starting node.
194     if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
195       VisitStack.back().MinVisited = minVisitNum;
196
197 #if 0 // Enable if needed when debugging.
198     dbgs() << "TarjanSCC: Popped node " << visitingN <<
199           " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
200           nodeVisitNumbers[visitingN] << "\n";
201 #endif
202
203     if (minVisitNum != nodeVisitNumbers[visitingN])
204       continue;
205
206     // A full SCC is on the SCCNodeStack!  It includes all nodes below
207     // visitingN on the stack.  Copy those nodes to CurrentSCC,
208     // reset their minVisit values, and return (this suspends
209     // the DFS traversal till the next ++).
210     do {
211       CurrentSCC.push_back(SCCNodeStack.back());
212       SCCNodeStack.pop_back();
213       nodeVisitNumbers[CurrentSCC.back()] = ~0U;
214     } while (CurrentSCC.back() != visitingN);
215     return;
216   }
217 }
218
219 template <class GraphT, class GT>
220 bool scc_iterator<GraphT, GT>::hasLoop() const {
221     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
222     if (CurrentSCC.size() > 1)
223       return true;
224     NodeType *N = CurrentSCC.front();
225     for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
226          ++CI)
227       if (*CI == N)
228         return true;
229     return false;
230   }
231
232 /// \brief Construct the begin iterator for a deduced graph type T.
233 template <class T> scc_iterator<T> scc_begin(const T &G) {
234   return scc_iterator<T>::begin(G);
235 }
236
237 /// \brief Construct the end iterator for a deduced graph type T.
238 template <class T> scc_iterator<T> scc_end(const T &G) {
239   return scc_iterator<T>::end(G);
240 }
241
242 /// \brief Construct the begin iterator for a deduced graph type T's Inverse<T>.
243 template <class T> scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
244   return scc_iterator<Inverse<T> >::begin(G);
245 }
246
247 /// \brief Construct the end iterator for a deduced graph type T's Inverse<T>.
248 template <class T> scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
249   return scc_iterator<Inverse<T> >::end(G);
250 }
251
252 } // End llvm namespace
253
254 #endif