SmallVectorize.
[oota-llvm.git] / include / llvm / Analysis / DominatorInternals.h
1 //=== llvm/Analysis/DominatorInternals.h - Dominator Calculation -*- 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
10 #ifndef LLVM_ANALYSIS_DOMINATOR_INTERNALS_H
11 #define LLVM_ANALYSIS_DOMINATOR_INTERNALS_H
12
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15
16 //===----------------------------------------------------------------------===//
17 //
18 // DominatorTree construction - This pass constructs immediate dominator
19 // information for a flow-graph based on the algorithm described in this
20 // document:
21 //
22 //   A Fast Algorithm for Finding Dominators in a Flowgraph
23 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
24 //
25 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
26 // LINK, but it turns out that the theoretically slower O(n*log(n))
27 // implementation is actually faster than the "efficient" algorithm (even for
28 // large CFGs) because the constant overheads are substantially smaller.  The
29 // lower-complexity version can be enabled with the following #define:
30 //
31 #define BALANCE_IDOM_TREE 0
32 //
33 //===----------------------------------------------------------------------===//
34
35 namespace llvm {
36
37 template<class GraphT>
38 unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
39                  typename GraphT::NodeType* V, unsigned N) {
40   // This is more understandable as a recursive algorithm, but we can't use the
41   // recursive algorithm due to stack depth issues.  Keep it here for
42   // documentation purposes.
43 #if 0
44   InfoRec &VInfo = DT.Info[DT.Roots[i]];
45   VInfo.DFSNum = VInfo.Semi = ++N;
46   VInfo.Label = V;
47
48   Vertex.push_back(V);        // Vertex[n] = V;
49   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
50   //Info[V].Child = 0;        // Child[v] = 0
51   VInfo.Size = 1;             // Size[v] = 1
52
53   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
54     InfoRec &SuccVInfo = DT.Info[*SI];
55     if (SuccVInfo.Semi == 0) {
56       SuccVInfo.Parent = V;
57       N = DTDFSPass(DT, *SI, N);
58     }
59   }
60 #else
61   bool IsChilOfArtificialExit = (N != 0);
62
63   std::vector<std::pair<typename GraphT::NodeType*,
64                         typename GraphT::ChildIteratorType> > Worklist;
65   Worklist.push_back(std::make_pair(V, GraphT::child_begin(V)));
66   while (!Worklist.empty()) {
67     typename GraphT::NodeType* BB = Worklist.back().first;
68     typename GraphT::ChildIteratorType NextSucc = Worklist.back().second;
69
70     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
71                                                                     DT.Info[BB];
72
73     // First time we visited this BB?
74     if (NextSucc == GraphT::child_begin(BB)) {
75       BBInfo.DFSNum = BBInfo.Semi = ++N;
76       BBInfo.Label = BB;
77
78       DT.Vertex.push_back(BB);       // Vertex[n] = V;
79       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
80       //BBInfo[V].Child = 0;      // Child[v] = 0
81       BBInfo.Size = 1;            // Size[v] = 1
82
83       if (IsChilOfArtificialExit)
84         BBInfo.Parent = 1;
85
86       IsChilOfArtificialExit = false;
87     }
88
89     // store the DFS number of the current BB - the reference to BBInfo might
90     // get invalidated when processing the successors.
91     unsigned BBDFSNum = BBInfo.DFSNum;
92
93     // If we are done with this block, remove it from the worklist.
94     if (NextSucc == GraphT::child_end(BB)) {
95       Worklist.pop_back();
96       continue;
97     }
98
99     // Increment the successor number for the next time we get to it.
100     ++Worklist.back().second;
101     
102     // Visit the successor next, if it isn't already visited.
103     typename GraphT::NodeType* Succ = *NextSucc;
104
105     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &SuccVInfo =
106                                                                   DT.Info[Succ];
107     if (SuccVInfo.Semi == 0) {
108       SuccVInfo.Parent = BBDFSNum;
109       Worklist.push_back(std::make_pair(Succ, GraphT::child_begin(Succ)));
110     }
111   }
112 #endif
113     return N;
114 }
115
116 template<class GraphT>
117 void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
118               typename GraphT::NodeType *VIn) {
119   SmallVector<typename GraphT::NodeType*, 32> Work;
120   SmallPtrSet<typename GraphT::NodeType*, 32> Visited;
121   typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInVAInfo =
122                                       DT.Info[DT.Vertex[DT.Info[VIn].Ancestor]];
123
124   if (VInVAInfo.Ancestor != 0)
125     Work.push_back(VIn);
126   
127   while (!Work.empty()) {
128     typename GraphT::NodeType* V = Work.back();
129     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
130                                                                      DT.Info[V];
131     typename GraphT::NodeType* VAncestor = DT.Vertex[VInfo.Ancestor];
132     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VAInfo =
133                                                              DT.Info[VAncestor];
134
135     // Process Ancestor first
136     if (Visited.insert(VAncestor) &&
137         VAInfo.Ancestor != 0) {
138       Work.push_back(VAncestor);
139       continue;
140     } 
141     Work.pop_back(); 
142
143     // Update VInfo based on Ancestor info
144     if (VAInfo.Ancestor == 0)
145       continue;
146     typename GraphT::NodeType* VAncestorLabel = VAInfo.Label;
147     typename GraphT::NodeType* VLabel = VInfo.Label;
148     if (DT.Info[VAncestorLabel].Semi < DT.Info[VLabel].Semi)
149       VInfo.Label = VAncestorLabel;
150     VInfo.Ancestor = VAInfo.Ancestor;
151   }
152 }
153
154 template<class GraphT>
155 typename GraphT::NodeType* 
156 Eval(DominatorTreeBase<typename GraphT::NodeType>& DT,
157      typename GraphT::NodeType *V) {
158   typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
159                                                                      DT.Info[V];
160 #if !BALANCE_IDOM_TREE
161   // Higher-complexity but faster implementation
162   if (VInfo.Ancestor == 0)
163     return V;
164   Compress<GraphT>(DT, V);
165   return VInfo.Label;
166 #else
167   // Lower-complexity but slower implementation
168   if (VInfo.Ancestor == 0)
169     return VInfo.Label;
170   Compress<GraphT>(DT, V);
171   GraphT::NodeType* VLabel = VInfo.Label;
172
173   GraphT::NodeType* VAncestorLabel = DT.Info[VInfo.Ancestor].Label;
174   if (DT.Info[VAncestorLabel].Semi >= DT.Info[VLabel].Semi)
175     return VLabel;
176   else
177     return VAncestorLabel;
178 #endif
179 }
180
181 template<class GraphT>
182 void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
183           unsigned DFSNumV, typename GraphT::NodeType* W,
184         typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo) {
185 #if !BALANCE_IDOM_TREE
186   // Higher-complexity but faster implementation
187   WInfo.Ancestor = DFSNumV;
188 #else
189   // Lower-complexity but slower implementation
190   GraphT::NodeType* WLabel = WInfo.Label;
191   unsigned WLabelSemi = DT.Info[WLabel].Semi;
192   GraphT::NodeType* S = W;
193   InfoRec *SInfo = &DT.Info[S];
194
195   GraphT::NodeType* SChild = SInfo->Child;
196   InfoRec *SChildInfo = &DT.Info[SChild];
197
198   while (WLabelSemi < DT.Info[SChildInfo->Label].Semi) {
199     GraphT::NodeType* SChildChild = SChildInfo->Child;
200     if (SInfo->Size+DT.Info[SChildChild].Size >= 2*SChildInfo->Size) {
201       SChildInfo->Ancestor = S;
202       SInfo->Child = SChild = SChildChild;
203       SChildInfo = &DT.Info[SChild];
204     } else {
205       SChildInfo->Size = SInfo->Size;
206       S = SInfo->Ancestor = SChild;
207       SInfo = SChildInfo;
208       SChild = SChildChild;
209       SChildInfo = &DT.Info[SChild];
210     }
211   }
212
213   DominatorTreeBase::InfoRec &VInfo = DT.Info[V];
214   SInfo->Label = WLabel;
215
216   assert(V != W && "The optimization here will not work in this case!");
217   unsigned WSize = WInfo.Size;
218   unsigned VSize = (VInfo.Size += WSize);
219
220   if (VSize < 2*WSize)
221     std::swap(S, VInfo.Child);
222
223   while (S) {
224     SInfo = &DT.Info[S];
225     SInfo->Ancestor = V;
226     S = SInfo->Child;
227   }
228 #endif
229 }
230
231 template<class FuncT, class NodeT>
232 void Calculate(DominatorTreeBase<typename GraphTraits<NodeT>::NodeType>& DT,
233                FuncT& F) {
234   typedef GraphTraits<NodeT> GraphT;
235
236   unsigned N = 0;
237   bool MultipleRoots = (DT.Roots.size() > 1);
238   if (MultipleRoots) {
239     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
240         DT.Info[NULL];
241     BBInfo.DFSNum = BBInfo.Semi = ++N;
242     BBInfo.Label = NULL;
243
244     DT.Vertex.push_back(NULL);       // Vertex[n] = V;
245       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
246       //BBInfo[V].Child = 0;      // Child[v] = 0
247     BBInfo.Size = 1;            // Size[v] = 1
248   }
249
250   // Step #1: Number blocks in depth-first order and initialize variables used
251   // in later stages of the algorithm.
252   for (unsigned i = 0, e = static_cast<unsigned>(DT.Roots.size());
253        i != e; ++i)
254     N = DFSPass<GraphT>(DT, DT.Roots[i], N);
255
256   // it might be that some blocks did not get a DFS number (e.g., blocks of 
257   // infinite loops). In these cases an artificial exit node is required.
258   MultipleRoots |= (DT.isPostDominator() && N != F.size());
259
260   for (unsigned i = N; i >= 2; --i) {
261     typename GraphT::NodeType* W = DT.Vertex[i];
262     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo =
263                                                                      DT.Info[W];
264
265     // Step #2: Calculate the semidominators of all vertices
266
267     // initialize the semi dominator to point to the parent node
268     WInfo.Semi = WInfo.Parent;
269     typedef GraphTraits<Inverse<NodeT> > InvTraits;
270     for (typename InvTraits::ChildIteratorType CI =
271          InvTraits::child_begin(W),
272          E = InvTraits::child_end(W); CI != E; ++CI) {
273       typename InvTraits::NodeType *N = *CI;
274       if (DT.Info.count(N)) {  // Only if this predecessor is reachable!
275         unsigned SemiU = DT.Info[Eval<GraphT>(DT, N)].Semi;
276         if (SemiU < WInfo.Semi)
277           WInfo.Semi = SemiU;
278       }
279     }
280
281     DT.Info[DT.Vertex[WInfo.Semi]].Bucket.push_back(W);
282
283     typename GraphT::NodeType* WParent = DT.Vertex[WInfo.Parent];
284     Link<GraphT>(DT, WInfo.Parent, W, WInfo);
285
286     // Step #3: Implicitly define the immediate dominator of vertices
287     std::vector<typename GraphT::NodeType*> &WParentBucket =
288                                                         DT.Info[WParent].Bucket;
289     while (!WParentBucket.empty()) {
290       typename GraphT::NodeType* V = WParentBucket.back();
291       WParentBucket.pop_back();
292       typename GraphT::NodeType* U = Eval<GraphT>(DT, V);
293       DT.IDoms[V] = DT.Info[U].Semi < DT.Info[V].Semi ? U : WParent;
294     }
295   }
296
297   // Step #4: Explicitly define the immediate dominator of each vertex
298   for (unsigned i = 2; i <= N; ++i) {
299     typename GraphT::NodeType* W = DT.Vertex[i];
300     typename GraphT::NodeType*& WIDom = DT.IDoms[W];
301     if (WIDom != DT.Vertex[DT.Info[W].Semi])
302       WIDom = DT.IDoms[WIDom];
303   }
304
305   if (DT.Roots.empty()) return;
306
307   // Add a node for the root.  This node might be the actual root, if there is
308   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
309   // which postdominates all real exits if there are multiple exit blocks, or
310   // an infinite loop.
311   typename GraphT::NodeType* Root = !MultipleRoots ? DT.Roots[0] : 0;
312
313   DT.DomTreeNodes[Root] = DT.RootNode =
314                         new DomTreeNodeBase<typename GraphT::NodeType>(Root, 0);
315
316   // Loop over all of the reachable blocks in the function...
317   for (unsigned i = 2; i <= N; ++i) {
318     typename GraphT::NodeType* W = DT.Vertex[i];
319
320     DomTreeNodeBase<typename GraphT::NodeType> *BBNode = DT.DomTreeNodes[W];
321     if (BBNode) continue;  // Haven't calculated this node yet?
322
323     typename GraphT::NodeType* ImmDom = DT.getIDom(W);
324
325     assert(ImmDom || DT.DomTreeNodes[NULL]);
326
327     // Get or calculate the node for the immediate dominator
328     DomTreeNodeBase<typename GraphT::NodeType> *IDomNode =
329                                                      DT.getNodeForBlock(ImmDom);
330
331     // Add a new tree node for this BasicBlock, and link it as a child of
332     // IDomNode
333     DomTreeNodeBase<typename GraphT::NodeType> *C =
334                     new DomTreeNodeBase<typename GraphT::NodeType>(W, IDomNode);
335     DT.DomTreeNodes[W] = IDomNode->addChild(C);
336   }
337
338   // Free temporary memory used to construct idom's
339   DT.IDoms.clear();
340   DT.Info.clear();
341   std::vector<typename GraphT::NodeType*>().swap(DT.Vertex);
342
343   DT.updateDFSNumbers();
344 }
345
346 }
347
348 #endif