MLIR 23.0.0git
Dominance.cpp
Go to the documentation of this file.
1//===- Dominance.cpp - Dominator analysis for CFGs ------------------------===//
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// Implementation of dominance related classes and instantiations of extern
10// templates.
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/IR/Dominance.h"
15#include "mlir/IR/Operation.h"
17#include "llvm/Support/GenericDomTreeConstruction.h"
18
19using namespace mlir;
20using namespace mlir::detail;
21
22template class llvm::DominatorTreeBase<Block, /*IsPostDom=*/false>;
23template class llvm::DominatorTreeBase<Block, /*IsPostDom=*/true>;
24template class llvm::DomTreeNodeBase<Block>;
25
26//===----------------------------------------------------------------------===//
27// DominanceInfoBase
28//===----------------------------------------------------------------------===//
29
30template <bool IsPostDom>
32 for (auto entry : dominanceInfos)
33 delete entry.second.getPointer();
34}
35
36template <bool IsPostDom>
38 for (auto entry : dominanceInfos)
39 delete entry.second.getPointer();
40 dominanceInfos.clear();
41}
43template <bool IsPostDom>
44void DominanceInfoBase<IsPostDom>::invalidate(Region *region, bool recursive) {
45 auto invalidate = [&](Region *r) {
46 auto it = dominanceInfos.find(r);
47 if (it != dominanceInfos.end()) {
48 delete it->second.getPointer();
49 dominanceInfos.erase(it);
50 }
51 };
52 if (recursive)
53 region->walk([&](Region *r) { invalidate(r); });
54 else
55 invalidate(region);
56}
57
58/// Return the dom tree and "hasSSADominance" bit for the given region. The
59/// DomTree will be null for single-block regions. This lazily constructs the
60/// DomTree on demand when needsDomTree=true.
61template <bool IsPostDom>
63 bool needsDomTree) const
64 -> llvm::PointerIntPair<DomTree *, 1, bool> {
65 // Check to see if we already have this information.
66 auto itAndInserted = dominanceInfos.insert({region, {nullptr, true}});
67 auto &entry = itAndInserted.first->second;
68
69 // This method builds on knowledge that multi-block regions always have
70 // SSADominance. Graph regions are only allowed to be single-block regions,
71 // but of course single-block regions may also have SSA dominance.
72 if (!itAndInserted.second) {
73 // We do have it, so we know the 'hasSSADominance' bit is correct, but we
74 // may not have constructed a DominatorTree yet. If we need it, build it.
75 if (needsDomTree && !entry.getPointer() && !region->hasOneBlock()) {
76 auto *domTree = new DomTree();
77 domTree->recalculate(*region);
78 entry.setPointer(domTree);
79 }
80 return entry;
81 }
82
83 // Nope, lazily construct it. Create a DomTree if this is a multi-block
84 // region.
85 if (!region->hasOneBlock()) {
86 auto *domTree = new DomTree();
87 domTree->recalculate(*region);
88 entry.setPointer(domTree);
89 // Multiblock regions always have SSA dominance, leave `second` set to true.
90 return entry;
91 }
92
93 // Single block regions have a more complicated predicate.
94 if (Operation *parentOp = region->getParentOp()) {
95 if (!parentOp->isRegistered()) { // We don't know about unregistered ops.
96 entry.setInt(false);
97 } else if (auto regionKindItf = dyn_cast<RegionKindInterface>(parentOp)) {
98 // Registered ops can opt-out of SSA dominance with
99 // RegionKindInterface.
100 entry.setInt(regionKindItf.hasSSADominance(region->getRegionNumber()));
101 }
102 }
103
104 return entry;
105}
106
107/// Return the ancestor block enclosing the specified block. This returns null
108/// if we reach the top of the hierarchy.
109static Block *getAncestorBlock(Block *block) {
110 if (Operation *ancestorOp = block->getParentOp())
111 return ancestorOp->getBlock();
112 return nullptr;
113}
114
115/// Walks up the list of containers of the given block and calls the
116/// user-defined traversal function for every pair of a region and block that
117/// could be found during traversal. If the user-defined function returns true
118/// for a given pair, traverseAncestors will return the current block. Nullptr
119/// otherwise.
120template <typename FuncT>
121static Block *traverseAncestors(Block *block, const FuncT &func) {
122 do {
123 // Invoke the user-defined traversal function for each block.
124 if (func(block))
125 return block;
126 } while ((block = getAncestorBlock(block)));
127 return nullptr;
128}
129
130/// Tries to update the given block references to live in the same region by
131/// exploring the relationship of both blocks with respect to their regions.
133 // If both block do not live in the same region, we will have to check their
134 // parent operations.
135 Region *aRegion = a->getParent();
136 Region *bRegion = b->getParent();
137 if (aRegion == bRegion)
138 return true;
139
140 // Iterate over all ancestors of `a`, counting the depth of `a`. If one of
141 // `a`s ancestors are in the same region as `b`, then we stop early because we
142 // found our NCA.
143 size_t aRegionDepth = 0;
144 if (Block *aResult = traverseAncestors(a, [&](Block *block) {
145 ++aRegionDepth;
146 return block->getParent() == bRegion;
147 })) {
148 a = aResult;
149 return true;
150 }
151
152 // Iterate over all ancestors of `b`, counting the depth of `b`. If one of
153 // `b`s ancestors are in the same region as `a`, then we stop early because
154 // we found our NCA.
155 size_t bRegionDepth = 0;
156 if (Block *bResult = traverseAncestors(b, [&](Block *block) {
157 ++bRegionDepth;
158 return block->getParent() == aRegion;
159 })) {
160 b = bResult;
161 return true;
162 }
163
164 // Otherwise we found two blocks that are siblings at some level. Walk the
165 // deepest one up until we reach the top or find an NCA.
166 while (true) {
167 if (aRegionDepth > bRegionDepth) {
168 a = getAncestorBlock(a);
169 --aRegionDepth;
170 } else if (aRegionDepth < bRegionDepth) {
172 --bRegionDepth;
173 } else {
174 break;
175 }
176 }
177
178 // If we found something with the same level, then we can march both up at the
179 // same time from here on out.
180 while (a) {
181 // If they are at the same level, and have the same parent region then we
182 // succeeded.
183 if (a->getParent() == b->getParent())
184 return true;
185
186 a = getAncestorBlock(a);
188 }
189
190 // They don't share an NCA, perhaps they are in different modules or
191 // something.
192 return false;
193}
194
195template <bool IsPostDom>
196Block *
198 Block *b) const {
199 // If either a or b are null, then conservatively return nullptr.
200 if (!a || !b)
201 return nullptr;
202
203 // If they are the same block, then we are done.
204 if (a == b)
205 return a;
206
207 // Try to find blocks that are in the same region.
209 return nullptr;
210
211 // If the common ancestor in a common region is the same block, then return
212 // it.
213 if (a == b)
214 return a;
215
216 // Otherwise, there must be multiple blocks in the region, check the
217 // DomTree.
218 return getDomTree(a->getParent()).findNearestCommonDominator(a, b);
219}
220
221/// Returns the given block iterator if it lies within the region region.
222/// Otherwise, otherwise finds the ancestor of the given block iterator that
223/// lies within the given region. Returns and "empty" iterator if the latter
224/// fails.
225///
226/// Note: This is a variant of Region::findAncestorOpInRegion that operates on
227/// block iterators instead of ops.
228static std::pair<Block *, Block::iterator>
230 // Case 1: The iterator lies within the region region.
231 if (b->getParent() == r)
232 return std::make_pair(b, it);
233
234 // Otherwise: Find ancestor iterator. Bail if we run out of parent ops.
235 Operation *parentOp = b->getParentOp();
236 if (!parentOp)
237 return std::make_pair(static_cast<Block *>(nullptr), Block::iterator());
238 Operation *op = r->findAncestorOpInRegion(*parentOp);
239 if (!op)
240 return std::make_pair(static_cast<Block *>(nullptr), Block::iterator());
241 return std::make_pair(op->getBlock(), op->getIterator());
242}
243
244/// Given two iterators into the same block, return "true" if `a` is before `b.
245/// Note: This is a variant of Operation::isBeforeInBlock that operates on
246/// block iterators instead of ops.
247static bool isBeforeInBlock(Block *block, Block::iterator a,
249 if (a == b)
250 return false;
251 if (a == block->end())
252 return false;
253 if (b == block->end())
254 return true;
255 return a->isBeforeInBlock(&*b);
256}
257
258template <bool IsPostDom>
260 Block *aBlock, Block::iterator aIt, Block *bBlock, Block::iterator bIt,
261 bool enclosingOk) const {
262 assert(aBlock && bBlock && "expected non-null blocks");
263
264 // A block iterator (post)dominates, but does not properly (post)dominate,
265 // itself unless this is a graph region.
266 if (aBlock == bBlock && aIt == bIt)
267 return !hasSSADominance(aBlock);
268
269 // If the iterators are in different regions, then normalize one into the
270 // other.
271 Region *aRegion = aBlock->getParent();
272 if (aRegion != bBlock->getParent()) {
273 // Scoot up b's region tree until we find a location in A's region that
274 // encloses it. If this fails, then we know there is no (post)dom relation.
275 if (!aRegion) {
276 bBlock = nullptr;
277 bIt = Block::iterator();
278 } else {
279 std::tie(bBlock, bIt) =
280 findAncestorIteratorInRegion(aRegion, bBlock, bIt);
281 }
282 if (!bBlock)
283 return false;
284 assert(bBlock->getParent() == aRegion && "expected block in regionA");
285
286 // If 'a' encloses 'b', then we consider it to (post)dominate.
287 if (aBlock == bBlock && aIt == bIt && enclosingOk)
288 return true;
289 }
290
291 // Ok, they are in the same region now.
292 if (aBlock == bBlock) {
293 // Dominance changes based on the region type. In a region with SSA
294 // dominance, uses inside the same block must follow defs. In other
295 // regions kinds, uses and defs can come in any order inside a block.
296 if (!hasSSADominance(aBlock))
297 return true;
298 if constexpr (IsPostDom) {
299 return isBeforeInBlock(aBlock, bIt, aIt);
300 } else {
301 return isBeforeInBlock(aBlock, aIt, bIt);
302 }
303 }
304
305 // If the blocks are different, use DomTree to resolve the query.
306 return getDomTree(aRegion).properlyDominates(aBlock, bBlock);
307}
308
309/// Return true if the specified block is reachable from the entry block of
310/// its region.
311template <bool IsPostDom>
313 // If this is the first block in its region, then it is obviously reachable.
314 Region *region = a->getParent();
315 if (&region->front() == a)
316 return true;
317
318 // Otherwise this is some block in a multi-block region. Check DomTree.
319 return getDomTree(region).isReachableFromEntry(a);
320}
321
322template class detail::DominanceInfoBase</*IsPostDom=*/true>;
323template class detail::DominanceInfoBase</*IsPostDom=*/false>;
324
325//===----------------------------------------------------------------------===//
326// DominanceInfo
327//===----------------------------------------------------------------------===//
328
330 bool enclosingOpOk) const {
331 return super::properlyDominatesImpl(a->getBlock(), a->getIterator(),
332 b->getBlock(), b->getIterator(),
333 enclosingOpOk);
334}
335
337 return super::properlyDominatesImpl(a, a->begin(), b, b->begin(),
338 /*enclosingOk=*/true);
339}
340
341/// Return true if the `a` value properly dominates operation `b`, i.e if the
342/// operation that defines `a` properlyDominates `b` and the operation that
343/// defines `a` does not contain `b`.
345 // block arguments properly dominate all operations in their own block, so
346 // we use a dominates check here, not a properlyDominates check.
347 if (auto blockArg = dyn_cast<BlockArgument>(a))
348 return dominates(blockArg.getOwner(), b->getBlock());
349
350 // `a` properlyDominates `b` if the operation defining `a` properlyDominates
351 // `b`, but `a` does not itself enclose `b` in one of its regions.
352 return properlyDominates(a.getDefiningOp(), b, /*enclosingOpOk=*/false);
353}
354
355//===----------------------------------------------------------------------===//
356// PostDominanceInfo
357//===----------------------------------------------------------------------===//
358
360 bool enclosingOpOk) const {
361 return super::properlyDominatesImpl(a->getBlock(), a->getIterator(),
362 b->getBlock(), b->getIterator(),
363 enclosingOpOk);
364}
365
367 return super::properlyDominatesImpl(a, a->end(), b, b->end(),
368 /*enclosingOk=*/true);
369}
static Block * getAncestorBlock(Block *block)
Return the ancestor block enclosing the specified block.
static bool tryGetBlocksInSameRegion(Block *&a, Block *&b)
Tries to update the given block references to live in the same region by exploring the relationship o...
static Block * traverseAncestors(Block *block, const FuncT &func)
Walks up the list of containers of the given block and calls the user-defined traversal function for ...
static std::pair< Block *, Block::iterator > findAncestorIteratorInRegion(Region *r, Block *b, Block::iterator it)
Returns the given block iterator if it lies within the region region.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Block represents an ordered list of Operations.
Definition Block.h:33
OpListType::iterator iterator
Definition Block.h:150
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
iterator end()
Definition Block.h:154
iterator begin()
Definition Block.h:153
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
bool properlyDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly dominates operation B, i.e.
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
Definition Dominance.h:161
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
bool properlyPostDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly postdominates operation B.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
Operation * findAncestorOpInRegion(Operation &op)
Returns 'op' if 'op' lies in this region, or otherwise finds the ancestor of 'op' that lies in this r...
Definition Region.cpp:168
unsigned getRegionNumber()
Return the number of this region in the parent operation.
Definition Region.cpp:62
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:200
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
Definition Region.h:296
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
llvm::PointerIntPair< DomTree *, 1, bool > getDominanceInfo(Region *region, bool needsDomTree) const
Return the dom tree and "hasSSADominance" bit for the given region.
Definition Dominance.cpp:62
DenseMap< Region *, llvm::PointerIntPair< DomTree *, 1, bool > > dominanceInfos
A mapping of regions to their base dominator tree and a cached "hasSSADominance" bit.
Definition Dominance.h:133
DomTree & getDomTree(Region *region) const
Definition Dominance.h:104
bool isReachableFromEntry(Block *a) const
Return true if the specified block is reachable from the entry block of its region.
bool properlyDominatesImpl(Block *aBlock, Block::iterator aIt, Block *bBlock, Block::iterator bIt, bool enclosingOk=true) const
Return "true" if block iterator A properly (post)dominates block iterator B.
Block * findNearestCommonDominator(Block *a, Block *b) const
Finds the nearest common dominator block for the two given blocks a and b.
void invalidate()
Invalidate dominance info.
Definition Dominance.cpp:37
AttrTypeReplacer.
Include the generated interface declarations.