[C++11] Add predecessors(BasicBlock *) / successors(BasicBlock *) iterator ranges.
[oota-llvm.git] / lib / IR / Dominators.cpp
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
41 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!
80 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.
117 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
143 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 BasicBlock *BB : predecessors(End)) {
183     if (BB == Start)
184       continue;
185
186     if (!dominates(End, BB))
187       return false;
188   }
189   return true;
190 }
191
192 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
193   // Assert that we have a single edge. We could handle them by simply
194   // returning false, but since isSingleEdge is linear on the number of
195   // edges, the callers can normally handle them more efficiently.
196   assert(BBE.isSingleEdge());
197
198   Instruction *UserInst = cast<Instruction>(U.getUser());
199   // A PHI in the end of the edge is dominated by it.
200   PHINode *PN = dyn_cast<PHINode>(UserInst);
201   if (PN && PN->getParent() == BBE.getEnd() &&
202       PN->getIncomingBlock(U) == BBE.getStart())
203     return true;
204
205   // Otherwise use the edge-dominates-block query, which
206   // handles the crazy critical edge cases properly.
207   const BasicBlock *UseBB;
208   if (PN)
209     UseBB = PN->getIncomingBlock(U);
210   else
211     UseBB = UserInst->getParent();
212   return dominates(BBE, UseBB);
213 }
214
215 bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
216   Instruction *UserInst = cast<Instruction>(U.getUser());
217   const BasicBlock *DefBB = Def->getParent();
218
219   // Determine the block in which the use happens. PHI nodes use
220   // their operands on edges; simulate this by thinking of the use
221   // happening at the end of the predecessor block.
222   const BasicBlock *UseBB;
223   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
224     UseBB = PN->getIncomingBlock(U);
225   else
226     UseBB = UserInst->getParent();
227
228   // Any unreachable use is dominated, even if Def == User.
229   if (!isReachableFromEntry(UseBB))
230     return true;
231
232   // Unreachable definitions don't dominate anything.
233   if (!isReachableFromEntry(DefBB))
234     return false;
235
236   // Invoke instructions define their return values on the edges
237   // to their normal successors, so we have to handle them specially.
238   // Among other things, this means they don't dominate anything in
239   // their own block, except possibly a phi, so we don't need to
240   // walk the block in any case.
241   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
242     BasicBlock *NormalDest = II->getNormalDest();
243     BasicBlockEdge E(DefBB, NormalDest);
244     return dominates(E, U);
245   }
246
247   // If the def and use are in different blocks, do a simple CFG dominator
248   // tree query.
249   if (DefBB != UseBB)
250     return dominates(DefBB, UseBB);
251
252   // Ok, def and use are in the same block. If the def is an invoke, it
253   // doesn't dominate anything in the block. If it's a PHI, it dominates
254   // everything in the block.
255   if (isa<PHINode>(UserInst))
256     return true;
257
258   // Otherwise, just loop through the basic block until we find Def or User.
259   BasicBlock::const_iterator I = DefBB->begin();
260   for (; &*I != Def && &*I != UserInst; ++I)
261     /*empty*/;
262
263   return &*I != UserInst;
264 }
265
266 bool DominatorTree::isReachableFromEntry(const Use &U) const {
267   Instruction *I = dyn_cast<Instruction>(U.getUser());
268
269   // ConstantExprs aren't really reachable from the entry block, but they
270   // don't need to be treated like unreachable code either.
271   if (!I) return true;
272
273   // PHI nodes use their operands on their incoming edges.
274   if (PHINode *PN = dyn_cast<PHINode>(I))
275     return isReachableFromEntry(PN->getIncomingBlock(U));
276
277   // Everything else uses their operands in their own block.
278   return isReachableFromEntry(I->getParent());
279 }
280
281 void DominatorTree::verifyDomTree() const {
282   if (!VerifyDomInfo)
283     return;
284
285   Function &F = *getRoot()->getParent();
286
287   DominatorTree OtherDT;
288   OtherDT.recalculate(F);
289   if (compare(OtherDT)) {
290     errs() << "DominatorTree is not up to date!\nComputed:\n";
291     print(errs());
292     errs() << "\nActual:\n";
293     OtherDT.print(errs());
294     abort();
295   }
296 }
297
298 //===----------------------------------------------------------------------===//
299 //  DominatorTreeWrapperPass Implementation
300 //===----------------------------------------------------------------------===//
301 //
302 // The implementation details of the wrapper pass that holds a DominatorTree.
303 //
304 //===----------------------------------------------------------------------===//
305
306 char DominatorTreeWrapperPass::ID = 0;
307 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
308                 "Dominator Tree Construction", true, true)
309
310 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
311   DT.recalculate(F);
312   return false;
313 }
314
315 void DominatorTreeWrapperPass::verifyAnalysis() const { DT.verifyDomTree(); }
316
317 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
318   DT.print(OS);
319 }
320