1ef860a24SChandler Carruth //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2ef860a24SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ef860a24SChandler Carruth //
7ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
8ef860a24SChandler Carruth //
9ef860a24SChandler Carruth // This file implements simple dominator construction algorithms for finding
10ef860a24SChandler Carruth // forward dominators.  Postdominators are available in libanalysis, but are not
11ef860a24SChandler Carruth // included in libvmcore, because it's not needed.  Forward dominators are
12ef860a24SChandler Carruth // needed to support the Verifier pass.
13ef860a24SChandler Carruth //
14ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
15ef860a24SChandler Carruth 
165ad5f15cSChandler Carruth #include "llvm/IR/Dominators.h"
17*e188aae4Sserge-sans-paille #include "llvm/ADT/StringRef.h"
18432a3883SNico Weber #include "llvm/Config/llvm-config.h"
191305dc33SChandler Carruth #include "llvm/IR/CFG.h"
20*e188aae4Sserge-sans-paille #include "llvm/IR/Function.h"
21*e188aae4Sserge-sans-paille #include "llvm/IR/Instruction.h"
229fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
2364764b44SChandler Carruth #include "llvm/IR/PassManager.h"
2405da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
25*e188aae4Sserge-sans-paille #include "llvm/PassRegistry.h"
26*e188aae4Sserge-sans-paille #include "llvm/Support/Casting.h"
27ef860a24SChandler Carruth #include "llvm/Support/CommandLine.h"
28ef860a24SChandler Carruth #include "llvm/Support/raw_ostream.h"
29*e188aae4Sserge-sans-paille 
30*e188aae4Sserge-sans-paille #include <cassert>
31*e188aae4Sserge-sans-paille 
32*e188aae4Sserge-sans-paille namespace llvm {
33*e188aae4Sserge-sans-paille class Argument;
34*e188aae4Sserge-sans-paille class Constant;
35*e188aae4Sserge-sans-paille class Value;
36*e188aae4Sserge-sans-paille } // namespace llvm
37ef860a24SChandler Carruth using namespace llvm;
38ef860a24SChandler Carruth 
3969b3ff9dSSerge Pavlov bool llvm::VerifyDomInfo = false;
40ef860a24SChandler Carruth static cl::opt<bool, true>
418065f0b9SZachary Turner     VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo), cl::Hidden,
42ef860a24SChandler Carruth                    cl::desc("Verify dominator info (time consuming)"));
43ef860a24SChandler Carruth 
44ffb4fb7fSJakub Kuderski #ifdef EXPENSIVE_CHECKS
45ffb4fb7fSJakub Kuderski static constexpr bool ExpensiveChecksEnabled = true;
46ffb4fb7fSJakub Kuderski #else
47ffb4fb7fSJakub Kuderski static constexpr bool ExpensiveChecksEnabled = false;
48ffb4fb7fSJakub Kuderski #endif
49ffb4fb7fSJakub Kuderski 
isSingleEdge() const50ef860a24SChandler Carruth bool BasicBlockEdge::isSingleEdge() const {
51edb12a83SChandler Carruth   const Instruction *TI = Start->getTerminator();
52ef860a24SChandler Carruth   unsigned NumEdgesToEnd = 0;
53ef860a24SChandler Carruth   for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
54ef860a24SChandler Carruth     if (TI->getSuccessor(i) == End)
55ef860a24SChandler Carruth       ++NumEdgesToEnd;
56ef860a24SChandler Carruth     if (NumEdgesToEnd >= 2)
57ef860a24SChandler Carruth       return false;
58ef860a24SChandler Carruth   }
59ef860a24SChandler Carruth   assert(NumEdgesToEnd == 1);
60ef860a24SChandler Carruth   return true;
61ef860a24SChandler Carruth }
62ef860a24SChandler Carruth 
63ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
64ef860a24SChandler Carruth //  DominatorTree Implementation
65ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
66ef860a24SChandler Carruth //
67ef860a24SChandler Carruth // Provide public access to DominatorTree information.  Implementation details
68e509db41SChandler Carruth // can be found in Dominators.h, GenericDomTree.h, and
69e509db41SChandler Carruth // GenericDomTreeConstruction.h.
70ef860a24SChandler Carruth //
71ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
72ef860a24SChandler Carruth 
73a667d1adSBenjamin Kramer template class llvm::DomTreeNodeBase<BasicBlock>;
74b292c22cSJakub Kuderski template class llvm::DominatorTreeBase<BasicBlock, false>; // DomTreeBase
75b292c22cSJakub Kuderski template class llvm::DominatorTreeBase<BasicBlock, true>; // PostDomTreeBase
76ef860a24SChandler Carruth 
77148c4454SAlina Sbirlea template class llvm::cfg::Update<BasicBlock *>;
78624463a0SJakub Kuderski 
79c271dea0SJakub Kuderski template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBDomTree>(
80c271dea0SJakub Kuderski     DomTreeBuilder::BBDomTree &DT);
81d4b3f19bSAlina Sbirlea template void
82d4b3f19bSAlina Sbirlea llvm::DomTreeBuilder::CalculateWithUpdates<DomTreeBuilder::BBDomTree>(
83d4b3f19bSAlina Sbirlea     DomTreeBuilder::BBDomTree &DT, BBUpdates U);
84d4b3f19bSAlina Sbirlea 
85c271dea0SJakub Kuderski template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBPostDomTree>(
86c271dea0SJakub Kuderski     DomTreeBuilder::BBPostDomTree &DT);
87d4b3f19bSAlina Sbirlea // No CalculateWithUpdates<PostDomTree> instantiation, unless a usecase arises.
885af07f5cSJakub Kuderski 
8913e9ef17SJakub Kuderski template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBDomTree>(
9013e9ef17SJakub Kuderski     DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);
9113e9ef17SJakub Kuderski template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBPostDomTree>(
9213e9ef17SJakub Kuderski     DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);
9313e9ef17SJakub Kuderski 
94eb59ff22SJakub Kuderski template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBDomTree>(
95eb59ff22SJakub Kuderski     DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);
96eb59ff22SJakub Kuderski template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBPostDomTree>(
97eb59ff22SJakub Kuderski     DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);
98eb59ff22SJakub Kuderski 
99624463a0SJakub Kuderski template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBDomTree>(
100f55ad397SAlina Sbirlea     DomTreeBuilder::BBDomTree &DT, DomTreeBuilder::BBDomTreeGraphDiff &,
101f55ad397SAlina Sbirlea     DomTreeBuilder::BBDomTreeGraphDiff *);
102624463a0SJakub Kuderski template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBPostDomTree>(
103f55ad397SAlina Sbirlea     DomTreeBuilder::BBPostDomTree &DT, DomTreeBuilder::BBPostDomTreeGraphDiff &,
104f55ad397SAlina Sbirlea     DomTreeBuilder::BBPostDomTreeGraphDiff *);
105624463a0SJakub Kuderski 
1065af07f5cSJakub Kuderski template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBDomTree>(
107ffb4fb7fSJakub Kuderski     const DomTreeBuilder::BBDomTree &DT,
108ffb4fb7fSJakub Kuderski     DomTreeBuilder::BBDomTree::VerificationLevel VL);
109b292c22cSJakub Kuderski template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBPostDomTree>(
110ffb4fb7fSJakub Kuderski     const DomTreeBuilder::BBPostDomTree &DT,
111ffb4fb7fSJakub Kuderski     DomTreeBuilder::BBPostDomTree::VerificationLevel VL);
11230616362SRafael Espindola 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator &)113ca68a3ecSChandler Carruth bool DominatorTree::invalidate(Function &F, const PreservedAnalyses &PA,
114ca68a3ecSChandler Carruth                                FunctionAnalysisManager::Invalidator &) {
115ca68a3ecSChandler Carruth   // Check whether the analysis, all analyses on functions, or the function's
116ca68a3ecSChandler Carruth   // CFG have been preserved.
117ca68a3ecSChandler Carruth   auto PAC = PA.getChecker<DominatorTreeAnalysis>();
118ca68a3ecSChandler Carruth   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
119ca68a3ecSChandler Carruth            PAC.preservedSet<CFGAnalyses>());
120ca68a3ecSChandler Carruth }
121ca68a3ecSChandler Carruth 
dominates(const BasicBlock * BB,const Use & U) const12297a7bc58SPhilip Reames bool DominatorTree::dominates(const BasicBlock *BB, const Use &U) const {
12397a7bc58SPhilip Reames   Instruction *UserInst = cast<Instruction>(U.getUser());
12497a7bc58SPhilip Reames   if (auto *PN = dyn_cast<PHINode>(UserInst))
12597a7bc58SPhilip Reames     // A phi use using a value from a block is dominated by the end of that
12697a7bc58SPhilip Reames     // block.  Note that the phi's parent block may not be.
12797a7bc58SPhilip Reames     return dominates(BB, PN->getIncomingBlock(U));
12897a7bc58SPhilip Reames   else
12997a7bc58SPhilip Reames     return properlyDominates(BB, UserInst->getParent());
13097a7bc58SPhilip Reames }
13197a7bc58SPhilip Reames 
132ef860a24SChandler Carruth // dominates - Return true if Def dominates a use in User. This performs
133ef860a24SChandler Carruth // the special checks necessary if Def and User are in the same basic block.
134ef860a24SChandler Carruth // Note that Def doesn't dominate a use in Def itself!
dominates(const Value * DefV,const Instruction * User) const13532b6e9a4SNikita Popov bool DominatorTree::dominates(const Value *DefV,
136ef860a24SChandler Carruth                               const Instruction *User) const {
13732b6e9a4SNikita Popov   const Instruction *Def = dyn_cast<Instruction>(DefV);
13832b6e9a4SNikita Popov   if (!Def) {
139c0e8c943SNikita Popov     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
140c0e8c943SNikita Popov            "Should be called with an instruction, argument or constant");
141c0e8c943SNikita Popov     return true; // Arguments and constants dominate everything.
14232b6e9a4SNikita Popov   }
14332b6e9a4SNikita Popov 
144ef860a24SChandler Carruth   const BasicBlock *UseBB = User->getParent();
145ef860a24SChandler Carruth   const BasicBlock *DefBB = Def->getParent();
146ef860a24SChandler Carruth 
147ef860a24SChandler Carruth   // Any unreachable use is dominated, even if Def == User.
148ef860a24SChandler Carruth   if (!isReachableFromEntry(UseBB))
149ef860a24SChandler Carruth     return true;
150ef860a24SChandler Carruth 
151ef860a24SChandler Carruth   // Unreachable definitions don't dominate anything.
152ef860a24SChandler Carruth   if (!isReachableFromEntry(DefBB))
153ef860a24SChandler Carruth     return false;
154ef860a24SChandler Carruth 
155ef860a24SChandler Carruth   // An instruction doesn't dominate a use in itself.
156ef860a24SChandler Carruth   if (Def == User)
157ef860a24SChandler Carruth     return false;
158ef860a24SChandler Carruth 
1598a1c45d6SDavid Majnemer   // The value defined by an invoke dominates an instruction only if it
1608a1c45d6SDavid Majnemer   // dominates every instruction in UseBB.
1618a1c45d6SDavid Majnemer   // A PHI is dominated only if the instruction dominates every possible use in
1628a1c45d6SDavid Majnemer   // the UseBB.
163248a5db3SJames Y Knight   if (isa<InvokeInst>(Def) || isa<CallBrInst>(Def) || isa<PHINode>(User))
164ef860a24SChandler Carruth     return dominates(Def, UseBB);
165ef860a24SChandler Carruth 
166ef860a24SChandler Carruth   if (DefBB != UseBB)
167ef860a24SChandler Carruth     return dominates(DefBB, UseBB);
168ef860a24SChandler Carruth 
1697593a480SVedant Kumar   return Def->comesBefore(User);
170ef860a24SChandler Carruth }
171ef860a24SChandler Carruth 
172ef860a24SChandler Carruth // true if Def would dominate a use in any instruction in UseBB.
173ef860a24SChandler Carruth // note that dominates(Def, Def->getParent()) is false.
dominates(const Instruction * Def,const BasicBlock * UseBB) const174ef860a24SChandler Carruth bool DominatorTree::dominates(const Instruction *Def,
175ef860a24SChandler Carruth                               const BasicBlock *UseBB) const {
176ef860a24SChandler Carruth   const BasicBlock *DefBB = Def->getParent();
177ef860a24SChandler Carruth 
178ef860a24SChandler Carruth   // Any unreachable use is dominated, even if DefBB == UseBB.
179ef860a24SChandler Carruth   if (!isReachableFromEntry(UseBB))
180ef860a24SChandler Carruth     return true;
181ef860a24SChandler Carruth 
182ef860a24SChandler Carruth   // Unreachable definitions don't dominate anything.
183ef860a24SChandler Carruth   if (!isReachableFromEntry(DefBB))
184ef860a24SChandler Carruth     return false;
185ef860a24SChandler Carruth 
186ef860a24SChandler Carruth   if (DefBB == UseBB)
187ef860a24SChandler Carruth     return false;
188ef860a24SChandler Carruth 
1898a1c45d6SDavid Majnemer   // Invoke results are only usable in the normal destination, not in the
1908a1c45d6SDavid Majnemer   // exceptional destination.
1910bc0eef7SDavid Majnemer   if (const auto *II = dyn_cast<InvokeInst>(Def)) {
192ef860a24SChandler Carruth     BasicBlock *NormalDest = II->getNormalDest();
193ef860a24SChandler Carruth     BasicBlockEdge E(DefBB, NormalDest);
194ef860a24SChandler Carruth     return dominates(E, UseBB);
195ef860a24SChandler Carruth   }
1960bc0eef7SDavid Majnemer 
197248a5db3SJames Y Knight   // Callbr results are similarly only usable in the default destination.
198248a5db3SJames Y Knight   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
199248a5db3SJames Y Knight     BasicBlock *NormalDest = CBI->getDefaultDest();
200248a5db3SJames Y Knight     BasicBlockEdge E(DefBB, NormalDest);
201248a5db3SJames Y Knight     return dominates(E, UseBB);
202248a5db3SJames Y Knight   }
203248a5db3SJames Y Knight 
2040bc0eef7SDavid Majnemer   return dominates(DefBB, UseBB);
2050bc0eef7SDavid Majnemer }
206ef860a24SChandler Carruth 
dominates(const BasicBlockEdge & BBE,const BasicBlock * UseBB) const207ef860a24SChandler Carruth bool DominatorTree::dominates(const BasicBlockEdge &BBE,
208ef860a24SChandler Carruth                               const BasicBlock *UseBB) const {
209ef860a24SChandler Carruth   // If the BB the edge ends in doesn't dominate the use BB, then the
210ef860a24SChandler Carruth   // edge also doesn't.
211ef860a24SChandler Carruth   const BasicBlock *Start = BBE.getStart();
212ef860a24SChandler Carruth   const BasicBlock *End = BBE.getEnd();
213ef860a24SChandler Carruth   if (!dominates(End, UseBB))
214ef860a24SChandler Carruth     return false;
215ef860a24SChandler Carruth 
216ef860a24SChandler Carruth   // Simple case: if the end BB has a single predecessor, the fact that it
217ef860a24SChandler Carruth   // dominates the use block implies that the edge also does.
218ef860a24SChandler Carruth   if (End->getSinglePredecessor())
219ef860a24SChandler Carruth     return true;
220ef860a24SChandler Carruth 
221ef860a24SChandler Carruth   // The normal edge from the invoke is critical. Conceptually, what we would
222ef860a24SChandler Carruth   // like to do is split it and check if the new block dominates the use.
223ef860a24SChandler Carruth   // With X being the new block, the graph would look like:
224ef860a24SChandler Carruth   //
225ef860a24SChandler Carruth   //        DefBB
226ef860a24SChandler Carruth   //          /\      .  .
227ef860a24SChandler Carruth   //         /  \     .  .
228ef860a24SChandler Carruth   //        /    \    .  .
229ef860a24SChandler Carruth   //       /      \   |  |
230ef860a24SChandler Carruth   //      A        X  B  C
231ef860a24SChandler Carruth   //      |         \ | /
232ef860a24SChandler Carruth   //      .          \|/
233ef860a24SChandler Carruth   //      .      NormalDest
234ef860a24SChandler Carruth   //      .
235ef860a24SChandler Carruth   //
236ef860a24SChandler Carruth   // Given the definition of dominance, NormalDest is dominated by X iff X
237ef860a24SChandler Carruth   // dominates all of NormalDest's predecessors (X, B, C in the example). X
238ef860a24SChandler Carruth   // trivially dominates itself, so we only have to find if it dominates the
239ef860a24SChandler Carruth   // other predecessors. Since the only way out of X is via NormalDest, X can
240ef860a24SChandler Carruth   // only properly dominate a node if NormalDest dominates that node too.
2414ef096b0SAdam Nemet   int IsDuplicateEdge = 0;
2426a337f85SKazu Hirata   for (const BasicBlock *BB : predecessors(End)) {
2434ef096b0SAdam Nemet     if (BB == Start) {
2444ef096b0SAdam Nemet       // If there are multiple edges between Start and End, by definition they
2454ef096b0SAdam Nemet       // can't dominate anything.
2464ef096b0SAdam Nemet       if (IsDuplicateEdge++)
2474ef096b0SAdam Nemet         return false;
248ef860a24SChandler Carruth       continue;
2494ef096b0SAdam Nemet     }
250ef860a24SChandler Carruth 
251ef860a24SChandler Carruth     if (!dominates(End, BB))
252ef860a24SChandler Carruth       return false;
253ef860a24SChandler Carruth   }
254ef860a24SChandler Carruth   return true;
255ef860a24SChandler Carruth }
256ef860a24SChandler Carruth 
dominates(const BasicBlockEdge & BBE,const Use & U) const25773523021SChandler Carruth bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
258ef860a24SChandler Carruth   Instruction *UserInst = cast<Instruction>(U.getUser());
259ef860a24SChandler Carruth   // A PHI in the end of the edge is dominated by it.
260ef860a24SChandler Carruth   PHINode *PN = dyn_cast<PHINode>(UserInst);
261ef860a24SChandler Carruth   if (PN && PN->getParent() == BBE.getEnd() &&
262ef860a24SChandler Carruth       PN->getIncomingBlock(U) == BBE.getStart())
263ef860a24SChandler Carruth     return true;
264ef860a24SChandler Carruth 
265ef860a24SChandler Carruth   // Otherwise use the edge-dominates-block query, which
266ef860a24SChandler Carruth   // handles the crazy critical edge cases properly.
267ef860a24SChandler Carruth   const BasicBlock *UseBB;
268ef860a24SChandler Carruth   if (PN)
269ef860a24SChandler Carruth     UseBB = PN->getIncomingBlock(U);
270ef860a24SChandler Carruth   else
271ef860a24SChandler Carruth     UseBB = UserInst->getParent();
272ef860a24SChandler Carruth   return dominates(BBE, UseBB);
273ef860a24SChandler Carruth }
274ef860a24SChandler Carruth 
dominates(const Value * DefV,const Use & U) const27532b6e9a4SNikita Popov bool DominatorTree::dominates(const Value *DefV, const Use &U) const {
27632b6e9a4SNikita Popov   const Instruction *Def = dyn_cast<Instruction>(DefV);
27732b6e9a4SNikita Popov   if (!Def) {
278c0e8c943SNikita Popov     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
279c0e8c943SNikita Popov            "Should be called with an instruction, argument or constant");
280c0e8c943SNikita Popov     return true; // Arguments and constants dominate everything.
28132b6e9a4SNikita Popov   }
28232b6e9a4SNikita Popov 
283ef860a24SChandler Carruth   Instruction *UserInst = cast<Instruction>(U.getUser());
284ef860a24SChandler Carruth   const BasicBlock *DefBB = Def->getParent();
285ef860a24SChandler Carruth 
286ef860a24SChandler Carruth   // Determine the block in which the use happens. PHI nodes use
287ef860a24SChandler Carruth   // their operands on edges; simulate this by thinking of the use
288ef860a24SChandler Carruth   // happening at the end of the predecessor block.
289ef860a24SChandler Carruth   const BasicBlock *UseBB;
290ef860a24SChandler Carruth   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
291ef860a24SChandler Carruth     UseBB = PN->getIncomingBlock(U);
292ef860a24SChandler Carruth   else
293ef860a24SChandler Carruth     UseBB = UserInst->getParent();
294ef860a24SChandler Carruth 
295ef860a24SChandler Carruth   // Any unreachable use is dominated, even if Def == User.
296ef860a24SChandler Carruth   if (!isReachableFromEntry(UseBB))
297ef860a24SChandler Carruth     return true;
298ef860a24SChandler Carruth 
299ef860a24SChandler Carruth   // Unreachable definitions don't dominate anything.
300ef860a24SChandler Carruth   if (!isReachableFromEntry(DefBB))
301ef860a24SChandler Carruth     return false;
302ef860a24SChandler Carruth 
3038a1c45d6SDavid Majnemer   // Invoke instructions define their return values on the edges to their normal
3048a1c45d6SDavid Majnemer   // successors, so we have to handle them specially.
305ef860a24SChandler Carruth   // Among other things, this means they don't dominate anything in
306ef860a24SChandler Carruth   // their own block, except possibly a phi, so we don't need to
307ef860a24SChandler Carruth   // walk the block in any case.
308ef860a24SChandler Carruth   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
309ef860a24SChandler Carruth     BasicBlock *NormalDest = II->getNormalDest();
310ef860a24SChandler Carruth     BasicBlockEdge E(DefBB, NormalDest);
311ef860a24SChandler Carruth     return dominates(E, U);
312ef860a24SChandler Carruth   }
313ef860a24SChandler Carruth 
314248a5db3SJames Y Knight   // Callbr results are similarly only usable in the default destination.
315248a5db3SJames Y Knight   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
316248a5db3SJames Y Knight     BasicBlock *NormalDest = CBI->getDefaultDest();
317248a5db3SJames Y Knight     BasicBlockEdge E(DefBB, NormalDest);
318248a5db3SJames Y Knight     return dominates(E, U);
319248a5db3SJames Y Knight   }
320248a5db3SJames Y Knight 
321ef860a24SChandler Carruth   // If the def and use are in different blocks, do a simple CFG dominator
322ef860a24SChandler Carruth   // tree query.
323ef860a24SChandler Carruth   if (DefBB != UseBB)
324ef860a24SChandler Carruth     return dominates(DefBB, UseBB);
325ef860a24SChandler Carruth 
326ef860a24SChandler Carruth   // Ok, def and use are in the same block. If the def is an invoke, it
327ef860a24SChandler Carruth   // doesn't dominate anything in the block. If it's a PHI, it dominates
328ef860a24SChandler Carruth   // everything in the block.
329ef860a24SChandler Carruth   if (isa<PHINode>(UserInst))
330ef860a24SChandler Carruth     return true;
331ef860a24SChandler Carruth 
3327593a480SVedant Kumar   return Def->comesBefore(UserInst);
333ef860a24SChandler Carruth }
334ef860a24SChandler Carruth 
isReachableFromEntry(const Use & U) const335ef860a24SChandler Carruth bool DominatorTree::isReachableFromEntry(const Use &U) const {
336ef860a24SChandler Carruth   Instruction *I = dyn_cast<Instruction>(U.getUser());
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   // ConstantExprs aren't really reachable from the entry block, but they
339ef860a24SChandler Carruth   // don't need to be treated like unreachable code either.
340ef860a24SChandler Carruth   if (!I) return true;
341ef860a24SChandler Carruth 
342ef860a24SChandler Carruth   // PHI nodes use their operands on their incoming edges.
343ef860a24SChandler Carruth   if (PHINode *PN = dyn_cast<PHINode>(I))
344ef860a24SChandler Carruth     return isReachableFromEntry(PN->getIncomingBlock(U));
345ef860a24SChandler Carruth 
346ef860a24SChandler Carruth   // Everything else uses their operands in their own block.
347ef860a24SChandler Carruth   return isReachableFromEntry(I->getParent());
348ef860a24SChandler Carruth }
34973523021SChandler Carruth 
3504ac9a690SMax Kazantsev // Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.
dominates(const BasicBlockEdge & BBE1,const BasicBlockEdge & BBE2) const3514ac9a690SMax Kazantsev bool DominatorTree::dominates(const BasicBlockEdge &BBE1,
3524ac9a690SMax Kazantsev                               const BasicBlockEdge &BBE2) const {
3534ac9a690SMax Kazantsev   if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())
3544ac9a690SMax Kazantsev     return true;
3554ac9a690SMax Kazantsev   return dominates(BBE1, BBE2.getStart());
3564ac9a690SMax Kazantsev }
3574ac9a690SMax Kazantsev 
35873523021SChandler Carruth //===----------------------------------------------------------------------===//
35964764b44SChandler Carruth //  DominatorTreeAnalysis and related pass implementations
36064764b44SChandler Carruth //===----------------------------------------------------------------------===//
36164764b44SChandler Carruth //
36264764b44SChandler Carruth // This implements the DominatorTreeAnalysis which is used with the new pass
36364764b44SChandler Carruth // manager. It also implements some methods from utility passes.
36464764b44SChandler Carruth //
36564764b44SChandler Carruth //===----------------------------------------------------------------------===//
36664764b44SChandler Carruth 
run(Function & F,FunctionAnalysisManager &)367164a2aa6SChandler Carruth DominatorTree DominatorTreeAnalysis::run(Function &F,
36836e0d01eSSean Silva                                          FunctionAnalysisManager &) {
36964764b44SChandler Carruth   DominatorTree DT;
37064764b44SChandler Carruth   DT.recalculate(F);
37164764b44SChandler Carruth   return DT;
37264764b44SChandler Carruth }
37364764b44SChandler Carruth 
374dab4eae2SChandler Carruth AnalysisKey DominatorTreeAnalysis::Key;
375df0cd726SNAKAMURA Takumi 
DominatorTreePrinterPass(raw_ostream & OS)37664764b44SChandler Carruth DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
37764764b44SChandler Carruth 
run(Function & F,FunctionAnalysisManager & AM)37864764b44SChandler Carruth PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
379b47f8010SChandler Carruth                                                 FunctionAnalysisManager &AM) {
38064764b44SChandler Carruth   OS << "DominatorTree for function: " << F.getName() << "\n";
381b47f8010SChandler Carruth   AM.getResult<DominatorTreeAnalysis>(F).print(OS);
38264764b44SChandler Carruth 
38364764b44SChandler Carruth   return PreservedAnalyses::all();
38464764b44SChandler Carruth }
38564764b44SChandler Carruth 
run(Function & F,FunctionAnalysisManager & AM)38664764b44SChandler Carruth PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
387b47f8010SChandler Carruth                                                  FunctionAnalysisManager &AM) {
3887c35de12SDavid Green   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3897c35de12SDavid Green   assert(DT.verify());
3907c35de12SDavid Green   (void)DT;
39164764b44SChandler Carruth   return PreservedAnalyses::all();
39264764b44SChandler Carruth }
39364764b44SChandler Carruth 
39464764b44SChandler Carruth //===----------------------------------------------------------------------===//
39573523021SChandler Carruth //  DominatorTreeWrapperPass Implementation
39673523021SChandler Carruth //===----------------------------------------------------------------------===//
39773523021SChandler Carruth //
39864764b44SChandler Carruth // The implementation details of the wrapper pass that holds a DominatorTree
39964764b44SChandler Carruth // suitable for use with the legacy pass manager.
40073523021SChandler Carruth //
40173523021SChandler Carruth //===----------------------------------------------------------------------===//
40273523021SChandler Carruth 
40373523021SChandler Carruth char DominatorTreeWrapperPass::ID = 0;
40405da2fe5SReid Kleckner 
DominatorTreeWrapperPass()40505da2fe5SReid Kleckner DominatorTreeWrapperPass::DominatorTreeWrapperPass() : FunctionPass(ID) {
40605da2fe5SReid Kleckner   initializeDominatorTreeWrapperPassPass(*PassRegistry::getPassRegistry());
40705da2fe5SReid Kleckner }
40805da2fe5SReid Kleckner 
40973523021SChandler Carruth INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
41073523021SChandler Carruth                 "Dominator Tree Construction", true, true)
41173523021SChandler Carruth 
runOnFunction(Function & F)41273523021SChandler Carruth bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
41373523021SChandler Carruth   DT.recalculate(F);
41473523021SChandler Carruth   return false;
41573523021SChandler Carruth }
41673523021SChandler Carruth 
verifyAnalysis() const417e340f851SAdam Nemet void DominatorTreeWrapperPass::verifyAnalysis() const {
4187c35de12SDavid Green   if (VerifyDomInfo)
4197c35de12SDavid Green     assert(DT.verify(DominatorTree::VerificationLevel::Full));
4207c35de12SDavid Green   else if (ExpensiveChecksEnabled)
4217c35de12SDavid Green     assert(DT.verify(DominatorTree::VerificationLevel::Basic));
422e340f851SAdam Nemet }
42373523021SChandler Carruth 
print(raw_ostream & OS,const Module *) const42473523021SChandler Carruth void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
42573523021SChandler Carruth   DT.print(OS);
42673523021SChandler Carruth }
427