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"
30 static std::ostream &operator<<(std::ostream &o,
31 const std::set<BasicBlock*> &BBs) {
32 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
35 WriteAsOperand(o, *I, false);
37 o << " <<exit node>>";
42 //===----------------------------------------------------------------------===//
43 // DominatorTree Implementation
44 //===----------------------------------------------------------------------===//
46 // DominatorTree construction - This pass constructs immediate dominator
47 // information for a flow-graph based on the algorithm described in this
50 // A Fast Algorithm for Finding Dominators in a Flowgraph
51 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
53 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
54 // LINK, but it turns out that the theoretically slower O(n*log(n))
55 // implementation is actually faster than the "efficient" algorithm (even for
56 // large CFGs) because the constant overheads are substantially smaller. The
57 // lower-complexity version can be enabled with the following #define:
59 #define BALANCE_IDOM_TREE 0
61 //===----------------------------------------------------------------------===//
63 char DominatorTree::ID = 0;
64 static RegisterPass<DominatorTree>
65 E("domtree", "Dominator Tree Construction", true);
67 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
69 // This is more understandable as a recursive algorithm, but we can't use the
70 // recursive algorithm due to stack depth issues. Keep it here for
71 // documentation purposes.
76 Vertex.push_back(V); // Vertex[n] = V;
77 //Info[V].Ancestor = 0; // Ancestor[n] = 0
78 //Info[V].Child = 0; // Child[v] = 0
79 VInfo.Size = 1; // Size[v] = 1
81 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
82 InfoRec &SuccVInfo = Info[*SI];
83 if (SuccVInfo.Semi == 0) {
85 N = DFSPass(*SI, SuccVInfo, N);
89 std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
90 Worklist.push_back(std::make_pair(V, 0U));
91 while (!Worklist.empty()) {
92 BasicBlock *BB = Worklist.back().first;
93 unsigned NextSucc = Worklist.back().second;
95 // First time we visited this BB?
97 InfoRec &BBInfo = Info[BB];
101 Vertex.push_back(BB); // Vertex[n] = V;
102 //BBInfo[V].Ancestor = 0; // Ancestor[n] = 0
103 //BBInfo[V].Child = 0; // Child[v] = 0
104 BBInfo.Size = 1; // Size[v] = 1
107 // If we are done with this block, remove it from the worklist.
108 if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
113 // Otherwise, increment the successor number for the next time we get to it.
114 ++Worklist.back().second;
116 // Visit the successor next, if it isn't already visited.
117 BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
119 InfoRec &SuccVInfo = Info[Succ];
120 if (SuccVInfo.Semi == 0) {
121 SuccVInfo.Parent = BB;
122 Worklist.push_back(std::make_pair(Succ, 0U));
129 void DominatorTree::Compress(BasicBlock *VIn) {
131 std::vector<BasicBlock *> Work;
132 std::set<BasicBlock *> Visited;
133 InfoRec &VInInfo = Info[VIn];
134 BasicBlock *VInAncestor = VInInfo.Ancestor;
135 InfoRec &VInVAInfo = Info[VInAncestor];
137 if (VInVAInfo.Ancestor != 0)
140 while (!Work.empty()) {
141 BasicBlock *V = Work.back();
142 InfoRec &VInfo = Info[V];
143 BasicBlock *VAncestor = VInfo.Ancestor;
144 InfoRec &VAInfo = Info[VAncestor];
146 // Process Ancestor first
147 if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
148 Work.push_back(VAncestor);
149 Visited.insert(VAncestor);
154 // Update VINfo based on Ancestor info
155 if (VAInfo.Ancestor == 0)
157 BasicBlock *VAncestorLabel = VAInfo.Label;
158 BasicBlock *VLabel = VInfo.Label;
159 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
160 VInfo.Label = VAncestorLabel;
161 VInfo.Ancestor = VAInfo.Ancestor;
165 BasicBlock *DominatorTree::Eval(BasicBlock *V) {
166 InfoRec &VInfo = Info[V];
167 #if !BALANCE_IDOM_TREE
168 // Higher-complexity but faster implementation
169 if (VInfo.Ancestor == 0)
174 // Lower-complexity but slower implementation
175 if (VInfo.Ancestor == 0)
178 BasicBlock *VLabel = VInfo.Label;
180 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
181 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
184 return VAncestorLabel;
188 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
189 #if !BALANCE_IDOM_TREE
190 // Higher-complexity but faster implementation
193 // Lower-complexity but slower implementation
194 BasicBlock *WLabel = WInfo.Label;
195 unsigned WLabelSemi = Info[WLabel].Semi;
197 InfoRec *SInfo = &Info[S];
199 BasicBlock *SChild = SInfo->Child;
200 InfoRec *SChildInfo = &Info[SChild];
202 while (WLabelSemi < Info[SChildInfo->Label].Semi) {
203 BasicBlock *SChildChild = SChildInfo->Child;
204 if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
205 SChildInfo->Ancestor = S;
206 SInfo->Child = SChild = SChildChild;
207 SChildInfo = &Info[SChild];
209 SChildInfo->Size = SInfo->Size;
210 S = SInfo->Ancestor = SChild;
212 SChild = SChildChild;
213 SChildInfo = &Info[SChild];
217 InfoRec &VInfo = Info[V];
218 SInfo->Label = WLabel;
220 assert(V != W && "The optimization here will not work in this case!");
221 unsigned WSize = WInfo.Size;
222 unsigned VSize = (VInfo.Size += WSize);
225 std::swap(S, VInfo.Child);
235 void DominatorTree::calculate(Function& F) {
236 BasicBlock* Root = Roots[0];
238 // Add a node for the root...
239 ETNode *ERoot = new ETNode(Root);
240 ETNodes[Root] = ERoot;
241 DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0, ERoot);
245 // Step #1: Number blocks in depth-first order and initialize variables used
246 // in later stages of the algorithm.
248 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
249 N = DFSPass(Roots[i], Info[Roots[i]], 0);
251 for (unsigned i = N; i >= 2; --i) {
252 BasicBlock *W = Vertex[i];
253 InfoRec &WInfo = Info[W];
255 // Step #2: Calculate the semidominators of all vertices
256 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
257 if (Info.count(*PI)) { // Only if this predecessor is reachable!
258 unsigned SemiU = Info[Eval(*PI)].Semi;
259 if (SemiU < WInfo.Semi)
263 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
265 BasicBlock *WParent = WInfo.Parent;
266 Link(WParent, W, WInfo);
268 // Step #3: Implicitly define the immediate dominator of vertices
269 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
270 while (!WParentBucket.empty()) {
271 BasicBlock *V = WParentBucket.back();
272 WParentBucket.pop_back();
273 BasicBlock *U = Eval(V);
274 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
278 // Step #4: Explicitly define the immediate dominator of each vertex
279 for (unsigned i = 2; i <= N; ++i) {
280 BasicBlock *W = Vertex[i];
281 BasicBlock *&WIDom = IDoms[W];
282 if (WIDom != Vertex[Info[W].Semi])
283 WIDom = IDoms[WIDom];
286 // Loop over all of the reachable blocks in the function...
287 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
288 if (BasicBlock *ImmDom = getIDom(I)) { // Reachable block.
289 DomTreeNode *&BBNode = DomTreeNodes[I];
290 if (!BBNode) { // Haven't calculated this node yet?
291 // Get or calculate the node for the immediate dominator
292 DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
294 // Add a new tree node for this BasicBlock, and link it as a child of
296 ETNode *ET = new ETNode(I);
298 DomTreeNode *C = new DomTreeNode(I, IDomNode, ET);
300 BBNode = IDomNode->addChild(C);
304 // Free temporary memory used to construct idom's
307 std::vector<BasicBlock*>().swap(Vertex);
312 void DominatorTreeBase::updateDFSNumbers()
315 // Iterate over all nodes in depth first order.
316 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
317 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
318 E = df_end(Roots[i]); I != E; ++I) {
320 DomTreeNode *BBNode = getNode(BB);
322 if (!BBNode->getIDom())
323 BBNode->assignDFSNumber(dfsnum);
324 //ETNode *ETN = BBNode->getETNode();
325 //if (ETN && !ETN->hasFather())
326 // ETN->assignDFSNumber(dfsnum);
333 /// isReachableFromEntry - Return true if A is dominated by the entry
334 /// block of the function containing it.
335 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
336 return dominates(&A->getParent()->getEntryBlock(), A);
339 // dominates - Return true if A dominates B. THis performs the
340 // special checks necessary if A and B are in the same basic block.
341 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
342 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
343 if (BBA != BBB) return dominates(BBA, BBB);
345 // It is not possible to determine dominance between two PHI nodes
346 // based on their ordering.
347 if (isa<PHINode>(A) && isa<PHINode>(B))
350 // Loop through the basic block until we find A or B.
351 BasicBlock::iterator I = BBA->begin();
352 for (; &*I != A && &*I != B; ++I) /*empty*/;
354 if(!IsPostDominators) {
355 // A dominates B if it is found first in the basic block.
358 // A post-dominates B if B is found first in the basic block.
363 // DominatorTreeBase::reset - Free all of the tree node memory.
365 void DominatorTreeBase::reset() {
366 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), 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, BasicBlock *B) {
379 assert (!isPostDominator() && "This is not implemented for post dominators");
380 assert (A->getParent() == B->getParent() && "Two blocks are not in same function");
382 // If either A or B is a entry block then it is nearest common dominator.
383 BasicBlock &Entry = A->getParent()->getEntryBlock();
384 if (A == &Entry || B == &Entry)
387 // If A and B are same then A is nearest common dominator.
388 DomTreeNode *NodeA = getNode(A);
389 if (A != 0 && A == B)
392 DomTreeNode *NodeB = getNode(B);
394 // Collect NodeA dominators set.
395 std::set<DomTreeNode *> NodeADoms;
396 NodeADoms.insert(NodeA);
397 DomTreeNode *IDomA = NodeA->getIDom();
399 NodeADoms.insert(IDomA);
400 IDomA = IDomA->getIDom();
403 // If B dominates A then B is nearest common dominator.
404 if (NodeADoms.count(NodeB) != 0)
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);
465 if (!ETN->hasFather())
466 ETN->setFather(IDom->getETNode());
467 else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
469 ETN->setFather(IDom->getETNode());
474 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
475 DomTreeNode *&BBNode = DomTreeNodes[BB];
476 if (BBNode) return BBNode;
478 // Haven't calculated this node yet? Get or calculate the node for the
479 // immediate dominator.
480 BasicBlock *IDom = getIDom(BB);
481 DomTreeNode *IDomNode = getNodeForBlock(IDom);
483 // Add a new tree node for this BasicBlock, and link it as a child of
485 ETNode *ET = new ETNode(BB);
487 DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
488 DomTreeNodes[BB] = C;
489 return BBNode = IDomNode->addChild(C);
492 static std::ostream &operator<<(std::ostream &o,
493 const DomTreeNode *Node) {
494 if (Node->getBlock())
495 WriteAsOperand(o, Node->getBlock(), false);
497 o << " <<exit node>>";
501 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
503 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
504 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
506 PrintDomTree(*I, o, Lev+1);
509 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
510 o << "=============================--------------------------------\n"
511 << "Inorder Dominator Tree:\n";
512 PrintDomTree(getRootNode(), o, 1);
515 void DominatorTreeBase::dump() {
519 bool DominatorTree::runOnFunction(Function &F) {
520 reset(); // Reset from the last time we were run...
521 Roots.push_back(&F.getEntryBlock());
526 //===----------------------------------------------------------------------===//
527 // DominanceFrontier Implementation
528 //===----------------------------------------------------------------------===//
530 char DominanceFrontier::ID = 0;
531 static RegisterPass<DominanceFrontier>
532 G("domfrontier", "Dominance Frontier Construction", true);
535 class DFCalculateWorkObject {
537 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
538 const DomTreeNode *N,
539 const DomTreeNode *PN)
540 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
541 BasicBlock *currentBB;
542 BasicBlock *parentBB;
543 const DomTreeNode *Node;
544 const DomTreeNode *parentNode;
548 const DominanceFrontier::DomSetType &
549 DominanceFrontier::calculate(const DominatorTree &DT,
550 const DomTreeNode *Node) {
551 BasicBlock *BB = Node->getBlock();
552 DomSetType *Result = NULL;
554 std::vector<DFCalculateWorkObject> workList;
555 SmallPtrSet<BasicBlock *, 32> visited;
557 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
559 DFCalculateWorkObject *currentW = &workList.back();
560 assert (currentW && "Missing work object.");
562 BasicBlock *currentBB = currentW->currentBB;
563 BasicBlock *parentBB = currentW->parentBB;
564 const DomTreeNode *currentNode = currentW->Node;
565 const DomTreeNode *parentNode = currentW->parentNode;
566 assert (currentBB && "Invalid work object. Missing current Basic Block");
567 assert (currentNode && "Invalid work object. Missing current Node");
568 DomSetType &S = Frontiers[currentBB];
570 // Visit each block only once.
571 if (visited.count(currentBB) == 0) {
572 visited.insert(currentBB);
574 // Loop over CFG successors to calculate DFlocal[currentNode]
575 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
577 // Does Node immediately dominate this successor?
578 if (DT[*SI]->getIDom() != currentNode)
583 // At this point, S is DFlocal. Now we union in DFup's of our children...
584 // Loop through and visit the nodes that Node immediately dominates (Node's
585 // children in the IDomTree)
586 bool visitChild = false;
587 for (DomTreeNode::const_iterator NI = currentNode->begin(),
588 NE = currentNode->end(); NI != NE; ++NI) {
589 DomTreeNode *IDominee = *NI;
590 BasicBlock *childBB = IDominee->getBlock();
591 if (visited.count(childBB) == 0) {
592 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
593 IDominee, currentNode));
598 // If all children are visited or there is any child then pop this block
599 // from the workList.
607 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
608 DomSetType &parentSet = Frontiers[parentBB];
609 for (; CDFI != CDFE; ++CDFI) {
610 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
611 parentSet.insert(*CDFI);
616 } while (!workList.empty());
621 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
622 for (const_iterator I = begin(), E = end(); I != E; ++I) {
623 o << " DomFrontier for BB";
625 WriteAsOperand(o, I->first, false);
627 o << " <<exit node>>";
628 o << " is:\t" << I->second << "\n";
632 void DominanceFrontierBase::dump() {
637 //===----------------------------------------------------------------------===//
638 // ETOccurrence Implementation
639 //===----------------------------------------------------------------------===//
641 void ETOccurrence::Splay() {
642 ETOccurrence *father;
643 ETOccurrence *grandfather;
651 fatherdepth = Parent->Depth;
652 grandfather = father->Parent;
654 // If we have no grandparent, a single zig or zag will do.
656 setDepthAdd(fatherdepth);
657 MinOccurrence = father->MinOccurrence;
660 // See what we have to rotate
661 if (father->Left == this) {
663 father->setLeft(Right);
666 father->Left->setDepthAdd(occdepth);
669 father->setRight(Left);
672 father->Right->setDepthAdd(occdepth);
674 father->setDepth(-occdepth);
677 father->recomputeMin();
681 // If we have a grandfather, we need to do some
682 // combination of zig and zag.
683 int grandfatherdepth = grandfather->Depth;
685 setDepthAdd(fatherdepth + grandfatherdepth);
686 MinOccurrence = grandfather->MinOccurrence;
687 Min = grandfather->Min;
689 ETOccurrence *greatgrandfather = grandfather->Parent;
691 if (grandfather->Left == father) {
692 if (father->Left == this) {
694 grandfather->setLeft(father->Right);
695 father->setLeft(Right);
697 father->setRight(grandfather);
699 father->setDepth(-occdepth);
702 father->Left->setDepthAdd(occdepth);
704 grandfather->setDepth(-fatherdepth);
705 if (grandfather->Left)
706 grandfather->Left->setDepthAdd(fatherdepth);
709 grandfather->setLeft(Right);
710 father->setRight(Left);
712 setRight(grandfather);
714 father->setDepth(-occdepth);
716 father->Right->setDepthAdd(occdepth);
717 grandfather->setDepth(-occdepth - fatherdepth);
718 if (grandfather->Left)
719 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
722 if (father->Left == this) {
724 grandfather->setRight(Left);
725 father->setLeft(Right);
726 setLeft(grandfather);
729 father->setDepth(-occdepth);
731 father->Left->setDepthAdd(occdepth);
732 grandfather->setDepth(-occdepth - fatherdepth);
733 if (grandfather->Right)
734 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
736 grandfather->setRight(father->Left);
737 father->setRight(Left);
739 father->setLeft(grandfather);
741 father->setDepth(-occdepth);
743 father->Right->setDepthAdd(occdepth);
744 grandfather->setDepth(-fatherdepth);
745 if (grandfather->Right)
746 grandfather->Right->setDepthAdd(fatherdepth);
750 // Might need one more rotate depending on greatgrandfather.
751 setParent(greatgrandfather);
752 if (greatgrandfather) {
753 if (greatgrandfather->Left == grandfather)
754 greatgrandfather->Left = this;
756 greatgrandfather->Right = this;
759 grandfather->recomputeMin();
760 father->recomputeMin();
764 //===----------------------------------------------------------------------===//
765 // ETNode implementation
766 //===----------------------------------------------------------------------===//
768 void ETNode::Split() {
769 ETOccurrence *right, *left;
770 ETOccurrence *rightmost = RightmostOcc;
771 ETOccurrence *parent;
773 // Update the occurrence tree first.
774 RightmostOcc->Splay();
776 // Find the leftmost occurrence in the rightmost subtree, then splay
778 for (right = rightmost->Right; right->Left; right = right->Left);
783 right->Left->Parent = NULL;
789 parent->Right->Parent = NULL;
791 right->setLeft(left);
793 right->recomputeMin();
796 rightmost->Depth = 0;
801 // Now update *our* tree
803 if (Father->Son == this)
806 if (Father->Son == this)
816 void ETNode::setFather(ETNode *NewFather) {
817 ETOccurrence *rightmost;
818 ETOccurrence *leftpart;
819 ETOccurrence *NewFatherOcc;
822 // First update the path in the splay tree
823 NewFatherOcc = new ETOccurrence(NewFather);
825 rightmost = NewFather->RightmostOcc;
828 leftpart = rightmost->Left;
833 NewFatherOcc->setLeft(leftpart);
834 NewFatherOcc->setRight(temp);
838 NewFatherOcc->recomputeMin();
840 rightmost->setLeft(NewFatherOcc);
842 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
843 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
844 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
848 ParentOcc = NewFatherOcc;
870 bool ETNode::Below(ETNode *other) {
871 ETOccurrence *up = other->RightmostOcc;
872 ETOccurrence *down = RightmostOcc;
879 ETOccurrence *left, *right;
889 right->Parent = NULL;
893 if (left == down || left->Parent != NULL) {
900 // If the two occurrences are in different trees, put things
901 // back the way they were.
902 if (right && right->Parent != NULL)
909 if (down->Depth <= 0)
912 return !down->Right || down->Right->Min + down->Depth >= 0;
915 ETNode *ETNode::NCA(ETNode *other) {
916 ETOccurrence *occ1 = RightmostOcc;
917 ETOccurrence *occ2 = other->RightmostOcc;
919 ETOccurrence *left, *right, *ret;
920 ETOccurrence *occmin;
934 right->Parent = NULL;
937 if (left == occ2 || (left && left->Parent != NULL)) {
942 right->Parent = occ1;
946 occ1->setRight(occ2);
951 if (occ2->Depth > 0) {
953 mindepth = occ1->Depth;
956 mindepth = occ2->Depth + occ1->Depth;
959 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
960 return ret->MinOccurrence->OccFor;
962 return occmin->OccFor;
965 void ETNode::assignDFSNumber(int num) {
966 std::vector<ETNode *> workStack;
967 std::set<ETNode *> visitedNodes;
969 workStack.push_back(this);
970 visitedNodes.insert(this);
971 this->DFSNumIn = num++;
973 while (!workStack.empty()) {
974 ETNode *Node = workStack.back();
976 // If this is leaf node then set DFSNumOut and pop the stack
978 Node->DFSNumOut = num++;
979 workStack.pop_back();
983 ETNode *son = Node->Son;
985 // Visit Node->Son first
986 if (visitedNodes.count(son) == 0) {
987 son->DFSNumIn = num++;
988 workStack.push_back(son);
989 visitedNodes.insert(son);
993 bool visitChild = false;
994 // Visit remaining children
995 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
996 if (visitedNodes.count(s) == 0) {
999 workStack.push_back(s);
1000 visitedNodes.insert(s);
1005 // If we reach here means all children are visited
1006 Node->DFSNumOut = num++;
1007 workStack.pop_back();
1012 //===----------------------------------------------------------------------===//
1013 // ETForest implementation
1014 //===----------------------------------------------------------------------===//
1016 char ETForest::ID = 0;
1017 static RegisterPass<ETForest>
1018 D("etforest", "ET Forest Construction", true);
1020 void ETForestBase::reset() {
1021 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
1026 void ETForestBase::updateDFSNumbers()
1029 // Iterate over all nodes in depth first order.
1030 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
1031 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
1032 E = df_end(Roots[i]); I != E; ++I) {
1033 BasicBlock *BB = *I;
1034 ETNode *ETN = getNode(BB);
1035 if (ETN && !ETN->hasFather())
1036 ETN->assignDFSNumber(dfsnum);
1039 DFSInfoValid = true;
1042 // dominates - Return true if A dominates B. THis performs the
1043 // special checks necessary if A and B are in the same basic block.
1044 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1045 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1046 if (BBA != BBB) return dominates(BBA, BBB);
1048 // It is not possible to determine dominance between two PHI nodes
1049 // based on their ordering.
1050 if (isa<PHINode>(A) && isa<PHINode>(B))
1053 // Loop through the basic block until we find A or B.
1054 BasicBlock::iterator I = BBA->begin();
1055 for (; &*I != A && &*I != B; ++I) /*empty*/;
1057 if(!IsPostDominators) {
1058 // A dominates B if it is found first in the basic block.
1061 // A post-dominates B if B is found first in the basic block.
1066 /// isReachableFromEntry - Return true if A is dominated by the entry
1067 /// block of the function containing it.
1068 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1069 return dominates(&A->getParent()->getEntryBlock(), A);
1072 // FIXME : There is no need to make getNodeForBlock public. Fix
1073 // predicate simplifier.
1074 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1075 ETNode *&BBNode = Nodes[BB];
1076 if (BBNode) return BBNode;
1078 // Haven't calculated this node yet? Get or calculate the node for the
1079 // immediate dominator.
1080 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1082 // If we are unreachable, we may not have an immediate dominator.
1083 if (!node || !node->getIDom())
1084 return BBNode = new ETNode(BB);
1086 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1088 // Add a new tree node for this BasicBlock, and link it as a child of
1090 BBNode = new ETNode(BB);
1091 BBNode->setFather(IDomNode);
1096 void ETForest::calculate(const DominatorTree &DT) {
1097 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1098 BasicBlock *Root = Roots[0];
1099 Nodes[Root] = new ETNode(Root); // Add a node for the root
1101 Function *F = Root->getParent();
1102 // Loop over all of the reachable blocks in the function...
1103 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1104 DomTreeNode* node = DT.getNode(I);
1105 if (node && node->getIDom()) { // Reachable block.
1106 BasicBlock* ImmDom = node->getIDom()->getBlock();
1107 ETNode *&BBNode = Nodes[I];
1108 if (!BBNode) { // Haven't calculated this node yet?
1109 // Get or calculate the node for the immediate dominator
1110 ETNode *IDomNode = getNodeForBlock(ImmDom);
1112 // Add a new ETNode for this BasicBlock, and set it's parent
1113 // to it's immediate dominator.
1114 BBNode = new ETNode(I);
1115 BBNode->setFather(IDomNode);
1120 // Make sure we've got nodes around for every block
1121 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1122 ETNode *&BBNode = Nodes[I];
1124 BBNode = new ETNode(I);
1127 updateDFSNumbers ();
1130 //===----------------------------------------------------------------------===//
1131 // ETForestBase Implementation
1132 //===----------------------------------------------------------------------===//
1134 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1135 ETNode *&BBNode = Nodes[BB];
1136 assert(!BBNode && "BasicBlock already in ET-Forest");
1138 BBNode = new ETNode(BB);
1139 BBNode->setFather(getNode(IDom));
1140 DFSInfoValid = false;
1143 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1144 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1145 assert(getNode(newIDom) && "IDom not in ET-Forest");
1147 ETNode *Node = getNode(BB);
1148 if (Node->hasFather()) {
1149 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1153 Node->setFather(getNode(newIDom));
1154 DFSInfoValid= false;
1157 void ETForestBase::print(std::ostream &o, const Module *) const {
1158 o << "=============================--------------------------------\n";
1159 o << "ET Forest:\n";
1165 o << " up to date\n";
1167 Function *F = getRoots()[0]->getParent();
1168 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1169 o << " DFS Numbers For Basic Block:";
1170 WriteAsOperand(o, I, false);
1172 if (ETNode *EN = getNode(I)) {
1173 o << "In: " << EN->getDFSNumIn();
1174 o << " Out: " << EN->getDFSNumOut() << "\n";
1176 o << "No associated ETNode";
1183 void ETForestBase::dump() {