Make the copy member of StringRef/ArrayRef generic wrt allocators.
[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     ++visitNum;
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";
92 #endif
93   }
94
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.
106         DFSVisitOne(childN);
107         continue;
108       }
109
110       unsigned childNum = Visited->second;
111       if (VisitStack.back().MinVisited > childNum)
112         VisitStack.back().MinVisited = childNum;
113     }
114   }
115
116   // Compute the next SCC using the DFS traversal.
117   void GetNextSCC() {
118     CurrentSCC.clear(); // Prepare to compute the next SCC
119     while (!VisitStack.empty()) {
120       DFSVisitChildren();
121
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();
127
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;
131
132 #if 0 // Enable if needed when debugging.
133       dbgs() << "TarjanSCC: Popped node " << visitingN <<
134             " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
135             nodeVisitNumbers[visitingN] << "\n";
136 #endif
137
138       if (minVisitNum != nodeVisitNumbers[visitingN])
139         continue;
140
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 ++).
145       do {
146         CurrentSCC.push_back(SCCNodeStack.back());
147         SCCNodeStack.pop_back();
148         nodeVisitNumbers[CurrentSCC.back()] = ~0U;
149       } while (CurrentSCC.back() != visitingN);
150       return;
151     }
152   }
153
154   inline scc_iterator(NodeType *entryN) : visitNum(0) {
155     DFSVisitOne(entryN);
156     GetNextSCC();
157   }
158
159   // End is when the DFS stack is empty.
160   inline scc_iterator() {}
161
162 public:
163   static inline scc_iterator begin(const GraphT &G) {
164     return scc_iterator(GT::getEntryNode(G));
165   }
166   static inline scc_iterator end(const GraphT &) { return scc_iterator(); }
167
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();
173   }
174
175   inline bool operator==(const scc_iterator &x) const {
176     return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
177   }
178   inline bool operator!=(const scc_iterator &x) const { return !operator==(x); }
179
180   inline scc_iterator &operator++() {
181     GetNextSCC();
182     return *this;
183   }
184   inline scc_iterator operator++(int) {
185     scc_iterator tmp = *this;
186     ++*this;
187     return tmp;
188   }
189
190   inline const SccTy &operator*() const {
191     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
192     return CurrentSCC;
193   }
194   inline SccTy &operator*() {
195     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
196     return CurrentSCC;
197   }
198
199   /// \brief Test if the current SCC has a loop.
200   ///
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)
206       return true;
207     NodeType *N = CurrentSCC.front();
208     for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
209          ++CI)
210       if (*CI == N)
211         return true;
212     return false;
213   }
214
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);
221   }
222 };
223
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);
227 }
228
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);
232 }
233
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);
237 }
238
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);
242 }
243
244 } // End llvm namespace
245
246 #endif