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 DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0);
242 // Step #1: Number blocks in depth-first order and initialize variables used
243 // in later stages of the algorithm.
245 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
246 N = DFSPass(Roots[i], Info[Roots[i]], 0);
248 for (unsigned i = N; i >= 2; --i) {
249 BasicBlock *W = Vertex[i];
250 InfoRec &WInfo = Info[W];
252 // Step #2: Calculate the semidominators of all vertices
253 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
254 if (Info.count(*PI)) { // Only if this predecessor is reachable!
255 unsigned SemiU = Info[Eval(*PI)].Semi;
256 if (SemiU < WInfo.Semi)
260 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
262 BasicBlock *WParent = WInfo.Parent;
263 Link(WParent, W, WInfo);
265 // Step #3: Implicitly define the immediate dominator of vertices
266 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
267 while (!WParentBucket.empty()) {
268 BasicBlock *V = WParentBucket.back();
269 WParentBucket.pop_back();
270 BasicBlock *U = Eval(V);
271 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
275 // Step #4: Explicitly define the immediate dominator of each vertex
276 for (unsigned i = 2; i <= N; ++i) {
277 BasicBlock *W = Vertex[i];
278 BasicBlock *&WIDom = IDoms[W];
279 if (WIDom != Vertex[Info[W].Semi])
280 WIDom = IDoms[WIDom];
283 // Loop over all of the reachable blocks in the function...
284 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
285 if (BasicBlock *ImmDom = getIDom(I)) { // Reachable block.
286 DomTreeNode *&BBNode = DomTreeNodes[I];
287 if (!BBNode) { // Haven't calculated this node yet?
288 // Get or calculate the node for the immediate dominator
289 DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
291 // Add a new tree node for this BasicBlock, and link it as a child of
293 DomTreeNode *C = new DomTreeNode(I, IDomNode);
295 BBNode = IDomNode->addChild(C);
299 // Free temporary memory used to construct idom's
302 std::vector<BasicBlock*>().swap(Vertex);
307 void DominatorTreeBase::updateDFSNumbers()
310 // Iterate over all nodes in depth first order.
311 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
312 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
313 E = df_end(Roots[i]); I != E; ++I) {
315 DomTreeNode *BBNode = getNode(BB);
317 if (!BBNode->getIDom())
318 BBNode->assignDFSNumber(dfsnum);
325 /// isReachableFromEntry - Return true if A is dominated by the entry
326 /// block of the function containing it.
327 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
328 return dominates(&A->getParent()->getEntryBlock(), A);
331 // dominates - Return true if A dominates B. THis performs the
332 // special checks necessary if A and B are in the same basic block.
333 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
334 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
335 if (BBA != BBB) return dominates(BBA, BBB);
337 // It is not possible to determine dominance between two PHI nodes
338 // based on their ordering.
339 if (isa<PHINode>(A) && isa<PHINode>(B))
342 // Loop through the basic block until we find A or B.
343 BasicBlock::iterator I = BBA->begin();
344 for (; &*I != A && &*I != B; ++I) /*empty*/;
346 if(!IsPostDominators) {
347 // A dominates B if it is found first in the basic block.
350 // A post-dominates B if B is found first in the basic block.
355 // DominatorTreeBase::reset - Free all of the tree node memory.
357 void DominatorTreeBase::reset() {
358 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(),
359 E = DomTreeNodes.end(); I != E; ++I)
361 DomTreeNodes.clear();
368 /// findNearestCommonDominator - Find nearest common dominator basic block
369 /// for basic block A and B. If there is no such block then return NULL.
370 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A,
373 assert (!isPostDominator()
374 && "This is not implemented for post dominators");
375 assert (A->getParent() == B->getParent()
376 && "Two blocks are not in same function");
378 // If either A or B is a entry block then it is nearest common dominator.
379 BasicBlock &Entry = A->getParent()->getEntryBlock();
380 if (A == &Entry || B == &Entry)
383 // If B dominates A then B is nearest common dominator.
387 // If A dominates B then A is nearest common dominator.
391 DomTreeNode *NodeA = getNode(A);
392 DomTreeNode *NodeB = getNode(B);
394 // Collect NodeA dominators set.
395 SmallPtrSet<DomTreeNode*, 16> NodeADoms;
396 NodeADoms.insert(NodeA);
397 DomTreeNode *IDomA = NodeA->getIDom();
399 NodeADoms.insert(IDomA);
400 IDomA = IDomA->getIDom();
403 // Walk NodeB immediate dominators chain and find common dominator node.
404 DomTreeNode *IDomB = NodeB->getIDom();
406 if (NodeADoms.count(IDomB) != 0)
407 return IDomB->getBlock();
409 IDomB = IDomB->getIDom();
415 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
417 void DomTreeNode::assignDFSNumber(int num) {
418 std::vector<DomTreeNode *> workStack;
419 std::set<DomTreeNode *> visitedNodes;
421 workStack.push_back(this);
422 visitedNodes.insert(this);
423 this->DFSNumIn = num++;
425 while (!workStack.empty()) {
426 DomTreeNode *Node = workStack.back();
428 bool visitChild = false;
429 for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
430 E = Node->end(); DI != E && !visitChild; ++DI) {
431 DomTreeNode *Child = *DI;
432 if (visitedNodes.count(Child) == 0) {
434 Child->DFSNumIn = num++;
435 workStack.push_back(Child);
436 visitedNodes.insert(Child);
440 // If we reach here means all children are visited
441 Node->DFSNumOut = num++;
442 workStack.pop_back();
447 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
448 assert(IDom && "No immediate dominator?");
449 if (IDom != NewIDom) {
450 std::vector<DomTreeNode*>::iterator I =
451 std::find(IDom->Children.begin(), IDom->Children.end(), this);
452 assert(I != IDom->Children.end() &&
453 "Not in immediate dominator children set!");
454 // I am no longer your child...
455 IDom->Children.erase(I);
457 // Switch to new dominator
459 IDom->Children.push_back(this);
463 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
464 DomTreeNode *&BBNode = DomTreeNodes[BB];
465 if (BBNode) return BBNode;
467 // Haven't calculated this node yet? Get or calculate the node for the
468 // immediate dominator.
469 BasicBlock *IDom = getIDom(BB);
470 DomTreeNode *IDomNode = getNodeForBlock(IDom);
472 // Add a new tree node for this BasicBlock, and link it as a child of
474 DomTreeNode *C = new DomTreeNode(BB, IDomNode);
475 DomTreeNodes[BB] = C;
476 return BBNode = IDomNode->addChild(C);
479 static std::ostream &operator<<(std::ostream &o,
480 const DomTreeNode *Node) {
481 if (Node->getBlock())
482 WriteAsOperand(o, Node->getBlock(), false);
484 o << " <<exit node>>";
488 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
490 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
491 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
493 PrintDomTree(*I, o, Lev+1);
496 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
497 o << "=============================--------------------------------\n"
498 << "Inorder Dominator Tree:\n";
499 PrintDomTree(getRootNode(), o, 1);
502 void DominatorTreeBase::dump() {
506 bool DominatorTree::runOnFunction(Function &F) {
507 reset(); // Reset from the last time we were run...
508 Roots.push_back(&F.getEntryBlock());
513 //===----------------------------------------------------------------------===//
514 // DominanceFrontier Implementation
515 //===----------------------------------------------------------------------===//
517 char DominanceFrontier::ID = 0;
518 static RegisterPass<DominanceFrontier>
519 G("domfrontier", "Dominance Frontier Construction", true);
522 class DFCalculateWorkObject {
524 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
525 const DomTreeNode *N,
526 const DomTreeNode *PN)
527 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
528 BasicBlock *currentBB;
529 BasicBlock *parentBB;
530 const DomTreeNode *Node;
531 const DomTreeNode *parentNode;
535 const DominanceFrontier::DomSetType &
536 DominanceFrontier::calculate(const DominatorTree &DT,
537 const DomTreeNode *Node) {
538 BasicBlock *BB = Node->getBlock();
539 DomSetType *Result = NULL;
541 std::vector<DFCalculateWorkObject> workList;
542 SmallPtrSet<BasicBlock *, 32> visited;
544 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
546 DFCalculateWorkObject *currentW = &workList.back();
547 assert (currentW && "Missing work object.");
549 BasicBlock *currentBB = currentW->currentBB;
550 BasicBlock *parentBB = currentW->parentBB;
551 const DomTreeNode *currentNode = currentW->Node;
552 const DomTreeNode *parentNode = currentW->parentNode;
553 assert (currentBB && "Invalid work object. Missing current Basic Block");
554 assert (currentNode && "Invalid work object. Missing current Node");
555 DomSetType &S = Frontiers[currentBB];
557 // Visit each block only once.
558 if (visited.count(currentBB) == 0) {
559 visited.insert(currentBB);
561 // Loop over CFG successors to calculate DFlocal[currentNode]
562 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
564 // Does Node immediately dominate this successor?
565 if (DT[*SI]->getIDom() != currentNode)
570 // At this point, S is DFlocal. Now we union in DFup's of our children...
571 // Loop through and visit the nodes that Node immediately dominates (Node's
572 // children in the IDomTree)
573 bool visitChild = false;
574 for (DomTreeNode::const_iterator NI = currentNode->begin(),
575 NE = currentNode->end(); NI != NE; ++NI) {
576 DomTreeNode *IDominee = *NI;
577 BasicBlock *childBB = IDominee->getBlock();
578 if (visited.count(childBB) == 0) {
579 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
580 IDominee, currentNode));
585 // If all children are visited or there is any child then pop this block
586 // from the workList.
594 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
595 DomSetType &parentSet = Frontiers[parentBB];
596 for (; CDFI != CDFE; ++CDFI) {
597 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
598 parentSet.insert(*CDFI);
603 } while (!workList.empty());
608 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
609 for (const_iterator I = begin(), E = end(); I != E; ++I) {
610 o << " DomFrontier for BB";
612 WriteAsOperand(o, I->first, false);
614 o << " <<exit node>>";
615 o << " is:\t" << I->second << "\n";
619 void DominanceFrontierBase::dump() {
624 //===----------------------------------------------------------------------===//
625 // ETOccurrence Implementation
626 //===----------------------------------------------------------------------===//
628 void ETOccurrence::Splay() {
629 ETOccurrence *father;
630 ETOccurrence *grandfather;
638 fatherdepth = Parent->Depth;
639 grandfather = father->Parent;
641 // If we have no grandparent, a single zig or zag will do.
643 setDepthAdd(fatherdepth);
644 MinOccurrence = father->MinOccurrence;
647 // See what we have to rotate
648 if (father->Left == this) {
650 father->setLeft(Right);
653 father->Left->setDepthAdd(occdepth);
656 father->setRight(Left);
659 father->Right->setDepthAdd(occdepth);
661 father->setDepth(-occdepth);
664 father->recomputeMin();
668 // If we have a grandfather, we need to do some
669 // combination of zig and zag.
670 int grandfatherdepth = grandfather->Depth;
672 setDepthAdd(fatherdepth + grandfatherdepth);
673 MinOccurrence = grandfather->MinOccurrence;
674 Min = grandfather->Min;
676 ETOccurrence *greatgrandfather = grandfather->Parent;
678 if (grandfather->Left == father) {
679 if (father->Left == this) {
681 grandfather->setLeft(father->Right);
682 father->setLeft(Right);
684 father->setRight(grandfather);
686 father->setDepth(-occdepth);
689 father->Left->setDepthAdd(occdepth);
691 grandfather->setDepth(-fatherdepth);
692 if (grandfather->Left)
693 grandfather->Left->setDepthAdd(fatherdepth);
696 grandfather->setLeft(Right);
697 father->setRight(Left);
699 setRight(grandfather);
701 father->setDepth(-occdepth);
703 father->Right->setDepthAdd(occdepth);
704 grandfather->setDepth(-occdepth - fatherdepth);
705 if (grandfather->Left)
706 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
709 if (father->Left == this) {
711 grandfather->setRight(Left);
712 father->setLeft(Right);
713 setLeft(grandfather);
716 father->setDepth(-occdepth);
718 father->Left->setDepthAdd(occdepth);
719 grandfather->setDepth(-occdepth - fatherdepth);
720 if (grandfather->Right)
721 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
723 grandfather->setRight(father->Left);
724 father->setRight(Left);
726 father->setLeft(grandfather);
728 father->setDepth(-occdepth);
730 father->Right->setDepthAdd(occdepth);
731 grandfather->setDepth(-fatherdepth);
732 if (grandfather->Right)
733 grandfather->Right->setDepthAdd(fatherdepth);
737 // Might need one more rotate depending on greatgrandfather.
738 setParent(greatgrandfather);
739 if (greatgrandfather) {
740 if (greatgrandfather->Left == grandfather)
741 greatgrandfather->Left = this;
743 greatgrandfather->Right = this;
746 grandfather->recomputeMin();
747 father->recomputeMin();
751 //===----------------------------------------------------------------------===//
752 // ETNode implementation
753 //===----------------------------------------------------------------------===//
755 void ETNode::Split() {
756 ETOccurrence *right, *left;
757 ETOccurrence *rightmost = RightmostOcc;
758 ETOccurrence *parent;
760 // Update the occurrence tree first.
761 RightmostOcc->Splay();
763 // Find the leftmost occurrence in the rightmost subtree, then splay
765 for (right = rightmost->Right; right->Left; right = right->Left);
770 right->Left->Parent = NULL;
776 parent->Right->Parent = NULL;
778 right->setLeft(left);
780 right->recomputeMin();
783 rightmost->Depth = 0;
788 // Now update *our* tree
790 if (Father->Son == this)
793 if (Father->Son == this)
803 void ETNode::setFather(ETNode *NewFather) {
804 ETOccurrence *rightmost;
805 ETOccurrence *leftpart;
806 ETOccurrence *NewFatherOcc;
809 // First update the path in the splay tree
810 NewFatherOcc = new ETOccurrence(NewFather);
812 rightmost = NewFather->RightmostOcc;
815 leftpart = rightmost->Left;
820 NewFatherOcc->setLeft(leftpart);
821 NewFatherOcc->setRight(temp);
825 NewFatherOcc->recomputeMin();
827 rightmost->setLeft(NewFatherOcc);
829 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
830 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
831 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
835 ParentOcc = NewFatherOcc;
857 bool ETNode::Below(ETNode *other) {
858 ETOccurrence *up = other->RightmostOcc;
859 ETOccurrence *down = RightmostOcc;
866 ETOccurrence *left, *right;
876 right->Parent = NULL;
880 if (left == down || left->Parent != NULL) {
887 // If the two occurrences are in different trees, put things
888 // back the way they were.
889 if (right && right->Parent != NULL)
896 if (down->Depth <= 0)
899 return !down->Right || down->Right->Min + down->Depth >= 0;
902 ETNode *ETNode::NCA(ETNode *other) {
903 ETOccurrence *occ1 = RightmostOcc;
904 ETOccurrence *occ2 = other->RightmostOcc;
906 ETOccurrence *left, *right, *ret;
907 ETOccurrence *occmin;
921 right->Parent = NULL;
924 if (left == occ2 || (left && left->Parent != NULL)) {
929 right->Parent = occ1;
933 occ1->setRight(occ2);
938 if (occ2->Depth > 0) {
940 mindepth = occ1->Depth;
943 mindepth = occ2->Depth + occ1->Depth;
946 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
947 return ret->MinOccurrence->OccFor;
949 return occmin->OccFor;
952 void ETNode::assignDFSNumber(int num) {
953 std::vector<ETNode *> workStack;
954 std::set<ETNode *> visitedNodes;
956 workStack.push_back(this);
957 visitedNodes.insert(this);
958 this->DFSNumIn = num++;
960 while (!workStack.empty()) {
961 ETNode *Node = workStack.back();
963 // If this is leaf node then set DFSNumOut and pop the stack
965 Node->DFSNumOut = num++;
966 workStack.pop_back();
970 ETNode *son = Node->Son;
972 // Visit Node->Son first
973 if (visitedNodes.count(son) == 0) {
974 son->DFSNumIn = num++;
975 workStack.push_back(son);
976 visitedNodes.insert(son);
980 bool visitChild = false;
981 // Visit remaining children
982 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
983 if (visitedNodes.count(s) == 0) {
986 workStack.push_back(s);
987 visitedNodes.insert(s);
992 // If we reach here means all children are visited
993 Node->DFSNumOut = num++;
994 workStack.pop_back();
999 //===----------------------------------------------------------------------===//
1000 // ETForest implementation
1001 //===----------------------------------------------------------------------===//
1003 char ETForest::ID = 0;
1004 static RegisterPass<ETForest>
1005 D("etforest", "ET Forest Construction", true);
1007 void ETForestBase::reset() {
1008 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1013 void ETForestBase::updateDFSNumbers()
1016 // Iterate over all nodes in depth first order.
1017 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1018 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1019 E = df_end(Roots[i]); I != E; ++I) {
1020 BasicBlock *BB = *I;
1021 ETNode *ETN = getNode(BB);
1022 if (ETN && !ETN->hasFather())
1023 ETN->assignDFSNumber(dfsnum);
1026 DFSInfoValid = true;
1029 // dominates - Return true if A dominates B. THis performs the
1030 // special checks necessary if A and B are in the same basic block.
1031 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1032 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1033 if (BBA != BBB) return dominates(BBA, BBB);
1035 // It is not possible to determine dominance between two PHI nodes
1036 // based on their ordering.
1037 if (isa<PHINode>(A) && isa<PHINode>(B))
1040 // Loop through the basic block until we find A or B.
1041 BasicBlock::iterator I = BBA->begin();
1042 for (; &*I != A && &*I != B; ++I) /*empty*/;
1044 if(!IsPostDominators) {
1045 // A dominates B if it is found first in the basic block.
1048 // A post-dominates B if B is found first in the basic block.
1053 /// isReachableFromEntry - Return true if A is dominated by the entry
1054 /// block of the function containing it.
1055 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1056 return dominates(&A->getParent()->getEntryBlock(), A);
1059 // FIXME : There is no need to make getNodeForBlock public. Fix
1060 // predicate simplifier.
1061 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1062 ETNode *&BBNode = Nodes[BB];
1063 if (BBNode) return BBNode;
1065 // Haven't calculated this node yet? Get or calculate the node for the
1066 // immediate dominator.
1067 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1069 // If we are unreachable, we may not have an immediate dominator.
1070 if (!node || !node->getIDom())
1071 return BBNode = new ETNode(BB);
1073 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1075 // Add a new tree node for this BasicBlock, and link it as a child of
1077 BBNode = new ETNode(BB);
1078 BBNode->setFather(IDomNode);
1083 void ETForest::calculate(const DominatorTree &DT) {
1084 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1085 BasicBlock *Root = Roots[0];
1086 Nodes[Root] = new ETNode(Root); // Add a node for the root
1088 Function *F = Root->getParent();
1089 // Loop over all of the reachable blocks in the function...
1090 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1091 DomTreeNode* node = DT.getNode(I);
1092 if (node && node->getIDom()) { // Reachable block.
1093 BasicBlock* ImmDom = node->getIDom()->getBlock();
1094 ETNode *&BBNode = Nodes[I];
1095 if (!BBNode) { // Haven't calculated this node yet?
1096 // Get or calculate the node for the immediate dominator
1097 ETNode *IDomNode = getNodeForBlock(ImmDom);
1099 // Add a new ETNode for this BasicBlock, and set it's parent
1100 // to it's immediate dominator.
1101 BBNode = new ETNode(I);
1102 BBNode->setFather(IDomNode);
1107 // Make sure we've got nodes around for every block
1108 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1109 ETNode *&BBNode = Nodes[I];
1111 BBNode = new ETNode(I);
1114 updateDFSNumbers ();
1117 //===----------------------------------------------------------------------===//
1118 // ETForestBase Implementation
1119 //===----------------------------------------------------------------------===//
1121 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1122 ETNode *&BBNode = Nodes[BB];
1123 assert(!BBNode && "BasicBlock already in ET-Forest");
1125 BBNode = new ETNode(BB);
1126 BBNode->setFather(getNode(IDom));
1127 DFSInfoValid = false;
1130 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1131 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1132 assert(getNode(newIDom) && "IDom not in ET-Forest");
1134 ETNode *Node = getNode(BB);
1135 if (Node->hasFather()) {
1136 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1140 Node->setFather(getNode(newIDom));
1141 DFSInfoValid= false;
1144 void ETForestBase::print(std::ostream &o, const Module *) const {
1145 o << "=============================--------------------------------\n";
1146 o << "ET Forest:\n";
1152 o << " up to date\n";
1154 Function *F = getRoots()[0]->getParent();
1155 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1156 o << " DFS Numbers For Basic Block:";
1157 WriteAsOperand(o, I, false);
1159 if (ETNode *EN = getNode(I)) {
1160 o << "In: " << EN->getDFSNumIn();
1161 o << " Out: " << EN->getDFSNumOut() << "\n";
1163 o << "No associated ETNode";
1170 void ETForestBase::dump() {