1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/SetOperations.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Analysis/DominatorInternals.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/CommandLine.h"
32 // Always verify dominfo if expensive checking is enabled.
34 static bool VerifyDomInfo = true;
36 static bool VerifyDomInfo = false;
38 static cl::opt<bool,true>
39 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
40 cl::desc("Verify dominator info (time consuming)"));
42 //===----------------------------------------------------------------------===//
43 // DominatorTree Implementation
44 //===----------------------------------------------------------------------===//
46 // Provide public access to DominatorTree information. Implementation details
47 // can be found in DominatorCalculation.h.
49 //===----------------------------------------------------------------------===//
51 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
52 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
54 char DominatorTree::ID = 0;
55 static RegisterPass<DominatorTree>
56 E("domtree", "Dominator Tree Construction", true, true);
58 bool DominatorTree::runOnFunction(Function &F) {
63 void DominatorTree::verifyAnalysis() const {
64 if (!VerifyDomInfo) return;
66 Function &F = *getRoot()->getParent();
68 DominatorTree OtherDT;
69 OtherDT.getBase().recalculate(F);
70 assert(!compare(OtherDT) && "Invalid DominatorTree info!");
73 void DominatorTree::print(raw_ostream &OS, const Module *) const {
77 // dominates - Return true if A dominates a use in B. This performs the
78 // special checks necessary if A and B are in the same basic block.
79 bool DominatorTree::dominates(const Instruction *A, const Instruction *B) const{
80 const BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
82 // If A is an invoke instruction, its value is only available in this normal
84 if (const InvokeInst *II = dyn_cast<InvokeInst>(A))
85 BBA = II->getNormalDest();
87 if (BBA != BBB) return dominates(BBA, BBB);
89 // It is not possible to determine dominance between two PHI nodes
90 // based on their ordering.
91 if (isa<PHINode>(A) && isa<PHINode>(B))
94 // Loop through the basic block until we find A or B.
95 BasicBlock::const_iterator I = BBA->begin();
96 for (; &*I != A && &*I != B; ++I)
104 //===----------------------------------------------------------------------===//
105 // DominanceFrontier Implementation
106 //===----------------------------------------------------------------------===//
108 char DominanceFrontier::ID = 0;
109 static RegisterPass<DominanceFrontier>
110 G("domfrontier", "Dominance Frontier Construction", true, true);
112 void DominanceFrontier::verifyAnalysis() const {
113 if (!VerifyDomInfo) return;
115 DominatorTree &DT = getAnalysis<DominatorTree>();
117 DominanceFrontier OtherDF;
118 const std::vector<BasicBlock*> &DTRoots = DT.getRoots();
119 OtherDF.calculate(DT, DT.getNode(DTRoots[0]));
120 assert(!compare(OtherDF) && "Invalid DominanceFrontier info!");
123 // NewBB is split and now it has one successor. Update dominance frontier to
124 // reflect this change.
125 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
126 assert(NewBB->getTerminator()->getNumSuccessors() == 1
127 && "NewBB should have a single successor!");
128 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
130 SmallVector<BasicBlock*, 8> PredBlocks;
131 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
133 PredBlocks.push_back(*PI);
135 if (PredBlocks.empty())
136 // If NewBB does not have any predecessors then it is a entry block.
137 // In this case, NewBB and its successor NewBBSucc dominates all
141 // NewBBSucc inherits original NewBB frontier.
142 DominanceFrontier::iterator NewBBI = find(NewBB);
143 if (NewBBI != end()) {
144 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
145 DominanceFrontier::DomSetType NewBBSuccSet;
146 NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
147 addBasicBlock(NewBBSucc, NewBBSuccSet);
150 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
151 // DF(NewBBSucc) without the stuff that the new block does not dominate
153 DominatorTree &DT = getAnalysis<DominatorTree>();
154 if (DT.dominates(NewBB, NewBBSucc)) {
155 DominanceFrontier::iterator DFI = find(NewBBSucc);
157 DominanceFrontier::DomSetType Set = DFI->second;
158 // Filter out stuff in Set that we do not dominate a predecessor of.
159 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
160 E = Set.end(); SetI != E;) {
161 bool DominatesPred = false;
162 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
164 if (DT.dominates(NewBB, *PI))
165 DominatesPred = true;
172 if (NewBBI != end()) {
173 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
174 E = Set.end(); SetI != E; ++SetI) {
175 BasicBlock *SB = *SetI;
176 addToFrontier(NewBBI, SB);
179 addBasicBlock(NewBB, Set);
183 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
184 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
185 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
186 DominanceFrontier::DomSetType NewDFSet;
187 NewDFSet.insert(NewBBSucc);
188 addBasicBlock(NewBB, NewDFSet);
191 // Now we must loop over all of the dominance frontiers in the function,
192 // replacing occurrences of NewBBSucc with NewBB in some cases. All
193 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
194 // their dominance frontier must be updated to contain NewBB instead.
196 for (Function::iterator FI = NewBB->getParent()->begin(),
197 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
198 DominanceFrontier::iterator DFI = find(FI);
199 if (DFI == end()) continue; // unreachable block.
201 // Only consider nodes that have NewBBSucc in their dominator frontier.
202 if (!DFI->second.count(NewBBSucc)) continue;
204 // Verify whether this block dominates a block in predblocks. If not, do
206 bool BlockDominatesAny = false;
207 for (SmallVectorImpl<BasicBlock*>::const_iterator BI = PredBlocks.begin(),
208 BE = PredBlocks.end(); BI != BE; ++BI) {
209 if (DT.dominates(FI, *BI)) {
210 BlockDominatesAny = true;
215 // If NewBBSucc should not stay in our dominator frontier, remove it.
216 // We remove it unless there is a predecessor of NewBBSucc that we
217 // dominate, but we don't strictly dominate NewBBSucc.
218 bool ShouldRemove = true;
219 if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
220 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
221 // Check to see if it dominates any predecessors of NewBBSucc.
222 for (pred_iterator PI = pred_begin(NewBBSucc),
223 E = pred_end(NewBBSucc); PI != E; ++PI)
224 if (DT.dominates(FI, *PI)) {
225 ShouldRemove = false;
231 removeFromFrontier(DFI, NewBBSucc);
232 if (BlockDominatesAny && (&*FI == NewBB || !DT.dominates(FI, NewBB)))
233 addToFrontier(DFI, NewBB);
238 class DFCalculateWorkObject {
240 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
241 const DomTreeNode *N,
242 const DomTreeNode *PN)
243 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
244 BasicBlock *currentBB;
245 BasicBlock *parentBB;
246 const DomTreeNode *Node;
247 const DomTreeNode *parentNode;
251 const DominanceFrontier::DomSetType &
252 DominanceFrontier::calculate(const DominatorTree &DT,
253 const DomTreeNode *Node) {
254 BasicBlock *BB = Node->getBlock();
255 DomSetType *Result = NULL;
257 std::vector<DFCalculateWorkObject> workList;
258 SmallPtrSet<BasicBlock *, 32> visited;
260 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
262 DFCalculateWorkObject *currentW = &workList.back();
263 assert (currentW && "Missing work object.");
265 BasicBlock *currentBB = currentW->currentBB;
266 BasicBlock *parentBB = currentW->parentBB;
267 const DomTreeNode *currentNode = currentW->Node;
268 const DomTreeNode *parentNode = currentW->parentNode;
269 assert (currentBB && "Invalid work object. Missing current Basic Block");
270 assert (currentNode && "Invalid work object. Missing current Node");
271 DomSetType &S = Frontiers[currentBB];
273 // Visit each block only once.
274 if (visited.count(currentBB) == 0) {
275 visited.insert(currentBB);
277 // Loop over CFG successors to calculate DFlocal[currentNode]
278 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
280 // Does Node immediately dominate this successor?
281 if (DT[*SI]->getIDom() != currentNode)
286 // At this point, S is DFlocal. Now we union in DFup's of our children...
287 // Loop through and visit the nodes that Node immediately dominates (Node's
288 // children in the IDomTree)
289 bool visitChild = false;
290 for (DomTreeNode::const_iterator NI = currentNode->begin(),
291 NE = currentNode->end(); NI != NE; ++NI) {
292 DomTreeNode *IDominee = *NI;
293 BasicBlock *childBB = IDominee->getBlock();
294 if (visited.count(childBB) == 0) {
295 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
296 IDominee, currentNode));
301 // If all children are visited or there is any child then pop this block
302 // from the workList.
310 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
311 DomSetType &parentSet = Frontiers[parentBB];
312 for (; CDFI != CDFE; ++CDFI) {
313 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
314 parentSet.insert(*CDFI);
319 } while (!workList.empty());
324 void DominanceFrontierBase::print(raw_ostream &OS, const Module* ) const {
325 for (const_iterator I = begin(), E = end(); I != E; ++I) {
326 OS << " DomFrontier for BB ";
328 WriteAsOperand(OS, I->first, false);
330 OS << " <<exit node>>";
333 const std::set<BasicBlock*> &BBs = I->second;
335 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
339 WriteAsOperand(OS, *I, false);
341 OS << "<<exit node>>";
347 void DominanceFrontierBase::dump() const {