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 assert (!isPostDominator()
329 && "This is not implemented for post dominators");
330 return dominates(&A->getParent()->getEntryBlock(), A);
333 // dominates - Return true if A dominates B. THis performs the
334 // special checks necessary if A and B are in the same basic block.
335 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
336 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
337 if (BBA != BBB) return dominates(BBA, BBB);
339 // It is not possible to determine dominance between two PHI nodes
340 // based on their ordering.
341 if (isa<PHINode>(A) && isa<PHINode>(B))
344 // Loop through the basic block until we find A or B.
345 BasicBlock::iterator I = BBA->begin();
346 for (; &*I != A && &*I != B; ++I) /*empty*/;
348 if(!IsPostDominators) {
349 // A dominates B if it is found first in the basic block.
352 // A post-dominates B if B is found first in the basic block.
357 // DominatorTreeBase::reset - Free all of the tree node memory.
359 void DominatorTreeBase::reset() {
360 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(),
361 E = DomTreeNodes.end(); I != E; ++I)
363 DomTreeNodes.clear();
370 /// findNearestCommonDominator - Find nearest common dominator basic block
371 /// for basic block A and B. If there is no such block then return NULL.
372 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A,
375 assert (!isPostDominator()
376 && "This is not implemented for post dominators");
377 assert (A->getParent() == B->getParent()
378 && "Two blocks are not in same function");
380 // If either A or B is a entry block then it is nearest common dominator.
381 BasicBlock &Entry = A->getParent()->getEntryBlock();
382 if (A == &Entry || B == &Entry)
385 // If B dominates A then B is nearest common dominator.
389 // If A dominates B then A is nearest common dominator.
393 DomTreeNode *NodeA = getNode(A);
394 DomTreeNode *NodeB = getNode(B);
396 // Collect NodeA dominators set.
397 SmallPtrSet<DomTreeNode*, 16> NodeADoms;
398 NodeADoms.insert(NodeA);
399 DomTreeNode *IDomA = NodeA->getIDom();
401 NodeADoms.insert(IDomA);
402 IDomA = IDomA->getIDom();
405 // Walk NodeB immediate dominators chain and find common dominator node.
406 DomTreeNode *IDomB = NodeB->getIDom();
408 if (NodeADoms.count(IDomB) != 0)
409 return IDomB->getBlock();
411 IDomB = IDomB->getIDom();
417 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
419 void DomTreeNode::assignDFSNumber(int num) {
420 std::vector<DomTreeNode *> workStack;
421 std::set<DomTreeNode *> visitedNodes;
423 workStack.push_back(this);
424 visitedNodes.insert(this);
425 this->DFSNumIn = num++;
427 while (!workStack.empty()) {
428 DomTreeNode *Node = workStack.back();
430 bool visitChild = false;
431 for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
432 E = Node->end(); DI != E && !visitChild; ++DI) {
433 DomTreeNode *Child = *DI;
434 if (visitedNodes.count(Child) == 0) {
436 Child->DFSNumIn = num++;
437 workStack.push_back(Child);
438 visitedNodes.insert(Child);
442 // If we reach here means all children are visited
443 Node->DFSNumOut = num++;
444 workStack.pop_back();
449 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
450 assert(IDom && "No immediate dominator?");
451 if (IDom != NewIDom) {
452 std::vector<DomTreeNode*>::iterator I =
453 std::find(IDom->Children.begin(), IDom->Children.end(), this);
454 assert(I != IDom->Children.end() &&
455 "Not in immediate dominator children set!");
456 // I am no longer your child...
457 IDom->Children.erase(I);
459 // Switch to new dominator
461 IDom->Children.push_back(this);
465 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
466 DomTreeNode *&BBNode = DomTreeNodes[BB];
467 if (BBNode) return BBNode;
469 // Haven't calculated this node yet? Get or calculate the node for the
470 // immediate dominator.
471 BasicBlock *IDom = getIDom(BB);
472 DomTreeNode *IDomNode = getNodeForBlock(IDom);
474 // Add a new tree node for this BasicBlock, and link it as a child of
476 DomTreeNode *C = new DomTreeNode(BB, IDomNode);
477 DomTreeNodes[BB] = C;
478 return BBNode = IDomNode->addChild(C);
481 static std::ostream &operator<<(std::ostream &o,
482 const DomTreeNode *Node) {
483 if (Node->getBlock())
484 WriteAsOperand(o, Node->getBlock(), false);
486 o << " <<exit node>>";
490 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
492 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
493 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
495 PrintDomTree(*I, o, Lev+1);
498 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
499 o << "=============================--------------------------------\n"
500 << "Inorder Dominator Tree:\n";
501 PrintDomTree(getRootNode(), o, 1);
504 void DominatorTreeBase::dump() {
508 bool DominatorTree::runOnFunction(Function &F) {
509 reset(); // Reset from the last time we were run...
510 Roots.push_back(&F.getEntryBlock());
515 //===----------------------------------------------------------------------===//
516 // DominanceFrontier Implementation
517 //===----------------------------------------------------------------------===//
519 char DominanceFrontier::ID = 0;
520 static RegisterPass<DominanceFrontier>
521 G("domfrontier", "Dominance Frontier Construction", true);
524 class DFCalculateWorkObject {
526 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
527 const DomTreeNode *N,
528 const DomTreeNode *PN)
529 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
530 BasicBlock *currentBB;
531 BasicBlock *parentBB;
532 const DomTreeNode *Node;
533 const DomTreeNode *parentNode;
537 const DominanceFrontier::DomSetType &
538 DominanceFrontier::calculate(const DominatorTree &DT,
539 const DomTreeNode *Node) {
540 BasicBlock *BB = Node->getBlock();
541 DomSetType *Result = NULL;
543 std::vector<DFCalculateWorkObject> workList;
544 SmallPtrSet<BasicBlock *, 32> visited;
546 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
548 DFCalculateWorkObject *currentW = &workList.back();
549 assert (currentW && "Missing work object.");
551 BasicBlock *currentBB = currentW->currentBB;
552 BasicBlock *parentBB = currentW->parentBB;
553 const DomTreeNode *currentNode = currentW->Node;
554 const DomTreeNode *parentNode = currentW->parentNode;
555 assert (currentBB && "Invalid work object. Missing current Basic Block");
556 assert (currentNode && "Invalid work object. Missing current Node");
557 DomSetType &S = Frontiers[currentBB];
559 // Visit each block only once.
560 if (visited.count(currentBB) == 0) {
561 visited.insert(currentBB);
563 // Loop over CFG successors to calculate DFlocal[currentNode]
564 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
566 // Does Node immediately dominate this successor?
567 if (DT[*SI]->getIDom() != currentNode)
572 // At this point, S is DFlocal. Now we union in DFup's of our children...
573 // Loop through and visit the nodes that Node immediately dominates (Node's
574 // children in the IDomTree)
575 bool visitChild = false;
576 for (DomTreeNode::const_iterator NI = currentNode->begin(),
577 NE = currentNode->end(); NI != NE; ++NI) {
578 DomTreeNode *IDominee = *NI;
579 BasicBlock *childBB = IDominee->getBlock();
580 if (visited.count(childBB) == 0) {
581 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
582 IDominee, currentNode));
587 // If all children are visited or there is any child then pop this block
588 // from the workList.
596 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
597 DomSetType &parentSet = Frontiers[parentBB];
598 for (; CDFI != CDFE; ++CDFI) {
599 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
600 parentSet.insert(*CDFI);
605 } while (!workList.empty());
610 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
611 for (const_iterator I = begin(), E = end(); I != E; ++I) {
612 o << " DomFrontier for BB";
614 WriteAsOperand(o, I->first, false);
616 o << " <<exit node>>";
617 o << " is:\t" << I->second << "\n";
621 void DominanceFrontierBase::dump() {
626 //===----------------------------------------------------------------------===//
627 // ETOccurrence Implementation
628 //===----------------------------------------------------------------------===//
630 void ETOccurrence::Splay() {
631 ETOccurrence *father;
632 ETOccurrence *grandfather;
640 fatherdepth = Parent->Depth;
641 grandfather = father->Parent;
643 // If we have no grandparent, a single zig or zag will do.
645 setDepthAdd(fatherdepth);
646 MinOccurrence = father->MinOccurrence;
649 // See what we have to rotate
650 if (father->Left == this) {
652 father->setLeft(Right);
655 father->Left->setDepthAdd(occdepth);
658 father->setRight(Left);
661 father->Right->setDepthAdd(occdepth);
663 father->setDepth(-occdepth);
666 father->recomputeMin();
670 // If we have a grandfather, we need to do some
671 // combination of zig and zag.
672 int grandfatherdepth = grandfather->Depth;
674 setDepthAdd(fatherdepth + grandfatherdepth);
675 MinOccurrence = grandfather->MinOccurrence;
676 Min = grandfather->Min;
678 ETOccurrence *greatgrandfather = grandfather->Parent;
680 if (grandfather->Left == father) {
681 if (father->Left == this) {
683 grandfather->setLeft(father->Right);
684 father->setLeft(Right);
686 father->setRight(grandfather);
688 father->setDepth(-occdepth);
691 father->Left->setDepthAdd(occdepth);
693 grandfather->setDepth(-fatherdepth);
694 if (grandfather->Left)
695 grandfather->Left->setDepthAdd(fatherdepth);
698 grandfather->setLeft(Right);
699 father->setRight(Left);
701 setRight(grandfather);
703 father->setDepth(-occdepth);
705 father->Right->setDepthAdd(occdepth);
706 grandfather->setDepth(-occdepth - fatherdepth);
707 if (grandfather->Left)
708 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
711 if (father->Left == this) {
713 grandfather->setRight(Left);
714 father->setLeft(Right);
715 setLeft(grandfather);
718 father->setDepth(-occdepth);
720 father->Left->setDepthAdd(occdepth);
721 grandfather->setDepth(-occdepth - fatherdepth);
722 if (grandfather->Right)
723 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
725 grandfather->setRight(father->Left);
726 father->setRight(Left);
728 father->setLeft(grandfather);
730 father->setDepth(-occdepth);
732 father->Right->setDepthAdd(occdepth);
733 grandfather->setDepth(-fatherdepth);
734 if (grandfather->Right)
735 grandfather->Right->setDepthAdd(fatherdepth);
739 // Might need one more rotate depending on greatgrandfather.
740 setParent(greatgrandfather);
741 if (greatgrandfather) {
742 if (greatgrandfather->Left == grandfather)
743 greatgrandfather->Left = this;
745 greatgrandfather->Right = this;
748 grandfather->recomputeMin();
749 father->recomputeMin();
753 //===----------------------------------------------------------------------===//
754 // ETNode implementation
755 //===----------------------------------------------------------------------===//
757 void ETNode::Split() {
758 ETOccurrence *right, *left;
759 ETOccurrence *rightmost = RightmostOcc;
760 ETOccurrence *parent;
762 // Update the occurrence tree first.
763 RightmostOcc->Splay();
765 // Find the leftmost occurrence in the rightmost subtree, then splay
767 for (right = rightmost->Right; right->Left; right = right->Left);
772 right->Left->Parent = NULL;
778 parent->Right->Parent = NULL;
780 right->setLeft(left);
782 right->recomputeMin();
785 rightmost->Depth = 0;
790 // Now update *our* tree
792 if (Father->Son == this)
795 if (Father->Son == this)
805 void ETNode::setFather(ETNode *NewFather) {
806 ETOccurrence *rightmost;
807 ETOccurrence *leftpart;
808 ETOccurrence *NewFatherOcc;
811 // First update the path in the splay tree
812 NewFatherOcc = new ETOccurrence(NewFather);
814 rightmost = NewFather->RightmostOcc;
817 leftpart = rightmost->Left;
822 NewFatherOcc->setLeft(leftpart);
823 NewFatherOcc->setRight(temp);
827 NewFatherOcc->recomputeMin();
829 rightmost->setLeft(NewFatherOcc);
831 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
832 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
833 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
837 ParentOcc = NewFatherOcc;
859 bool ETNode::Below(ETNode *other) {
860 ETOccurrence *up = other->RightmostOcc;
861 ETOccurrence *down = RightmostOcc;
868 ETOccurrence *left, *right;
878 right->Parent = NULL;
882 if (left == down || left->Parent != NULL) {
889 // If the two occurrences are in different trees, put things
890 // back the way they were.
891 if (right && right->Parent != NULL)
898 if (down->Depth <= 0)
901 return !down->Right || down->Right->Min + down->Depth >= 0;
904 ETNode *ETNode::NCA(ETNode *other) {
905 ETOccurrence *occ1 = RightmostOcc;
906 ETOccurrence *occ2 = other->RightmostOcc;
908 ETOccurrence *left, *right, *ret;
909 ETOccurrence *occmin;
923 right->Parent = NULL;
926 if (left == occ2 || (left && left->Parent != NULL)) {
931 right->Parent = occ1;
935 occ1->setRight(occ2);
940 if (occ2->Depth > 0) {
942 mindepth = occ1->Depth;
945 mindepth = occ2->Depth + occ1->Depth;
948 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
949 return ret->MinOccurrence->OccFor;
951 return occmin->OccFor;
954 void ETNode::assignDFSNumber(int num) {
955 std::vector<ETNode *> workStack;
956 std::set<ETNode *> visitedNodes;
958 workStack.push_back(this);
959 visitedNodes.insert(this);
960 this->DFSNumIn = num++;
962 while (!workStack.empty()) {
963 ETNode *Node = workStack.back();
965 // If this is leaf node then set DFSNumOut and pop the stack
967 Node->DFSNumOut = num++;
968 workStack.pop_back();
972 ETNode *son = Node->Son;
974 // Visit Node->Son first
975 if (visitedNodes.count(son) == 0) {
976 son->DFSNumIn = num++;
977 workStack.push_back(son);
978 visitedNodes.insert(son);
982 bool visitChild = false;
983 // Visit remaining children
984 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
985 if (visitedNodes.count(s) == 0) {
988 workStack.push_back(s);
989 visitedNodes.insert(s);
994 // If we reach here means all children are visited
995 Node->DFSNumOut = num++;
996 workStack.pop_back();
1001 //===----------------------------------------------------------------------===//
1002 // ETForest implementation
1003 //===----------------------------------------------------------------------===//
1005 char ETForest::ID = 0;
1006 static RegisterPass<ETForest>
1007 D("etforest", "ET Forest Construction", true);
1009 void ETForestBase::reset() {
1010 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1015 void ETForestBase::updateDFSNumbers()
1018 // Iterate over all nodes in depth first order.
1019 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1020 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1021 E = df_end(Roots[i]); I != E; ++I) {
1022 BasicBlock *BB = *I;
1023 ETNode *ETN = getNode(BB);
1024 if (ETN && !ETN->hasFather())
1025 ETN->assignDFSNumber(dfsnum);
1028 DFSInfoValid = true;
1031 // dominates - Return true if A dominates B. THis performs the
1032 // special checks necessary if A and B are in the same basic block.
1033 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1034 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1035 if (BBA != BBB) return dominates(BBA, BBB);
1037 // It is not possible to determine dominance between two PHI nodes
1038 // based on their ordering.
1039 if (isa<PHINode>(A) && isa<PHINode>(B))
1042 // Loop through the basic block until we find A or B.
1043 BasicBlock::iterator I = BBA->begin();
1044 for (; &*I != A && &*I != B; ++I) /*empty*/;
1046 if(!IsPostDominators) {
1047 // A dominates B if it is found first in the basic block.
1050 // A post-dominates B if B is found first in the basic block.
1055 /// isReachableFromEntry - Return true if A is dominated by the entry
1056 /// block of the function containing it.
1057 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1058 return dominates(&A->getParent()->getEntryBlock(), A);
1061 // FIXME : There is no need to make getNodeForBlock public. Fix
1062 // predicate simplifier.
1063 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1064 ETNode *&BBNode = Nodes[BB];
1065 if (BBNode) return BBNode;
1067 // Haven't calculated this node yet? Get or calculate the node for the
1068 // immediate dominator.
1069 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1071 // If we are unreachable, we may not have an immediate dominator.
1072 if (!node || !node->getIDom())
1073 return BBNode = new ETNode(BB);
1075 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1077 // Add a new tree node for this BasicBlock, and link it as a child of
1079 BBNode = new ETNode(BB);
1080 BBNode->setFather(IDomNode);
1085 void ETForest::calculate(const DominatorTree &DT) {
1086 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1087 BasicBlock *Root = Roots[0];
1088 Nodes[Root] = new ETNode(Root); // Add a node for the root
1090 Function *F = Root->getParent();
1091 // Loop over all of the reachable blocks in the function...
1092 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1093 DomTreeNode* node = DT.getNode(I);
1094 if (node && node->getIDom()) { // Reachable block.
1095 BasicBlock* ImmDom = node->getIDom()->getBlock();
1096 ETNode *&BBNode = Nodes[I];
1097 if (!BBNode) { // Haven't calculated this node yet?
1098 // Get or calculate the node for the immediate dominator
1099 ETNode *IDomNode = getNodeForBlock(ImmDom);
1101 // Add a new ETNode for this BasicBlock, and set it's parent
1102 // to it's immediate dominator.
1103 BBNode = new ETNode(I);
1104 BBNode->setFather(IDomNode);
1109 // Make sure we've got nodes around for every block
1110 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1111 ETNode *&BBNode = Nodes[I];
1113 BBNode = new ETNode(I);
1116 updateDFSNumbers ();
1119 //===----------------------------------------------------------------------===//
1120 // ETForestBase Implementation
1121 //===----------------------------------------------------------------------===//
1123 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1124 ETNode *&BBNode = Nodes[BB];
1125 assert(!BBNode && "BasicBlock already in ET-Forest");
1127 BBNode = new ETNode(BB);
1128 BBNode->setFather(getNode(IDom));
1129 DFSInfoValid = false;
1132 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1133 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1134 assert(getNode(newIDom) && "IDom not in ET-Forest");
1136 ETNode *Node = getNode(BB);
1137 if (Node->hasFather()) {
1138 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1142 Node->setFather(getNode(newIDom));
1143 DFSInfoValid= false;
1146 void ETForestBase::print(std::ostream &o, const Module *) const {
1147 o << "=============================--------------------------------\n";
1148 o << "ET Forest:\n";
1154 o << " up to date\n";
1156 Function *F = getRoots()[0]->getParent();
1157 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1158 o << " DFS Numbers For Basic Block:";
1159 WriteAsOperand(o, I, false);
1161 if (ETNode *EN = getNode(I)) {
1162 o << "In: " << EN->getDFSNumIn();
1163 o << " Out: " << EN->getDFSNumOut() << "\n";
1165 o << "No associated ETNode";
1172 void ETForestBase::dump() {