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/IR/CFG.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/PassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/GenericDomTreeConstruction.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 using namespace llvm;
29 
30 // Always verify dominfo if expensive checking is enabled.
31 #ifdef EXPENSIVE_CHECKS
32 bool llvm::VerifyDomInfo = true;
33 #else
34 bool llvm::VerifyDomInfo = false;
35 #endif
36 static cl::opt<bool,true>
37 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
38                cl::desc("Verify dominator info (time consuming)"));
39 
40 bool BasicBlockEdge::isSingleEdge() const {
41   const TerminatorInst *TI = Start->getTerminator();
42   unsigned NumEdgesToEnd = 0;
43   for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
44     if (TI->getSuccessor(i) == End)
45       ++NumEdgesToEnd;
46     if (NumEdgesToEnd >= 2)
47       return false;
48   }
49   assert(NumEdgesToEnd == 1);
50   return true;
51 }
52 
53 //===----------------------------------------------------------------------===//
54 //  DominatorTree Implementation
55 //===----------------------------------------------------------------------===//
56 //
57 // Provide public access to DominatorTree information.  Implementation details
58 // can be found in Dominators.h, GenericDomTree.h, and
59 // GenericDomTreeConstruction.h.
60 //
61 //===----------------------------------------------------------------------===//
62 
63 template class llvm::DomTreeNodeBase<BasicBlock>;
64 template class llvm::DominatorTreeBase<BasicBlock, false>; // DomTreeBase
65 template class llvm::DominatorTreeBase<BasicBlock, true>; // PostDomTreeBase
66 
67 template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBDomTree>(
68     DomTreeBuilder::BBDomTree &DT);
69 template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBPostDomTree>(
70     DomTreeBuilder::BBPostDomTree &DT);
71 
72 template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBDomTree>(
73     DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);
74 template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBPostDomTree>(
75     DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);
76 
77 template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBDomTree>(
78     DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);
79 template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBPostDomTree>(
80     DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);
81 
82 template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBDomTree>(
83     const DomTreeBuilder::BBDomTree &DT);
84 template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBPostDomTree>(
85     const DomTreeBuilder::BBPostDomTree &DT);
86 
87 bool DominatorTree::invalidate(Function &F, const PreservedAnalyses &PA,
88                                FunctionAnalysisManager::Invalidator &) {
89   // Check whether the analysis, all analyses on functions, or the function's
90   // CFG have been preserved.
91   auto PAC = PA.getChecker<DominatorTreeAnalysis>();
92   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
93            PAC.preservedSet<CFGAnalyses>());
94 }
95 
96 // dominates - Return true if Def dominates a use in User. This performs
97 // the special checks necessary if Def and User are in the same basic block.
98 // Note that Def doesn't dominate a use in Def itself!
99 bool DominatorTree::dominates(const Instruction *Def,
100                               const Instruction *User) const {
101   const BasicBlock *UseBB = User->getParent();
102   const BasicBlock *DefBB = Def->getParent();
103 
104   // Any unreachable use is dominated, even if Def == User.
105   if (!isReachableFromEntry(UseBB))
106     return true;
107 
108   // Unreachable definitions don't dominate anything.
109   if (!isReachableFromEntry(DefBB))
110     return false;
111 
112   // An instruction doesn't dominate a use in itself.
113   if (Def == User)
114     return false;
115 
116   // The value defined by an invoke dominates an instruction only if it
117   // dominates every instruction in UseBB.
118   // A PHI is dominated only if the instruction dominates every possible use in
119   // the UseBB.
120   if (isa<InvokeInst>(Def) || isa<PHINode>(User))
121     return dominates(Def, UseBB);
122 
123   if (DefBB != UseBB)
124     return dominates(DefBB, UseBB);
125 
126   // Loop through the basic block until we find Def or User.
127   BasicBlock::const_iterator I = DefBB->begin();
128   for (; &*I != Def && &*I != User; ++I)
129     /*empty*/;
130 
131   return &*I == Def;
132 }
133 
134 // true if Def would dominate a use in any instruction in UseBB.
135 // note that dominates(Def, Def->getParent()) is false.
136 bool DominatorTree::dominates(const Instruction *Def,
137                               const BasicBlock *UseBB) const {
138   const BasicBlock *DefBB = Def->getParent();
139 
140   // Any unreachable use is dominated, even if DefBB == UseBB.
141   if (!isReachableFromEntry(UseBB))
142     return true;
143 
144   // Unreachable definitions don't dominate anything.
145   if (!isReachableFromEntry(DefBB))
146     return false;
147 
148   if (DefBB == UseBB)
149     return false;
150 
151   // Invoke results are only usable in the normal destination, not in the
152   // exceptional destination.
153   if (const auto *II = dyn_cast<InvokeInst>(Def)) {
154     BasicBlock *NormalDest = II->getNormalDest();
155     BasicBlockEdge E(DefBB, NormalDest);
156     return dominates(E, UseBB);
157   }
158 
159   return dominates(DefBB, UseBB);
160 }
161 
162 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
163                               const BasicBlock *UseBB) const {
164   // If the BB the edge ends in doesn't dominate the use BB, then the
165   // edge also doesn't.
166   const BasicBlock *Start = BBE.getStart();
167   const BasicBlock *End = BBE.getEnd();
168   if (!dominates(End, UseBB))
169     return false;
170 
171   // Simple case: if the end BB has a single predecessor, the fact that it
172   // dominates the use block implies that the edge also does.
173   if (End->getSinglePredecessor())
174     return true;
175 
176   // The normal edge from the invoke is critical. Conceptually, what we would
177   // like to do is split it and check if the new block dominates the use.
178   // With X being the new block, the graph would look like:
179   //
180   //        DefBB
181   //          /\      .  .
182   //         /  \     .  .
183   //        /    \    .  .
184   //       /      \   |  |
185   //      A        X  B  C
186   //      |         \ | /
187   //      .          \|/
188   //      .      NormalDest
189   //      .
190   //
191   // Given the definition of dominance, NormalDest is dominated by X iff X
192   // dominates all of NormalDest's predecessors (X, B, C in the example). X
193   // trivially dominates itself, so we only have to find if it dominates the
194   // other predecessors. Since the only way out of X is via NormalDest, X can
195   // only properly dominate a node if NormalDest dominates that node too.
196   int IsDuplicateEdge = 0;
197   for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
198        PI != E; ++PI) {
199     const BasicBlock *BB = *PI;
200     if (BB == Start) {
201       // If there are multiple edges between Start and End, by definition they
202       // can't dominate anything.
203       if (IsDuplicateEdge++)
204         return false;
205       continue;
206     }
207 
208     if (!dominates(End, BB))
209       return false;
210   }
211   return true;
212 }
213 
214 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
215   Instruction *UserInst = cast<Instruction>(U.getUser());
216   // A PHI in the end of the edge is dominated by it.
217   PHINode *PN = dyn_cast<PHINode>(UserInst);
218   if (PN && PN->getParent() == BBE.getEnd() &&
219       PN->getIncomingBlock(U) == BBE.getStart())
220     return true;
221 
222   // Otherwise use the edge-dominates-block query, which
223   // handles the crazy critical edge cases properly.
224   const BasicBlock *UseBB;
225   if (PN)
226     UseBB = PN->getIncomingBlock(U);
227   else
228     UseBB = UserInst->getParent();
229   return dominates(BBE, UseBB);
230 }
231 
232 bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
233   Instruction *UserInst = cast<Instruction>(U.getUser());
234   const BasicBlock *DefBB = Def->getParent();
235 
236   // Determine the block in which the use happens. PHI nodes use
237   // their operands on edges; simulate this by thinking of the use
238   // happening at the end of the predecessor block.
239   const BasicBlock *UseBB;
240   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
241     UseBB = PN->getIncomingBlock(U);
242   else
243     UseBB = UserInst->getParent();
244 
245   // Any unreachable use is dominated, even if Def == User.
246   if (!isReachableFromEntry(UseBB))
247     return true;
248 
249   // Unreachable definitions don't dominate anything.
250   if (!isReachableFromEntry(DefBB))
251     return false;
252 
253   // Invoke instructions define their return values on the edges to their normal
254   // successors, so we have to handle them specially.
255   // Among other things, this means they don't dominate anything in
256   // their own block, except possibly a phi, so we don't need to
257   // walk the block in any case.
258   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
259     BasicBlock *NormalDest = II->getNormalDest();
260     BasicBlockEdge E(DefBB, NormalDest);
261     return dominates(E, U);
262   }
263 
264   // If the def and use are in different blocks, do a simple CFG dominator
265   // tree query.
266   if (DefBB != UseBB)
267     return dominates(DefBB, UseBB);
268 
269   // Ok, def and use are in the same block. If the def is an invoke, it
270   // doesn't dominate anything in the block. If it's a PHI, it dominates
271   // everything in the block.
272   if (isa<PHINode>(UserInst))
273     return true;
274 
275   // Otherwise, just loop through the basic block until we find Def or User.
276   BasicBlock::const_iterator I = DefBB->begin();
277   for (; &*I != Def && &*I != UserInst; ++I)
278     /*empty*/;
279 
280   return &*I != UserInst;
281 }
282 
283 bool DominatorTree::isReachableFromEntry(const Use &U) const {
284   Instruction *I = dyn_cast<Instruction>(U.getUser());
285 
286   // ConstantExprs aren't really reachable from the entry block, but they
287   // don't need to be treated like unreachable code either.
288   if (!I) return true;
289 
290   // PHI nodes use their operands on their incoming edges.
291   if (PHINode *PN = dyn_cast<PHINode>(I))
292     return isReachableFromEntry(PN->getIncomingBlock(U));
293 
294   // Everything else uses their operands in their own block.
295   return isReachableFromEntry(I->getParent());
296 }
297 
298 void DominatorTree::verifyDomTree() const {
299   // Perform the expensive checks only when VerifyDomInfo is set.
300   if (VerifyDomInfo && !verify()) {
301     errs() << "\n~~~~~~~~~~~\n\t\tDomTree verification failed!\n~~~~~~~~~~~\n";
302     print(errs());
303     abort();
304   }
305 
306   Function &F = *getRoot()->getParent();
307 
308   DominatorTree OtherDT;
309   OtherDT.recalculate(F);
310   if (compare(OtherDT)) {
311     errs() << "DominatorTree is not up to date!\nComputed:\n";
312     print(errs());
313     errs() << "\nActual:\n";
314     OtherDT.print(errs());
315     abort();
316   }
317 }
318 
319 //===----------------------------------------------------------------------===//
320 //  DominatorTreeAnalysis and related pass implementations
321 //===----------------------------------------------------------------------===//
322 //
323 // This implements the DominatorTreeAnalysis which is used with the new pass
324 // manager. It also implements some methods from utility passes.
325 //
326 //===----------------------------------------------------------------------===//
327 
328 DominatorTree DominatorTreeAnalysis::run(Function &F,
329                                          FunctionAnalysisManager &) {
330   DominatorTree DT;
331   DT.recalculate(F);
332   return DT;
333 }
334 
335 AnalysisKey DominatorTreeAnalysis::Key;
336 
337 DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
338 
339 PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
340                                                 FunctionAnalysisManager &AM) {
341   OS << "DominatorTree for function: " << F.getName() << "\n";
342   AM.getResult<DominatorTreeAnalysis>(F).print(OS);
343 
344   return PreservedAnalyses::all();
345 }
346 
347 PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
348                                                  FunctionAnalysisManager &AM) {
349   AM.getResult<DominatorTreeAnalysis>(F).verifyDomTree();
350 
351   return PreservedAnalyses::all();
352 }
353 
354 //===----------------------------------------------------------------------===//
355 //  DominatorTreeWrapperPass Implementation
356 //===----------------------------------------------------------------------===//
357 //
358 // The implementation details of the wrapper pass that holds a DominatorTree
359 // suitable for use with the legacy pass manager.
360 //
361 //===----------------------------------------------------------------------===//
362 
363 char DominatorTreeWrapperPass::ID = 0;
364 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
365                 "Dominator Tree Construction", true, true)
366 
367 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
368   DT.recalculate(F);
369   return false;
370 }
371 
372 void DominatorTreeWrapperPass::verifyAnalysis() const {
373     if (VerifyDomInfo)
374       DT.verifyDomTree();
375 }
376 
377 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
378   DT.print(OS);
379 }
380 
381