Move splitBlock into DomTreeBase from DomTree.
[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<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.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       typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
71                                                                     DT.Info[BB];
72       BBInfo.Semi = ++N;
73       BBInfo.Label = BB;
74
75       DT.Vertex.push_back(BB);       // Vertex[n] = V;
76       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
77       //BBInfo[V].Child = 0;      // Child[v] = 0
78       BBInfo.Size = 1;            // Size[v] = 1
79     }
80     
81     // If we are done with this block, remove it from the worklist.
82     if (NextSucc == GraphT::child_end(BB)) {
83       Worklist.pop_back();
84       continue;
85     }
86
87     // Increment the successor number for the next time we get to it.
88     ++Worklist.back().second;
89     
90     // Visit the successor next, if it isn't already visited.
91     typename GraphT::NodeType* Succ = *NextSucc;
92
93     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &SuccVInfo =
94                                                                   DT.Info[Succ];
95     if (SuccVInfo.Semi == 0) {
96       SuccVInfo.Parent = BB;
97       Worklist.push_back(std::make_pair(Succ, GraphT::child_begin(Succ)));
98     }
99   }
100 #endif
101     return N;
102 }
103
104 template<class GraphT>
105 void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
106               typename GraphT::NodeType *VIn) {
107   std::vector<typename GraphT::NodeType*> Work;
108   SmallPtrSet<typename GraphT::NodeType*, 32> Visited;
109   typename GraphT::NodeType* VInAncestor = DT.Info[VIn].Ancestor;
110   typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInVAInfo =
111                                                            DT.Info[VInAncestor];
112
113   if (VInVAInfo.Ancestor != 0)
114     Work.push_back(VIn);
115   
116   while (!Work.empty()) {
117     typename GraphT::NodeType* V = Work.back();
118     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
119                                                                      DT.Info[V];
120     typename GraphT::NodeType* VAncestor = VInfo.Ancestor;
121     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VAInfo =
122                                                              DT.Info[VAncestor];
123
124     // Process Ancestor first
125     if (Visited.insert(VAncestor) &&
126         VAInfo.Ancestor != 0) {
127       Work.push_back(VAncestor);
128       continue;
129     } 
130     Work.pop_back(); 
131
132     // Update VInfo based on Ancestor info
133     if (VAInfo.Ancestor == 0)
134       continue;
135     typename GraphT::NodeType* VAncestorLabel = VAInfo.Label;
136     typename GraphT::NodeType* VLabel = VInfo.Label;
137     if (DT.Info[VAncestorLabel].Semi < DT.Info[VLabel].Semi)
138       VInfo.Label = VAncestorLabel;
139     VInfo.Ancestor = VAInfo.Ancestor;
140   }
141 }
142
143 template<class GraphT>
144 typename GraphT::NodeType* Eval(DominatorTreeBase<typename GraphT::NodeType>& DT,
145                                 typename GraphT::NodeType *V) {
146   typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
147                                                                      DT.Info[V];
148 #if !BALANCE_IDOM_TREE
149   // Higher-complexity but faster implementation
150   if (VInfo.Ancestor == 0)
151     return V;
152   Compress<GraphT>(DT, V);
153   return VInfo.Label;
154 #else
155   // Lower-complexity but slower implementation
156   if (VInfo.Ancestor == 0)
157     return VInfo.Label;
158   Compress<GraphT>(DT, V);
159   GraphT::NodeType* VLabel = VInfo.Label;
160
161   GraphT::NodeType* VAncestorLabel = DT.Info[VInfo.Ancestor].Label;
162   if (DT.Info[VAncestorLabel].Semi >= DT.Info[VLabel].Semi)
163     return VLabel;
164   else
165     return VAncestorLabel;
166 #endif
167 }
168
169 template<class GraphT>
170 void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
171           typename GraphT::NodeType* V, typename GraphT::NodeType* W,
172         typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo) {
173 #if !BALANCE_IDOM_TREE
174   // Higher-complexity but faster implementation
175   WInfo.Ancestor = V;
176 #else
177   // Lower-complexity but slower implementation
178   GraphT::NodeType* WLabel = WInfo.Label;
179   unsigned WLabelSemi = DT.Info[WLabel].Semi;
180   GraphT::NodeType* S = W;
181   InfoRec *SInfo = &DT.Info[S];
182
183   GraphT::NodeType* SChild = SInfo->Child;
184   InfoRec *SChildInfo = &DT.Info[SChild];
185
186   while (WLabelSemi < DT.Info[SChildInfo->Label].Semi) {
187     GraphT::NodeType* SChildChild = SChildInfo->Child;
188     if (SInfo->Size+DT.Info[SChildChild].Size >= 2*SChildInfo->Size) {
189       SChildInfo->Ancestor = S;
190       SInfo->Child = SChild = SChildChild;
191       SChildInfo = &DT.Info[SChild];
192     } else {
193       SChildInfo->Size = SInfo->Size;
194       S = SInfo->Ancestor = SChild;
195       SInfo = SChildInfo;
196       SChild = SChildChild;
197       SChildInfo = &DT.Info[SChild];
198     }
199   }
200
201   DominatorTreeBase::InfoRec &VInfo = DT.Info[V];
202   SInfo->Label = WLabel;
203
204   assert(V != W && "The optimization here will not work in this case!");
205   unsigned WSize = WInfo.Size;
206   unsigned VSize = (VInfo.Size += WSize);
207
208   if (VSize < 2*WSize)
209     std::swap(S, VInfo.Child);
210
211   while (S) {
212     SInfo = &DT.Info[S];
213     SInfo->Ancestor = V;
214     S = SInfo->Child;
215   }
216 #endif
217 }
218
219 template<class NodeT, class GraphT>
220 void Calculate(DominatorTreeBase<typename GraphT::NodeType>& DT, Function& F) {
221   // Step #1: Number blocks in depth-first order and initialize variables used
222   // in later stages of the algorithm.
223   unsigned N = 0;
224   for (unsigned i = 0, e = DT.Roots.size(); i != e; ++i)
225     N = DFSPass<GraphT>(DT, DT.Roots[i], N);
226
227   for (unsigned i = N; i >= 2; --i) {
228     typename GraphT::NodeType* W = DT.Vertex[i];
229     typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo =
230                                                                      DT.Info[W];
231
232     // Step #2: Calculate the semidominators of all vertices
233     for (typename GraphTraits<Inverse<NodeT> >::ChildIteratorType CI =
234          GraphTraits<Inverse<NodeT> >::child_begin(W),
235          E = GraphTraits<Inverse<NodeT> >::child_end(W); CI != E; ++CI)
236       if (DT.Info.count(*CI)) {  // Only if this predecessor is reachable!
237         unsigned SemiU = DT.Info[Eval<GraphT>(DT, *CI)].Semi;
238         if (SemiU < WInfo.Semi)
239           WInfo.Semi = SemiU;
240       }
241
242     DT.Info[DT.Vertex[WInfo.Semi]].Bucket.push_back(W);
243
244     typename GraphT::NodeType* WParent = WInfo.Parent;
245     Link<GraphT>(DT, WParent, W, WInfo);
246
247     // Step #3: Implicitly define the immediate dominator of vertices
248     std::vector<typename GraphT::NodeType*> &WParentBucket =
249                                                         DT.Info[WParent].Bucket;
250     while (!WParentBucket.empty()) {
251       typename GraphT::NodeType* V = WParentBucket.back();
252       WParentBucket.pop_back();
253       typename GraphT::NodeType* U = Eval<GraphT>(DT, V);
254       DT.IDoms[V] = DT.Info[U].Semi < DT.Info[V].Semi ? U : WParent;
255     }
256   }
257
258   // Step #4: Explicitly define the immediate dominator of each vertex
259   for (unsigned i = 2; i <= N; ++i) {
260     typename GraphT::NodeType* W = DT.Vertex[i];
261     typename GraphT::NodeType*& WIDom = DT.IDoms[W];
262     if (WIDom != DT.Vertex[DT.Info[W].Semi])
263       WIDom = DT.IDoms[WIDom];
264   }
265   
266   if (DT.Roots.empty()) return;
267   
268   // Add a node for the root.  This node might be the actual root, if there is
269   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
270   // which postdominates all real exits if there are multiple exit blocks.
271   typename GraphT::NodeType* Root = DT.Roots.size() == 1 ? DT.Roots[0]
272                                                          : 0;
273   DT.DomTreeNodes[Root] = DT.RootNode = new DomTreeNode(Root, 0);
274   
275   // Loop over all of the reachable blocks in the function...
276   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
277     if (typename GraphT::NodeType* ImmDom = DT.getIDom(I)) {
278       // Reachable block.
279       DomTreeNode *BBNode = DT.DomTreeNodes[I];
280       if (BBNode) continue;  // Haven't calculated this node yet?
281
282       // Get or calculate the node for the immediate dominator
283       DomTreeNode *IDomNode = DT.getNodeForBlock(ImmDom);
284
285       // Add a new tree node for this BasicBlock, and link it as a child of
286       // IDomNode
287       DomTreeNode *C = new DomTreeNode(I, IDomNode);
288       DT.DomTreeNodes[I] = IDomNode->addChild(C);
289     }
290   
291   // Free temporary memory used to construct idom's
292   DT.IDoms.clear();
293   DT.Info.clear();
294   std::vector<typename GraphT::NodeType*>().swap(DT.Vertex);
295   
296   // FIXME: This does not work on PostDomTrees.  It seems likely that this is
297   // due to an error in the algorithm for post-dominators.  This really should
298   // be investigated and fixed at some point.
299   // DT.updateDFSNumbers();
300
301   // Start out with the DFS numbers being invalid.  Let them be computed if
302   // demanded.
303   DT.DFSInfoValid = false;
304 }
305
306 // NewBB is split and now it has one successor. Update dominator tree to
307 // reflect this change.
308 template<class NodeT, class GraphT>
309 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
310            typename GraphT::NodeType* NewBB) {
311   assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
312          && "NewBB should have a single successor!");
313   typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
314
315   std::vector<typename GraphT::NodeType*> PredBlocks;
316   for (typename GraphTraits<Inverse<NodeT> >::ChildIteratorType PI =
317        GraphTraits<Inverse<NodeT> >::child_begin(NewBB),
318        PE = GraphTraits<Inverse<NodeT> >::child_end(NewBB); PI != PE; ++PI)
319     PredBlocks.push_back(*PI);  
320
321     assert(!PredBlocks.empty() && "No predblocks??");
322
323     // The newly inserted basic block will dominate existing basic blocks iff the
324     // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
325     // the non-pred blocks, then they all must be the same block!
326     //
327     bool NewBBDominatesNewBBSucc = true;
328     {
329       typename GraphT::NodeType* OnePred = PredBlocks[0];
330       unsigned i = 1, e = PredBlocks.size();
331       for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
332         assert(i != e && "Didn't find reachable pred?");
333         OnePred = PredBlocks[i];
334       }
335   
336       for (; i != e; ++i)
337         if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
338           NewBBDominatesNewBBSucc = false;
339           break;
340         }
341
342     if (NewBBDominatesNewBBSucc)
343       for (typename GraphTraits<Inverse<NodeT> >::ChildIteratorType PI =
344            GraphTraits<Inverse<NodeT> >::child_begin(NewBBSucc),
345            E = GraphTraits<Inverse<NodeT> >::child_end(NewBBSucc); PI != E; ++PI)
346         if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
347           NewBBDominatesNewBBSucc = false;
348           break;
349         }
350   }
351
352   // The other scenario where the new block can dominate its successors are when
353   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
354   // already.
355   if (!NewBBDominatesNewBBSucc) {
356     NewBBDominatesNewBBSucc = true;
357     for (typename GraphTraits<Inverse<NodeT> >::ChildIteratorType PI = 
358          GraphTraits<Inverse<NodeT> >::child_begin(NewBBSucc),
359          E = GraphTraits<Inverse<NodeT> >::child_end(NewBBSucc); PI != E; ++PI)
360        if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
361         NewBBDominatesNewBBSucc = false;
362         break;
363       }
364   }
365
366   // Find NewBB's immediate dominator and create new dominator tree node for
367   // NewBB.
368   BasicBlock *NewBBIDom = 0;
369   unsigned i = 0;
370   for (i = 0; i < PredBlocks.size(); ++i)
371     if (DT.isReachableFromEntry(PredBlocks[i])) {
372       NewBBIDom = PredBlocks[i];
373       break;
374     }
375   assert(i != PredBlocks.size() && "No reachable preds?");
376   for (i = i + 1; i < PredBlocks.size(); ++i) {
377     if (DT.isReachableFromEntry(PredBlocks[i]))
378       NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
379   }
380   assert(NewBBIDom && "No immediate dominator found??");
381
382   // Create the new dominator tree node... and set the idom of NewBB.
383   DomTreeNode *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
384
385   // If NewBB strictly dominates other blocks, then it is now the immediate
386   // dominator of NewBBSucc.  Update the dominator tree as appropriate.
387   if (NewBBDominatesNewBBSucc) {
388     DomTreeNode *NewBBSuccNode = DT.getNode(NewBBSucc);
389     DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
390   }
391 }
392
393 }
394
395 #endif