5e0ab84cf9784fb94a23f88c745bbf8dd088ced6
[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 "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Support/Streams.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 namespace llvm {
29 static std::ostream &operator<<(std::ostream &o,
30                                 const std::set<BasicBlock*> &BBs) {
31   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
32        I != E; ++I)
33     if (*I)
34       WriteAsOperand(o, *I, false);
35     else
36       o << " <<exit node>>";
37   return o;
38 }
39 }
40
41 //===----------------------------------------------------------------------===//
42 //  DominatorTree Implementation
43 //===----------------------------------------------------------------------===//
44 //
45 // DominatorTree construction - This pass constructs immediate dominator
46 // information for a flow-graph based on the algorithm described in this
47 // document:
48 //
49 //   A Fast Algorithm for Finding Dominators in a Flowgraph
50 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
51 //
52 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
53 // LINK, but it turns out that the theoretically slower O(n*log(n))
54 // implementation is actually faster than the "efficient" algorithm (even for
55 // large CFGs) because the constant overheads are substantially smaller.  The
56 // lower-complexity version can be enabled with the following #define:
57 //
58 #define BALANCE_IDOM_TREE 0
59 //
60 //===----------------------------------------------------------------------===//
61
62 char DominatorTree::ID = 0;
63 static RegisterPass<DominatorTree>
64 E("domtree", "Dominator Tree Construction", true);
65
66 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
67                                       unsigned N) {
68   // This is more understandable as a recursive algorithm, but we can't use the
69   // recursive algorithm due to stack depth issues.  Keep it here for
70   // documentation purposes.
71 #if 0
72   VInfo.Semi = ++N;
73   VInfo.Label = V;
74
75   Vertex.push_back(V);        // Vertex[n] = V;
76   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
77   //Info[V].Child = 0;        // Child[v] = 0
78   VInfo.Size = 1;             // Size[v] = 1
79
80   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
81     InfoRec &SuccVInfo = Info[*SI];
82     if (SuccVInfo.Semi == 0) {
83       SuccVInfo.Parent = V;
84       N = DFSPass(*SI, SuccVInfo, N);
85     }
86   }
87 #else
88   std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
89   Worklist.push_back(std::make_pair(V, 0U));
90   while (!Worklist.empty()) {
91     BasicBlock *BB = Worklist.back().first;
92     unsigned NextSucc = Worklist.back().second;
93     
94     // First time we visited this BB?
95     if (NextSucc == 0) {
96       InfoRec &BBInfo = Info[BB];
97       BBInfo.Semi = ++N;
98       BBInfo.Label = BB;
99       
100       Vertex.push_back(BB);       // Vertex[n] = V;
101       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
102       //BBInfo[V].Child = 0;      // Child[v] = 0
103       BBInfo.Size = 1;            // Size[v] = 1
104     }
105     
106     // If we are done with this block, remove it from the worklist.
107     if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
108       Worklist.pop_back();
109       continue;
110     }
111     
112     // Otherwise, increment the successor number for the next time we get to it.
113     ++Worklist.back().second;
114     
115     // Visit the successor next, if it isn't already visited.
116     BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
117     
118     InfoRec &SuccVInfo = Info[Succ];
119     if (SuccVInfo.Semi == 0) {
120       SuccVInfo.Parent = BB;
121       Worklist.push_back(std::make_pair(Succ, 0U));
122     }
123   }
124 #endif
125   return N;
126 }
127
128 void DominatorTree::Compress(BasicBlock *VIn) {
129
130   std::vector<BasicBlock *> Work;
131   std::set<BasicBlock *> Visited;
132   InfoRec &VInInfo = Info[VIn];
133   BasicBlock *VInAncestor = VInInfo.Ancestor;
134   InfoRec &VInVAInfo = Info[VInAncestor];
135
136   if (VInVAInfo.Ancestor != 0)
137     Work.push_back(VIn);
138   
139   while (!Work.empty()) {
140     BasicBlock *V = Work.back();
141     InfoRec &VInfo = Info[V];
142     BasicBlock *VAncestor = VInfo.Ancestor;
143     InfoRec &VAInfo = Info[VAncestor];
144
145     // Process Ancestor first
146     if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
147       Work.push_back(VAncestor);
148       Visited.insert(VAncestor);
149       continue;
150     } 
151     Work.pop_back(); 
152
153     // Update VINfo based on Ancestor info
154     if (VAInfo.Ancestor == 0)
155       continue;
156     BasicBlock *VAncestorLabel = VAInfo.Label;
157     BasicBlock *VLabel = VInfo.Label;
158     if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
159       VInfo.Label = VAncestorLabel;
160     VInfo.Ancestor = VAInfo.Ancestor;
161   }
162 }
163
164 BasicBlock *DominatorTree::Eval(BasicBlock *V) {
165   InfoRec &VInfo = Info[V];
166 #if !BALANCE_IDOM_TREE
167   // Higher-complexity but faster implementation
168   if (VInfo.Ancestor == 0)
169     return V;
170   Compress(V);
171   return VInfo.Label;
172 #else
173   // Lower-complexity but slower implementation
174   if (VInfo.Ancestor == 0)
175     return VInfo.Label;
176   Compress(V);
177   BasicBlock *VLabel = VInfo.Label;
178
179   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
180   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
181     return VLabel;
182   else
183     return VAncestorLabel;
184 #endif
185 }
186
187 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
188 #if !BALANCE_IDOM_TREE
189   // Higher-complexity but faster implementation
190   WInfo.Ancestor = V;
191 #else
192   // Lower-complexity but slower implementation
193   BasicBlock *WLabel = WInfo.Label;
194   unsigned WLabelSemi = Info[WLabel].Semi;
195   BasicBlock *S = W;
196   InfoRec *SInfo = &Info[S];
197
198   BasicBlock *SChild = SInfo->Child;
199   InfoRec *SChildInfo = &Info[SChild];
200
201   while (WLabelSemi < Info[SChildInfo->Label].Semi) {
202     BasicBlock *SChildChild = SChildInfo->Child;
203     if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
204       SChildInfo->Ancestor = S;
205       SInfo->Child = SChild = SChildChild;
206       SChildInfo = &Info[SChild];
207     } else {
208       SChildInfo->Size = SInfo->Size;
209       S = SInfo->Ancestor = SChild;
210       SInfo = SChildInfo;
211       SChild = SChildChild;
212       SChildInfo = &Info[SChild];
213     }
214   }
215
216   InfoRec &VInfo = Info[V];
217   SInfo->Label = WLabel;
218
219   assert(V != W && "The optimization here will not work in this case!");
220   unsigned WSize = WInfo.Size;
221   unsigned VSize = (VInfo.Size += WSize);
222
223   if (VSize < 2*WSize)
224     std::swap(S, VInfo.Child);
225
226   while (S) {
227     SInfo = &Info[S];
228     SInfo->Ancestor = V;
229     S = SInfo->Child;
230   }
231 #endif
232 }
233
234 void DominatorTree::calculate(Function& F) {
235   BasicBlock* Root = Roots[0];
236
237   // Add a node for the root...
238   ETNode *ERoot = new ETNode(Root);
239   ETNodes[Root] = ERoot;
240   DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0, ERoot);
241
242   Vertex.push_back(0);
243
244   // Step #1: Number blocks in depth-first order and initialize variables used
245   // in later stages of the algorithm.
246   unsigned N = 0;
247   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
248     N = DFSPass(Roots[i], Info[Roots[i]], 0);
249
250   for (unsigned i = N; i >= 2; --i) {
251     BasicBlock *W = Vertex[i];
252     InfoRec &WInfo = Info[W];
253
254     // Step #2: Calculate the semidominators of all vertices
255     for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
256       if (Info.count(*PI)) {  // Only if this predecessor is reachable!
257         unsigned SemiU = Info[Eval(*PI)].Semi;
258         if (SemiU < WInfo.Semi)
259           WInfo.Semi = SemiU;
260       }
261
262     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
263
264     BasicBlock *WParent = WInfo.Parent;
265     Link(WParent, W, WInfo);
266
267     // Step #3: Implicitly define the immediate dominator of vertices
268     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
269     while (!WParentBucket.empty()) {
270       BasicBlock *V = WParentBucket.back();
271       WParentBucket.pop_back();
272       BasicBlock *U = Eval(V);
273       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
274     }
275   }
276
277   // Step #4: Explicitly define the immediate dominator of each vertex
278   for (unsigned i = 2; i <= N; ++i) {
279     BasicBlock *W = Vertex[i];
280     BasicBlock *&WIDom = IDoms[W];
281     if (WIDom != Vertex[Info[W].Semi])
282       WIDom = IDoms[WIDom];
283   }
284
285   // Loop over all of the reachable blocks in the function...
286   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
287     if (BasicBlock *ImmDom = getIDom(I)) {  // Reachable block.
288       DomTreeNode *&BBNode = DomTreeNodes[I];
289       if (!BBNode) {  // Haven't calculated this node yet?
290         // Get or calculate the node for the immediate dominator
291         DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
292
293         // Add a new tree node for this BasicBlock, and link it as a child of
294         // IDomNode
295         ETNode *ET = new ETNode(I);
296         ETNodes[I] = ET;
297         DomTreeNode *C = new DomTreeNode(I, IDomNode, ET);
298         DomTreeNodes[I] = C;
299         BBNode = IDomNode->addChild(C);
300       }
301     }
302
303   // Free temporary memory used to construct idom's
304   Info.clear();
305   IDoms.clear();
306   std::vector<BasicBlock*>().swap(Vertex);
307
308   updateDFSNumbers();
309 }
310
311 void DominatorTreeBase::updateDFSNumbers()
312 {
313   int dfsnum = 0;
314   // Iterate over all nodes in depth first order.
315   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
316     for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
317            E = df_end(Roots[i]); I != E; ++I) {
318       BasicBlock *BB = *I;
319       DomTreeNode *BBNode = getNode(BB);
320       if (BBNode) {
321         if (!BBNode->getIDom())
322           BBNode->assignDFSNumber(dfsnum);
323         //ETNode *ETN = BBNode->getETNode();
324         //if (ETN && !ETN->hasFather())
325         //  ETN->assignDFSNumber(dfsnum);
326       }
327   }
328   SlowQueries = 0;
329   DFSInfoValid = true;
330 }
331
332 /// isReachableFromEntry - Return true if A is dominated by the entry
333 /// block of the function containing it.
334 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
335   return dominates(&A->getParent()->getEntryBlock(), A);
336 }
337
338 // dominates - Return true if A dominates B. THis performs the
339 // special checks necessary if A and B are in the same basic block.
340 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
341   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
342   if (BBA != BBB) return dominates(BBA, BBB);
343   
344   // It is not possible to determine dominance between two PHI nodes 
345   // based on their ordering.
346   if (isa<PHINode>(A) && isa<PHINode>(B)) 
347     return false;
348
349   // Loop through the basic block until we find A or B.
350   BasicBlock::iterator I = BBA->begin();
351   for (; &*I != A && &*I != B; ++I) /*empty*/;
352   
353   if(!IsPostDominators) {
354     // A dominates B if it is found first in the basic block.
355     return &*I == A;
356   } else {
357     // A post-dominates B if B is found first in the basic block.
358     return &*I == B;
359   }
360 }
361
362 // DominatorTreeBase::reset - Free all of the tree node memory.
363 //
364 void DominatorTreeBase::reset() {
365   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), 
366          E = DomTreeNodes.end(); I != E; ++I)
367     delete I->second;
368   DomTreeNodes.clear();
369   IDoms.clear();
370   Roots.clear();
371   Vertex.clear();
372   RootNode = 0;
373 }
374
375 /// findNearestCommonDominator - Find nearest common dominator basic block
376 /// for basic block A and B. If there is no such block then return NULL.
377 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A, 
378                                                           BasicBlock *B) {
379
380   assert (!isPostDominator() 
381           && "This is not implemented for post dominators");
382   assert (A->getParent() == B->getParent() 
383           && "Two blocks are not in same function");
384
385   // If either A or B is a entry block then it is nearest common dominator.
386   BasicBlock &Entry  = A->getParent()->getEntryBlock();
387   if (A == &Entry || B == &Entry)
388     return &Entry;
389
390   // If A and B are same then A is nearest common dominator.
391   DomTreeNode *NodeA = getNode(A);
392   if (A != 0 && A == B)
393     return A;
394
395   DomTreeNode *NodeB = getNode(B);
396
397   // If B immediately dominates A then B is nearest common dominator.
398   if (NodeA->getIDom() == NodeB)
399     return B;
400
401   // If A immediately dominates B then A is nearest common dominator.
402   if (NodeB->getIDom() == NodeA) 
403     return A;
404
405   // Collect NodeA dominators set.
406   // SmallPtrSet<DomTreeNode*, 16> NodeADoms;
407   std::set<DomTreeNode*> NodeADoms;
408   NodeADoms.insert(NodeA);
409   DomTreeNode *IDomA = NodeA->getIDom();
410   while(IDomA) {
411     NodeADoms.insert(IDomA);
412     IDomA = IDomA->getIDom();
413   }
414
415   // If B dominates A then B is nearest common dominator.
416   if (NodeADoms.count(NodeB) != 0)
417     return B;
418
419   // Walk NodeB immediate dominators chain and find common dominator node.
420   DomTreeNode *IDomB = NodeB->getIDom();
421   while(IDomB) {
422     if (NodeADoms.count(IDomB) != 0)
423       return IDomB->getBlock();
424
425     IDomB = IDomB->getIDom();
426   }
427
428   return NULL;
429 }
430
431 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
432 /// in dfs order.
433 void DomTreeNode::assignDFSNumber(int num) {
434   std::vector<DomTreeNode *>  workStack;
435   std::set<DomTreeNode *> visitedNodes;
436   
437   workStack.push_back(this);
438   visitedNodes.insert(this);
439   this->DFSNumIn = num++;
440   
441   while (!workStack.empty()) {
442     DomTreeNode  *Node = workStack.back();
443     
444     bool visitChild = false;
445     for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
446            E = Node->end(); DI != E && !visitChild; ++DI) {
447       DomTreeNode *Child = *DI;
448       if (visitedNodes.count(Child) == 0) {
449         visitChild = true;
450         Child->DFSNumIn = num++;
451         workStack.push_back(Child);
452         visitedNodes.insert(Child);
453       }
454     }
455     if (!visitChild) {
456       // If we reach here means all children are visited
457       Node->DFSNumOut = num++;
458       workStack.pop_back();
459     }
460   }
461 }
462
463 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
464   assert(IDom && "No immediate dominator?");
465   if (IDom != NewIDom) {
466     std::vector<DomTreeNode*>::iterator I =
467       std::find(IDom->Children.begin(), IDom->Children.end(), this);
468     assert(I != IDom->Children.end() &&
469            "Not in immediate dominator children set!");
470     // I am no longer your child...
471     IDom->Children.erase(I);
472
473     // Switch to new dominator
474     IDom = NewIDom;
475     IDom->Children.push_back(this);
476
477     if (!ETN->hasFather())
478       ETN->setFather(IDom->getETNode());
479     else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
480         ETN->Split();
481         ETN->setFather(IDom->getETNode());
482     }
483   }
484 }
485
486 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
487   DomTreeNode *&BBNode = DomTreeNodes[BB];
488   if (BBNode) return BBNode;
489
490   // Haven't calculated this node yet?  Get or calculate the node for the
491   // immediate dominator.
492   BasicBlock *IDom = getIDom(BB);
493   DomTreeNode *IDomNode = getNodeForBlock(IDom);
494
495   // Add a new tree node for this BasicBlock, and link it as a child of
496   // IDomNode
497   ETNode *ET = new ETNode(BB);
498   ETNodes[BB] = ET;
499   DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
500   DomTreeNodes[BB] = C;
501   return BBNode = IDomNode->addChild(C);
502 }
503
504 static std::ostream &operator<<(std::ostream &o,
505                                 const DomTreeNode *Node) {
506   if (Node->getBlock())
507     WriteAsOperand(o, Node->getBlock(), false);
508   else
509     o << " <<exit node>>";
510   return o << "\n";
511 }
512
513 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
514                          unsigned Lev) {
515   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
516   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
517        I != E; ++I)
518     PrintDomTree(*I, o, Lev+1);
519 }
520
521 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
522   o << "=============================--------------------------------\n"
523     << "Inorder Dominator Tree:\n";
524   PrintDomTree(getRootNode(), o, 1);
525 }
526
527 void DominatorTreeBase::dump() {
528   print (llvm::cerr);
529 }
530
531 bool DominatorTree::runOnFunction(Function &F) {
532   reset();     // Reset from the last time we were run...
533   Roots.push_back(&F.getEntryBlock());
534   calculate(F);
535   return false;
536 }
537
538 //===----------------------------------------------------------------------===//
539 //  DominanceFrontier Implementation
540 //===----------------------------------------------------------------------===//
541
542 char DominanceFrontier::ID = 0;
543 static RegisterPass<DominanceFrontier>
544 G("domfrontier", "Dominance Frontier Construction", true);
545
546 namespace {
547   class DFCalculateWorkObject {
548   public:
549     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
550                           const DomTreeNode *N,
551                           const DomTreeNode *PN)
552     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
553     BasicBlock *currentBB;
554     BasicBlock *parentBB;
555     const DomTreeNode *Node;
556     const DomTreeNode *parentNode;
557   };
558 }
559
560 const DominanceFrontier::DomSetType &
561 DominanceFrontier::calculate(const DominatorTree &DT,
562                              const DomTreeNode *Node) {
563   BasicBlock *BB = Node->getBlock();
564   DomSetType *Result = NULL;
565
566   std::vector<DFCalculateWorkObject> workList;
567   SmallPtrSet<BasicBlock *, 32> visited;
568
569   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
570   do {
571     DFCalculateWorkObject *currentW = &workList.back();
572     assert (currentW && "Missing work object.");
573
574     BasicBlock *currentBB = currentW->currentBB;
575     BasicBlock *parentBB = currentW->parentBB;
576     const DomTreeNode *currentNode = currentW->Node;
577     const DomTreeNode *parentNode = currentW->parentNode;
578     assert (currentBB && "Invalid work object. Missing current Basic Block");
579     assert (currentNode && "Invalid work object. Missing current Node");
580     DomSetType &S = Frontiers[currentBB];
581
582     // Visit each block only once.
583     if (visited.count(currentBB) == 0) {
584       visited.insert(currentBB);
585
586       // Loop over CFG successors to calculate DFlocal[currentNode]
587       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
588            SI != SE; ++SI) {
589         // Does Node immediately dominate this successor?
590         if (DT[*SI]->getIDom() != currentNode)
591           S.insert(*SI);
592       }
593     }
594
595     // At this point, S is DFlocal.  Now we union in DFup's of our children...
596     // Loop through and visit the nodes that Node immediately dominates (Node's
597     // children in the IDomTree)
598     bool visitChild = false;
599     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
600            NE = currentNode->end(); NI != NE; ++NI) {
601       DomTreeNode *IDominee = *NI;
602       BasicBlock *childBB = IDominee->getBlock();
603       if (visited.count(childBB) == 0) {
604         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
605                                                  IDominee, currentNode));
606         visitChild = true;
607       }
608     }
609
610     // If all children are visited or there is any child then pop this block
611     // from the workList.
612     if (!visitChild) {
613
614       if (!parentBB) {
615         Result = &S;
616         break;
617       }
618
619       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
620       DomSetType &parentSet = Frontiers[parentBB];
621       for (; CDFI != CDFE; ++CDFI) {
622         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
623           parentSet.insert(*CDFI);
624       }
625       workList.pop_back();
626     }
627
628   } while (!workList.empty());
629
630   return *Result;
631 }
632
633 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
634   for (const_iterator I = begin(), E = end(); I != E; ++I) {
635     o << "  DomFrontier for BB";
636     if (I->first)
637       WriteAsOperand(o, I->first, false);
638     else
639       o << " <<exit node>>";
640     o << " is:\t" << I->second << "\n";
641   }
642 }
643
644 void DominanceFrontierBase::dump() {
645   print (llvm::cerr);
646 }
647
648
649 //===----------------------------------------------------------------------===//
650 // ETOccurrence Implementation
651 //===----------------------------------------------------------------------===//
652
653 void ETOccurrence::Splay() {
654   ETOccurrence *father;
655   ETOccurrence *grandfather;
656   int occdepth;
657   int fatherdepth;
658   
659   while (Parent) {
660     occdepth = Depth;
661     
662     father = Parent;
663     fatherdepth = Parent->Depth;
664     grandfather = father->Parent;
665     
666     // If we have no grandparent, a single zig or zag will do.
667     if (!grandfather) {
668       setDepthAdd(fatherdepth);
669       MinOccurrence = father->MinOccurrence;
670       Min = father->Min;
671       
672       // See what we have to rotate
673       if (father->Left == this) {
674         // Zig
675         father->setLeft(Right);
676         setRight(father);
677         if (father->Left)
678           father->Left->setDepthAdd(occdepth);
679       } else {
680         // Zag
681         father->setRight(Left);
682         setLeft(father);
683         if (father->Right)
684           father->Right->setDepthAdd(occdepth);
685       }
686       father->setDepth(-occdepth);
687       Parent = NULL;
688       
689       father->recomputeMin();
690       return;
691     }
692     
693     // If we have a grandfather, we need to do some
694     // combination of zig and zag.
695     int grandfatherdepth = grandfather->Depth;
696     
697     setDepthAdd(fatherdepth + grandfatherdepth);
698     MinOccurrence = grandfather->MinOccurrence;
699     Min = grandfather->Min;
700     
701     ETOccurrence *greatgrandfather = grandfather->Parent;
702     
703     if (grandfather->Left == father) {
704       if (father->Left == this) {
705         // Zig zig
706         grandfather->setLeft(father->Right);
707         father->setLeft(Right);
708         setRight(father);
709         father->setRight(grandfather);
710         
711         father->setDepth(-occdepth);
712         
713         if (father->Left)
714           father->Left->setDepthAdd(occdepth);
715         
716         grandfather->setDepth(-fatherdepth);
717         if (grandfather->Left)
718           grandfather->Left->setDepthAdd(fatherdepth);
719       } else {
720         // Zag zig
721         grandfather->setLeft(Right);
722         father->setRight(Left);
723         setLeft(father);
724         setRight(grandfather);
725         
726         father->setDepth(-occdepth);
727         if (father->Right)
728           father->Right->setDepthAdd(occdepth);
729         grandfather->setDepth(-occdepth - fatherdepth);
730         if (grandfather->Left)
731           grandfather->Left->setDepthAdd(occdepth + fatherdepth);
732       }
733     } else {
734       if (father->Left == this) {
735         // Zig zag
736         grandfather->setRight(Left);
737         father->setLeft(Right);
738         setLeft(grandfather);
739         setRight(father);
740         
741         father->setDepth(-occdepth);
742         if (father->Left)
743           father->Left->setDepthAdd(occdepth);
744         grandfather->setDepth(-occdepth - fatherdepth);
745         if (grandfather->Right)
746           grandfather->Right->setDepthAdd(occdepth + fatherdepth);
747       } else {              // Zag Zag
748         grandfather->setRight(father->Left);
749         father->setRight(Left);
750         setLeft(father);
751         father->setLeft(grandfather);
752         
753         father->setDepth(-occdepth);
754         if (father->Right)
755           father->Right->setDepthAdd(occdepth);
756         grandfather->setDepth(-fatherdepth);
757         if (grandfather->Right)
758           grandfather->Right->setDepthAdd(fatherdepth);
759       }
760     }
761     
762     // Might need one more rotate depending on greatgrandfather.
763     setParent(greatgrandfather);
764     if (greatgrandfather) {
765       if (greatgrandfather->Left == grandfather)
766         greatgrandfather->Left = this;
767       else
768         greatgrandfather->Right = this;
769       
770     }
771     grandfather->recomputeMin();
772     father->recomputeMin();
773   }
774 }
775
776 //===----------------------------------------------------------------------===//
777 // ETNode implementation
778 //===----------------------------------------------------------------------===//
779
780 void ETNode::Split() {
781   ETOccurrence *right, *left;
782   ETOccurrence *rightmost = RightmostOcc;
783   ETOccurrence *parent;
784
785   // Update the occurrence tree first.
786   RightmostOcc->Splay();
787
788   // Find the leftmost occurrence in the rightmost subtree, then splay
789   // around it.
790   for (right = rightmost->Right; right->Left; right = right->Left);
791
792   right->Splay();
793
794   // Start splitting
795   right->Left->Parent = NULL;
796   parent = ParentOcc;
797   parent->Splay();
798   ParentOcc = NULL;
799
800   left = parent->Left;
801   parent->Right->Parent = NULL;
802
803   right->setLeft(left);
804
805   right->recomputeMin();
806
807   rightmost->Splay();
808   rightmost->Depth = 0;
809   rightmost->Min = 0;
810
811   delete parent;
812
813   // Now update *our* tree
814
815   if (Father->Son == this)
816     Father->Son = Right;
817
818   if (Father->Son == this)
819     Father->Son = NULL;
820   else {
821     Left->Right = Right;
822     Right->Left = Left;
823   }
824   Left = Right = NULL;
825   Father = NULL;
826 }
827
828 void ETNode::setFather(ETNode *NewFather) {
829   ETOccurrence *rightmost;
830   ETOccurrence *leftpart;
831   ETOccurrence *NewFatherOcc;
832   ETOccurrence *temp;
833
834   // First update the path in the splay tree
835   NewFatherOcc = new ETOccurrence(NewFather);
836
837   rightmost = NewFather->RightmostOcc;
838   rightmost->Splay();
839
840   leftpart = rightmost->Left;
841
842   temp = RightmostOcc;
843   temp->Splay();
844
845   NewFatherOcc->setLeft(leftpart);
846   NewFatherOcc->setRight(temp);
847
848   temp->Depth++;
849   temp->Min++;
850   NewFatherOcc->recomputeMin();
851
852   rightmost->setLeft(NewFatherOcc);
853
854   if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
855     rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
856     rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
857   }
858
859   delete ParentOcc;
860   ParentOcc = NewFatherOcc;
861
862   // Update *our* tree
863   ETNode *left;
864   ETNode *right;
865
866   Father = NewFather;
867   right = Father->Son;
868
869   if (right)
870     left = right->Left;
871   else
872     left = right = this;
873
874   left->Right = this;
875   right->Left = this;
876   Left = left;
877   Right = right;
878
879   Father->Son = this;
880 }
881
882 bool ETNode::Below(ETNode *other) {
883   ETOccurrence *up = other->RightmostOcc;
884   ETOccurrence *down = RightmostOcc;
885
886   if (this == other)
887     return true;
888
889   up->Splay();
890
891   ETOccurrence *left, *right;
892   left = up->Left;
893   right = up->Right;
894
895   if (!left)
896     return false;
897
898   left->Parent = NULL;
899
900   if (right)
901     right->Parent = NULL;
902
903   down->Splay();
904
905   if (left == down || left->Parent != NULL) {
906     if (right)
907       right->Parent = up;
908     up->setLeft(down);
909   } else {
910     left->Parent = up;
911
912     // If the two occurrences are in different trees, put things
913     // back the way they were.
914     if (right && right->Parent != NULL)
915       up->setRight(down);
916     else
917       up->setRight(right);
918     return false;
919   }
920
921   if (down->Depth <= 0)
922     return false;
923
924   return !down->Right || down->Right->Min + down->Depth >= 0;
925 }
926
927 ETNode *ETNode::NCA(ETNode *other) {
928   ETOccurrence *occ1 = RightmostOcc;
929   ETOccurrence *occ2 = other->RightmostOcc;
930   
931   ETOccurrence *left, *right, *ret;
932   ETOccurrence *occmin;
933   int mindepth;
934   
935   if (this == other)
936     return this;
937   
938   occ1->Splay();
939   left = occ1->Left;
940   right = occ1->Right;
941   
942   if (left)
943     left->Parent = NULL;
944   
945   if (right)
946     right->Parent = NULL;
947   occ2->Splay();
948
949   if (left == occ2 || (left && left->Parent != NULL)) {
950     ret = occ2->Right;
951     
952     occ1->setLeft(occ2);
953     if (right)
954       right->Parent = occ1;
955   } else {
956     ret = occ2->Left;
957     
958     occ1->setRight(occ2);
959     if (left)
960       left->Parent = occ1;
961   }
962
963   if (occ2->Depth > 0) {
964     occmin = occ1;
965     mindepth = occ1->Depth;
966   } else {
967     occmin = occ2;
968     mindepth = occ2->Depth + occ1->Depth;
969   }
970   
971   if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
972     return ret->MinOccurrence->OccFor;
973   else
974     return occmin->OccFor;
975 }
976
977 void ETNode::assignDFSNumber(int num) {
978   std::vector<ETNode *>  workStack;
979   std::set<ETNode *> visitedNodes;
980   
981   workStack.push_back(this);
982   visitedNodes.insert(this);
983   this->DFSNumIn = num++;
984
985   while (!workStack.empty()) {
986     ETNode  *Node = workStack.back();
987     
988     // If this is leaf node then set DFSNumOut and pop the stack
989     if (!Node->Son) {
990       Node->DFSNumOut = num++;
991       workStack.pop_back();
992       continue;
993     }
994     
995     ETNode *son = Node->Son;
996     
997     // Visit Node->Son first
998     if (visitedNodes.count(son) == 0) {
999       son->DFSNumIn = num++;
1000       workStack.push_back(son);
1001       visitedNodes.insert(son);
1002       continue;
1003     }
1004     
1005     bool visitChild = false;
1006     // Visit remaining children
1007     for (ETNode *s = son->Right;  s != son && !visitChild; s = s->Right) {
1008       if (visitedNodes.count(s) == 0) {
1009         visitChild = true;
1010         s->DFSNumIn = num++;
1011         workStack.push_back(s);
1012         visitedNodes.insert(s);
1013       }
1014     }
1015     
1016     if (!visitChild) {
1017       // If we reach here means all children are visited
1018       Node->DFSNumOut = num++;
1019       workStack.pop_back();
1020     }
1021   }
1022 }
1023
1024 //===----------------------------------------------------------------------===//
1025 // ETForest implementation
1026 //===----------------------------------------------------------------------===//
1027
1028 char ETForest::ID = 0;
1029 static RegisterPass<ETForest>
1030 D("etforest", "ET Forest Construction", true);
1031
1032 void ETForestBase::reset() {
1033   for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1034     delete I->second;
1035   Nodes.clear();
1036 }
1037
1038 void ETForestBase::updateDFSNumbers()
1039 {
1040   int dfsnum = 0;
1041   // Iterate over all nodes in depth first order.
1042   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1043     for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1044            E = df_end(Roots[i]); I != E; ++I) {
1045       BasicBlock *BB = *I;
1046       ETNode *ETN = getNode(BB);
1047       if (ETN && !ETN->hasFather())
1048         ETN->assignDFSNumber(dfsnum);    
1049   }
1050   SlowQueries = 0;
1051   DFSInfoValid = true;
1052 }
1053
1054 // dominates - Return true if A dominates B. THis performs the
1055 // special checks necessary if A and B are in the same basic block.
1056 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1057   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1058   if (BBA != BBB) return dominates(BBA, BBB);
1059   
1060   // It is not possible to determine dominance between two PHI nodes 
1061   // based on their ordering.
1062   if (isa<PHINode>(A) && isa<PHINode>(B)) 
1063     return false;
1064
1065   // Loop through the basic block until we find A or B.
1066   BasicBlock::iterator I = BBA->begin();
1067   for (; &*I != A && &*I != B; ++I) /*empty*/;
1068   
1069   if(!IsPostDominators) {
1070     // A dominates B if it is found first in the basic block.
1071     return &*I == A;
1072   } else {
1073     // A post-dominates B if B is found first in the basic block.
1074     return &*I == B;
1075   }
1076 }
1077
1078 /// isReachableFromEntry - Return true if A is dominated by the entry
1079 /// block of the function containing it.
1080 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1081   return dominates(&A->getParent()->getEntryBlock(), A);
1082 }
1083
1084 // FIXME : There is no need to make getNodeForBlock public. Fix
1085 // predicate simplifier.
1086 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1087   ETNode *&BBNode = Nodes[BB];
1088   if (BBNode) return BBNode;
1089
1090   // Haven't calculated this node yet?  Get or calculate the node for the
1091   // immediate dominator.
1092   DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1093
1094   // If we are unreachable, we may not have an immediate dominator.
1095   if (!node || !node->getIDom())
1096     return BBNode = new ETNode(BB);
1097   else {
1098     ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1099     
1100     // Add a new tree node for this BasicBlock, and link it as a child of
1101     // IDomNode
1102     BBNode = new ETNode(BB);
1103     BBNode->setFather(IDomNode);
1104     return BBNode;
1105   }
1106 }
1107
1108 void ETForest::calculate(const DominatorTree &DT) {
1109   assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1110   BasicBlock *Root = Roots[0];
1111   Nodes[Root] = new ETNode(Root); // Add a node for the root
1112
1113   Function *F = Root->getParent();
1114   // Loop over all of the reachable blocks in the function...
1115   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1116     DomTreeNode* node = DT.getNode(I);
1117     if (node && node->getIDom()) {  // Reachable block.
1118       BasicBlock* ImmDom = node->getIDom()->getBlock();
1119       ETNode *&BBNode = Nodes[I];
1120       if (!BBNode) {  // Haven't calculated this node yet?
1121         // Get or calculate the node for the immediate dominator
1122         ETNode *IDomNode =  getNodeForBlock(ImmDom);
1123
1124         // Add a new ETNode for this BasicBlock, and set it's parent
1125         // to it's immediate dominator.
1126         BBNode = new ETNode(I);
1127         BBNode->setFather(IDomNode);
1128       }
1129     }
1130   }
1131
1132   // Make sure we've got nodes around for every block
1133   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1134     ETNode *&BBNode = Nodes[I];
1135     if (!BBNode)
1136       BBNode = new ETNode(I);
1137   }
1138
1139   updateDFSNumbers ();
1140 }
1141
1142 //===----------------------------------------------------------------------===//
1143 // ETForestBase Implementation
1144 //===----------------------------------------------------------------------===//
1145
1146 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1147   ETNode *&BBNode = Nodes[BB];
1148   assert(!BBNode && "BasicBlock already in ET-Forest");
1149
1150   BBNode = new ETNode(BB);
1151   BBNode->setFather(getNode(IDom));
1152   DFSInfoValid = false;
1153 }
1154
1155 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1156   assert(getNode(BB) && "BasicBlock not in ET-Forest");
1157   assert(getNode(newIDom) && "IDom not in ET-Forest");
1158   
1159   ETNode *Node = getNode(BB);
1160   if (Node->hasFather()) {
1161     if (Node->getFather()->getData<BasicBlock>() == newIDom)
1162       return;
1163     Node->Split();
1164   }
1165   Node->setFather(getNode(newIDom));
1166   DFSInfoValid= false;
1167 }
1168
1169 void ETForestBase::print(std::ostream &o, const Module *) const {
1170   o << "=============================--------------------------------\n";
1171   o << "ET Forest:\n";
1172   o << "DFS Info ";
1173   if (DFSInfoValid)
1174     o << "is";
1175   else
1176     o << "is not";
1177   o << " up to date\n";
1178
1179   Function *F = getRoots()[0]->getParent();
1180   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1181     o << "  DFS Numbers For Basic Block:";
1182     WriteAsOperand(o, I, false);
1183     o << " are:";
1184     if (ETNode *EN = getNode(I)) {
1185       o << "In: " << EN->getDFSNumIn();
1186       o << " Out: " << EN->getDFSNumOut() << "\n";
1187     } else {
1188       o << "No associated ETNode";
1189     }
1190     o << "\n";
1191   }
1192   o << "\n";
1193 }
1194
1195 void ETForestBase::dump() {
1196   print (llvm::cerr);
1197 }