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