1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/GenericDomTreeConstruction.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 using namespace llvm;
30
31 // Always verify dominfo if expensive checking is enabled.
32 #ifdef XDEBUG
33 static bool VerifyDomInfo = true;
34 #else
35 static bool VerifyDomInfo = false;
36 #endif
37 static cl::opt<bool,true>
38 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
39 cl::desc("Verify dominator info (time consuming)"));
40
isSingleEdge() const41 bool BasicBlockEdge::isSingleEdge() const {
42 const TerminatorInst *TI = Start->getTerminator();
43 unsigned NumEdgesToEnd = 0;
44 for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
45 if (TI->getSuccessor(i) == End)
46 ++NumEdgesToEnd;
47 if (NumEdgesToEnd >= 2)
48 return false;
49 }
50 assert(NumEdgesToEnd == 1);
51 return true;
52 }
53
54 //===----------------------------------------------------------------------===//
55 // DominatorTree Implementation
56 //===----------------------------------------------------------------------===//
57 //
58 // Provide public access to DominatorTree information. Implementation details
59 // can be found in Dominators.h, GenericDomTree.h, and
60 // GenericDomTreeConstruction.h.
61 //
62 //===----------------------------------------------------------------------===//
63
64 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
65 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
66
67 #define LLVM_COMMA ,
68 TEMPLATE_INSTANTIATION(void llvm::Calculate<Function LLVM_COMMA BasicBlock *>(
69 DominatorTreeBase<GraphTraits<BasicBlock *>::NodeType> &DT LLVM_COMMA
70 Function &F));
71 TEMPLATE_INSTANTIATION(
72 void llvm::Calculate<Function LLVM_COMMA Inverse<BasicBlock *> >(
73 DominatorTreeBase<GraphTraits<Inverse<BasicBlock *> >::NodeType> &DT
74 LLVM_COMMA Function &F));
75 #undef LLVM_COMMA
76
77 // dominates - Return true if Def dominates a use in User. This performs
78 // the special checks necessary if Def and User are in the same basic block.
79 // Note that Def doesn't dominate a use in Def itself!
dominates(const Instruction * Def,const Instruction * User) const80 bool DominatorTree::dominates(const Instruction *Def,
81 const Instruction *User) const {
82 const BasicBlock *UseBB = User->getParent();
83 const BasicBlock *DefBB = Def->getParent();
84
85 // Any unreachable use is dominated, even if Def == User.
86 if (!isReachableFromEntry(UseBB))
87 return true;
88
89 // Unreachable definitions don't dominate anything.
90 if (!isReachableFromEntry(DefBB))
91 return false;
92
93 // An instruction doesn't dominate a use in itself.
94 if (Def == User)
95 return false;
96
97 // The value defined by an invoke dominates an instruction only if
98 // it dominates every instruction in UseBB.
99 // A PHI is dominated only if the instruction dominates every possible use
100 // in the UseBB.
101 if (isa<InvokeInst>(Def) || isa<PHINode>(User))
102 return dominates(Def, UseBB);
103
104 if (DefBB != UseBB)
105 return dominates(DefBB, UseBB);
106
107 // Loop through the basic block until we find Def or User.
108 BasicBlock::const_iterator I = DefBB->begin();
109 for (; &*I != Def && &*I != User; ++I)
110 /*empty*/;
111
112 return &*I == Def;
113 }
114
115 // true if Def would dominate a use in any instruction in UseBB.
116 // note that dominates(Def, Def->getParent()) is false.
dominates(const Instruction * Def,const BasicBlock * UseBB) const117 bool DominatorTree::dominates(const Instruction *Def,
118 const BasicBlock *UseBB) const {
119 const BasicBlock *DefBB = Def->getParent();
120
121 // Any unreachable use is dominated, even if DefBB == UseBB.
122 if (!isReachableFromEntry(UseBB))
123 return true;
124
125 // Unreachable definitions don't dominate anything.
126 if (!isReachableFromEntry(DefBB))
127 return false;
128
129 if (DefBB == UseBB)
130 return false;
131
132 const InvokeInst *II = dyn_cast<InvokeInst>(Def);
133 if (!II)
134 return dominates(DefBB, UseBB);
135
136 // Invoke results are only usable in the normal destination, not in the
137 // exceptional destination.
138 BasicBlock *NormalDest = II->getNormalDest();
139 BasicBlockEdge E(DefBB, NormalDest);
140 return dominates(E, UseBB);
141 }
142
dominates(const BasicBlockEdge & BBE,const BasicBlock * UseBB) const143 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
144 const BasicBlock *UseBB) const {
145 // Assert that we have a single edge. We could handle them by simply
146 // returning false, but since isSingleEdge is linear on the number of
147 // edges, the callers can normally handle them more efficiently.
148 assert(BBE.isSingleEdge());
149
150 // If the BB the edge ends in doesn't dominate the use BB, then the
151 // edge also doesn't.
152 const BasicBlock *Start = BBE.getStart();
153 const BasicBlock *End = BBE.getEnd();
154 if (!dominates(End, UseBB))
155 return false;
156
157 // Simple case: if the end BB has a single predecessor, the fact that it
158 // dominates the use block implies that the edge also does.
159 if (End->getSinglePredecessor())
160 return true;
161
162 // The normal edge from the invoke is critical. Conceptually, what we would
163 // like to do is split it and check if the new block dominates the use.
164 // With X being the new block, the graph would look like:
165 //
166 // DefBB
167 // /\ . .
168 // / \ . .
169 // / \ . .
170 // / \ | |
171 // A X B C
172 // | \ | /
173 // . \|/
174 // . NormalDest
175 // .
176 //
177 // Given the definition of dominance, NormalDest is dominated by X iff X
178 // dominates all of NormalDest's predecessors (X, B, C in the example). X
179 // trivially dominates itself, so we only have to find if it dominates the
180 // other predecessors. Since the only way out of X is via NormalDest, X can
181 // only properly dominate a node if NormalDest dominates that node too.
182 for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
183 PI != E; ++PI) {
184 const BasicBlock *BB = *PI;
185 if (BB == Start)
186 continue;
187
188 if (!dominates(End, BB))
189 return false;
190 }
191 return true;
192 }
193
dominates(const BasicBlockEdge & BBE,const Use & U) const194 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
195 // Assert that we have a single edge. We could handle them by simply
196 // returning false, but since isSingleEdge is linear on the number of
197 // edges, the callers can normally handle them more efficiently.
198 assert(BBE.isSingleEdge());
199
200 Instruction *UserInst = cast<Instruction>(U.getUser());
201 // A PHI in the end of the edge is dominated by it.
202 PHINode *PN = dyn_cast<PHINode>(UserInst);
203 if (PN && PN->getParent() == BBE.getEnd() &&
204 PN->getIncomingBlock(U) == BBE.getStart())
205 return true;
206
207 // Otherwise use the edge-dominates-block query, which
208 // handles the crazy critical edge cases properly.
209 const BasicBlock *UseBB;
210 if (PN)
211 UseBB = PN->getIncomingBlock(U);
212 else
213 UseBB = UserInst->getParent();
214 return dominates(BBE, UseBB);
215 }
216
dominates(const Instruction * Def,const Use & U) const217 bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
218 Instruction *UserInst = cast<Instruction>(U.getUser());
219 const BasicBlock *DefBB = Def->getParent();
220
221 // Determine the block in which the use happens. PHI nodes use
222 // their operands on edges; simulate this by thinking of the use
223 // happening at the end of the predecessor block.
224 const BasicBlock *UseBB;
225 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
226 UseBB = PN->getIncomingBlock(U);
227 else
228 UseBB = UserInst->getParent();
229
230 // Any unreachable use is dominated, even if Def == User.
231 if (!isReachableFromEntry(UseBB))
232 return true;
233
234 // Unreachable definitions don't dominate anything.
235 if (!isReachableFromEntry(DefBB))
236 return false;
237
238 // Invoke instructions define their return values on the edges
239 // to their normal successors, so we have to handle them specially.
240 // Among other things, this means they don't dominate anything in
241 // their own block, except possibly a phi, so we don't need to
242 // walk the block in any case.
243 if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
244 BasicBlock *NormalDest = II->getNormalDest();
245 BasicBlockEdge E(DefBB, NormalDest);
246 return dominates(E, U);
247 }
248
249 // If the def and use are in different blocks, do a simple CFG dominator
250 // tree query.
251 if (DefBB != UseBB)
252 return dominates(DefBB, UseBB);
253
254 // Ok, def and use are in the same block. If the def is an invoke, it
255 // doesn't dominate anything in the block. If it's a PHI, it dominates
256 // everything in the block.
257 if (isa<PHINode>(UserInst))
258 return true;
259
260 // Otherwise, just loop through the basic block until we find Def or User.
261 BasicBlock::const_iterator I = DefBB->begin();
262 for (; &*I != Def && &*I != UserInst; ++I)
263 /*empty*/;
264
265 return &*I != UserInst;
266 }
267
isReachableFromEntry(const Use & U) const268 bool DominatorTree::isReachableFromEntry(const Use &U) const {
269 Instruction *I = dyn_cast<Instruction>(U.getUser());
270
271 // ConstantExprs aren't really reachable from the entry block, but they
272 // don't need to be treated like unreachable code either.
273 if (!I) return true;
274
275 // PHI nodes use their operands on their incoming edges.
276 if (PHINode *PN = dyn_cast<PHINode>(I))
277 return isReachableFromEntry(PN->getIncomingBlock(U));
278
279 // Everything else uses their operands in their own block.
280 return isReachableFromEntry(I->getParent());
281 }
282
verifyDomTree() const283 void DominatorTree::verifyDomTree() const {
284 if (!VerifyDomInfo)
285 return;
286
287 Function &F = *getRoot()->getParent();
288
289 DominatorTree OtherDT;
290 OtherDT.recalculate(F);
291 if (compare(OtherDT)) {
292 errs() << "DominatorTree is not up to date!\nComputed:\n";
293 print(errs());
294 errs() << "\nActual:\n";
295 OtherDT.print(errs());
296 abort();
297 }
298 }
299
300 //===----------------------------------------------------------------------===//
301 // DominatorTreeWrapperPass Implementation
302 //===----------------------------------------------------------------------===//
303 //
304 // The implementation details of the wrapper pass that holds a DominatorTree.
305 //
306 //===----------------------------------------------------------------------===//
307
308 char DominatorTreeWrapperPass::ID = 0;
309 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
310 "Dominator Tree Construction", true, true)
311
runOnFunction(Function & F)312 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
313 DT.recalculate(F);
314 return false;
315 }
316
verifyAnalysis() const317 void DominatorTreeWrapperPass::verifyAnalysis() const { DT.verifyDomTree(); }
318
print(raw_ostream & OS,const Module *) const319 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
320 DT.print(OS);
321 }
322
323