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