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