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 NodeADoms.insert(NodeA);
408 DomTreeNode *IDomA = NodeA->getIDom();
410 NodeADoms.insert(IDomA);
411 IDomA = IDomA->getIDom();
414 // If B dominates A then B is nearest common dominator.
415 if (NodeADoms.count(NodeB) != 0)
418 // Walk NodeB immediate dominators chain and find common dominator node.
419 DomTreeNode *IDomB = NodeB->getIDom();
421 if (NodeADoms.count(IDomB) != 0)
422 return IDomB->getBlock();
424 IDomB = IDomB->getIDom();
430 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
432 void DomTreeNode::assignDFSNumber(int num) {
433 std::vector<DomTreeNode *> workStack;
434 std::set<DomTreeNode *> visitedNodes;
436 workStack.push_back(this);
437 visitedNodes.insert(this);
438 this->DFSNumIn = num++;
440 while (!workStack.empty()) {
441 DomTreeNode *Node = workStack.back();
443 bool visitChild = false;
444 for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
445 E = Node->end(); DI != E && !visitChild; ++DI) {
446 DomTreeNode *Child = *DI;
447 if (visitedNodes.count(Child) == 0) {
449 Child->DFSNumIn = num++;
450 workStack.push_back(Child);
451 visitedNodes.insert(Child);
455 // If we reach here means all children are visited
456 Node->DFSNumOut = num++;
457 workStack.pop_back();
462 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
463 assert(IDom && "No immediate dominator?");
464 if (IDom != NewIDom) {
465 std::vector<DomTreeNode*>::iterator I =
466 std::find(IDom->Children.begin(), IDom->Children.end(), this);
467 assert(I != IDom->Children.end() &&
468 "Not in immediate dominator children set!");
469 // I am no longer your child...
470 IDom->Children.erase(I);
472 // Switch to new dominator
474 IDom->Children.push_back(this);
476 if (!ETN->hasFather())
477 ETN->setFather(IDom->getETNode());
478 else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
480 ETN->setFather(IDom->getETNode());
485 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
486 DomTreeNode *&BBNode = DomTreeNodes[BB];
487 if (BBNode) return BBNode;
489 // Haven't calculated this node yet? Get or calculate the node for the
490 // immediate dominator.
491 BasicBlock *IDom = getIDom(BB);
492 DomTreeNode *IDomNode = getNodeForBlock(IDom);
494 // Add a new tree node for this BasicBlock, and link it as a child of
496 ETNode *ET = new ETNode(BB);
498 DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
499 DomTreeNodes[BB] = C;
500 return BBNode = IDomNode->addChild(C);
503 static std::ostream &operator<<(std::ostream &o,
504 const DomTreeNode *Node) {
505 if (Node->getBlock())
506 WriteAsOperand(o, Node->getBlock(), false);
508 o << " <<exit node>>";
512 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
514 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
515 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
517 PrintDomTree(*I, o, Lev+1);
520 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
521 o << "=============================--------------------------------\n"
522 << "Inorder Dominator Tree:\n";
523 PrintDomTree(getRootNode(), o, 1);
526 void DominatorTreeBase::dump() {
530 bool DominatorTree::runOnFunction(Function &F) {
531 reset(); // Reset from the last time we were run...
532 Roots.push_back(&F.getEntryBlock());
537 //===----------------------------------------------------------------------===//
538 // DominanceFrontier Implementation
539 //===----------------------------------------------------------------------===//
541 char DominanceFrontier::ID = 0;
542 static RegisterPass<DominanceFrontier>
543 G("domfrontier", "Dominance Frontier Construction", true);
546 class DFCalculateWorkObject {
548 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
549 const DomTreeNode *N,
550 const DomTreeNode *PN)
551 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
552 BasicBlock *currentBB;
553 BasicBlock *parentBB;
554 const DomTreeNode *Node;
555 const DomTreeNode *parentNode;
559 const DominanceFrontier::DomSetType &
560 DominanceFrontier::calculate(const DominatorTree &DT,
561 const DomTreeNode *Node) {
562 BasicBlock *BB = Node->getBlock();
563 DomSetType *Result = NULL;
565 std::vector<DFCalculateWorkObject> workList;
566 SmallPtrSet<BasicBlock *, 32> visited;
568 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
570 DFCalculateWorkObject *currentW = &workList.back();
571 assert (currentW && "Missing work object.");
573 BasicBlock *currentBB = currentW->currentBB;
574 BasicBlock *parentBB = currentW->parentBB;
575 const DomTreeNode *currentNode = currentW->Node;
576 const DomTreeNode *parentNode = currentW->parentNode;
577 assert (currentBB && "Invalid work object. Missing current Basic Block");
578 assert (currentNode && "Invalid work object. Missing current Node");
579 DomSetType &S = Frontiers[currentBB];
581 // Visit each block only once.
582 if (visited.count(currentBB) == 0) {
583 visited.insert(currentBB);
585 // Loop over CFG successors to calculate DFlocal[currentNode]
586 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
588 // Does Node immediately dominate this successor?
589 if (DT[*SI]->getIDom() != currentNode)
594 // At this point, S is DFlocal. Now we union in DFup's of our children...
595 // Loop through and visit the nodes that Node immediately dominates (Node's
596 // children in the IDomTree)
597 bool visitChild = false;
598 for (DomTreeNode::const_iterator NI = currentNode->begin(),
599 NE = currentNode->end(); NI != NE; ++NI) {
600 DomTreeNode *IDominee = *NI;
601 BasicBlock *childBB = IDominee->getBlock();
602 if (visited.count(childBB) == 0) {
603 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
604 IDominee, currentNode));
609 // If all children are visited or there is any child then pop this block
610 // from the workList.
618 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
619 DomSetType &parentSet = Frontiers[parentBB];
620 for (; CDFI != CDFE; ++CDFI) {
621 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
622 parentSet.insert(*CDFI);
627 } while (!workList.empty());
632 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
633 for (const_iterator I = begin(), E = end(); I != E; ++I) {
634 o << " DomFrontier for BB";
636 WriteAsOperand(o, I->first, false);
638 o << " <<exit node>>";
639 o << " is:\t" << I->second << "\n";
643 void DominanceFrontierBase::dump() {
648 //===----------------------------------------------------------------------===//
649 // ETOccurrence Implementation
650 //===----------------------------------------------------------------------===//
652 void ETOccurrence::Splay() {
653 ETOccurrence *father;
654 ETOccurrence *grandfather;
662 fatherdepth = Parent->Depth;
663 grandfather = father->Parent;
665 // If we have no grandparent, a single zig or zag will do.
667 setDepthAdd(fatherdepth);
668 MinOccurrence = father->MinOccurrence;
671 // See what we have to rotate
672 if (father->Left == this) {
674 father->setLeft(Right);
677 father->Left->setDepthAdd(occdepth);
680 father->setRight(Left);
683 father->Right->setDepthAdd(occdepth);
685 father->setDepth(-occdepth);
688 father->recomputeMin();
692 // If we have a grandfather, we need to do some
693 // combination of zig and zag.
694 int grandfatherdepth = grandfather->Depth;
696 setDepthAdd(fatherdepth + grandfatherdepth);
697 MinOccurrence = grandfather->MinOccurrence;
698 Min = grandfather->Min;
700 ETOccurrence *greatgrandfather = grandfather->Parent;
702 if (grandfather->Left == father) {
703 if (father->Left == this) {
705 grandfather->setLeft(father->Right);
706 father->setLeft(Right);
708 father->setRight(grandfather);
710 father->setDepth(-occdepth);
713 father->Left->setDepthAdd(occdepth);
715 grandfather->setDepth(-fatherdepth);
716 if (grandfather->Left)
717 grandfather->Left->setDepthAdd(fatherdepth);
720 grandfather->setLeft(Right);
721 father->setRight(Left);
723 setRight(grandfather);
725 father->setDepth(-occdepth);
727 father->Right->setDepthAdd(occdepth);
728 grandfather->setDepth(-occdepth - fatherdepth);
729 if (grandfather->Left)
730 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
733 if (father->Left == this) {
735 grandfather->setRight(Left);
736 father->setLeft(Right);
737 setLeft(grandfather);
740 father->setDepth(-occdepth);
742 father->Left->setDepthAdd(occdepth);
743 grandfather->setDepth(-occdepth - fatherdepth);
744 if (grandfather->Right)
745 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
747 grandfather->setRight(father->Left);
748 father->setRight(Left);
750 father->setLeft(grandfather);
752 father->setDepth(-occdepth);
754 father->Right->setDepthAdd(occdepth);
755 grandfather->setDepth(-fatherdepth);
756 if (grandfather->Right)
757 grandfather->Right->setDepthAdd(fatherdepth);
761 // Might need one more rotate depending on greatgrandfather.
762 setParent(greatgrandfather);
763 if (greatgrandfather) {
764 if (greatgrandfather->Left == grandfather)
765 greatgrandfather->Left = this;
767 greatgrandfather->Right = this;
770 grandfather->recomputeMin();
771 father->recomputeMin();
775 //===----------------------------------------------------------------------===//
776 // ETNode implementation
777 //===----------------------------------------------------------------------===//
779 void ETNode::Split() {
780 ETOccurrence *right, *left;
781 ETOccurrence *rightmost = RightmostOcc;
782 ETOccurrence *parent;
784 // Update the occurrence tree first.
785 RightmostOcc->Splay();
787 // Find the leftmost occurrence in the rightmost subtree, then splay
789 for (right = rightmost->Right; right->Left; right = right->Left);
794 right->Left->Parent = NULL;
800 parent->Right->Parent = NULL;
802 right->setLeft(left);
804 right->recomputeMin();
807 rightmost->Depth = 0;
812 // Now update *our* tree
814 if (Father->Son == this)
817 if (Father->Son == this)
827 void ETNode::setFather(ETNode *NewFather) {
828 ETOccurrence *rightmost;
829 ETOccurrence *leftpart;
830 ETOccurrence *NewFatherOcc;
833 // First update the path in the splay tree
834 NewFatherOcc = new ETOccurrence(NewFather);
836 rightmost = NewFather->RightmostOcc;
839 leftpart = rightmost->Left;
844 NewFatherOcc->setLeft(leftpart);
845 NewFatherOcc->setRight(temp);
849 NewFatherOcc->recomputeMin();
851 rightmost->setLeft(NewFatherOcc);
853 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
854 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
855 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
859 ParentOcc = NewFatherOcc;
881 bool ETNode::Below(ETNode *other) {
882 ETOccurrence *up = other->RightmostOcc;
883 ETOccurrence *down = RightmostOcc;
890 ETOccurrence *left, *right;
900 right->Parent = NULL;
904 if (left == down || left->Parent != NULL) {
911 // If the two occurrences are in different trees, put things
912 // back the way they were.
913 if (right && right->Parent != NULL)
920 if (down->Depth <= 0)
923 return !down->Right || down->Right->Min + down->Depth >= 0;
926 ETNode *ETNode::NCA(ETNode *other) {
927 ETOccurrence *occ1 = RightmostOcc;
928 ETOccurrence *occ2 = other->RightmostOcc;
930 ETOccurrence *left, *right, *ret;
931 ETOccurrence *occmin;
945 right->Parent = NULL;
948 if (left == occ2 || (left && left->Parent != NULL)) {
953 right->Parent = occ1;
957 occ1->setRight(occ2);
962 if (occ2->Depth > 0) {
964 mindepth = occ1->Depth;
967 mindepth = occ2->Depth + occ1->Depth;
970 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
971 return ret->MinOccurrence->OccFor;
973 return occmin->OccFor;
976 void ETNode::assignDFSNumber(int num) {
977 std::vector<ETNode *> workStack;
978 std::set<ETNode *> visitedNodes;
980 workStack.push_back(this);
981 visitedNodes.insert(this);
982 this->DFSNumIn = num++;
984 while (!workStack.empty()) {
985 ETNode *Node = workStack.back();
987 // If this is leaf node then set DFSNumOut and pop the stack
989 Node->DFSNumOut = num++;
990 workStack.pop_back();
994 ETNode *son = Node->Son;
996 // Visit Node->Son first
997 if (visitedNodes.count(son) == 0) {
998 son->DFSNumIn = num++;
999 workStack.push_back(son);
1000 visitedNodes.insert(son);
1004 bool visitChild = false;
1005 // Visit remaining children
1006 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
1007 if (visitedNodes.count(s) == 0) {
1009 s->DFSNumIn = num++;
1010 workStack.push_back(s);
1011 visitedNodes.insert(s);
1016 // If we reach here means all children are visited
1017 Node->DFSNumOut = num++;
1018 workStack.pop_back();
1023 //===----------------------------------------------------------------------===//
1024 // ETForest implementation
1025 //===----------------------------------------------------------------------===//
1027 char ETForest::ID = 0;
1028 static RegisterPass<ETForest>
1029 D("etforest", "ET Forest Construction", true);
1031 void ETForestBase::reset() {
1032 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1037 void ETForestBase::updateDFSNumbers()
1040 // Iterate over all nodes in depth first order.
1041 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1042 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1043 E = df_end(Roots[i]); I != E; ++I) {
1044 BasicBlock *BB = *I;
1045 ETNode *ETN = getNode(BB);
1046 if (ETN && !ETN->hasFather())
1047 ETN->assignDFSNumber(dfsnum);
1050 DFSInfoValid = true;
1053 // dominates - Return true if A dominates B. THis performs the
1054 // special checks necessary if A and B are in the same basic block.
1055 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1056 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1057 if (BBA != BBB) return dominates(BBA, BBB);
1059 // It is not possible to determine dominance between two PHI nodes
1060 // based on their ordering.
1061 if (isa<PHINode>(A) && isa<PHINode>(B))
1064 // Loop through the basic block until we find A or B.
1065 BasicBlock::iterator I = BBA->begin();
1066 for (; &*I != A && &*I != B; ++I) /*empty*/;
1068 if(!IsPostDominators) {
1069 // A dominates B if it is found first in the basic block.
1072 // A post-dominates B if B is found first in the basic block.
1077 /// isReachableFromEntry - Return true if A is dominated by the entry
1078 /// block of the function containing it.
1079 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1080 return dominates(&A->getParent()->getEntryBlock(), A);
1083 // FIXME : There is no need to make getNodeForBlock public. Fix
1084 // predicate simplifier.
1085 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1086 ETNode *&BBNode = Nodes[BB];
1087 if (BBNode) return BBNode;
1089 // Haven't calculated this node yet? Get or calculate the node for the
1090 // immediate dominator.
1091 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1093 // If we are unreachable, we may not have an immediate dominator.
1094 if (!node || !node->getIDom())
1095 return BBNode = new ETNode(BB);
1097 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1099 // Add a new tree node for this BasicBlock, and link it as a child of
1101 BBNode = new ETNode(BB);
1102 BBNode->setFather(IDomNode);
1107 void ETForest::calculate(const DominatorTree &DT) {
1108 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1109 BasicBlock *Root = Roots[0];
1110 Nodes[Root] = new ETNode(Root); // Add a node for the root
1112 Function *F = Root->getParent();
1113 // Loop over all of the reachable blocks in the function...
1114 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1115 DomTreeNode* node = DT.getNode(I);
1116 if (node && node->getIDom()) { // Reachable block.
1117 BasicBlock* ImmDom = node->getIDom()->getBlock();
1118 ETNode *&BBNode = Nodes[I];
1119 if (!BBNode) { // Haven't calculated this node yet?
1120 // Get or calculate the node for the immediate dominator
1121 ETNode *IDomNode = getNodeForBlock(ImmDom);
1123 // Add a new ETNode for this BasicBlock, and set it's parent
1124 // to it's immediate dominator.
1125 BBNode = new ETNode(I);
1126 BBNode->setFather(IDomNode);
1131 // Make sure we've got nodes around for every block
1132 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1133 ETNode *&BBNode = Nodes[I];
1135 BBNode = new ETNode(I);
1138 updateDFSNumbers ();
1141 //===----------------------------------------------------------------------===//
1142 // ETForestBase Implementation
1143 //===----------------------------------------------------------------------===//
1145 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1146 ETNode *&BBNode = Nodes[BB];
1147 assert(!BBNode && "BasicBlock already in ET-Forest");
1149 BBNode = new ETNode(BB);
1150 BBNode->setFather(getNode(IDom));
1151 DFSInfoValid = false;
1154 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1155 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1156 assert(getNode(newIDom) && "IDom not in ET-Forest");
1158 ETNode *Node = getNode(BB);
1159 if (Node->hasFather()) {
1160 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1164 Node->setFather(getNode(newIDom));
1165 DFSInfoValid= false;
1168 void ETForestBase::print(std::ostream &o, const Module *) const {
1169 o << "=============================--------------------------------\n";
1170 o << "ET Forest:\n";
1176 o << " up to date\n";
1178 Function *F = getRoots()[0]->getParent();
1179 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1180 o << " DFS Numbers For Basic Block:";
1181 WriteAsOperand(o, I, false);
1183 if (ETNode *EN = getNode(I)) {
1184 o << "In: " << EN->getDFSNumIn();
1185 o << " Out: " << EN->getDFSNumOut() << "\n";
1187 o << "No associated ETNode";
1194 void ETForestBase::dump() {