1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
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();
34 WriteAsOperand(o, *I, false);
36 o << " <<exit node>>";
41 //===----------------------------------------------------------------------===//
42 // DominatorTree Implementation
43 //===----------------------------------------------------------------------===//
45 // DominatorTree construction - This pass constructs immediate dominator
46 // information for a flow-graph based on the algorithm described in this
49 // A Fast Algorithm for Finding Dominators in a Flowgraph
50 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
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:
58 #define BALANCE_IDOM_TREE 0
60 //===----------------------------------------------------------------------===//
62 char DominatorTree::ID = 0;
63 static RegisterPass<DominatorTree>
64 E("domtree", "Dominator Tree Construction", true);
66 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
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.
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
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) {
84 N = DFSPass(*SI, SuccVInfo, N);
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;
94 // First time we visited this BB?
96 InfoRec &BBInfo = Info[BB];
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
106 // If we are done with this block, remove it from the worklist.
107 if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
112 // Otherwise, increment the successor number for the next time we get to it.
113 ++Worklist.back().second;
115 // Visit the successor next, if it isn't already visited.
116 BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
118 InfoRec &SuccVInfo = Info[Succ];
119 if (SuccVInfo.Semi == 0) {
120 SuccVInfo.Parent = BB;
121 Worklist.push_back(std::make_pair(Succ, 0U));
128 void DominatorTree::Compress(BasicBlock *VIn) {
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];
136 if (VInVAInfo.Ancestor != 0)
139 while (!Work.empty()) {
140 BasicBlock *V = Work.back();
141 InfoRec &VInfo = Info[V];
142 BasicBlock *VAncestor = VInfo.Ancestor;
143 InfoRec &VAInfo = Info[VAncestor];
145 // Process Ancestor first
146 if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
147 Work.push_back(VAncestor);
148 Visited.insert(VAncestor);
153 // Update VINfo based on Ancestor info
154 if (VAInfo.Ancestor == 0)
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;
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)
173 // Lower-complexity but slower implementation
174 if (VInfo.Ancestor == 0)
177 BasicBlock *VLabel = VInfo.Label;
179 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
180 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
183 return VAncestorLabel;
187 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
188 #if !BALANCE_IDOM_TREE
189 // Higher-complexity but faster implementation
192 // Lower-complexity but slower implementation
193 BasicBlock *WLabel = WInfo.Label;
194 unsigned WLabelSemi = Info[WLabel].Semi;
196 InfoRec *SInfo = &Info[S];
198 BasicBlock *SChild = SInfo->Child;
199 InfoRec *SChildInfo = &Info[SChild];
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];
208 SChildInfo->Size = SInfo->Size;
209 S = SInfo->Ancestor = SChild;
211 SChild = SChildChild;
212 SChildInfo = &Info[SChild];
216 InfoRec &VInfo = Info[V];
217 SInfo->Label = WLabel;
219 assert(V != W && "The optimization here will not work in this case!");
220 unsigned WSize = WInfo.Size;
221 unsigned VSize = (VInfo.Size += WSize);
224 std::swap(S, VInfo.Child);
234 void DominatorTree::calculate(Function& F) {
235 BasicBlock* Root = Roots[0];
237 // Add a node for the root...
238 ETNode *ERoot = new ETNode(Root);
239 ETNodes[Root] = ERoot;
240 DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0, ERoot);
244 // Step #1: Number blocks in depth-first order and initialize variables used
245 // in later stages of the algorithm.
247 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
248 N = DFSPass(Roots[i], Info[Roots[i]], 0);
250 for (unsigned i = N; i >= 2; --i) {
251 BasicBlock *W = Vertex[i];
252 InfoRec &WInfo = Info[W];
254 // Step #2: Calculate the semidominators of all vertices
255 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
256 if (Info.count(*PI)) { // Only if this predecessor is reachable!
257 unsigned SemiU = Info[Eval(*PI)].Semi;
258 if (SemiU < WInfo.Semi)
262 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
264 BasicBlock *WParent = WInfo.Parent;
265 Link(WParent, W, WInfo);
267 // Step #3: Implicitly define the immediate dominator of vertices
268 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
269 while (!WParentBucket.empty()) {
270 BasicBlock *V = WParentBucket.back();
271 WParentBucket.pop_back();
272 BasicBlock *U = Eval(V);
273 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
277 // Step #4: Explicitly define the immediate dominator of each vertex
278 for (unsigned i = 2; i <= N; ++i) {
279 BasicBlock *W = Vertex[i];
280 BasicBlock *&WIDom = IDoms[W];
281 if (WIDom != Vertex[Info[W].Semi])
282 WIDom = IDoms[WIDom];
285 // Loop over all of the reachable blocks in the function...
286 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
287 if (BasicBlock *ImmDom = getIDom(I)) { // Reachable block.
288 DomTreeNode *&BBNode = DomTreeNodes[I];
289 if (!BBNode) { // Haven't calculated this node yet?
290 // Get or calculate the node for the immediate dominator
291 DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
293 // Add a new tree node for this BasicBlock, and link it as a child of
295 ETNode *ET = new ETNode(I);
297 DomTreeNode *C = new DomTreeNode(I, IDomNode, ET);
299 BBNode = IDomNode->addChild(C);
303 // Free temporary memory used to construct idom's
306 std::vector<BasicBlock*>().swap(Vertex);
311 void DominatorTreeBase::updateDFSNumbers()
314 // Iterate over all nodes in depth first order.
315 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
316 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
317 E = df_end(Roots[i]); I != E; ++I) {
319 DomTreeNode *BBNode = getNode(BB);
321 if (!BBNode->getIDom())
322 BBNode->assignDFSNumber(dfsnum);
323 //ETNode *ETN = BBNode->getETNode();
324 //if (ETN && !ETN->hasFather())
325 // ETN->assignDFSNumber(dfsnum);
332 /// isReachableFromEntry - Return true if A is dominated by the entry
333 /// block of the function containing it.
334 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
335 return dominates(&A->getParent()->getEntryBlock(), A);
338 // dominates - Return true if A dominates B. THis performs the
339 // special checks necessary if A and B are in the same basic block.
340 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
341 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
342 if (BBA != BBB) return dominates(BBA, BBB);
344 // It is not possible to determine dominance between two PHI nodes
345 // based on their ordering.
346 if (isa<PHINode>(A) && isa<PHINode>(B))
349 // Loop through the basic block until we find A or B.
350 BasicBlock::iterator I = BBA->begin();
351 for (; &*I != A && &*I != B; ++I) /*empty*/;
353 if(!IsPostDominators) {
354 // A dominates B if it is found first in the basic block.
357 // A post-dominates B if B is found first in the basic block.
362 // DominatorTreeBase::reset - Free all of the tree node memory.
364 void DominatorTreeBase::reset() {
365 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(),
366 E = DomTreeNodes.end(); I != E; ++I)
368 DomTreeNodes.clear();
375 /// findNearestCommonDominator - Find nearest common dominator basic block
376 /// for basic block A and B. If there is no such block then return NULL.
377 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A,
380 assert (!isPostDominator()
381 && "This is not implemented for post dominators");
382 assert (A->getParent() == B->getParent()
383 && "Two blocks are not in same function");
385 // If either A or B is a entry block then it is nearest common dominator.
386 BasicBlock &Entry = A->getParent()->getEntryBlock();
387 if (A == &Entry || B == &Entry)
390 // If A and B are same then A is nearest common dominator.
391 DomTreeNode *NodeA = getNode(A);
392 if (A != 0 && A == B)
395 DomTreeNode *NodeB = getNode(B);
397 // If B immediately dominates A then B is nearest common dominator.
398 if (NodeA->getIDom() == NodeB)
401 // If A immediately dominates B then A is nearest common dominator.
402 if (NodeB->getIDom() == NodeA)
405 // Collect NodeA dominators set.
406 // SmallPtrSet<DomTreeNode*, 16> NodeADoms;
407 std::set<DomTreeNode*> NodeADoms;
408 NodeADoms.insert(NodeA);
409 DomTreeNode *IDomA = NodeA->getIDom();
411 NodeADoms.insert(IDomA);
412 IDomA = IDomA->getIDom();
415 // If B dominates A then B is nearest common dominator.
416 if (NodeADoms.count(NodeB) != 0)
419 // Walk NodeB immediate dominators chain and find common dominator node.
420 DomTreeNode *IDomB = NodeB->getIDom();
422 if (NodeADoms.count(IDomB) != 0)
423 return IDomB->getBlock();
425 IDomB = IDomB->getIDom();
431 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
433 void DomTreeNode::assignDFSNumber(int num) {
434 std::vector<DomTreeNode *> workStack;
435 std::set<DomTreeNode *> visitedNodes;
437 workStack.push_back(this);
438 visitedNodes.insert(this);
439 this->DFSNumIn = num++;
441 while (!workStack.empty()) {
442 DomTreeNode *Node = workStack.back();
444 bool visitChild = false;
445 for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
446 E = Node->end(); DI != E && !visitChild; ++DI) {
447 DomTreeNode *Child = *DI;
448 if (visitedNodes.count(Child) == 0) {
450 Child->DFSNumIn = num++;
451 workStack.push_back(Child);
452 visitedNodes.insert(Child);
456 // If we reach here means all children are visited
457 Node->DFSNumOut = num++;
458 workStack.pop_back();
463 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
464 assert(IDom && "No immediate dominator?");
465 if (IDom != NewIDom) {
466 std::vector<DomTreeNode*>::iterator I =
467 std::find(IDom->Children.begin(), IDom->Children.end(), this);
468 assert(I != IDom->Children.end() &&
469 "Not in immediate dominator children set!");
470 // I am no longer your child...
471 IDom->Children.erase(I);
473 // Switch to new dominator
475 IDom->Children.push_back(this);
477 if (!ETN->hasFather())
478 ETN->setFather(IDom->getETNode());
479 else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
481 ETN->setFather(IDom->getETNode());
486 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
487 DomTreeNode *&BBNode = DomTreeNodes[BB];
488 if (BBNode) return BBNode;
490 // Haven't calculated this node yet? Get or calculate the node for the
491 // immediate dominator.
492 BasicBlock *IDom = getIDom(BB);
493 DomTreeNode *IDomNode = getNodeForBlock(IDom);
495 // Add a new tree node for this BasicBlock, and link it as a child of
497 ETNode *ET = new ETNode(BB);
499 DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
500 DomTreeNodes[BB] = C;
501 return BBNode = IDomNode->addChild(C);
504 static std::ostream &operator<<(std::ostream &o,
505 const DomTreeNode *Node) {
506 if (Node->getBlock())
507 WriteAsOperand(o, Node->getBlock(), false);
509 o << " <<exit node>>";
513 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
515 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
516 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
518 PrintDomTree(*I, o, Lev+1);
521 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
522 o << "=============================--------------------------------\n"
523 << "Inorder Dominator Tree:\n";
524 PrintDomTree(getRootNode(), o, 1);
527 void DominatorTreeBase::dump() {
531 bool DominatorTree::runOnFunction(Function &F) {
532 reset(); // Reset from the last time we were run...
533 Roots.push_back(&F.getEntryBlock());
538 //===----------------------------------------------------------------------===//
539 // DominanceFrontier Implementation
540 //===----------------------------------------------------------------------===//
542 char DominanceFrontier::ID = 0;
543 static RegisterPass<DominanceFrontier>
544 G("domfrontier", "Dominance Frontier Construction", true);
547 class DFCalculateWorkObject {
549 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
550 const DomTreeNode *N,
551 const DomTreeNode *PN)
552 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
553 BasicBlock *currentBB;
554 BasicBlock *parentBB;
555 const DomTreeNode *Node;
556 const DomTreeNode *parentNode;
560 const DominanceFrontier::DomSetType &
561 DominanceFrontier::calculate(const DominatorTree &DT,
562 const DomTreeNode *Node) {
563 BasicBlock *BB = Node->getBlock();
564 DomSetType *Result = NULL;
566 std::vector<DFCalculateWorkObject> workList;
567 SmallPtrSet<BasicBlock *, 32> visited;
569 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
571 DFCalculateWorkObject *currentW = &workList.back();
572 assert (currentW && "Missing work object.");
574 BasicBlock *currentBB = currentW->currentBB;
575 BasicBlock *parentBB = currentW->parentBB;
576 const DomTreeNode *currentNode = currentW->Node;
577 const DomTreeNode *parentNode = currentW->parentNode;
578 assert (currentBB && "Invalid work object. Missing current Basic Block");
579 assert (currentNode && "Invalid work object. Missing current Node");
580 DomSetType &S = Frontiers[currentBB];
582 // Visit each block only once.
583 if (visited.count(currentBB) == 0) {
584 visited.insert(currentBB);
586 // Loop over CFG successors to calculate DFlocal[currentNode]
587 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
589 // Does Node immediately dominate this successor?
590 if (DT[*SI]->getIDom() != currentNode)
595 // At this point, S is DFlocal. Now we union in DFup's of our children...
596 // Loop through and visit the nodes that Node immediately dominates (Node's
597 // children in the IDomTree)
598 bool visitChild = false;
599 for (DomTreeNode::const_iterator NI = currentNode->begin(),
600 NE = currentNode->end(); NI != NE; ++NI) {
601 DomTreeNode *IDominee = *NI;
602 BasicBlock *childBB = IDominee->getBlock();
603 if (visited.count(childBB) == 0) {
604 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
605 IDominee, currentNode));
610 // If all children are visited or there is any child then pop this block
611 // from the workList.
619 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
620 DomSetType &parentSet = Frontiers[parentBB];
621 for (; CDFI != CDFE; ++CDFI) {
622 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
623 parentSet.insert(*CDFI);
628 } while (!workList.empty());
633 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
634 for (const_iterator I = begin(), E = end(); I != E; ++I) {
635 o << " DomFrontier for BB";
637 WriteAsOperand(o, I->first, false);
639 o << " <<exit node>>";
640 o << " is:\t" << I->second << "\n";
644 void DominanceFrontierBase::dump() {
649 //===----------------------------------------------------------------------===//
650 // ETOccurrence Implementation
651 //===----------------------------------------------------------------------===//
653 void ETOccurrence::Splay() {
654 ETOccurrence *father;
655 ETOccurrence *grandfather;
663 fatherdepth = Parent->Depth;
664 grandfather = father->Parent;
666 // If we have no grandparent, a single zig or zag will do.
668 setDepthAdd(fatherdepth);
669 MinOccurrence = father->MinOccurrence;
672 // See what we have to rotate
673 if (father->Left == this) {
675 father->setLeft(Right);
678 father->Left->setDepthAdd(occdepth);
681 father->setRight(Left);
684 father->Right->setDepthAdd(occdepth);
686 father->setDepth(-occdepth);
689 father->recomputeMin();
693 // If we have a grandfather, we need to do some
694 // combination of zig and zag.
695 int grandfatherdepth = grandfather->Depth;
697 setDepthAdd(fatherdepth + grandfatherdepth);
698 MinOccurrence = grandfather->MinOccurrence;
699 Min = grandfather->Min;
701 ETOccurrence *greatgrandfather = grandfather->Parent;
703 if (grandfather->Left == father) {
704 if (father->Left == this) {
706 grandfather->setLeft(father->Right);
707 father->setLeft(Right);
709 father->setRight(grandfather);
711 father->setDepth(-occdepth);
714 father->Left->setDepthAdd(occdepth);
716 grandfather->setDepth(-fatherdepth);
717 if (grandfather->Left)
718 grandfather->Left->setDepthAdd(fatherdepth);
721 grandfather->setLeft(Right);
722 father->setRight(Left);
724 setRight(grandfather);
726 father->setDepth(-occdepth);
728 father->Right->setDepthAdd(occdepth);
729 grandfather->setDepth(-occdepth - fatherdepth);
730 if (grandfather->Left)
731 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
734 if (father->Left == this) {
736 grandfather->setRight(Left);
737 father->setLeft(Right);
738 setLeft(grandfather);
741 father->setDepth(-occdepth);
743 father->Left->setDepthAdd(occdepth);
744 grandfather->setDepth(-occdepth - fatherdepth);
745 if (grandfather->Right)
746 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
748 grandfather->setRight(father->Left);
749 father->setRight(Left);
751 father->setLeft(grandfather);
753 father->setDepth(-occdepth);
755 father->Right->setDepthAdd(occdepth);
756 grandfather->setDepth(-fatherdepth);
757 if (grandfather->Right)
758 grandfather->Right->setDepthAdd(fatherdepth);
762 // Might need one more rotate depending on greatgrandfather.
763 setParent(greatgrandfather);
764 if (greatgrandfather) {
765 if (greatgrandfather->Left == grandfather)
766 greatgrandfather->Left = this;
768 greatgrandfather->Right = this;
771 grandfather->recomputeMin();
772 father->recomputeMin();
776 //===----------------------------------------------------------------------===//
777 // ETNode implementation
778 //===----------------------------------------------------------------------===//
780 void ETNode::Split() {
781 ETOccurrence *right, *left;
782 ETOccurrence *rightmost = RightmostOcc;
783 ETOccurrence *parent;
785 // Update the occurrence tree first.
786 RightmostOcc->Splay();
788 // Find the leftmost occurrence in the rightmost subtree, then splay
790 for (right = rightmost->Right; right->Left; right = right->Left);
795 right->Left->Parent = NULL;
801 parent->Right->Parent = NULL;
803 right->setLeft(left);
805 right->recomputeMin();
808 rightmost->Depth = 0;
813 // Now update *our* tree
815 if (Father->Son == this)
818 if (Father->Son == this)
828 void ETNode::setFather(ETNode *NewFather) {
829 ETOccurrence *rightmost;
830 ETOccurrence *leftpart;
831 ETOccurrence *NewFatherOcc;
834 // First update the path in the splay tree
835 NewFatherOcc = new ETOccurrence(NewFather);
837 rightmost = NewFather->RightmostOcc;
840 leftpart = rightmost->Left;
845 NewFatherOcc->setLeft(leftpart);
846 NewFatherOcc->setRight(temp);
850 NewFatherOcc->recomputeMin();
852 rightmost->setLeft(NewFatherOcc);
854 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
855 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
856 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
860 ParentOcc = NewFatherOcc;
882 bool ETNode::Below(ETNode *other) {
883 ETOccurrence *up = other->RightmostOcc;
884 ETOccurrence *down = RightmostOcc;
891 ETOccurrence *left, *right;
901 right->Parent = NULL;
905 if (left == down || left->Parent != NULL) {
912 // If the two occurrences are in different trees, put things
913 // back the way they were.
914 if (right && right->Parent != NULL)
921 if (down->Depth <= 0)
924 return !down->Right || down->Right->Min + down->Depth >= 0;
927 ETNode *ETNode::NCA(ETNode *other) {
928 ETOccurrence *occ1 = RightmostOcc;
929 ETOccurrence *occ2 = other->RightmostOcc;
931 ETOccurrence *left, *right, *ret;
932 ETOccurrence *occmin;
946 right->Parent = NULL;
949 if (left == occ2 || (left && left->Parent != NULL)) {
954 right->Parent = occ1;
958 occ1->setRight(occ2);
963 if (occ2->Depth > 0) {
965 mindepth = occ1->Depth;
968 mindepth = occ2->Depth + occ1->Depth;
971 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
972 return ret->MinOccurrence->OccFor;
974 return occmin->OccFor;
977 void ETNode::assignDFSNumber(int num) {
978 std::vector<ETNode *> workStack;
979 std::set<ETNode *> visitedNodes;
981 workStack.push_back(this);
982 visitedNodes.insert(this);
983 this->DFSNumIn = num++;
985 while (!workStack.empty()) {
986 ETNode *Node = workStack.back();
988 // If this is leaf node then set DFSNumOut and pop the stack
990 Node->DFSNumOut = num++;
991 workStack.pop_back();
995 ETNode *son = Node->Son;
997 // Visit Node->Son first
998 if (visitedNodes.count(son) == 0) {
999 son->DFSNumIn = num++;
1000 workStack.push_back(son);
1001 visitedNodes.insert(son);
1005 bool visitChild = false;
1006 // Visit remaining children
1007 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
1008 if (visitedNodes.count(s) == 0) {
1010 s->DFSNumIn = num++;
1011 workStack.push_back(s);
1012 visitedNodes.insert(s);
1017 // If we reach here means all children are visited
1018 Node->DFSNumOut = num++;
1019 workStack.pop_back();
1024 //===----------------------------------------------------------------------===//
1025 // ETForest implementation
1026 //===----------------------------------------------------------------------===//
1028 char ETForest::ID = 0;
1029 static RegisterPass<ETForest>
1030 D("etforest", "ET Forest Construction", true);
1032 void ETForestBase::reset() {
1033 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1038 void ETForestBase::updateDFSNumbers()
1041 // Iterate over all nodes in depth first order.
1042 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1043 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1044 E = df_end(Roots[i]); I != E; ++I) {
1045 BasicBlock *BB = *I;
1046 ETNode *ETN = getNode(BB);
1047 if (ETN && !ETN->hasFather())
1048 ETN->assignDFSNumber(dfsnum);
1051 DFSInfoValid = true;
1054 // dominates - Return true if A dominates B. THis performs the
1055 // special checks necessary if A and B are in the same basic block.
1056 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1057 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1058 if (BBA != BBB) return dominates(BBA, BBB);
1060 // It is not possible to determine dominance between two PHI nodes
1061 // based on their ordering.
1062 if (isa<PHINode>(A) && isa<PHINode>(B))
1065 // Loop through the basic block until we find A or B.
1066 BasicBlock::iterator I = BBA->begin();
1067 for (; &*I != A && &*I != B; ++I) /*empty*/;
1069 if(!IsPostDominators) {
1070 // A dominates B if it is found first in the basic block.
1073 // A post-dominates B if B is found first in the basic block.
1078 /// isReachableFromEntry - Return true if A is dominated by the entry
1079 /// block of the function containing it.
1080 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1081 return dominates(&A->getParent()->getEntryBlock(), A);
1084 // FIXME : There is no need to make getNodeForBlock public. Fix
1085 // predicate simplifier.
1086 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1087 ETNode *&BBNode = Nodes[BB];
1088 if (BBNode) return BBNode;
1090 // Haven't calculated this node yet? Get or calculate the node for the
1091 // immediate dominator.
1092 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1094 // If we are unreachable, we may not have an immediate dominator.
1095 if (!node || !node->getIDom())
1096 return BBNode = new ETNode(BB);
1098 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1100 // Add a new tree node for this BasicBlock, and link it as a child of
1102 BBNode = new ETNode(BB);
1103 BBNode->setFather(IDomNode);
1108 void ETForest::calculate(const DominatorTree &DT) {
1109 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1110 BasicBlock *Root = Roots[0];
1111 Nodes[Root] = new ETNode(Root); // Add a node for the root
1113 Function *F = Root->getParent();
1114 // Loop over all of the reachable blocks in the function...
1115 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1116 DomTreeNode* node = DT.getNode(I);
1117 if (node && node->getIDom()) { // Reachable block.
1118 BasicBlock* ImmDom = node->getIDom()->getBlock();
1119 ETNode *&BBNode = Nodes[I];
1120 if (!BBNode) { // Haven't calculated this node yet?
1121 // Get or calculate the node for the immediate dominator
1122 ETNode *IDomNode = getNodeForBlock(ImmDom);
1124 // Add a new ETNode for this BasicBlock, and set it's parent
1125 // to it's immediate dominator.
1126 BBNode = new ETNode(I);
1127 BBNode->setFather(IDomNode);
1132 // Make sure we've got nodes around for every block
1133 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1134 ETNode *&BBNode = Nodes[I];
1136 BBNode = new ETNode(I);
1139 updateDFSNumbers ();
1142 //===----------------------------------------------------------------------===//
1143 // ETForestBase Implementation
1144 //===----------------------------------------------------------------------===//
1146 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1147 ETNode *&BBNode = Nodes[BB];
1148 assert(!BBNode && "BasicBlock already in ET-Forest");
1150 BBNode = new ETNode(BB);
1151 BBNode->setFather(getNode(IDom));
1152 DFSInfoValid = false;
1155 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1156 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1157 assert(getNode(newIDom) && "IDom not in ET-Forest");
1159 ETNode *Node = getNode(BB);
1160 if (Node->hasFather()) {
1161 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1165 Node->setFather(getNode(newIDom));
1166 DFSInfoValid= false;
1169 void ETForestBase::print(std::ostream &o, const Module *) const {
1170 o << "=============================--------------------------------\n";
1171 o << "ET Forest:\n";
1177 o << " up to date\n";
1179 Function *F = getRoots()[0]->getParent();
1180 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1181 o << " DFS Numbers For Basic Block:";
1182 WriteAsOperand(o, I, false);
1184 if (ETNode *EN = getNode(I)) {
1185 o << "In: " << EN->getDFSNumIn();
1186 o << " Out: " << EN->getDFSNumOut() << "\n";
1188 o << "No associated ETNode";
1195 void ETForestBase::dump() {