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/Analysis/DominatorInternals.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Support/Streams.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...
355 Roots.push_back(&F.getEntryBlock());
356 IDoms[&F.getEntryBlock()] = 0;
357 DomTreeNodes[&F.getEntryBlock()] = 0;
360 Calculate<BasicBlock*>(*this, F);
367 //===----------------------------------------------------------------------===//
368 // DominanceFrontier Implementation
369 //===----------------------------------------------------------------------===//
371 char DominanceFrontier::ID = 0;
372 static RegisterPass<DominanceFrontier>
373 G("domfrontier", "Dominance Frontier Construction", true);
375 // NewBB is split and now it has one successor. Update dominace frontier to
376 // reflect this change.
377 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
378 assert(NewBB->getTerminator()->getNumSuccessors() == 1
379 && "NewBB should have a single successor!");
380 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
382 std::vector<BasicBlock*> PredBlocks;
383 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
385 PredBlocks.push_back(*PI);
387 if (PredBlocks.empty())
388 // If NewBB does not have any predecessors then it is a entry block.
389 // In this case, NewBB and its successor NewBBSucc dominates all
393 // NewBBSucc inherits original NewBB frontier.
394 DominanceFrontier::iterator NewBBI = find(NewBB);
395 if (NewBBI != end()) {
396 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
397 DominanceFrontier::DomSetType NewBBSuccSet;
398 NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
399 addBasicBlock(NewBBSucc, NewBBSuccSet);
402 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
403 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
405 DominatorTree &DT = getAnalysis<DominatorTree>();
406 if (DT.dominates(NewBB, NewBBSucc)) {
407 DominanceFrontier::iterator DFI = find(PredBlocks[0]);
409 DominanceFrontier::DomSetType Set = DFI->second;
410 // Filter out stuff in Set that we do not dominate a predecessor of.
411 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
412 E = Set.end(); SetI != E;) {
413 bool DominatesPred = false;
414 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
416 if (DT.dominates(NewBB, *PI))
417 DominatesPred = true;
424 if (NewBBI != end()) {
425 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
426 NewBBSet.insert(Set.begin(), Set.end());
428 addBasicBlock(NewBB, Set);
432 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
433 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
434 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
435 DominanceFrontier::DomSetType NewDFSet;
436 NewDFSet.insert(NewBBSucc);
437 addBasicBlock(NewBB, NewDFSet);
440 // Now we must loop over all of the dominance frontiers in the function,
441 // replacing occurrences of NewBBSucc with NewBB in some cases. All
442 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
443 // their dominance frontier must be updated to contain NewBB instead.
445 for (Function::iterator FI = NewBB->getParent()->begin(),
446 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
447 DominanceFrontier::iterator DFI = find(FI);
448 if (DFI == end()) continue; // unreachable block.
450 // Only consider nodes that have NewBBSucc in their dominator frontier.
451 if (!DFI->second.count(NewBBSucc)) continue;
453 // Verify whether this block dominates a block in predblocks. If not, do
455 bool BlockDominatesAny = false;
456 for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(),
457 BE = PredBlocks.end(); BI != BE; ++BI) {
458 if (DT.dominates(FI, *BI)) {
459 BlockDominatesAny = true;
464 if (!BlockDominatesAny)
467 // If NewBBSucc should not stay in our dominator frontier, remove it.
468 // We remove it unless there is a predecessor of NewBBSucc that we
469 // dominate, but we don't strictly dominate NewBBSucc.
470 bool ShouldRemove = true;
471 if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
472 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
473 // Check to see if it dominates any predecessors of NewBBSucc.
474 for (pred_iterator PI = pred_begin(NewBBSucc),
475 E = pred_end(NewBBSucc); PI != E; ++PI)
476 if (DT.dominates(FI, *PI)) {
477 ShouldRemove = false;
483 removeFromFrontier(DFI, NewBBSucc);
484 addToFrontier(DFI, NewBB);
489 class DFCalculateWorkObject {
491 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
492 const DomTreeNode *N,
493 const DomTreeNode *PN)
494 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
495 BasicBlock *currentBB;
496 BasicBlock *parentBB;
497 const DomTreeNode *Node;
498 const DomTreeNode *parentNode;
502 const DominanceFrontier::DomSetType &
503 DominanceFrontier::calculate(const DominatorTree &DT,
504 const DomTreeNode *Node) {
505 BasicBlock *BB = Node->getBlock();
506 DomSetType *Result = NULL;
508 std::vector<DFCalculateWorkObject> workList;
509 SmallPtrSet<BasicBlock *, 32> visited;
511 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
513 DFCalculateWorkObject *currentW = &workList.back();
514 assert (currentW && "Missing work object.");
516 BasicBlock *currentBB = currentW->currentBB;
517 BasicBlock *parentBB = currentW->parentBB;
518 const DomTreeNode *currentNode = currentW->Node;
519 const DomTreeNode *parentNode = currentW->parentNode;
520 assert (currentBB && "Invalid work object. Missing current Basic Block");
521 assert (currentNode && "Invalid work object. Missing current Node");
522 DomSetType &S = Frontiers[currentBB];
524 // Visit each block only once.
525 if (visited.count(currentBB) == 0) {
526 visited.insert(currentBB);
528 // Loop over CFG successors to calculate DFlocal[currentNode]
529 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
531 // Does Node immediately dominate this successor?
532 if (DT[*SI]->getIDom() != currentNode)
537 // At this point, S is DFlocal. Now we union in DFup's of our children...
538 // Loop through and visit the nodes that Node immediately dominates (Node's
539 // children in the IDomTree)
540 bool visitChild = false;
541 for (DomTreeNode::const_iterator NI = currentNode->begin(),
542 NE = currentNode->end(); NI != NE; ++NI) {
543 DomTreeNode *IDominee = *NI;
544 BasicBlock *childBB = IDominee->getBlock();
545 if (visited.count(childBB) == 0) {
546 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
547 IDominee, currentNode));
552 // If all children are visited or there is any child then pop this block
553 // from the workList.
561 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
562 DomSetType &parentSet = Frontiers[parentBB];
563 for (; CDFI != CDFE; ++CDFI) {
564 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
565 parentSet.insert(*CDFI);
570 } while (!workList.empty());
575 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
576 for (const_iterator I = begin(), E = end(); I != E; ++I) {
577 o << " DomFrontier for BB";
579 WriteAsOperand(o, I->first, false);
581 o << " <<exit node>>";
582 o << " is:\t" << I->second << "\n";
586 void DominanceFrontierBase::dump() {