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