f21c7d162e5129fa713ad291e21080acb30e8d81
[oota-llvm.git] / include / llvm / ADT / SCCIterator.h
1 //===-- Support/SCCIterator.h - SCC iterator --------------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This builds on the Support/GraphTraits.h file to find the strongly connected
11 // components (SCCs) of a graph in O(N+E) time using Tarjan's DFS algorithm.
12 //
13 // The SCC iterator has the important property that if a node in SCC S1 has an
14 // edge to a node in SCC S2, then it visits S1 *after* S2.
15 // 
16 // To visit S1 *before* S2, use the scc_iterator on the Inverse graph.
17 // (NOTE: This requires some simple wrappers and is not supported yet.)
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef SUPPORT_SCCITERATOR_H
22 #define SUPPORT_SCCITERATOR_H
23
24 #include "Support/GraphTraits.h"
25 #include "Support/iterator"
26 #include <vector>
27 #include <map>
28
29 namespace llvm {
30
31 //===----------------------------------------------------------------------===//
32 ///
33 /// scc_iterator - Enumerate the SCCs of a directed graph, in
34 /// reverse topological order of the SCC DAG.
35 ///
36 template<class GraphT, class GT = GraphTraits<GraphT> >
37 class scc_iterator
38   : public forward_iterator<std::vector<typename GT::NodeType>, ptrdiff_t> {
39   typedef typename GT::NodeType          NodeType;
40   typedef typename GT::ChildIteratorType ChildItTy;
41   typedef std::vector<NodeType*> SccTy;
42   typedef forward_iterator<SccTy, ptrdiff_t> super;
43   typedef typename super::reference reference;
44   typedef typename super::pointer pointer;
45
46   // The visit counters used to detect when a complete SCC is on the stack.
47   // visitNum is the global counter.
48   // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
49   unsigned visitNum;
50   std::map<NodeType *, unsigned> nodeVisitNumbers;
51
52   // SCCNodeStack - Stack holding nodes of the SCC.
53   std::vector<NodeType *> SCCNodeStack;
54
55   // CurrentSCC - The current SCC, retrieved using operator*().
56   SccTy CurrentSCC;
57
58   // VisitStack - Used to maintain the ordering.  Top = current block
59   // First element is basic block pointer, second is the 'next child' to visit
60   std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
61
62   // MinVistNumStack - Stack holding the "min" values for each node in the DFS.
63   // This is used to track the minimum uplink values for all children of
64   // the corresponding node on the VisitStack.
65   std::vector<unsigned> MinVisitNumStack;
66
67   // A single "visit" within the non-recursive DFS traversal.
68   void DFSVisitOne(NodeType* N) {
69     ++visitNum;                         // Global counter for the visit order
70     nodeVisitNumbers[N] = visitNum;
71     SCCNodeStack.push_back(N);
72     MinVisitNumStack.push_back(visitNum);
73     VisitStack.push_back(make_pair(N, GT::child_begin(N)));
74     //DEBUG(std::cerr << "TarjanSCC: Node " << N <<
75     //      " : visitNum = " << visitNum << "\n");
76   }
77
78   // The stack-based DFS traversal; defined below.
79   void DFSVisitChildren() {
80     assert(!VisitStack.empty());
81     while (VisitStack.back().second != GT::child_end(VisitStack.back().first))
82       { // TOS has at least one more child so continue DFS
83         NodeType *childN = *VisitStack.back().second++;
84         if (nodeVisitNumbers.find(childN) == nodeVisitNumbers.end())
85           { // this node has never been seen
86             DFSVisitOne(childN);
87           }
88         else
89           {
90             unsigned childNum = nodeVisitNumbers[childN];
91             if (MinVisitNumStack.back() > childNum)
92               MinVisitNumStack.back() = childNum;
93           }
94       }
95   }
96
97   // Compute the next SCC using the DFS traversal.
98   void GetNextSCC() {
99     assert(VisitStack.size() == MinVisitNumStack.size());
100     CurrentSCC.clear();                 // Prepare to compute the next SCC
101     while (! VisitStack.empty())
102       {
103         DFSVisitChildren();
104
105         assert(VisitStack.back().second ==
106                GT::child_end(VisitStack.back().first));
107         NodeType* visitingN = VisitStack.back().first;
108         unsigned minVisitNum = MinVisitNumStack.back();
109         VisitStack.pop_back();
110         MinVisitNumStack.pop_back();
111         if (! MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
112           MinVisitNumStack.back() = minVisitNum;
113
114         //DEBUG(std::cerr << "TarjanSCC: Popped node " << visitingN <<
115         //      " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
116         //      nodeVisitNumbers[visitingN] << "\n");
117
118         if (minVisitNum == nodeVisitNumbers[visitingN])
119           { // A full SCC is on the SCCNodeStack!  It includes all nodes below
120             // visitingN on the stack.  Copy those nodes to CurrentSCC,
121             // reset their minVisit values, and return (this suspends
122             // the DFS traversal till the next ++).
123             do {
124               CurrentSCC.push_back(SCCNodeStack.back());
125               SCCNodeStack.pop_back();
126               nodeVisitNumbers[CurrentSCC.back()] = ~0UL; 
127             } while (CurrentSCC.back() != visitingN);
128             return;
129           }
130       }
131   }
132
133   inline scc_iterator(NodeType *entryN) : visitNum(0) {
134     DFSVisitOne(entryN);
135     GetNextSCC();
136   }
137   inline scc_iterator() { /* End is when DFS stack is empty */ }
138
139 public:
140   typedef scc_iterator<GraphT, GT> _Self;
141
142   // Provide static "constructors"...
143   static inline _Self begin(GraphT& G) { return _Self(GT::getEntryNode(G)); }
144   static inline _Self end  (GraphT& G) { return _Self(); }
145
146   // Direct loop termination test (I.fini() is more efficient than I == end())
147   inline bool fini() const {
148     assert(!CurrentSCC.empty() || VisitStack.empty());
149     return CurrentSCC.empty();
150   }
151
152   inline bool operator==(const _Self& x) const { 
153     return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
154   }
155   inline bool operator!=(const _Self& x) const { return !operator==(x); }
156
157   // Iterator traversal: forward iteration only
158   inline _Self& operator++() {          // Preincrement
159     GetNextSCC();
160     return *this; 
161   }
162   inline _Self operator++(int) {        // Postincrement
163     _Self tmp = *this; ++*this; return tmp; 
164   }
165
166   // Retrieve a reference to the current SCC
167   inline const SccTy &operator*() const { 
168     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
169     return CurrentSCC;
170   }
171   inline SccTy &operator*() { 
172     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
173     return CurrentSCC;
174   }
175
176   // hasLoop() -- Test if the current SCC has a loop.  If it has more than one
177   // node, this is trivially true.  If not, it may still contain a loop if the
178   // node has an edge back to itself.
179   bool hasLoop() const {
180     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
181     if (CurrentSCC.size() > 1) return true;
182     NodeType *N = CurrentSCC.front();
183     for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
184       if (*CI == N)
185         return true;
186     return false;
187   }
188 };
189
190
191 // Global constructor for the SCC iterator.
192 template <class T>
193 scc_iterator<T> scc_begin(T G) {
194   return scc_iterator<T>::begin(G);
195 }
196
197 template <class T>
198 scc_iterator<T> scc_end(T G) {
199   return scc_iterator<T>::end(G);
200 }
201
202 } // End llvm namespace
203
204 #endif