Be a bit more efficient when processing the active and inactive
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
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 file implements simple dominator construction algorithms for finding
11 // forward dominators.  Postdominators are available in libanalysis, but are not
12 // included in libvmcore, because it's not needed.  Forward dominators are
13 // needed to support the Verifier pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/DepthFirstIterator.h"
21 #include "Support/SetOperations.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //  ImmediateDominators Implementation
27 //===----------------------------------------------------------------------===//
28 //
29 // Immediate Dominators construction - This pass constructs immediate dominator
30 // information for a flow-graph based on the algorithm described in this
31 // document:
32 //
33 //   A Fast Algorithm for Finding Dominators in a Flowgraph
34 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
35 //
36 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
37 // LINK, but it turns out that the theoretically slower O(n*log(n))
38 // implementation is actually faster than the "efficient" algorithm (even for
39 // large CFGs) because the constant overheads are substantially smaller.  The
40 // lower-complexity version can be enabled with the following #define:
41 //
42 #define BALANCE_IDOM_TREE 0
43 //
44 //===----------------------------------------------------------------------===//
45
46 static RegisterAnalysis<ImmediateDominators>
47 C("idom", "Immediate Dominators Construction", true);
48
49 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
50                                       unsigned N) {
51   VInfo.Semi = ++N;
52   VInfo.Label = V;
53
54   Vertex.push_back(V);        // Vertex[n] = V;
55   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
56   //Child[V] = 0;             // Child[v] = 0
57   VInfo.Size = 1;             // Size[v] = 1
58
59   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
60     InfoRec &SuccVInfo = Info[*SI];
61     if (SuccVInfo.Semi == 0) {
62       SuccVInfo.Parent = V;
63       N = DFSPass(*SI, SuccVInfo, N);
64     }
65   }
66   return N;
67 }
68
69 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
70   BasicBlock *VAncestor = VInfo.Ancestor;
71   InfoRec &VAInfo = Info[VAncestor];
72   if (VAInfo.Ancestor == 0)
73     return;
74
75   Compress(VAncestor, VAInfo);
76
77   BasicBlock *VAncestorLabel = VAInfo.Label; 
78   BasicBlock *VLabel = VInfo.Label;
79   if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
80     VInfo.Label = VAncestorLabel;
81
82   VInfo.Ancestor = VAInfo.Ancestor;
83 }
84
85 BasicBlock *ImmediateDominators::Eval(BasicBlock *V) {
86   InfoRec &VInfo = Info[V];
87 #if !BALANCE_IDOM_TREE
88   // Higher-complexity but faster implementation
89   if (VInfo.Ancestor == 0)
90     return V;
91   Compress(V, VInfo);
92   return VInfo.Label;
93 #else
94   // Lower-complexity but slower implementation
95   if (VInfo.Ancestor == 0)
96     return VInfo.Label;
97   Compress(V, VInfo);
98   BasicBlock *VLabel = VInfo.Label;
99
100   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
101   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
102     return VLabel;
103   else
104     return VAncestorLabel;
105 #endif
106 }
107
108 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
109 #if !BALANCE_IDOM_TREE
110   // Higher-complexity but faster implementation
111   WInfo.Ancestor = V;
112 #else
113   // Lower-complexity but slower implementation
114   BasicBlock *WLabel = WInfo.Label;
115   unsigned WLabelSemi = Info[WLabel].Semi;
116   BasicBlock *S = W;
117   InfoRec *SInfo = &Info[S];
118   
119   BasicBlock *SChild = SInfo->Child;
120   InfoRec *SChildInfo = &Info[SChild];
121   
122   while (WLabelSemi < Info[SChildInfo->Label].Semi) {
123     BasicBlock *SChildChild = SChildInfo->Child;
124     if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
125       SChildInfo->Ancestor = S;
126       SInfo->Child = SChild = SChildChild;
127       SChildInfo = &Info[SChild];
128     } else {
129       SChildInfo->Size = SInfo->Size;
130       S = SInfo->Ancestor = SChild;
131       SInfo = SChildInfo;
132       SChild = SChildChild;
133       SChildInfo = &Info[SChild];
134     }
135   }
136   
137   InfoRec &VInfo = Info[V];
138   SInfo->Label = WLabel;
139   
140   assert(V != W && "The optimization here will not work in this case!");
141   unsigned WSize = WInfo.Size;
142   unsigned VSize = (VInfo.Size += WSize);
143   
144   if (VSize < 2*WSize)
145     std::swap(S, VInfo.Child);
146   
147   while (S) {
148     SInfo = &Info[S];
149     SInfo->Ancestor = V;
150     S = SInfo->Child;
151   }
152 #endif
153 }
154
155
156
157 bool ImmediateDominators::runOnFunction(Function &F) {
158   IDoms.clear();     // Reset from the last time we were run...
159   BasicBlock *Root = &F.getEntryBlock();
160   Roots.clear();
161   Roots.push_back(Root);
162
163   Vertex.push_back(0);
164   
165   // Step #1: Number blocks in depth-first order and initialize variables used
166   // in later stages of the algorithm.
167   unsigned N = 0;
168   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
169     N = DFSPass(Roots[i], Info[Roots[i]], 0);
170
171   for (unsigned i = N; i >= 2; --i) {
172     BasicBlock *W = Vertex[i];
173     InfoRec &WInfo = Info[W];
174
175     // Step #2: Calculate the semidominators of all vertices
176     for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
177       if (Info.count(*PI)) {  // Only if this predecessor is reachable!
178         unsigned SemiU = Info[Eval(*PI)].Semi;
179         if (SemiU < WInfo.Semi)
180           WInfo.Semi = SemiU;
181       }
182     
183     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
184
185     BasicBlock *WParent = WInfo.Parent;
186     Link(WParent, W, WInfo);
187
188     // Step #3: Implicitly define the immediate dominator of vertices
189     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
190     while (!WParentBucket.empty()) {
191       BasicBlock *V = WParentBucket.back();
192       WParentBucket.pop_back();
193       BasicBlock *U = Eval(V);
194       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
195     }
196   }
197
198   // Step #4: Explicitly define the immediate dominator of each vertex
199   for (unsigned i = 2; i <= N; ++i) {
200     BasicBlock *W = Vertex[i];
201     BasicBlock *&WIDom = IDoms[W];
202     if (WIDom != Vertex[Info[W].Semi])
203       WIDom = IDoms[WIDom];
204   }
205
206   // Free temporary memory used to construct idom's
207   Info.clear();
208   std::vector<BasicBlock*>().swap(Vertex);
209
210   return false;
211 }
212
213 void ImmediateDominatorsBase::print(std::ostream &o) const {
214   Function *F = getRoots()[0]->getParent();
215   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
216     o << "  Immediate Dominator For Basic Block:";
217     WriteAsOperand(o, I, false);
218     o << " is:";
219     if (BasicBlock *ID = get(I))
220       WriteAsOperand(o, ID, false);
221     else
222       o << " <<exit node>>";
223     o << "\n";
224   }
225   o << "\n";
226 }
227
228
229
230 //===----------------------------------------------------------------------===//
231 //  DominatorSet Implementation
232 //===----------------------------------------------------------------------===//
233
234 static RegisterAnalysis<DominatorSet>
235 B("domset", "Dominator Set Construction", true);
236
237 // dominates - Return true if A dominates B.  This performs the special checks
238 // necessary if A and B are in the same basic block.
239 //
240 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
241   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
242   if (BBA != BBB) return dominates(BBA, BBB);
243   
244   // Loop through the basic block until we find A or B.
245   BasicBlock::iterator I = BBA->begin();
246   for (; &*I != A && &*I != B; ++I) /*empty*/;
247   
248   // A dominates B if it is found first in the basic block...
249   return &*I == A;
250 }
251
252
253 // runOnFunction - This method calculates the forward dominator sets for the
254 // specified function.
255 //
256 bool DominatorSet::runOnFunction(Function &F) {
257   BasicBlock *Root = &F.getEntryBlock();
258   Roots.clear();
259   Roots.push_back(Root);
260   assert(pred_begin(Root) == pred_end(Root) &&
261          "Root node has predecessors in function!");
262
263   ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
264   Doms.clear();
265   if (Roots.empty()) return false;
266
267   // Root nodes only dominate themselves.
268   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
269     Doms[Roots[i]].insert(Roots[i]);
270
271   // Loop over all of the blocks in the function, calculating dominator sets for
272   // each function.
273   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
274     if (BasicBlock *IDom = ID[I]) {   // Get idom if block is reachable
275       DomSetType &DS = Doms[I];
276       assert(DS.empty() && "Domset already filled in for this block?");
277       DS.insert(I);  // Blocks always dominate themselves
278       
279       // Insert all dominators into the set... 
280       while (IDom) {
281         // If we have already computed the dominator sets for our immediate
282         // dominator, just use it instead of walking all the way up to the root.
283         DomSetType &IDS = Doms[IDom];
284         if (!IDS.empty()) {
285           DS.insert(IDS.begin(), IDS.end());
286           break;
287         } else {
288           DS.insert(IDom);
289           IDom = ID[IDom];
290         }
291       }
292     } else {
293       // Ensure that every basic block has at least an empty set of nodes.  This
294       // is important for the case when there is unreachable blocks.
295       Doms[I];
296     }
297
298   return false;
299 }
300
301 namespace llvm {
302 static std::ostream &operator<<(std::ostream &o,
303                                 const std::set<BasicBlock*> &BBs) {
304   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
305        I != E; ++I)
306     if (*I)
307       WriteAsOperand(o, *I, false);
308     else
309       o << " <<exit node>>";
310   return o;
311 }
312 }
313
314 void DominatorSetBase::print(std::ostream &o) const {
315   for (const_iterator I = begin(), E = end(); I != E; ++I) {
316     o << "  DomSet For BB: ";
317     if (I->first)
318       WriteAsOperand(o, I->first, false);
319     else
320       o << " <<exit node>>";
321     o << " is:\t" << I->second << "\n";
322   }
323 }
324
325 //===----------------------------------------------------------------------===//
326 //  DominatorTree Implementation
327 //===----------------------------------------------------------------------===//
328
329 static RegisterAnalysis<DominatorTree>
330 E("domtree", "Dominator Tree Construction", true);
331
332 // DominatorTreeBase::reset - Free all of the tree node memory.
333 //
334 void DominatorTreeBase::reset() { 
335   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
336     delete I->second;
337   Nodes.clear();
338   RootNode = 0;
339 }
340
341 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
342   assert(IDom && "No immediate dominator?");
343   if (IDom != NewIDom) {
344     std::vector<Node*>::iterator I =
345       std::find(IDom->Children.begin(), IDom->Children.end(), this);
346     assert(I != IDom->Children.end() &&
347            "Not in immediate dominator children set!");
348     // I am no longer your child...
349     IDom->Children.erase(I);
350
351     // Switch to new dominator
352     IDom = NewIDom;
353     IDom->Children.push_back(this);
354   }
355 }
356
357 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
358   Node *&BBNode = Nodes[BB];
359   if (BBNode) return BBNode;
360
361   // Haven't calculated this node yet?  Get or calculate the node for the
362   // immediate dominator.
363   BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
364   Node *IDomNode = getNodeForBlock(IDom);
365     
366   // Add a new tree node for this BasicBlock, and link it as a child of
367   // IDomNode
368   return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
369 }
370
371 void DominatorTree::calculate(const ImmediateDominators &ID) {
372   assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
373   BasicBlock *Root = Roots[0];
374   Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
375
376   Function *F = Root->getParent();
377   // Loop over all of the reachable blocks in the function...
378   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
379     if (BasicBlock *ImmDom = ID.get(I)) {  // Reachable block.
380       Node *&BBNode = Nodes[I];
381       if (!BBNode) {  // Haven't calculated this node yet?
382         // Get or calculate the node for the immediate dominator
383         Node *IDomNode = getNodeForBlock(ImmDom);
384
385         // Add a new tree node for this BasicBlock, and link it as a child of
386         // IDomNode
387         BBNode = IDomNode->addChild(new Node(I, IDomNode));
388       }
389     }
390 }
391
392 static std::ostream &operator<<(std::ostream &o,
393                                 const DominatorTreeBase::Node *Node) {
394   if (Node->getBlock())
395     WriteAsOperand(o, Node->getBlock(), false);
396   else
397     o << " <<exit node>>";
398   return o << "\n";
399 }
400
401 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
402                          unsigned Lev) {
403   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
404   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
405        I != E; ++I)
406     PrintDomTree(*I, o, Lev+1);
407 }
408
409 void DominatorTreeBase::print(std::ostream &o) const {
410   o << "=============================--------------------------------\n"
411     << "Inorder Dominator Tree:\n";
412   PrintDomTree(getRootNode(), o, 1);
413 }
414
415
416 //===----------------------------------------------------------------------===//
417 //  DominanceFrontier Implementation
418 //===----------------------------------------------------------------------===//
419
420 static RegisterAnalysis<DominanceFrontier>
421 G("domfrontier", "Dominance Frontier Construction", true);
422
423 const DominanceFrontier::DomSetType &
424 DominanceFrontier::calculate(const DominatorTree &DT, 
425                              const DominatorTree::Node *Node) {
426   // Loop over CFG successors to calculate DFlocal[Node]
427   BasicBlock *BB = Node->getBlock();
428   DomSetType &S = Frontiers[BB];       // The new set to fill in...
429
430   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
431        SI != SE; ++SI) {
432     // Does Node immediately dominate this successor?
433     if (DT[*SI]->getIDom() != Node)
434       S.insert(*SI);
435   }
436
437   // At this point, S is DFlocal.  Now we union in DFup's of our children...
438   // Loop through and visit the nodes that Node immediately dominates (Node's
439   // children in the IDomTree)
440   //
441   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
442        NI != NE; ++NI) {
443     DominatorTree::Node *IDominee = *NI;
444     const DomSetType &ChildDF = calculate(DT, IDominee);
445
446     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
447     for (; CDFI != CDFE; ++CDFI) {
448       if (!Node->dominates(DT[*CDFI]))
449         S.insert(*CDFI);
450     }
451   }
452
453   return S;
454 }
455
456 void DominanceFrontierBase::print(std::ostream &o) const {
457   for (const_iterator I = begin(), E = end(); I != E; ++I) {
458     o << "  DomFrontier for BB";
459     if (I->first)
460       WriteAsOperand(o, I->first, false);
461     else
462       o << " <<exit node>>";
463     o << " is:\t" << I->second << "\n";
464   }
465 }
466