MLIR 24.0.0git
SideEffectInterfaces.cpp
Go to the documentation of this file.
1//===- SideEffectInterfaces.cpp - SideEffects in MLIR ---------------------===//
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
10
11#include "mlir/IR/SymbolTable.h"
12#include "llvm/ADT/SmallPtrSet.h"
13#include <utility>
14
15using namespace mlir;
16
17//===----------------------------------------------------------------------===//
18// SideEffect Interfaces
19//===----------------------------------------------------------------------===//
20
21/// Include the definitions of the side effect interfaces.
22#include "mlir/Interfaces/SideEffectInterfaces.cpp.inc"
23
24//===----------------------------------------------------------------------===//
25// MemoryEffects
26//===----------------------------------------------------------------------===//
27
29 return isa<Allocate, Free, Read, Write>(effect);
30}
31
32//===----------------------------------------------------------------------===//
33// SideEffect Utilities
34//===----------------------------------------------------------------------===//
35
37 return op->use_empty() && wouldOpBeTriviallyDead(op);
38}
39
40/// Return true if the op's own memory effects do not prevent erasure. Allowed
41/// effects are reads and effects on results allocated by the op itself.
42///
43/// If the op only has recursive effects, treat the op itself as having no
44/// effects. Without a memory effect interface or recursive effects, return
45/// false to conservatively assume live effects.
46///
47/// The caller must also check nested effects when `hasRecursiveEffects` is
48/// true. This function does not check uses or restrictions on erasing
49/// terminators and symbols.
50static bool hasOnlyRemovableEffects(Operation *op, bool hasRecursiveEffects) {
51 if (auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
53 effectInterface.getEffects(effects);
54
55 // Gather all results of this op that are allocated.
56 SmallPtrSet<Value, 4> allocResults;
57 for (const MemoryEffects::EffectInstance &effect : effects)
58 if (isa<MemoryEffects::Allocate>(effect.getEffect()) &&
59 effect.getValue() && effect.getValue().getDefiningOp() == op)
60 allocResults.insert(effect.getValue());
61 return llvm::all_of(effects,
62 [&](const MemoryEffects::EffectInstance &effect) {
63 // We can drop effects on values allocated by this
64 // operation and returned as results. Otherwise, the
65 // effect must be a read.
66 return allocResults.contains(effect.getValue()) ||
67 isa<MemoryEffects::Read>(effect.getEffect());
68 });
69 }
70 return hasRecursiveEffects;
71}
72
73/// Internal implementation of `mlir::wouldOpBeTriviallyDead` that also
74/// considers terminator operations as dead if they have no side effects. This
75/// allows for marking region operations as trivially dead without always being
76/// conservative of terminators.
78 Operation *root,
80 using State = DeadnessCache::State;
81 // Repeated queries on nested operations would otherwise scan the same
82 // subtrees. Cache each subtree after checking its effects, and skip cached
83 // subtrees on later queries. An explicit worklist also bounds C++ stack use
84 // for deeply nested IR. Uncached queries do not look up or record summaries.
85 struct WorkItem {
86 // Keep the unvisited range so a block can resume after a nested operation
87 // without adding every sibling to the worklist.
88 Block::iterator current;
90 Operation *complete = nullptr;
91 };
92 SmallVector<WorkItem, 1> worklist = {
93 {Block::iterator(root), ++Block::iterator(root)}};
94 while (!worklist.empty()) {
95 WorkItem &item = worklist.back();
96 if (item.current == item.end) {
97 if (cache && item.complete)
98 (*cache)[item.complete] = State::Dead;
99 worklist.pop_back();
100 continue;
101 }
102 Operation *op = &*item.current++;
103 bool cachedAlive = false;
104 if (cache) {
105 auto cached = cache->find(op);
106 if (cached != cache->end()) {
107 if (cached->second == State::Dead)
108 continue;
109 cachedAlive = true;
110 }
111 }
112 bool recursive = op->hasTrait<OpTrait::HasRecursiveMemoryEffects>();
113 if (cachedAlive || !hasOnlyRemovableEffects(op, recursive)) {
114 // One live effect keeps every ancestor up to the root live. The
115 // remaining subtrees cannot change the answer.
116 if (cache) {
117 for (Operation *ancestor = op;; ancestor = ancestor->getParentOp()) {
118 (*cache)[ancestor] = State::Alive;
119 if (ancestor == root)
120 break;
121 }
122 }
123 return false;
124 }
125 if (!recursive) {
126 if (cache)
127 (*cache)[op] = State::Dead;
128 continue;
129 }
130 // The first pushed block is processed last. Record the parent's summary
131 // only when that block is complete and all other blocks have been checked.
132 Operation *complete = cache ? op : nullptr;
133 for (Region &region : op->getRegions()) {
134 for (Block &block : region) {
135 worklist.push_back({block.begin(), block.end(), complete});
136 complete = nullptr;
137 }
138 }
139 if (complete)
140 (*cache)[complete] = State::Dead;
141 }
142 return true;
143}
144
146 // Cache only effects. Uses can change without a change to the defining op.
147 // Nested operations may have internal uses or be terminators even when the
148 // whole root can be erased, so these checks apply only to the root.
149 if (!root->use_empty() || root->mightHaveTrait<OpTrait::IsTerminator>() ||
150 isa<SymbolOpInterface>(root))
151 return false;
152
153 if (!pending.empty())
154 flushInvalidations();
155 auto cachedRoot = cache.find(root);
156 if (cachedRoot != cache.end())
157 return cachedRoot->second == State::Dead;
158
159 return wouldOpBeTriviallyDeadImpl(root, &cache);
160}
161
162void DeadnessCache::enqueue(Target target, Request request) {
163 auto [it, inserted] = pending.try_emplace(target, request);
164 if (inserted)
165 return;
166 if (it->second == Request::Cancelled) {
167 // New IR at a reused address starts with its own request.
168 --numCancelled;
169 it->second = request;
170 } else if (request == Request::Subtree) {
171 it->second = Request::Subtree;
172 }
173}
174
175void DeadnessCache::cancel(Target target) {
176 auto it = pending.find(target);
177 if (it == pending.end() || it->second == Request::Cancelled)
178 return;
179 it->second = Request::Cancelled;
180 ++numCancelled;
181 if (numCancelled >= pending.size() - numCancelled)
182 removeCancelled();
183}
184
185void DeadnessCache::removeCancelled() {
186 if (!numCancelled)
187 return;
188 pending.remove_if(
189 [](const auto &entry) { return entry.second == Request::Cancelled; });
190 numCancelled = 0;
191}
192
194 // An empty cache has no stale entries. The next query computes effects from
195 // the current IR, so skip queuing a redundant subtree walk.
196 if (cache.empty())
197 return;
198 // An operation for which deadness isn't cached can only invalidate
199 // deadness of ancestors (if it is removed). Siblings can share the
200 // same request from a common parent even if they are all erased
201 // before the next query.
202 if (op->getNumRegions() || cache.contains(op))
203 enqueue(op, Request::Subtree);
204 else if (Operation *parent = op->getParentOp())
206}
207
209 if (!cache.empty())
210 enqueue(op, Request::Ancestors);
211}
212
214 if (cache.empty())
215 return;
216 enqueue(block, Request::Subtree);
217 if (Operation *parent = block->getParentOp())
219}
220
222 cancel(block);
223 if (Operation *parent = block->getParentOp())
225}
226
228 cancel(op);
229 cache.erase(op);
230 if (Operation *parent = op->getParentOp())
232}
233
234void DeadnessCache::flushInvalidations() {
235 removeCancelled();
236 // A block can promote an ancestor request after this loop has passed its
237 // slot. Defer subtree walks until all such promotions are visible. Otherwise
238 // we could miss the promoted op's descendants and use stale cache entries.
239 for (size_t i = 0; i < pending.size(); ++i) {
240 Target target = pending.getArrayRef()[i].first;
241 if (auto *block = dyn_cast<Block *>(target)) {
242 for (Operation &op : *block)
243 enqueue(&op, Request::Subtree);
244 continue;
245 }
246 Operation *op = cast<Operation *>(target);
247 // Even a subtree request can name the last cached op. Erase it before
248 // scheduling its parent so we can stop queuing ancestors in that case.
249 cache.erase(op);
250 if (Operation *parent = op->getParentOp())
251 scheduleAncestorInvalidation(parent);
252 }
253
254 // A nested root has its own walk. Skip its descendants in the parent walk.
255 for (auto [target, request] : pending) {
256 Operation *root = dyn_cast<Operation *>(target);
257 if (!root || request != Request::Subtree)
258 continue;
259 root->walk<WalkOrder::PreOrder>([&](Operation *op) {
260 if (op != root && pending.lookup(op) == Request::Subtree)
261 return WalkResult::skip();
262 cache.erase(op);
263 return WalkResult::advance();
264 });
265 }
266 pending.clear();
267}
268
269template <typename EffectTy>
271 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
272 if (!memOp)
273 return false;
275 memOp.getEffects(effects);
276 bool hasSingleEffectOnVal = false;
277 // Iterate through `effects` and check if an effect of type `EffectTy` and
278 // only of that type is present.
279 for (auto &effect : effects) {
280 hasSingleEffectOnVal = isa<EffectTy>(effect.getEffect());
281 if (!hasSingleEffectOnVal)
282 return false;
283 }
284 return hasSingleEffectOnVal;
285}
290
291template <typename EffectTy>
293 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
294 if (!memOp)
295 return false;
297 memOp.getEffects(effects);
298 bool hasSingleEffectOnVal = false;
299 // Iterate through `effects` and check if an effect of type `EffectTy` and
300 // only of that type is present.
301 for (auto &effect : effects) {
302 if (effect.getValue() != value)
303 continue;
304 hasSingleEffectOnVal = isa<EffectTy>(effect.getEffect());
305 if (!hasSingleEffectOnVal)
306 return false;
307 }
308 return hasSingleEffectOnVal;
309}
310
312 Value value);
314 Value value);
316 Value value);
318 Value value);
319
320template <typename ValueTy, typename EffectTy>
321bool mlir::hasSingleEffect(Operation *op, ValueTy value) {
322 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
323 if (!memOp)
324 return false;
326 memOp.getEffects(effects);
327 bool hasSingleEffectOnVal = false;
328 // Iterate through `effects` and check if an effect of type `EffectTy` and
329 // only of that type is present on value.
330 for (auto &effect : effects) {
331 if (effect.getEffectValue<ValueTy>() != value)
332 continue;
333 hasSingleEffectOnVal = isa<EffectTy>(effect.getEffect());
334 if (!hasSingleEffectOnVal)
335 return false;
336 }
337 return hasSingleEffectOnVal;
338}
339
340template bool
342 OpOperand *);
343template bool
345 OpOperand *);
346template bool
348 OpOperand *);
349template bool
351 OpOperand *);
352template bool
355 OpResult);
357 OpResult);
359 OpResult);
360template bool
363template bool
366template bool
369template bool
372
373template <typename... EffectTys>
375 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
376 if (!memOp)
377 return false;
379 memOp.getEffects(effects);
380 return llvm::any_of(effects, [&](MemoryEffects::EffectInstance &effect) {
381 return isa<EffectTys...>(effect.getEffect());
382 });
383}
388template bool
390
391template <typename... EffectTys>
393 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
394 if (!memOp)
395 return false;
397 memOp.getEffects(effects);
398 return llvm::any_of(effects, [&](MemoryEffects::EffectInstance &effect) {
399 if (effect.getValue() != value)
400 return false;
401 return isa<EffectTys...>(effect.getEffect());
402 });
403}
405 Value value);
409template bool
411 Value value);
412
413template <typename ValueTy, typename... EffectTys>
414bool mlir::hasEffect(Operation *op, ValueTy value) {
415 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
416 if (!memOp)
417 return false;
419 memOp.getEffects(effects);
420 return llvm::any_of(effects, [&](MemoryEffects::EffectInstance &effect) {
421 if (effect.getEffectValue<ValueTy>() != value)
422 return false;
423 return isa<EffectTys...>(effect.getEffect());
424 });
425}
426template bool
429 OpOperand *);
431 OpOperand *);
433 OpOperand *);
434template bool
436 Operation *, OpOperand *);
437
439 OpResult);
441 OpResult);
443 OpResult);
445 OpResult);
446template bool
449
450template bool
453template bool
455template bool
457template bool
460template bool
463
465 return !isa<MemoryEffectOpInterface>(op) &&
467}
468
471 return false;
472 if (isa<SymbolOpInterface>(op))
473 return false;
475}
476
478 if (auto memInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
479 if (!memInterface.hasNoEffect())
480 return false;
481 // If the op does not have recursive side effects, then it is memory effect
482 // free.
484 return true;
485 } else if (!op->hasTrait<OpTrait::HasRecursiveMemoryEffects>()) {
486 // Otherwise, if the op does not implement the memory effect interface and
487 // it does not have recursive side effects, then it cannot be known that the
488 // op is moveable.
489 return false;
490 }
491
492 // Recurse into the regions and ensure that all nested ops are memory effect
493 // free.
494 for (Region &region : op->getRegions())
495 for (Operation &op : region.getOps())
496 if (!isMemoryEffectFree(&op))
497 return false;
498 return true;
499}
500
501// the returned vector may contain duplicate effects
502std::optional<llvm::SmallVector<MemoryEffects::EffectInstance>>
505 SmallVector<Operation *> effectingOps(1, rootOp);
506 while (!effectingOps.empty()) {
507 Operation *op = effectingOps.pop_back_val();
508
509 // If the operation has recursive effects, push all of the nested
510 // operations on to the stack to consider.
511 bool hasRecursiveEffects =
513 if (hasRecursiveEffects) {
514 for (Region &region : op->getRegions()) {
515 for (Block &block : region) {
516 for (Operation &nestedOp : block) {
517 effectingOps.push_back(&nestedOp);
518 }
519 }
520 }
521 }
522
523 if (auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
524 effectInterface.getEffects(effects);
525 } else if (!hasRecursiveEffects) {
526 // the operation does not have recursive memory effects or implement
527 // the memory effect op interface. Its effects are unknown.
528 return std::nullopt;
529 }
530 }
531 return effects;
532}
533
535 auto conditionallySpeculatable = dyn_cast<ConditionallySpeculatable>(op);
536 if (!conditionallySpeculatable)
537 return false;
538
539 switch (conditionallySpeculatable.getSpeculatability()) {
541 for (Region &region : op->getRegions()) {
542 for (Operation &op : region.getOps())
543 if (!isSpeculatable(&op))
544 return false;
545 }
546 return true;
547
549 return true;
550
552 return false;
553 }
554
555 llvm_unreachable("Unhandled enum in mlir::isSpeculatable!");
556}
557
558/// The implementation of this function replicates the `def Pure : TraitList`
559/// in `SideEffectInterfaces.td` and has to be kept in sync manually.
561 return isSpeculatable(op) && isMemoryEffectFree(op);
562}
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static bool hasOnlyRemovableEffects(Operation *op, bool hasRecursiveEffects)
Return true if the op's own memory effects do not prevent erasure.
static bool wouldOpBeTriviallyDeadImpl(Operation *root, DenseMap< Operation *, DeadnessCache::State > *cache=nullptr)
Internal implementation of mlir::wouldOpBeTriviallyDead that also considers terminator operations as ...
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType::iterator iterator
Definition Block.h:165
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
void scheduleBlockInvalidation(Block *block)
Report a change to a block and its contents.
bool isOpTriviallyDead(Operation *op)
Return true if the operation is unused and can be erased.
void scheduleAncestorInvalidation(Operation *op)
Invalidate the cached effects of this operation and its ancestors.
void notifyOperationErased(Operation *op)
Call once for each erased operation before it is detached or destroyed.
void scheduleInvalidation(Operation *op)
Report a change to this operation or its nested IR.
void notifyBlockErased(Block *block)
Call before an empty block is detached and destroyed.
This class represents an operand of an operation.
Definition Value.h:256
This is a value defined by a result of an operation.
Definition Value.h:456
This trait indicates that the memory effects of an operation includes the effects of operations neste...
This class provides the API for ops that are known to be terminators.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:906
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Definition Operation.h:811
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
EffectT * getEffect() const
Return the effect being applied.
T getEffectValue() const
Returns the OpOperand effect is applied on, or nullptr if there isn't a known value being effected.
Value getValue() const
Return the value the effect is applied on, or nullptr if there isn't a known value being affected.
This class represents a base class for a specific effect type.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
SideEffects::EffectInstance< Effect > EffectInstance
constexpr auto RecursivelySpeculatable
constexpr auto Speculatable
constexpr auto NotSpeculatable
Include the generated interface declarations.
bool hasSingleEffect(Operation *op)
Returns "true" if op has only an effect of type EffectTy.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
bool wouldOpBeTriviallyDead(Operation *op)
Return true if the given operation would be dead if unused, and has no side effects on memory that wo...
bool isSpeculatable(Operation *op)
Returns true if the given operation is speculatable, i.e.
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
std::optional< llvm::SmallVector< MemoryEffects::EffectInstance > > getEffectsRecursively(Operation *rootOp)
Returns the side effects of an operation.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
bool hasEffect(Operation *op)
Returns "true" if op has an effect of type EffectTy.
bool hasUnknownEffects(Operation *op)
Return "true" if op has unknown effects.
static bool classof(const SideEffects::Effect *effect)
Include the definitions of the side effect interfaces.