fc5d6a63ca935dd05505f6dae7a6bb8cd8e88d09
[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       ETNode *ETN = getNode(BB)->getETNode();
320       if (ETN && !ETN->hasFather())
321         ETN->assignDFSNumber(dfsnum);    
322   }
323   SlowQueries = 0;
324   DFSInfoValid = true;
325 }
326
327 // dominates - Return true if A dominates B. THis performs the
328 // special checks necessary if A and B are in the same basic block.
329 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
330   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
331   if (BBA != BBB) return dominates(BBA, BBB);
332   
333   // It is not possible to determine dominance between two PHI nodes 
334   // based on their ordering.
335   if (isa<PHINode>(A) && isa<PHINode>(B)) 
336     return false;
337
338   // Loop through the basic block until we find A or B.
339   BasicBlock::iterator I = BBA->begin();
340   for (; &*I != A && &*I != B; ++I) /*empty*/;
341   
342   if(!IsPostDominators) {
343     // A dominates B if it is found first in the basic block.
344     return &*I == A;
345   } else {
346     // A post-dominates B if B is found first in the basic block.
347     return &*I == B;
348   }
349 }
350
351 // DominatorTreeBase::reset - Free all of the tree node memory.
352 //
353 void DominatorTreeBase::reset() {
354   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
355     delete I->second;
356   DomTreeNodes.clear();
357   IDoms.clear();
358   Roots.clear();
359   Vertex.clear();
360   RootNode = 0;
361 }
362
363 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
364   assert(IDom && "No immediate dominator?");
365   if (IDom != NewIDom) {
366     std::vector<DomTreeNode*>::iterator I =
367       std::find(IDom->Children.begin(), IDom->Children.end(), this);
368     assert(I != IDom->Children.end() &&
369            "Not in immediate dominator children set!");
370     // I am no longer your child...
371     IDom->Children.erase(I);
372
373     // Switch to new dominator
374     IDom = NewIDom;
375     IDom->Children.push_back(this);
376
377     if (!ETN->hasFather())
378       ETN->setFather(IDom->getETNode());
379     else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
380         ETN->Split();
381         ETN->setFather(IDom->getETNode());
382     }
383   }
384 }
385
386 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
387   DomTreeNode *&BBNode = DomTreeNodes[BB];
388   if (BBNode) return BBNode;
389
390   // Haven't calculated this node yet?  Get or calculate the node for the
391   // immediate dominator.
392   BasicBlock *IDom = getIDom(BB);
393   DomTreeNode *IDomNode = getNodeForBlock(IDom);
394
395   // Add a new tree node for this BasicBlock, and link it as a child of
396   // IDomNode
397   ETNode *ET = new ETNode(BB);
398   ETNodes[BB] = ET;
399   DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
400   DomTreeNodes[BB] = C;
401   return BBNode = IDomNode->addChild(C);
402 }
403
404 static std::ostream &operator<<(std::ostream &o,
405                                 const DomTreeNode *Node) {
406   if (Node->getBlock())
407     WriteAsOperand(o, Node->getBlock(), false);
408   else
409     o << " <<exit node>>";
410   return o << "\n";
411 }
412
413 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
414                          unsigned Lev) {
415   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
416   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
417        I != E; ++I)
418     PrintDomTree(*I, o, Lev+1);
419 }
420
421 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
422   o << "=============================--------------------------------\n"
423     << "Inorder Dominator Tree:\n";
424   PrintDomTree(getRootNode(), o, 1);
425 }
426
427 void DominatorTreeBase::dump() {
428   print (llvm::cerr);
429 }
430
431 bool DominatorTree::runOnFunction(Function &F) {
432   reset();     // Reset from the last time we were run...
433   Roots.push_back(&F.getEntryBlock());
434   calculate(F);
435   return false;
436 }
437
438 //===----------------------------------------------------------------------===//
439 //  DominanceFrontier Implementation
440 //===----------------------------------------------------------------------===//
441
442 char DominanceFrontier::ID = 0;
443 static RegisterPass<DominanceFrontier>
444 G("domfrontier", "Dominance Frontier Construction", true);
445
446 namespace {
447   class DFCalculateWorkObject {
448   public:
449     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
450                           const DomTreeNode *N,
451                           const DomTreeNode *PN)
452     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
453     BasicBlock *currentBB;
454     BasicBlock *parentBB;
455     const DomTreeNode *Node;
456     const DomTreeNode *parentNode;
457   };
458 }
459
460 const DominanceFrontier::DomSetType &
461 DominanceFrontier::calculate(const DominatorTree &DT,
462                              const DomTreeNode *Node) {
463   BasicBlock *BB = Node->getBlock();
464   DomSetType *Result = NULL;
465
466   std::vector<DFCalculateWorkObject> workList;
467   SmallPtrSet<BasicBlock *, 32> visited;
468
469   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
470   do {
471     DFCalculateWorkObject *currentW = &workList.back();
472     assert (currentW && "Missing work object.");
473
474     BasicBlock *currentBB = currentW->currentBB;
475     BasicBlock *parentBB = currentW->parentBB;
476     const DomTreeNode *currentNode = currentW->Node;
477     const DomTreeNode *parentNode = currentW->parentNode;
478     assert (currentBB && "Invalid work object. Missing current Basic Block");
479     assert (currentNode && "Invalid work object. Missing current Node");
480     DomSetType &S = Frontiers[currentBB];
481
482     // Visit each block only once.
483     if (visited.count(currentBB) == 0) {
484       visited.insert(currentBB);
485
486       // Loop over CFG successors to calculate DFlocal[currentNode]
487       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
488            SI != SE; ++SI) {
489         // Does Node immediately dominate this successor?
490         if (DT[*SI]->getIDom() != currentNode)
491           S.insert(*SI);
492       }
493     }
494
495     // At this point, S is DFlocal.  Now we union in DFup's of our children...
496     // Loop through and visit the nodes that Node immediately dominates (Node's
497     // children in the IDomTree)
498     bool visitChild = false;
499     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
500            NE = currentNode->end(); NI != NE; ++NI) {
501       DomTreeNode *IDominee = *NI;
502       BasicBlock *childBB = IDominee->getBlock();
503       if (visited.count(childBB) == 0) {
504         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
505                                                  IDominee, currentNode));
506         visitChild = true;
507       }
508     }
509
510     // If all children are visited or there is any child then pop this block
511     // from the workList.
512     if (!visitChild) {
513
514       if (!parentBB) {
515         Result = &S;
516         break;
517       }
518
519       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
520       DomSetType &parentSet = Frontiers[parentBB];
521       for (; CDFI != CDFE; ++CDFI) {
522         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
523           parentSet.insert(*CDFI);
524       }
525       workList.pop_back();
526     }
527
528   } while (!workList.empty());
529
530   return *Result;
531 }
532
533 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
534   for (const_iterator I = begin(), E = end(); I != E; ++I) {
535     o << "  DomFrontier for BB";
536     if (I->first)
537       WriteAsOperand(o, I->first, false);
538     else
539       o << " <<exit node>>";
540     o << " is:\t" << I->second << "\n";
541   }
542 }
543
544 void DominanceFrontierBase::dump() {
545   print (llvm::cerr);
546 }
547
548
549 //===----------------------------------------------------------------------===//
550 // ETOccurrence Implementation
551 //===----------------------------------------------------------------------===//
552
553 void ETOccurrence::Splay() {
554   ETOccurrence *father;
555   ETOccurrence *grandfather;
556   int occdepth;
557   int fatherdepth;
558   
559   while (Parent) {
560     occdepth = Depth;
561     
562     father = Parent;
563     fatherdepth = Parent->Depth;
564     grandfather = father->Parent;
565     
566     // If we have no grandparent, a single zig or zag will do.
567     if (!grandfather) {
568       setDepthAdd(fatherdepth);
569       MinOccurrence = father->MinOccurrence;
570       Min = father->Min;
571       
572       // See what we have to rotate
573       if (father->Left == this) {
574         // Zig
575         father->setLeft(Right);
576         setRight(father);
577         if (father->Left)
578           father->Left->setDepthAdd(occdepth);
579       } else {
580         // Zag
581         father->setRight(Left);
582         setLeft(father);
583         if (father->Right)
584           father->Right->setDepthAdd(occdepth);
585       }
586       father->setDepth(-occdepth);
587       Parent = NULL;
588       
589       father->recomputeMin();
590       return;
591     }
592     
593     // If we have a grandfather, we need to do some
594     // combination of zig and zag.
595     int grandfatherdepth = grandfather->Depth;
596     
597     setDepthAdd(fatherdepth + grandfatherdepth);
598     MinOccurrence = grandfather->MinOccurrence;
599     Min = grandfather->Min;
600     
601     ETOccurrence *greatgrandfather = grandfather->Parent;
602     
603     if (grandfather->Left == father) {
604       if (father->Left == this) {
605         // Zig zig
606         grandfather->setLeft(father->Right);
607         father->setLeft(Right);
608         setRight(father);
609         father->setRight(grandfather);
610         
611         father->setDepth(-occdepth);
612         
613         if (father->Left)
614           father->Left->setDepthAdd(occdepth);
615         
616         grandfather->setDepth(-fatherdepth);
617         if (grandfather->Left)
618           grandfather->Left->setDepthAdd(fatherdepth);
619       } else {
620         // Zag zig
621         grandfather->setLeft(Right);
622         father->setRight(Left);
623         setLeft(father);
624         setRight(grandfather);
625         
626         father->setDepth(-occdepth);
627         if (father->Right)
628           father->Right->setDepthAdd(occdepth);
629         grandfather->setDepth(-occdepth - fatherdepth);
630         if (grandfather->Left)
631           grandfather->Left->setDepthAdd(occdepth + fatherdepth);
632       }
633     } else {
634       if (father->Left == this) {
635         // Zig zag
636         grandfather->setRight(Left);
637         father->setLeft(Right);
638         setLeft(grandfather);
639         setRight(father);
640         
641         father->setDepth(-occdepth);
642         if (father->Left)
643           father->Left->setDepthAdd(occdepth);
644         grandfather->setDepth(-occdepth - fatherdepth);
645         if (grandfather->Right)
646           grandfather->Right->setDepthAdd(occdepth + fatherdepth);
647       } else {              // Zag Zag
648         grandfather->setRight(father->Left);
649         father->setRight(Left);
650         setLeft(father);
651         father->setLeft(grandfather);
652         
653         father->setDepth(-occdepth);
654         if (father->Right)
655           father->Right->setDepthAdd(occdepth);
656         grandfather->setDepth(-fatherdepth);
657         if (grandfather->Right)
658           grandfather->Right->setDepthAdd(fatherdepth);
659       }
660     }
661     
662     // Might need one more rotate depending on greatgrandfather.
663     setParent(greatgrandfather);
664     if (greatgrandfather) {
665       if (greatgrandfather->Left == grandfather)
666         greatgrandfather->Left = this;
667       else
668         greatgrandfather->Right = this;
669       
670     }
671     grandfather->recomputeMin();
672     father->recomputeMin();
673   }
674 }
675
676 //===----------------------------------------------------------------------===//
677 // ETNode implementation
678 //===----------------------------------------------------------------------===//
679
680 void ETNode::Split() {
681   ETOccurrence *right, *left;
682   ETOccurrence *rightmost = RightmostOcc;
683   ETOccurrence *parent;
684
685   // Update the occurrence tree first.
686   RightmostOcc->Splay();
687
688   // Find the leftmost occurrence in the rightmost subtree, then splay
689   // around it.
690   for (right = rightmost->Right; right->Left; right = right->Left);
691
692   right->Splay();
693
694   // Start splitting
695   right->Left->Parent = NULL;
696   parent = ParentOcc;
697   parent->Splay();
698   ParentOcc = NULL;
699
700   left = parent->Left;
701   parent->Right->Parent = NULL;
702
703   right->setLeft(left);
704
705   right->recomputeMin();
706
707   rightmost->Splay();
708   rightmost->Depth = 0;
709   rightmost->Min = 0;
710
711   delete parent;
712
713   // Now update *our* tree
714
715   if (Father->Son == this)
716     Father->Son = Right;
717
718   if (Father->Son == this)
719     Father->Son = NULL;
720   else {
721     Left->Right = Right;
722     Right->Left = Left;
723   }
724   Left = Right = NULL;
725   Father = NULL;
726 }
727
728 void ETNode::setFather(ETNode *NewFather) {
729   ETOccurrence *rightmost;
730   ETOccurrence *leftpart;
731   ETOccurrence *NewFatherOcc;
732   ETOccurrence *temp;
733
734   // First update the path in the splay tree
735   NewFatherOcc = new ETOccurrence(NewFather);
736
737   rightmost = NewFather->RightmostOcc;
738   rightmost->Splay();
739
740   leftpart = rightmost->Left;
741
742   temp = RightmostOcc;
743   temp->Splay();
744
745   NewFatherOcc->setLeft(leftpart);
746   NewFatherOcc->setRight(temp);
747
748   temp->Depth++;
749   temp->Min++;
750   NewFatherOcc->recomputeMin();
751
752   rightmost->setLeft(NewFatherOcc);
753
754   if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
755     rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
756     rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
757   }
758
759   delete ParentOcc;
760   ParentOcc = NewFatherOcc;
761
762   // Update *our* tree
763   ETNode *left;
764   ETNode *right;
765
766   Father = NewFather;
767   right = Father->Son;
768
769   if (right)
770     left = right->Left;
771   else
772     left = right = this;
773
774   left->Right = this;
775   right->Left = this;
776   Left = left;
777   Right = right;
778
779   Father->Son = this;
780 }
781
782 bool ETNode::Below(ETNode *other) {
783   ETOccurrence *up = other->RightmostOcc;
784   ETOccurrence *down = RightmostOcc;
785
786   if (this == other)
787     return true;
788
789   up->Splay();
790
791   ETOccurrence *left, *right;
792   left = up->Left;
793   right = up->Right;
794
795   if (!left)
796     return false;
797
798   left->Parent = NULL;
799
800   if (right)
801     right->Parent = NULL;
802
803   down->Splay();
804
805   if (left == down || left->Parent != NULL) {
806     if (right)
807       right->Parent = up;
808     up->setLeft(down);
809   } else {
810     left->Parent = up;
811
812     // If the two occurrences are in different trees, put things
813     // back the way they were.
814     if (right && right->Parent != NULL)
815       up->setRight(down);
816     else
817       up->setRight(right);
818     return false;
819   }
820
821   if (down->Depth <= 0)
822     return false;
823
824   return !down->Right || down->Right->Min + down->Depth >= 0;
825 }
826
827 ETNode *ETNode::NCA(ETNode *other) {
828   ETOccurrence *occ1 = RightmostOcc;
829   ETOccurrence *occ2 = other->RightmostOcc;
830   
831   ETOccurrence *left, *right, *ret;
832   ETOccurrence *occmin;
833   int mindepth;
834   
835   if (this == other)
836     return this;
837   
838   occ1->Splay();
839   left = occ1->Left;
840   right = occ1->Right;
841   
842   if (left)
843     left->Parent = NULL;
844   
845   if (right)
846     right->Parent = NULL;
847   occ2->Splay();
848
849   if (left == occ2 || (left && left->Parent != NULL)) {
850     ret = occ2->Right;
851     
852     occ1->setLeft(occ2);
853     if (right)
854       right->Parent = occ1;
855   } else {
856     ret = occ2->Left;
857     
858     occ1->setRight(occ2);
859     if (left)
860       left->Parent = occ1;
861   }
862
863   if (occ2->Depth > 0) {
864     occmin = occ1;
865     mindepth = occ1->Depth;
866   } else {
867     occmin = occ2;
868     mindepth = occ2->Depth + occ1->Depth;
869   }
870   
871   if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
872     return ret->MinOccurrence->OccFor;
873   else
874     return occmin->OccFor;
875 }
876
877 void ETNode::assignDFSNumber(int num) {
878   std::vector<ETNode *>  workStack;
879   std::set<ETNode *> visitedNodes;
880   
881   workStack.push_back(this);
882   visitedNodes.insert(this);
883   this->DFSNumIn = num++;
884
885   while (!workStack.empty()) {
886     ETNode  *Node = workStack.back();
887     
888     // If this is leaf node then set DFSNumOut and pop the stack
889     if (!Node->Son) {
890       Node->DFSNumOut = num++;
891       workStack.pop_back();
892       continue;
893     }
894     
895     ETNode *son = Node->Son;
896     
897     // Visit Node->Son first
898     if (visitedNodes.count(son) == 0) {
899       son->DFSNumIn = num++;
900       workStack.push_back(son);
901       visitedNodes.insert(son);
902       continue;
903     }
904     
905     bool visitChild = false;
906     // Visit remaining children
907     for (ETNode *s = son->Right;  s != son && !visitChild; s = s->Right) {
908       if (visitedNodes.count(s) == 0) {
909         visitChild = true;
910         s->DFSNumIn = num++;
911         workStack.push_back(s);
912         visitedNodes.insert(s);
913       }
914     }
915     
916     if (!visitChild) {
917       // If we reach here means all children are visited
918       Node->DFSNumOut = num++;
919       workStack.pop_back();
920     }
921   }
922 }
923
924 //===----------------------------------------------------------------------===//
925 // ETForest implementation
926 //===----------------------------------------------------------------------===//
927
928 char ETForest::ID = 0;
929 static RegisterPass<ETForest>
930 D("etforest", "ET Forest Construction", true);
931
932 void ETForestBase::reset() {
933   for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
934     delete I->second;
935   Nodes.clear();
936 }
937
938 void ETForestBase::updateDFSNumbers()
939 {
940   int dfsnum = 0;
941   // Iterate over all nodes in depth first order.
942   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
943     for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
944            E = df_end(Roots[i]); I != E; ++I) {
945       BasicBlock *BB = *I;
946       ETNode *ETN = getNode(BB);
947       if (ETN && !ETN->hasFather())
948         ETN->assignDFSNumber(dfsnum);    
949   }
950   SlowQueries = 0;
951   DFSInfoValid = true;
952 }
953
954 // dominates - Return true if A dominates B. THis performs the
955 // special checks necessary if A and B are in the same basic block.
956 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
957   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
958   if (BBA != BBB) return dominates(BBA, BBB);
959   
960   // It is not possible to determine dominance between two PHI nodes 
961   // based on their ordering.
962   if (isa<PHINode>(A) && isa<PHINode>(B)) 
963     return false;
964
965   // Loop through the basic block until we find A or B.
966   BasicBlock::iterator I = BBA->begin();
967   for (; &*I != A && &*I != B; ++I) /*empty*/;
968   
969   if(!IsPostDominators) {
970     // A dominates B if it is found first in the basic block.
971     return &*I == A;
972   } else {
973     // A post-dominates B if B is found first in the basic block.
974     return &*I == B;
975   }
976 }
977
978 /// isReachableFromEntry - Return true if A is dominated by the entry
979 /// block of the function containing it.
980 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
981   return dominates(&A->getParent()->getEntryBlock(), A);
982 }
983
984 // FIXME : There is no need to make getNodeForBlock public. Fix
985 // predicate simplifier.
986 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
987   ETNode *&BBNode = Nodes[BB];
988   if (BBNode) return BBNode;
989
990   // Haven't calculated this node yet?  Get or calculate the node for the
991   // immediate dominator.
992   DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
993
994   // If we are unreachable, we may not have an immediate dominator.
995   if (!node || !node->getIDom())
996     return BBNode = new ETNode(BB);
997   else {
998     ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
999     
1000     // Add a new tree node for this BasicBlock, and link it as a child of
1001     // IDomNode
1002     BBNode = new ETNode(BB);
1003     BBNode->setFather(IDomNode);
1004     return BBNode;
1005   }
1006 }
1007
1008 void ETForest::calculate(const DominatorTree &DT) {
1009   assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1010   BasicBlock *Root = Roots[0];
1011   Nodes[Root] = new ETNode(Root); // Add a node for the root
1012
1013   Function *F = Root->getParent();
1014   // Loop over all of the reachable blocks in the function...
1015   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1016     DomTreeNode* node = DT.getNode(I);
1017     if (node && node->getIDom()) {  // Reachable block.
1018       BasicBlock* ImmDom = node->getIDom()->getBlock();
1019       ETNode *&BBNode = Nodes[I];
1020       if (!BBNode) {  // Haven't calculated this node yet?
1021         // Get or calculate the node for the immediate dominator
1022         ETNode *IDomNode =  getNodeForBlock(ImmDom);
1023
1024         // Add a new ETNode for this BasicBlock, and set it's parent
1025         // to it's immediate dominator.
1026         BBNode = new ETNode(I);
1027         BBNode->setFather(IDomNode);
1028       }
1029     }
1030   }
1031
1032   // Make sure we've got nodes around for every block
1033   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1034     ETNode *&BBNode = Nodes[I];
1035     if (!BBNode)
1036       BBNode = new ETNode(I);
1037   }
1038
1039   updateDFSNumbers ();
1040 }
1041
1042 //===----------------------------------------------------------------------===//
1043 // ETForestBase Implementation
1044 //===----------------------------------------------------------------------===//
1045
1046 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1047   ETNode *&BBNode = Nodes[BB];
1048   assert(!BBNode && "BasicBlock already in ET-Forest");
1049
1050   BBNode = new ETNode(BB);
1051   BBNode->setFather(getNode(IDom));
1052   DFSInfoValid = false;
1053 }
1054
1055 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1056   assert(getNode(BB) && "BasicBlock not in ET-Forest");
1057   assert(getNode(newIDom) && "IDom not in ET-Forest");
1058   
1059   ETNode *Node = getNode(BB);
1060   if (Node->hasFather()) {
1061     if (Node->getFather()->getData<BasicBlock>() == newIDom)
1062       return;
1063     Node->Split();
1064   }
1065   Node->setFather(getNode(newIDom));
1066   DFSInfoValid= false;
1067 }
1068
1069 void ETForestBase::print(std::ostream &o, const Module *) const {
1070   o << "=============================--------------------------------\n";
1071   o << "ET Forest:\n";
1072   o << "DFS Info ";
1073   if (DFSInfoValid)
1074     o << "is";
1075   else
1076     o << "is not";
1077   o << " up to date\n";
1078
1079   Function *F = getRoots()[0]->getParent();
1080   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1081     o << "  DFS Numbers For Basic Block:";
1082     WriteAsOperand(o, I, false);
1083     o << " are:";
1084     if (ETNode *EN = getNode(I)) {
1085       o << "In: " << EN->getDFSNumIn();
1086       o << " Out: " << EN->getDFSNumOut() << "\n";
1087     } else {
1088       o << "No associated ETNode";
1089     }
1090     o << "\n";
1091   }
1092   o << "\n";
1093 }
1094
1095 void ETForestBase::dump() {
1096   print (llvm::cerr);
1097 }