LLVM 24.0.0git
Dominators.cpp
Go to the documentation of this file.
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/StringRef.h"
18#include "llvm/Config/llvm-config.h"
19#include "llvm/IR/CFG.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instruction.h"
23#include "llvm/IR/PassManager.h"
25#include "llvm/PassRegistry.h"
31
32#include <cassert>
33
34namespace llvm {
35class Argument;
36class Constant;
37class Value;
38} // namespace llvm
39using namespace llvm;
40
44 cl::desc("Verify dominator info (time consuming)"));
45
46#ifdef EXPENSIVE_CHECKS
47static constexpr bool ExpensiveChecksEnabled = true;
48#else
49static constexpr bool ExpensiveChecksEnabled = false;
50#endif
51
52//===----------------------------------------------------------------------===//
53// DominatorTree Implementation
54//===----------------------------------------------------------------------===//
55//
56// Provide public access to DominatorTree information. Implementation details
57// can be found in Dominators.h, GenericDomTree.h, and
58// GenericDomTreeConstruction.h.
59//
60//===----------------------------------------------------------------------===//
61
63template class LLVM_EXPORT_TEMPLATE
65template class LLVM_EXPORT_TEMPLATE
67
69
71 FunctionAnalysisManager::Invalidator &) {
72 // Check whether the analysis, all analyses on functions, or the function's
73 // CFG have been preserved.
74 auto PAC = PA.getChecker<DominatorTreeAnalysis>();
75 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
76 PAC.preservedSet<CFGAnalyses>());
77}
78
79bool DominatorTree::dominates(const BasicBlock *BB, const Use &U) const {
80 Instruction *UserInst = cast<Instruction>(U.getUser());
81 if (auto *PN = dyn_cast<PHINode>(UserInst))
82 // A phi use using a value from a block is dominated by the end of that
83 // block. Note that the phi's parent block may not be.
84 return dominates(BB, PN->getIncomingBlock(U));
85 else
86 return properlyDominates(BB, UserInst->getParent());
87}
88
89// dominates - Return true if Def dominates a use in User. This performs
90// the special checks necessary if Def and User are in the same basic block.
91// Note that Def doesn't dominate a use in Def itself!
93 const Instruction *User) const {
94 const Instruction *Def = dyn_cast<Instruction>(DefV);
95 if (!Def) {
96 assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
97 "Should be called with an instruction, argument or constant");
98 return true; // Arguments and constants dominate everything.
99 }
100
101 const BasicBlock *UseBB = User->getParent();
102 const BasicBlock *DefBB = Def->getParent();
103
104 // Any unreachable use is dominated, even if Def == User.
105 const DomTreeNode *UseNode = getNode(UseBB);
106 if (!UseNode)
107 return true;
108
109 // Unreachable definitions don't dominate anything.
110 const DomTreeNode *DefNode = getNode(DefBB);
111 if (!DefNode)
112 return false;
113
114 // An instruction doesn't dominate a use in itself.
115 if (Def == User)
116 return false;
117
118 // The value defined by an invoke dominates an instruction only if it
119 // dominates every instruction in UseBB.
120 // A PHI is dominated only if the instruction dominates every possible use in
121 // the UseBB.
123 return dominates(Def, UseBB);
124
125 if (DefBB != UseBB)
126 return dominates(DefNode, UseNode);
127
128 return Def->comesBefore(User);
129}
130
131// true if Def would dominate a use in any instruction in UseBB.
132// note that dominates(Def, Def->getParent()) is false.
134 const BasicBlock *UseBB) const {
135 const BasicBlock *DefBB = Def->getParent();
136
137 // Any unreachable use is dominated, even if DefBB == UseBB.
138 const DomTreeNode *UseNode = getNode(UseBB);
139 if (!UseNode)
140 return true;
141
142 // Unreachable definitions don't dominate anything.
143 const DomTreeNode *DefNode = getNode(DefBB);
144 if (!DefNode)
145 return false;
146
147 if (DefBB == UseBB)
148 return false;
149
150 // Invoke results are only usable in the normal destination, not in the
151 // exceptional destination.
152 if (const auto *II = dyn_cast<InvokeInst>(Def)) {
153 BasicBlock *NormalDest = II->getNormalDest();
154 BasicBlockEdge E(DefBB, NormalDest);
155 return dominates(E, UseBB);
156 }
157
158 return dominates(DefNode, UseNode);
159}
160
162 const BasicBlock *UseBB) const {
163 // If the BB the edge ends in doesn't dominate the use BB, then the
164 // edge also doesn't.
165 const BasicBlock *Start = BBE.getStart();
166 const BasicBlock *End = BBE.getEnd();
167 const DomTreeNode *EndNode = getNode(End);
168 if (!dominates(EndNode, getNode(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 BasicBlock *BB : predecessors(End)) {
198 if (BB == Start) {
199 // If there are multiple edges between Start and End, by definition they
200 // can't dominate anything.
201 if (IsDuplicateEdge++)
202 return false;
203 continue;
204 }
205
206 if (!dominates(EndNode, getNode(BB)))
207 return false;
208 }
209 return true;
210}
211
212bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
213 Instruction *UserInst = cast<Instruction>(U.getUser());
214 // A PHI in the end of the edge is dominated by it.
215 PHINode *PN = dyn_cast<PHINode>(UserInst);
216 if (PN && PN->getParent() == BBE.getEnd() &&
217 PN->getIncomingBlock(U) == BBE.getStart())
218 return true;
219
220 // Otherwise use the edge-dominates-block query, which
221 // handles the crazy critical edge cases properly.
222 const BasicBlock *UseBB;
223 if (PN)
224 UseBB = PN->getIncomingBlock(U);
225 else
226 UseBB = UserInst->getParent();
227 return dominates(BBE, UseBB);
228}
229
230bool DominatorTree::dominates(const Value *DefV, const Use &U) const {
231 const Instruction *Def = dyn_cast<Instruction>(DefV);
232 if (!Def) {
233 assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
234 "Should be called with an instruction, argument or constant");
235 return true; // Arguments and constants dominate everything.
236 }
237
238 Instruction *UserInst = cast<Instruction>(U.getUser());
239 const BasicBlock *DefBB = Def->getParent();
240
241 // Determine the block in which the use happens. PHI nodes use
242 // their operands on edges; simulate this by thinking of the use
243 // happening at the end of the predecessor block.
244 const BasicBlock *UseBB;
245 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
246 UseBB = PN->getIncomingBlock(U);
247 else
248 UseBB = UserInst->getParent();
249
250 // Any unreachable use is dominated, even if Def == User.
251 const DomTreeNode *UseNode = getNode(UseBB);
252 if (!UseNode)
253 return true;
254
255 // Unreachable definitions don't dominate anything.
256 const DomTreeNode *DefNode = getNode(DefBB);
257 if (!DefNode)
258 return false;
259
260 // Invoke instructions define their return values on the edges to their normal
261 // successors, so we have to handle them specially.
262 // Among other things, this means they don't dominate anything in
263 // their own block, except possibly a phi, so we don't need to
264 // walk the block in any case.
265 if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
266 BasicBlock *NormalDest = II->getNormalDest();
267 BasicBlockEdge E(DefBB, NormalDest);
268 return dominates(E, U);
269 }
270
271 // If the def and use are in different blocks, do a simple CFG dominator
272 // tree query.
273 if (DefBB != UseBB)
274 return dominates(DefNode, UseNode);
275
276 // Ok, def and use are in the same block. If the def is an invoke, it
277 // doesn't dominate anything in the block. If it's a PHI, it dominates
278 // everything in the block.
279 if (isa<PHINode>(UserInst))
280 return true;
281
282 return Def->comesBefore(UserInst);
283}
284
286 Instruction *I = dyn_cast<Instruction>(U.getUser());
287
288 // ConstantExprs aren't really reachable from the entry block, but they
289 // don't need to be treated like unreachable code either.
290 if (!I) return true;
291
292 // PHI nodes use their operands on their incoming edges.
293 if (PHINode *PN = dyn_cast<PHINode>(I))
294 return isReachableFromEntry(PN->getIncomingBlock(U));
295
296 // Everything else uses their operands in their own block.
297 return isReachableFromEntry(I->getParent());
298}
299
300// Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.
302 const BasicBlockEdge &BBE2) const {
303 if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())
304 return true;
305 return dominates(BBE1, BBE2.getStart());
306}
307
309 Instruction *I2) const {
310 BasicBlock *BB1 = I1->getParent();
311 BasicBlock *BB2 = I2->getParent();
312 if (BB1 == BB2)
313 return I1->comesBefore(I2) ? I1 : I2;
314 if (!isReachableFromEntry(BB2))
315 return I1;
316 if (!isReachableFromEntry(BB1))
317 return I2;
318 BasicBlock *DomBB = findNearestCommonDominator(BB1, BB2);
319 if (BB1 == DomBB)
320 return I1;
321 if (BB2 == DomBB)
322 return I2;
323 return DomBB->getTerminator();
324}
325
326//===----------------------------------------------------------------------===//
327// DominatorTreeAnalysis and related pass implementations
328//===----------------------------------------------------------------------===//
329//
330// This implements the DominatorTreeAnalysis which is used with the new pass
331// manager. It also implements some methods from utility passes.
332//
333//===----------------------------------------------------------------------===//
334
341
342AnalysisKey DominatorTreeAnalysis::Key;
343
345
348 OS << "DominatorTree for function: " << F.getName() << "\n";
350
351 return PreservedAnalyses::all();
352}
353
356 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
357 assert(DT.verify());
358 (void)DT;
359 return PreservedAnalyses::all();
360}
361
362//===----------------------------------------------------------------------===//
363// DominatorTreeWrapperPass Implementation
364//===----------------------------------------------------------------------===//
365//
366// The implementation details of the wrapper pass that holds a DominatorTree
367// suitable for use with the legacy pass manager.
368//
369//===----------------------------------------------------------------------===//
370
372
374
376 "Dominator Tree Construction", true, true)
377
379 DT.recalculate(F);
380 return false;
381}
382
384 if (VerifyDomInfo)
385 assert(DT.verify(DominatorTree::VerificationLevel::Full));
386 else if (ExpensiveChecksEnabled)
387 assert(DT.verify(DominatorTree::VerificationLevel::Basic));
388}
389
391 DT.print(OS);
392}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:217
static cl::opt< bool, true > VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo), cl::Hidden, cl::desc("Verify dominator info (time consuming)"))
static bool runOnFunction(Function &F, bool PostInlining)
Generic dominator tree construction - this file provides routines to construct immediate dominator in...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static constexpr bool ExpensiveChecksEnabled
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
const BasicBlock * getEnd() const
Definition Dominators.h:85
const BasicBlock * getStart() const
Definition Dominators.h:81
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
This is an important base class in LLVM.
Definition Constant.h:43
Base class for the actual dominator tree node.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
LLVM_ABI DominatorTree run(Function &F, FunctionAnalysisManager &)
Run the analysis pass over a function and produce a dominator tree.
Core dominator tree base class.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
DomTreeNodeBase< BasicBlock > * getNode(const BasicBlock *BB) const
bool properlyDominates(const DomTreeNodeBase< BasicBlock > *A, const DomTreeNodeBase< BasicBlock > *B) const
LLVM_ABI DominatorTreePrinterPass(raw_ostream &OS)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
FunctionPass(char &pid)
Definition Pass.h:316
Invoke instruction.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)