Completely merge the implementation details of DomTree and PostDomTree.
[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 was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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/DenseMap.h"
15 #include "llvm/ADT/SmallPtrSet.h"
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& DT, typename GraphT::NodeType* V,
39                  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.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   std::vector<std::pair<typename GraphT::NodeType*,
62                         typename GraphT::ChildIteratorType> > Worklist;
63   Worklist.push_back(std::make_pair(V, GraphT::child_begin(V)));
64   while (!Worklist.empty()) {
65     typename GraphT::NodeType* BB = Worklist.back().first;
66     typename GraphT::ChildIteratorType NextSucc = Worklist.back().second;
67
68     // First time we visited this BB?
69     if (NextSucc == GraphT::child_begin(BB)) {
70       DominatorTree::InfoRec &BBInfo = DT.Info[BB];
71       BBInfo.Semi = ++N;
72       BBInfo.Label = BB;
73
74       DT.Vertex.push_back(BB);       // Vertex[n] = V;
75       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
76       //BBInfo[V].Child = 0;      // Child[v] = 0
77       BBInfo.Size = 1;            // Size[v] = 1
78     }
79     
80     // If we are done with this block, remove it from the worklist.
81     if (NextSucc == GraphT::child_end(BB)) {
82       Worklist.pop_back();
83       continue;
84     }
85
86     // Increment the successor number for the next time we get to it.
87     ++Worklist.back().second;
88     
89     // Visit the successor next, if it isn't already visited.
90     typename GraphT::NodeType* Succ = *NextSucc;
91
92     DominatorTree::InfoRec &SuccVInfo = DT.Info[Succ];
93     if (SuccVInfo.Semi == 0) {
94       SuccVInfo.Parent = BB;
95       Worklist.push_back(std::make_pair(Succ, GraphT::child_begin(Succ)));
96     }
97   }
98 #endif
99     return N;
100 }
101
102 template<class GraphT>
103 void Compress(DominatorTreeBase& DT, typename GraphT::NodeType *VIn) {
104   std::vector<typename GraphT::NodeType*> Work;
105   SmallPtrSet<typename GraphT::NodeType*, 32> Visited;
106   typename GraphT::NodeType* VInAncestor = DT.Info[VIn].Ancestor;
107   DominatorTreeBase::InfoRec &VInVAInfo = DT.Info[VInAncestor];
108
109   if (VInVAInfo.Ancestor != 0)
110     Work.push_back(VIn);
111   
112   while (!Work.empty()) {
113     typename GraphT::NodeType* V = Work.back();
114     DominatorTree::InfoRec &VInfo = DT.Info[V];
115     typename GraphT::NodeType* VAncestor = VInfo.Ancestor;
116     DominatorTreeBase::InfoRec &VAInfo = DT.Info[VAncestor];
117
118     // Process Ancestor first
119     if (Visited.insert(VAncestor) &&
120         VAInfo.Ancestor != 0) {
121       Work.push_back(VAncestor);
122       continue;
123     } 
124     Work.pop_back(); 
125
126     // Update VInfo based on Ancestor info
127     if (VAInfo.Ancestor == 0)
128       continue;
129     typename GraphT::NodeType* VAncestorLabel = VAInfo.Label;
130     typename GraphT::NodeType* VLabel = VInfo.Label;
131     if (DT.Info[VAncestorLabel].Semi < DT.Info[VLabel].Semi)
132       VInfo.Label = VAncestorLabel;
133     VInfo.Ancestor = VAInfo.Ancestor;
134   }
135 }
136
137 template<class GraphT>
138 typename GraphT::NodeType* Eval(DominatorTreeBase& DT,
139                                 typename GraphT::NodeType *V) {
140   DominatorTreeBase::InfoRec &VInfo = DT.Info[V];
141 #if !BALANCE_IDOM_TREE
142   // Higher-complexity but faster implementation
143   if (VInfo.Ancestor == 0)
144     return V;
145   Compress<GraphT>(DT, V);
146   return VInfo.Label;
147 #else
148   // Lower-complexity but slower implementation
149   if (VInfo.Ancestor == 0)
150     return VInfo.Label;
151   Compress<GraphT>(DT, V);
152   GraphT::NodeType* VLabel = VInfo.Label;
153
154   GraphT::NodeType* VAncestorLabel = DT.Info[VInfo.Ancestor].Label;
155   if (DT.Info[VAncestorLabel].Semi >= DT.Info[VLabel].Semi)
156     return VLabel;
157   else
158     return VAncestorLabel;
159 #endif
160 }
161
162 template<class GraphT>
163 void Link(DominatorTreeBase& DT, typename GraphT::NodeType* V,
164           typename GraphT::NodeType* W, DominatorTreeBase::InfoRec &WInfo) {
165 #if !BALANCE_IDOM_TREE
166   // Higher-complexity but faster implementation
167   WInfo.Ancestor = V;
168 #else
169   // Lower-complexity but slower implementation
170   GraphT::NodeType* WLabel = WInfo.Label;
171   unsigned WLabelSemi = DT.Info[WLabel].Semi;
172   GraphT::NodeType* S = W;
173   InfoRec *SInfo = &DT.Info[S];
174
175   GraphT::NodeType* SChild = SInfo->Child;
176   InfoRec *SChildInfo = &DT.Info[SChild];
177
178   while (WLabelSemi < DT.Info[SChildInfo->Label].Semi) {
179     GraphT::NodeType* SChildChild = SChildInfo->Child;
180     if (SInfo->Size+DT.Info[SChildChild].Size >= 2*SChildInfo->Size) {
181       SChildInfo->Ancestor = S;
182       SInfo->Child = SChild = SChildChild;
183       SChildInfo = &DT.Info[SChild];
184     } else {
185       SChildInfo->Size = SInfo->Size;
186       S = SInfo->Ancestor = SChild;
187       SInfo = SChildInfo;
188       SChild = SChildChild;
189       SChildInfo = &DT.Info[SChild];
190     }
191   }
192
193   DominatorTreeBase::InfoRec &VInfo = DT.Info[V];
194   SInfo->Label = WLabel;
195
196   assert(V != W && "The optimization here will not work in this case!");
197   unsigned WSize = WInfo.Size;
198   unsigned VSize = (VInfo.Size += WSize);
199
200   if (VSize < 2*WSize)
201     std::swap(S, VInfo.Child);
202
203   while (S) {
204     SInfo = &DT.Info[S];
205     SInfo->Ancestor = V;
206     S = SInfo->Child;
207   }
208 #endif
209 }
210
211 template<class NodeT>
212 void Calculate(DominatorTreeBase& DT, Function& F) {
213   // Step #1: Number blocks in depth-first order and initialize variables used
214   // in later stages of the algorithm.
215   unsigned N = 0;
216   for (unsigned i = 0, e = DT.Roots.size(); i != e; ++i)
217     N = DFSPass<GraphTraits<NodeT> >(DT, DT.Roots[i], N);
218
219   for (unsigned i = N; i >= 2; --i) {
220     typename GraphTraits<NodeT>::NodeType* W = DT.Vertex[i];
221     DominatorTree::InfoRec &WInfo = DT.Info[W];
222
223     // Step #2: Calculate the semidominators of all vertices
224     for (typename GraphTraits<Inverse<NodeT> >::ChildIteratorType CI =
225          GraphTraits<Inverse<NodeT> >::child_begin(W),
226          E = GraphTraits<Inverse<NodeT> >::child_end(W); CI != E; ++CI)
227       if (DT.Info.count(*CI)) {  // Only if this predecessor is reachable!
228         unsigned SemiU = DT.Info[Eval<GraphTraits<NodeT> >(DT, *CI)].Semi;
229         if (SemiU < WInfo.Semi)
230           WInfo.Semi = SemiU;
231       }
232
233     DT.Info[DT.Vertex[WInfo.Semi]].Bucket.push_back(W);
234
235     typename GraphTraits<NodeT>::NodeType* WParent = WInfo.Parent;
236     Link<GraphTraits<NodeT> >(DT, WParent, W, WInfo);
237
238     // Step #3: Implicitly define the immediate dominator of vertices
239     std::vector<typename GraphTraits<NodeT>::NodeType*> &WParentBucket =
240                                                         DT.Info[WParent].Bucket;
241     while (!WParentBucket.empty()) {
242       typename GraphTraits<NodeT>::NodeType* V = WParentBucket.back();
243       WParentBucket.pop_back();
244       typename GraphTraits<NodeT>::NodeType* U =
245                                                Eval<GraphTraits<NodeT> >(DT, V);
246       DT.IDoms[V] = DT.Info[U].Semi < DT.Info[V].Semi ? U : WParent;
247     }
248   }
249
250   // Step #4: Explicitly define the immediate dominator of each vertex
251   for (unsigned i = 2; i <= N; ++i) {
252     typename GraphTraits<NodeT>::NodeType* W = DT.Vertex[i];
253     typename GraphTraits<NodeT>::NodeType*& WIDom = DT.IDoms[W];
254     if (WIDom != DT.Vertex[DT.Info[W].Semi])
255       WIDom = DT.IDoms[WIDom];
256   }
257   
258   if (DT.Roots.empty()) return;
259   
260   // Add a node for the root.  This node might be the actual root, if there is
261   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
262   // which postdominates all real exits if there are multiple exit blocks.
263   typename GraphTraits<NodeT>::NodeType* Root = DT.Roots.size() == 1 ? DT.Roots[0]
264                                                                      : 0;
265   DT.DomTreeNodes[Root] = DT.RootNode = new DomTreeNode(Root, 0);
266   
267   // Loop over all of the reachable blocks in the function...
268   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
269     if (typename GraphTraits<NodeT>::NodeType* ImmDom = DT.getIDom(I)) {
270       // Reachable block.
271       DomTreeNode *BBNode = DT.DomTreeNodes[I];
272       if (BBNode) continue;  // Haven't calculated this node yet?
273
274       // Get or calculate the node for the immediate dominator
275       DomTreeNode *IDomNode = DT.getNodeForBlock(ImmDom);
276
277       // Add a new tree node for this BasicBlock, and link it as a child of
278       // IDomNode
279       DomTreeNode *C = new DomTreeNode(I, IDomNode);
280       DT.DomTreeNodes[I] = IDomNode->addChild(C);
281     }
282   
283   // Free temporary memory used to construct idom's
284   DT.IDoms.clear();
285   DT.Info.clear();
286   std::vector<typename GraphTraits<NodeT>::NodeType*>().swap(DT.Vertex);
287   
288   // FIXME: This does not work on PostDomTrees.  It seems likely that this is
289   // due to an error in the algorithm for post-dominators.  This really should
290   // be investigated and fixed at some point.
291   // DT.updateDFSNumbers();
292
293   // Start out with the DFS numbers being invalid.  Let them be computed if
294   // demanded.
295   DT.DFSInfoValid = false;
296 }
297
298 }
299
300 #endif