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