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