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