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