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 A and B are same then A is nearest common dominator.
384 DomTreeNode *NodeA = getNode(A);
385 if (A != 0 && A == B)
388 DomTreeNode *NodeB = getNode(B);
390 // If B dominates A then B is nearest common dominator.
394 // If A dominates B then A is nearest common dominator.
398 // Collect NodeA dominators set.
399 SmallPtrSet<DomTreeNode*, 16> NodeADoms;
400 NodeADoms.insert(NodeA);
401 DomTreeNode *IDomA = NodeA->getIDom();
403 NodeADoms.insert(IDomA);
404 IDomA = IDomA->getIDom();
407 // Walk NodeB immediate dominators chain and find common dominator node.
408 DomTreeNode *IDomB = NodeB->getIDom();
410 if (NodeADoms.count(IDomB) != 0)
411 return IDomB->getBlock();
413 IDomB = IDomB->getIDom();
419 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
421 void DomTreeNode::assignDFSNumber(int num) {
422 std::vector<DomTreeNode *> workStack;
423 std::set<DomTreeNode *> visitedNodes;
425 workStack.push_back(this);
426 visitedNodes.insert(this);
427 this->DFSNumIn = num++;
429 while (!workStack.empty()) {
430 DomTreeNode *Node = workStack.back();
432 bool visitChild = false;
433 for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
434 E = Node->end(); DI != E && !visitChild; ++DI) {
435 DomTreeNode *Child = *DI;
436 if (visitedNodes.count(Child) == 0) {
438 Child->DFSNumIn = num++;
439 workStack.push_back(Child);
440 visitedNodes.insert(Child);
444 // If we reach here means all children are visited
445 Node->DFSNumOut = num++;
446 workStack.pop_back();
451 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
452 assert(IDom && "No immediate dominator?");
453 if (IDom != NewIDom) {
454 std::vector<DomTreeNode*>::iterator I =
455 std::find(IDom->Children.begin(), IDom->Children.end(), this);
456 assert(I != IDom->Children.end() &&
457 "Not in immediate dominator children set!");
458 // I am no longer your child...
459 IDom->Children.erase(I);
461 // Switch to new dominator
463 IDom->Children.push_back(this);
467 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
468 DomTreeNode *&BBNode = DomTreeNodes[BB];
469 if (BBNode) return BBNode;
471 // Haven't calculated this node yet? Get or calculate the node for the
472 // immediate dominator.
473 BasicBlock *IDom = getIDom(BB);
474 DomTreeNode *IDomNode = getNodeForBlock(IDom);
476 // Add a new tree node for this BasicBlock, and link it as a child of
478 DomTreeNode *C = new DomTreeNode(BB, IDomNode);
479 DomTreeNodes[BB] = C;
480 return BBNode = IDomNode->addChild(C);
483 static std::ostream &operator<<(std::ostream &o,
484 const DomTreeNode *Node) {
485 if (Node->getBlock())
486 WriteAsOperand(o, Node->getBlock(), false);
488 o << " <<exit node>>";
492 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
494 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
495 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
497 PrintDomTree(*I, o, Lev+1);
500 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
501 o << "=============================--------------------------------\n"
502 << "Inorder Dominator Tree:\n";
503 PrintDomTree(getRootNode(), o, 1);
506 void DominatorTreeBase::dump() {
510 bool DominatorTree::runOnFunction(Function &F) {
511 reset(); // Reset from the last time we were run...
512 Roots.push_back(&F.getEntryBlock());
517 //===----------------------------------------------------------------------===//
518 // DominanceFrontier Implementation
519 //===----------------------------------------------------------------------===//
521 char DominanceFrontier::ID = 0;
522 static RegisterPass<DominanceFrontier>
523 G("domfrontier", "Dominance Frontier Construction", true);
526 class DFCalculateWorkObject {
528 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
529 const DomTreeNode *N,
530 const DomTreeNode *PN)
531 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
532 BasicBlock *currentBB;
533 BasicBlock *parentBB;
534 const DomTreeNode *Node;
535 const DomTreeNode *parentNode;
539 const DominanceFrontier::DomSetType &
540 DominanceFrontier::calculate(const DominatorTree &DT,
541 const DomTreeNode *Node) {
542 BasicBlock *BB = Node->getBlock();
543 DomSetType *Result = NULL;
545 std::vector<DFCalculateWorkObject> workList;
546 SmallPtrSet<BasicBlock *, 32> visited;
548 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
550 DFCalculateWorkObject *currentW = &workList.back();
551 assert (currentW && "Missing work object.");
553 BasicBlock *currentBB = currentW->currentBB;
554 BasicBlock *parentBB = currentW->parentBB;
555 const DomTreeNode *currentNode = currentW->Node;
556 const DomTreeNode *parentNode = currentW->parentNode;
557 assert (currentBB && "Invalid work object. Missing current Basic Block");
558 assert (currentNode && "Invalid work object. Missing current Node");
559 DomSetType &S = Frontiers[currentBB];
561 // Visit each block only once.
562 if (visited.count(currentBB) == 0) {
563 visited.insert(currentBB);
565 // Loop over CFG successors to calculate DFlocal[currentNode]
566 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
568 // Does Node immediately dominate this successor?
569 if (DT[*SI]->getIDom() != currentNode)
574 // At this point, S is DFlocal. Now we union in DFup's of our children...
575 // Loop through and visit the nodes that Node immediately dominates (Node's
576 // children in the IDomTree)
577 bool visitChild = false;
578 for (DomTreeNode::const_iterator NI = currentNode->begin(),
579 NE = currentNode->end(); NI != NE; ++NI) {
580 DomTreeNode *IDominee = *NI;
581 BasicBlock *childBB = IDominee->getBlock();
582 if (visited.count(childBB) == 0) {
583 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
584 IDominee, currentNode));
589 // If all children are visited or there is any child then pop this block
590 // from the workList.
598 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
599 DomSetType &parentSet = Frontiers[parentBB];
600 for (; CDFI != CDFE; ++CDFI) {
601 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
602 parentSet.insert(*CDFI);
607 } while (!workList.empty());
612 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
613 for (const_iterator I = begin(), E = end(); I != E; ++I) {
614 o << " DomFrontier for BB";
616 WriteAsOperand(o, I->first, false);
618 o << " <<exit node>>";
619 o << " is:\t" << I->second << "\n";
623 void DominanceFrontierBase::dump() {
628 //===----------------------------------------------------------------------===//
629 // ETOccurrence Implementation
630 //===----------------------------------------------------------------------===//
632 void ETOccurrence::Splay() {
633 ETOccurrence *father;
634 ETOccurrence *grandfather;
642 fatherdepth = Parent->Depth;
643 grandfather = father->Parent;
645 // If we have no grandparent, a single zig or zag will do.
647 setDepthAdd(fatherdepth);
648 MinOccurrence = father->MinOccurrence;
651 // See what we have to rotate
652 if (father->Left == this) {
654 father->setLeft(Right);
657 father->Left->setDepthAdd(occdepth);
660 father->setRight(Left);
663 father->Right->setDepthAdd(occdepth);
665 father->setDepth(-occdepth);
668 father->recomputeMin();
672 // If we have a grandfather, we need to do some
673 // combination of zig and zag.
674 int grandfatherdepth = grandfather->Depth;
676 setDepthAdd(fatherdepth + grandfatherdepth);
677 MinOccurrence = grandfather->MinOccurrence;
678 Min = grandfather->Min;
680 ETOccurrence *greatgrandfather = grandfather->Parent;
682 if (grandfather->Left == father) {
683 if (father->Left == this) {
685 grandfather->setLeft(father->Right);
686 father->setLeft(Right);
688 father->setRight(grandfather);
690 father->setDepth(-occdepth);
693 father->Left->setDepthAdd(occdepth);
695 grandfather->setDepth(-fatherdepth);
696 if (grandfather->Left)
697 grandfather->Left->setDepthAdd(fatherdepth);
700 grandfather->setLeft(Right);
701 father->setRight(Left);
703 setRight(grandfather);
705 father->setDepth(-occdepth);
707 father->Right->setDepthAdd(occdepth);
708 grandfather->setDepth(-occdepth - fatherdepth);
709 if (grandfather->Left)
710 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
713 if (father->Left == this) {
715 grandfather->setRight(Left);
716 father->setLeft(Right);
717 setLeft(grandfather);
720 father->setDepth(-occdepth);
722 father->Left->setDepthAdd(occdepth);
723 grandfather->setDepth(-occdepth - fatherdepth);
724 if (grandfather->Right)
725 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
727 grandfather->setRight(father->Left);
728 father->setRight(Left);
730 father->setLeft(grandfather);
732 father->setDepth(-occdepth);
734 father->Right->setDepthAdd(occdepth);
735 grandfather->setDepth(-fatherdepth);
736 if (grandfather->Right)
737 grandfather->Right->setDepthAdd(fatherdepth);
741 // Might need one more rotate depending on greatgrandfather.
742 setParent(greatgrandfather);
743 if (greatgrandfather) {
744 if (greatgrandfather->Left == grandfather)
745 greatgrandfather->Left = this;
747 greatgrandfather->Right = this;
750 grandfather->recomputeMin();
751 father->recomputeMin();
755 //===----------------------------------------------------------------------===//
756 // ETNode implementation
757 //===----------------------------------------------------------------------===//
759 void ETNode::Split() {
760 ETOccurrence *right, *left;
761 ETOccurrence *rightmost = RightmostOcc;
762 ETOccurrence *parent;
764 // Update the occurrence tree first.
765 RightmostOcc->Splay();
767 // Find the leftmost occurrence in the rightmost subtree, then splay
769 for (right = rightmost->Right; right->Left; right = right->Left);
774 right->Left->Parent = NULL;
780 parent->Right->Parent = NULL;
782 right->setLeft(left);
784 right->recomputeMin();
787 rightmost->Depth = 0;
792 // Now update *our* tree
794 if (Father->Son == this)
797 if (Father->Son == this)
807 void ETNode::setFather(ETNode *NewFather) {
808 ETOccurrence *rightmost;
809 ETOccurrence *leftpart;
810 ETOccurrence *NewFatherOcc;
813 // First update the path in the splay tree
814 NewFatherOcc = new ETOccurrence(NewFather);
816 rightmost = NewFather->RightmostOcc;
819 leftpart = rightmost->Left;
824 NewFatherOcc->setLeft(leftpart);
825 NewFatherOcc->setRight(temp);
829 NewFatherOcc->recomputeMin();
831 rightmost->setLeft(NewFatherOcc);
833 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
834 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
835 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
839 ParentOcc = NewFatherOcc;
861 bool ETNode::Below(ETNode *other) {
862 ETOccurrence *up = other->RightmostOcc;
863 ETOccurrence *down = RightmostOcc;
870 ETOccurrence *left, *right;
880 right->Parent = NULL;
884 if (left == down || left->Parent != NULL) {
891 // If the two occurrences are in different trees, put things
892 // back the way they were.
893 if (right && right->Parent != NULL)
900 if (down->Depth <= 0)
903 return !down->Right || down->Right->Min + down->Depth >= 0;
906 ETNode *ETNode::NCA(ETNode *other) {
907 ETOccurrence *occ1 = RightmostOcc;
908 ETOccurrence *occ2 = other->RightmostOcc;
910 ETOccurrence *left, *right, *ret;
911 ETOccurrence *occmin;
925 right->Parent = NULL;
928 if (left == occ2 || (left && left->Parent != NULL)) {
933 right->Parent = occ1;
937 occ1->setRight(occ2);
942 if (occ2->Depth > 0) {
944 mindepth = occ1->Depth;
947 mindepth = occ2->Depth + occ1->Depth;
950 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
951 return ret->MinOccurrence->OccFor;
953 return occmin->OccFor;
956 void ETNode::assignDFSNumber(int num) {
957 std::vector<ETNode *> workStack;
958 std::set<ETNode *> visitedNodes;
960 workStack.push_back(this);
961 visitedNodes.insert(this);
962 this->DFSNumIn = num++;
964 while (!workStack.empty()) {
965 ETNode *Node = workStack.back();
967 // If this is leaf node then set DFSNumOut and pop the stack
969 Node->DFSNumOut = num++;
970 workStack.pop_back();
974 ETNode *son = Node->Son;
976 // Visit Node->Son first
977 if (visitedNodes.count(son) == 0) {
978 son->DFSNumIn = num++;
979 workStack.push_back(son);
980 visitedNodes.insert(son);
984 bool visitChild = false;
985 // Visit remaining children
986 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
987 if (visitedNodes.count(s) == 0) {
990 workStack.push_back(s);
991 visitedNodes.insert(s);
996 // If we reach here means all children are visited
997 Node->DFSNumOut = num++;
998 workStack.pop_back();
1003 //===----------------------------------------------------------------------===//
1004 // ETForest implementation
1005 //===----------------------------------------------------------------------===//
1007 char ETForest::ID = 0;
1008 static RegisterPass<ETForest>
1009 D("etforest", "ET Forest Construction", true);
1011 void ETForestBase::reset() {
1012 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1017 void ETForestBase::updateDFSNumbers()
1020 // Iterate over all nodes in depth first order.
1021 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1022 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1023 E = df_end(Roots[i]); I != E; ++I) {
1024 BasicBlock *BB = *I;
1025 ETNode *ETN = getNode(BB);
1026 if (ETN && !ETN->hasFather())
1027 ETN->assignDFSNumber(dfsnum);
1030 DFSInfoValid = true;
1033 // dominates - Return true if A dominates B. THis performs the
1034 // special checks necessary if A and B are in the same basic block.
1035 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1036 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1037 if (BBA != BBB) return dominates(BBA, BBB);
1039 // It is not possible to determine dominance between two PHI nodes
1040 // based on their ordering.
1041 if (isa<PHINode>(A) && isa<PHINode>(B))
1044 // Loop through the basic block until we find A or B.
1045 BasicBlock::iterator I = BBA->begin();
1046 for (; &*I != A && &*I != B; ++I) /*empty*/;
1048 if(!IsPostDominators) {
1049 // A dominates B if it is found first in the basic block.
1052 // A post-dominates B if B is found first in the basic block.
1057 /// isReachableFromEntry - Return true if A is dominated by the entry
1058 /// block of the function containing it.
1059 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1060 return dominates(&A->getParent()->getEntryBlock(), A);
1063 // FIXME : There is no need to make getNodeForBlock public. Fix
1064 // predicate simplifier.
1065 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1066 ETNode *&BBNode = Nodes[BB];
1067 if (BBNode) return BBNode;
1069 // Haven't calculated this node yet? Get or calculate the node for the
1070 // immediate dominator.
1071 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1073 // If we are unreachable, we may not have an immediate dominator.
1074 if (!node || !node->getIDom())
1075 return BBNode = new ETNode(BB);
1077 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1079 // Add a new tree node for this BasicBlock, and link it as a child of
1081 BBNode = new ETNode(BB);
1082 BBNode->setFather(IDomNode);
1087 void ETForest::calculate(const DominatorTree &DT) {
1088 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1089 BasicBlock *Root = Roots[0];
1090 Nodes[Root] = new ETNode(Root); // Add a node for the root
1092 Function *F = Root->getParent();
1093 // Loop over all of the reachable blocks in the function...
1094 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1095 DomTreeNode* node = DT.getNode(I);
1096 if (node && node->getIDom()) { // Reachable block.
1097 BasicBlock* ImmDom = node->getIDom()->getBlock();
1098 ETNode *&BBNode = Nodes[I];
1099 if (!BBNode) { // Haven't calculated this node yet?
1100 // Get or calculate the node for the immediate dominator
1101 ETNode *IDomNode = getNodeForBlock(ImmDom);
1103 // Add a new ETNode for this BasicBlock, and set it's parent
1104 // to it's immediate dominator.
1105 BBNode = new ETNode(I);
1106 BBNode->setFather(IDomNode);
1111 // Make sure we've got nodes around for every block
1112 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1113 ETNode *&BBNode = Nodes[I];
1115 BBNode = new ETNode(I);
1118 updateDFSNumbers ();
1121 //===----------------------------------------------------------------------===//
1122 // ETForestBase Implementation
1123 //===----------------------------------------------------------------------===//
1125 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1126 ETNode *&BBNode = Nodes[BB];
1127 assert(!BBNode && "BasicBlock already in ET-Forest");
1129 BBNode = new ETNode(BB);
1130 BBNode->setFather(getNode(IDom));
1131 DFSInfoValid = false;
1134 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1135 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1136 assert(getNode(newIDom) && "IDom not in ET-Forest");
1138 ETNode *Node = getNode(BB);
1139 if (Node->hasFather()) {
1140 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1144 Node->setFather(getNode(newIDom));
1145 DFSInfoValid= false;
1148 void ETForestBase::print(std::ostream &o, const Module *) const {
1149 o << "=============================--------------------------------\n";
1150 o << "ET Forest:\n";
1156 o << " up to date\n";
1158 Function *F = getRoots()[0]->getParent();
1159 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1160 o << " DFS Numbers For Basic Block:";
1161 WriteAsOperand(o, I, false);
1163 if (ETNode *EN = getNode(I)) {
1164 o << "In: " << EN->getDFSNumIn();
1165 o << " Out: " << EN->getDFSNumOut() << "\n";
1167 o << "No associated ETNode";
1174 void ETForestBase::dump() {