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