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/ADT/SmallVector.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/Streams.h"
26 #include "DominatorCalculation.h"
31 static std::ostream &operator<<(std::ostream &o,
32 const std::set<BasicBlock*> &BBs) {
33 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
36 WriteAsOperand(o, *I, false);
38 o << " <<exit node>>";
43 //===----------------------------------------------------------------------===//
44 // DominatorTree Implementation
45 //===----------------------------------------------------------------------===//
47 // Provide public access to DominatorTree information. Implementation details
48 // can be found in DominatorCalculation.h.
50 //===----------------------------------------------------------------------===//
52 char DominatorTree::ID = 0;
53 static RegisterPass<DominatorTree>
54 E("domtree", "Dominator Tree Construction", true);
56 // NewBB is split and now it has one successor. Update dominator tree to
57 // reflect this change.
58 void DominatorTree::splitBlock(BasicBlock *NewBB) {
59 assert(NewBB->getTerminator()->getNumSuccessors() == 1
60 && "NewBB should have a single successor!");
61 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
63 std::vector<BasicBlock*> PredBlocks;
64 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
66 PredBlocks.push_back(*PI);
68 assert(!PredBlocks.empty() && "No predblocks??");
70 // The newly inserted basic block will dominate existing basic blocks iff the
71 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
72 // the non-pred blocks, then they all must be the same block!
74 bool NewBBDominatesNewBBSucc = true;
76 BasicBlock *OnePred = PredBlocks[0];
77 unsigned i = 1, e = PredBlocks.size();
78 for (i = 1; !isReachableFromEntry(OnePred); ++i) {
79 assert(i != e && "Didn't find reachable pred?");
80 OnePred = PredBlocks[i];
84 if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)) {
85 NewBBDominatesNewBBSucc = false;
89 if (NewBBDominatesNewBBSucc)
90 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
92 if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
93 NewBBDominatesNewBBSucc = false;
98 // The other scenario where the new block can dominate its successors are when
99 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
101 if (!NewBBDominatesNewBBSucc) {
102 NewBBDominatesNewBBSucc = true;
103 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
105 if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
106 NewBBDominatesNewBBSucc = false;
111 // Find NewBB's immediate dominator and create new dominator tree node for
113 BasicBlock *NewBBIDom = 0;
115 for (i = 0; i < PredBlocks.size(); ++i)
116 if (isReachableFromEntry(PredBlocks[i])) {
117 NewBBIDom = PredBlocks[i];
120 assert(i != PredBlocks.size() && "No reachable preds?");
121 for (i = i + 1; i < PredBlocks.size(); ++i) {
122 if (isReachableFromEntry(PredBlocks[i]))
123 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
125 assert(NewBBIDom && "No immediate dominator found??");
127 // Create the new dominator tree node... and set the idom of NewBB.
128 DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
130 // If NewBB strictly dominates other blocks, then it is now the immediate
131 // dominator of NewBBSucc. Update the dominator tree as appropriate.
132 if (NewBBDominatesNewBBSucc) {
133 DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
134 changeImmediateDominator(NewBBSuccNode, NewBBNode);
138 void DominatorTreeBase::updateDFSNumbers() {
141 SmallVector<std::pair<DomTreeNode*, DomTreeNode::iterator>, 32> WorkStack;
143 for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
144 DomTreeNode *ThisRoot = getNode(Roots[i]);
145 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
146 ThisRoot->DFSNumIn = DFSNum++;
148 while (!WorkStack.empty()) {
149 DomTreeNode *Node = WorkStack.back().first;
150 DomTreeNode::iterator ChildIt = WorkStack.back().second;
152 // If we visited all of the children of this node, "recurse" back up the
153 // stack setting the DFOutNum.
154 if (ChildIt == Node->end()) {
155 Node->DFSNumOut = DFSNum++;
156 WorkStack.pop_back();
158 // Otherwise, recursively visit this child.
159 DomTreeNode *Child = *ChildIt;
160 ++WorkStack.back().second;
162 WorkStack.push_back(std::make_pair(Child, Child->begin()));
163 Child->DFSNumIn = DFSNum++;
172 /// isReachableFromEntry - Return true if A is dominated by the entry
173 /// block of the function containing it.
174 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
175 assert (!isPostDominator()
176 && "This is not implemented for post dominators");
177 return dominates(&A->getParent()->getEntryBlock(), A);
180 // dominates - Return true if A dominates B. THis performs the
181 // special checks necessary if A and B are in the same basic block.
182 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
183 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
184 if (BBA != BBB) return dominates(BBA, BBB);
186 // It is not possible to determine dominance between two PHI nodes
187 // based on their ordering.
188 if (isa<PHINode>(A) && isa<PHINode>(B))
191 // Loop through the basic block until we find A or B.
192 BasicBlock::iterator I = BBA->begin();
193 for (; &*I != A && &*I != B; ++I) /*empty*/;
195 if(!IsPostDominators) {
196 // A dominates B if it is found first in the basic block.
199 // A post-dominates B if B is found first in the basic block.
204 // DominatorTreeBase::reset - Free all of the tree node memory.
206 void DominatorTreeBase::reset() {
207 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(),
208 E = DomTreeNodes.end(); I != E; ++I)
210 DomTreeNodes.clear();
217 DomTreeNode *DominatorTreeBase::getNodeForBlock(BasicBlock *BB) {
218 if (DomTreeNode *BBNode = DomTreeNodes[BB])
221 // Haven't calculated this node yet? Get or calculate the node for the
222 // immediate dominator.
223 BasicBlock *IDom = getIDom(BB);
224 DomTreeNode *IDomNode = getNodeForBlock(IDom);
226 // Add a new tree node for this BasicBlock, and link it as a child of
228 DomTreeNode *C = new DomTreeNode(BB, IDomNode);
229 return DomTreeNodes[BB] = IDomNode->addChild(C);
232 /// findNearestCommonDominator - Find nearest common dominator basic block
233 /// for basic block A and B. If there is no such block then return NULL.
234 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A,
237 assert (!isPostDominator()
238 && "This is not implemented for post dominators");
239 assert (A->getParent() == B->getParent()
240 && "Two blocks are not in same function");
242 // If either A or B is a entry block then it is nearest common dominator.
243 BasicBlock &Entry = A->getParent()->getEntryBlock();
244 if (A == &Entry || B == &Entry)
247 // If B dominates A then B is nearest common dominator.
251 // If A dominates B then A is nearest common dominator.
255 DomTreeNode *NodeA = getNode(A);
256 DomTreeNode *NodeB = getNode(B);
258 // Collect NodeA dominators set.
259 SmallPtrSet<DomTreeNode*, 16> NodeADoms;
260 NodeADoms.insert(NodeA);
261 DomTreeNode *IDomA = NodeA->getIDom();
263 NodeADoms.insert(IDomA);
264 IDomA = IDomA->getIDom();
267 // Walk NodeB immediate dominators chain and find common dominator node.
268 DomTreeNode *IDomB = NodeB->getIDom();
270 if (NodeADoms.count(IDomB) != 0)
271 return IDomB->getBlock();
273 IDomB = IDomB->getIDom();
279 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
280 assert(IDom && "No immediate dominator?");
281 if (IDom != NewIDom) {
282 std::vector<DomTreeNode*>::iterator I =
283 std::find(IDom->Children.begin(), IDom->Children.end(), this);
284 assert(I != IDom->Children.end() &&
285 "Not in immediate dominator children set!");
286 // I am no longer your child...
287 IDom->Children.erase(I);
289 // Switch to new dominator
291 IDom->Children.push_back(this);
295 static std::ostream &operator<<(std::ostream &o, const DomTreeNode *Node) {
296 if (Node->getBlock())
297 WriteAsOperand(o, Node->getBlock(), false);
299 o << " <<exit node>>";
301 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
306 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
308 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
309 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
311 PrintDomTree(*I, o, Lev+1);
314 /// eraseNode - Removes a node from the domiantor tree. Block must not
315 /// domiante any other blocks. Removes node from its immediate dominator's
316 /// children list. Deletes dominator node associated with basic block BB.
317 void DominatorTreeBase::eraseNode(BasicBlock *BB) {
318 DomTreeNode *Node = getNode(BB);
319 assert (Node && "Removing node that isn't in dominator tree.");
320 assert (Node->getChildren().empty() && "Node is not a leaf node.");
322 // Remove node from immediate dominator's children list.
323 DomTreeNode *IDom = Node->getIDom();
325 std::vector<DomTreeNode*>::iterator I =
326 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
327 assert(I != IDom->Children.end() &&
328 "Not in immediate dominator children set!");
329 // I am no longer your child...
330 IDom->Children.erase(I);
333 DomTreeNodes.erase(BB);
337 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
338 o << "=============================--------------------------------\n";
339 o << "Inorder Dominator Tree: ";
341 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
344 PrintDomTree(getRootNode(), o, 1);
347 void DominatorTreeBase::dump() {
351 bool DominatorTree::runOnFunction(Function &F) {
352 reset(); // Reset from the last time we were run...
353 Roots.push_back(&F.getEntryBlock());
354 DTcalculate(*this, F);
358 //===----------------------------------------------------------------------===//
359 // DominanceFrontier Implementation
360 //===----------------------------------------------------------------------===//
362 char DominanceFrontier::ID = 0;
363 static RegisterPass<DominanceFrontier>
364 G("domfrontier", "Dominance Frontier Construction", true);
366 // NewBB is split and now it has one successor. Update dominace frontier to
367 // reflect this change.
368 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
369 assert(NewBB->getTerminator()->getNumSuccessors() == 1
370 && "NewBB should have a single successor!");
371 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
373 std::vector<BasicBlock*> PredBlocks;
374 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
376 PredBlocks.push_back(*PI);
378 if (PredBlocks.empty())
379 // If NewBB does not have any predecessors then it is a entry block.
380 // In this case, NewBB and its successor NewBBSucc dominates all
384 // NewBBSucc inherits original NewBB frontier.
385 DominanceFrontier::iterator NewBBI = find(NewBB);
386 if (NewBBI != end()) {
387 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
388 DominanceFrontier::DomSetType NewBBSuccSet;
389 NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
390 addBasicBlock(NewBBSucc, NewBBSuccSet);
393 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
394 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
396 DominatorTree &DT = getAnalysis<DominatorTree>();
397 if (DT.dominates(NewBB, NewBBSucc)) {
398 DominanceFrontier::iterator DFI = find(PredBlocks[0]);
400 DominanceFrontier::DomSetType Set = DFI->second;
401 // Filter out stuff in Set that we do not dominate a predecessor of.
402 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
403 E = Set.end(); SetI != E;) {
404 bool DominatesPred = false;
405 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
407 if (DT.dominates(NewBB, *PI))
408 DominatesPred = true;
415 if (NewBBI != end()) {
416 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
417 NewBBSet.insert(Set.begin(), Set.end());
419 addBasicBlock(NewBB, Set);
423 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
424 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
425 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
426 DominanceFrontier::DomSetType NewDFSet;
427 NewDFSet.insert(NewBBSucc);
428 addBasicBlock(NewBB, NewDFSet);
431 // Now we must loop over all of the dominance frontiers in the function,
432 // replacing occurrences of NewBBSucc with NewBB in some cases. All
433 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
434 // their dominance frontier must be updated to contain NewBB instead.
436 for (Function::iterator FI = NewBB->getParent()->begin(),
437 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
438 DominanceFrontier::iterator DFI = find(FI);
439 if (DFI == end()) continue; // unreachable block.
441 // Only consider nodes that have NewBBSucc in their dominator frontier.
442 if (!DFI->second.count(NewBBSucc)) continue;
444 // Verify whether this block dominates a block in predblocks. If not, do
446 bool BlockDominatesAny = false;
447 for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(),
448 BE = PredBlocks.end(); BI != BE; ++BI) {
449 if (DT.dominates(FI, *BI)) {
450 BlockDominatesAny = true;
455 if (!BlockDominatesAny)
458 // If NewBBSucc should not stay in our dominator frontier, remove it.
459 // We remove it unless there is a predecessor of NewBBSucc that we
460 // dominate, but we don't strictly dominate NewBBSucc.
461 bool ShouldRemove = true;
462 if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
463 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
464 // Check to see if it dominates any predecessors of NewBBSucc.
465 for (pred_iterator PI = pred_begin(NewBBSucc),
466 E = pred_end(NewBBSucc); PI != E; ++PI)
467 if (DT.dominates(FI, *PI)) {
468 ShouldRemove = false;
474 removeFromFrontier(DFI, NewBBSucc);
475 addToFrontier(DFI, NewBB);
480 class DFCalculateWorkObject {
482 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
483 const DomTreeNode *N,
484 const DomTreeNode *PN)
485 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
486 BasicBlock *currentBB;
487 BasicBlock *parentBB;
488 const DomTreeNode *Node;
489 const DomTreeNode *parentNode;
493 const DominanceFrontier::DomSetType &
494 DominanceFrontier::calculate(const DominatorTree &DT,
495 const DomTreeNode *Node) {
496 BasicBlock *BB = Node->getBlock();
497 DomSetType *Result = NULL;
499 std::vector<DFCalculateWorkObject> workList;
500 SmallPtrSet<BasicBlock *, 32> visited;
502 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
504 DFCalculateWorkObject *currentW = &workList.back();
505 assert (currentW && "Missing work object.");
507 BasicBlock *currentBB = currentW->currentBB;
508 BasicBlock *parentBB = currentW->parentBB;
509 const DomTreeNode *currentNode = currentW->Node;
510 const DomTreeNode *parentNode = currentW->parentNode;
511 assert (currentBB && "Invalid work object. Missing current Basic Block");
512 assert (currentNode && "Invalid work object. Missing current Node");
513 DomSetType &S = Frontiers[currentBB];
515 // Visit each block only once.
516 if (visited.count(currentBB) == 0) {
517 visited.insert(currentBB);
519 // Loop over CFG successors to calculate DFlocal[currentNode]
520 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
522 // Does Node immediately dominate this successor?
523 if (DT[*SI]->getIDom() != currentNode)
528 // At this point, S is DFlocal. Now we union in DFup's of our children...
529 // Loop through and visit the nodes that Node immediately dominates (Node's
530 // children in the IDomTree)
531 bool visitChild = false;
532 for (DomTreeNode::const_iterator NI = currentNode->begin(),
533 NE = currentNode->end(); NI != NE; ++NI) {
534 DomTreeNode *IDominee = *NI;
535 BasicBlock *childBB = IDominee->getBlock();
536 if (visited.count(childBB) == 0) {
537 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
538 IDominee, currentNode));
543 // If all children are visited or there is any child then pop this block
544 // from the workList.
552 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
553 DomSetType &parentSet = Frontiers[parentBB];
554 for (; CDFI != CDFE; ++CDFI) {
555 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
556 parentSet.insert(*CDFI);
561 } while (!workList.empty());
566 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
567 for (const_iterator I = begin(), E = end(); I != E; ++I) {
568 o << " DomFrontier for BB";
570 WriteAsOperand(o, I->first, false);
572 o << " <<exit node>>";
573 o << " is:\t" << I->second << "\n";
577 void DominanceFrontierBase::dump() {