19#include "llvm/ADT/DenseMapInfo.h"
20#include "llvm/ADT/ScopedHashTable.h"
21#include "llvm/Support/Allocator.h"
22#include "llvm/Support/DebugLog.h"
23#include "llvm/Support/RecyclingAllocator.h"
28#define DEBUG_TYPE "cse"
32 static unsigned getHashValue(
const Operation *opC) {
40 auto *lhs =
const_cast<Operation *
>(lhsC);
41 auto *rhs =
const_cast<Operation *
>(rhsC);
55 CSEDriver(RewriterBase &rewriter, DominanceInfo *domInfo)
56 : rewriter(rewriter), domInfo(domInfo) {}
59 void simplify(Operation *op,
bool *changed =
nullptr);
62 void simplify(Region ®ion,
bool *changed =
nullptr);
64 int64_t getNumCSE()
const {
return numCSE; }
65 int64_t getNumDCE()
const {
return numDCE; }
69 using AllocatorTy = llvm::RecyclingAllocator<
70 llvm::BumpPtrAllocator,
71 llvm::ScopedHashTableVal<Operation *, Operation *>>;
72 using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *,
73 SimpleOperationInfo, AllocatorTy>;
77 struct MemEffectsCache {
78 SmallVector<Operation *> writes;
80 Operation *lastScanned =
nullptr;
86 : scope(knownValues), node(node), childIterator(node->begin()) {}
89 ScopedMapTy::ScopeTy scope;
92 DominanceInfoNode::const_iterator childIterator;
95 bool processed =
false;
100 LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op,
101 bool hasSSADominance,
102 MemEffectsCache &memEffectsCache);
103 void simplifyBlock(ScopedMapTy &knownValues,
Block *bb,
bool hasSSADominance);
104 void simplifyRegion(ScopedMapTy &knownValues, Region ®ion);
108 void eraseDeadOp(Operation *op);
110 void replaceUsesAndDelete(ScopedMapTy &knownValues, Operation *op,
111 Operation *existing,
bool hasSSADominance);
115 bool hasOtherSideEffectingOpInBetween(Operation *fromOp, Operation *toOp,
116 MemEffectsCache &memEffectsCache);
119 RewriterBase &rewriter;
121 DominanceInfo *domInfo =
nullptr;
129void CSEDriver::replaceUsesAndDelete(ScopedMapTy &knownValues,
Operation *op,
131 bool hasSSADominance) {
135 if (isa<UnknownLoc>(existing->
getLoc()) && !isa<UnknownLoc>(op->
getLoc()))
142 if (hasSSADominance) {
153 auto wasVisited = [&](OpOperand &operand) {
154 return !knownValues.count(operand.getOwner());
156 if (
auto *rewriteListener =
157 dyn_cast_if_present<RewriterBase::Listener>(rewriter.
getListener()))
159 if (all_of(v.getUses(), wasVisited))
160 rewriteListener->notifyOperationReplaced(op, existing);
172bool CSEDriver::hasOtherSideEffectingOpInBetween(Operation *fromOp,
174 MemEffectsCache &cache) {
177 "expected read effect on fromOp");
179 "expected read effect on toOp");
180 if (fromOp->getNextNode() == toOp)
183 SmallVector<MemoryEffects::EffectInstance> readEffects;
184 cast<MemoryEffectOpInterface>(fromOp).getEffects(readEffects);
185 auto getEffects = [](Operation *op) {
186 LDBG() <<
"CSE checking effects: " << op->
getName();
191 auto canConflict = [&](
const auto &effects) {
194 return llvm::any_of(*effects, [&](
const auto &effect) {
195 if (!isa<MemoryEffects::Write>(effect.getEffect()))
197 SideEffects::Resource *writeResource = effect.getResource();
198 return llvm::any_of(readEffects, [&](
const auto &readEffect) {
199 SideEffects::Resource *readResource = readEffect.getResource();
202 if (readEffect.getValue() && !writeResource->
isAddressable())
211 auto isBefore = [](Operation *a, Operation *
b) {
214 auto first = llvm::upper_bound(cache.writes, fromOp, isBefore);
215 unsigned &nextWrite = cache.nextWrite[fromOp];
216 nextWrite = std::max(nextWrite,
unsigned(first - cache.writes.begin()));
217 for (; nextWrite < cache.writes.size(); ++nextWrite)
218 if (canConflict(getEffects(cache.writes[nextWrite])))
222 for (Operation *op = cache.lastScanned->getNextNode(); op != toOp;
223 op = op->getNextNode()) {
224 cache.lastScanned = op;
225 auto effects = getEffects(op);
226 if (effects && llvm::none_of(*effects, [](
const auto &effect) {
227 return isa<MemoryEffects::Write>(effect.getEffect());
230 cache.writes.push_back(op);
233 nextWrite = cache.writes.size();
239LogicalResult CSEDriver::simplifyOperation(ScopedMapTy &knownValues,
240 Operation *op,
bool hasSSADominance,
241 MemEffectsCache &memEffectsCache) {
243 if (op->
hasTrait<OpTrait::IsTerminator>())
249 [](Region &r) { return r.empty() || r.hasOneBlock(); }))
261 if (!memEffectsCache.lastScanned)
262 memEffectsCache.lastScanned = op;
265 if (
auto *existing = knownValues.lookup(op)) {
267 !hasOtherSideEffectingOpInBetween(existing, op, memEffectsCache)) {
271 replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
275 knownValues.insert(op, op);
280 if (
auto *existing = knownValues.lookup(op)) {
281 replaceUsesAndDelete(knownValues, op, existing, hasSSADominance);
286 knownValues.insert(op, op);
290void CSEDriver::simplifyBlock(ScopedMapTy &knownValues,
Block *bb,
291 bool hasSSADominance) {
292 MemEffectsCache memEffectsCache;
293 for (
auto &op : llvm::make_early_inc_range(*bb)) {
309 ScopedMapTy nestedKnownValues;
311 simplifyRegion(nestedKnownValues, region);
315 simplifyRegion(knownValues, region);
320 if (succeeded(simplifyOperation(knownValues, &op, hasSSADominance,
326void CSEDriver::simplifyRegion(ScopedMapTy &knownValues, Region ®ion) {
335 ScopedMapTy::ScopeTy scope(knownValues);
336 simplifyBlock(knownValues, ®ion.
front(), hasSSADominance);
343 if (!hasSSADominance)
352 std::deque<std::unique_ptr<CFGStackNode>> stack;
355 stack.emplace_back(std::make_unique<CFGStackNode>(
358 while (!stack.empty()) {
359 auto ¤tNode = stack.back();
362 if (!currentNode->processed) {
363 currentNode->processed =
true;
364 simplifyBlock(knownValues, currentNode->node->getBlock(),
369 if (currentNode->childIterator != currentNode->node->end()) {
370 auto *childNode = *(currentNode->childIterator++);
372 std::make_unique<CFGStackNode>(knownValues, childNode));
381void CSEDriver::eraseDeadOp(Operation *op) {
392void CSEDriver::simplify(Operation *op,
bool *changed) {
394 ScopedMapTy knownValues;
396 simplifyRegion(knownValues, region);
398 *changed = numCSE || numDCE;
401void CSEDriver::simplify(Region ®ion,
bool *changed) {
402 ScopedMapTy knownValues;
403 simplifyRegion(knownValues, region);
405 *changed = numCSE || numDCE;
410 bool *changed,
int64_t *numCSE,
412 CSEDriver driver(rewriter, &domInfo);
413 driver.simplify(op, changed);
415 *numCSE = driver.getNumCSE();
417 *numDCE = driver.getNumDCE();
423 CSEDriver driver(rewriter, &domInfo);
424 driver.simplify(region, changed);
template bool mlir::hasEffect< MemoryEffects::Read >(Operation *)
template bool mlir::hasSingleEffect< MemoryEffects::Read >(Operation *)
A class for computing basic dominance information.
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Operation is the basic unit of execution within MLIR.
void setLoc(Location loc)
Set the source location the operation was defined or derived from.
bool use_empty()
Returns true if this operation has no uses.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Block * getBlock()
Returns the operation block that contains this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
OperationName getName()
The name of an operation is the key identifier for it.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
result_range getResults()
This class contains a list of basic blocks and a link to the parent operation it is attached to.
bool hasOneBlock()
Return true if this region has exactly one block.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceAllOpUsesWith(Operation *from, ValueRange to)
Find uses of from and replace them with to.
virtual bool replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
virtual bool isAddressable() const
Returns true if this resource is addressable (effects on it can alias pointer-based memory).
bool isDisjointFrom(const Resource *other) const
Returns true if this resource is disjoint from another.
DominanceInfoNode * getRootNode(Region *region)
Get the root dominance node of the given region.
bool hasSSADominance(Block *block) const
Return true if operations in the specified block are known to obey SSA dominance requirements.
void invalidate()
Invalidate dominance info.
Include the generated interface declarations.
void eliminateCommonSubExpressions(RewriterBase &rewriter, DominanceInfo &domInfo, Operation *op, bool *changed=nullptr, int64_t *numCSE=nullptr, int64_t *numDCE=nullptr)
Eliminate common subexpressions within the given operation.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::DomTreeNodeBase< Block > DominanceInfoNode
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
static llvm::hash_code ignoreHashValue(Value)
Helper that can be used with computeHash above to ignore operation operands/result mapping.
static bool isEquivalentTo(Operation *lhs, Operation *rhs, function_ref< LogicalResult(Value, Value)> checkEquivalent, function_ref< void(Value, Value)> markEquivalent=nullptr, Flags flags=Flags::None, function_ref< LogicalResult(ValueRange, ValueRange)> checkCommutativeEquivalent=nullptr)
Compare two operations (including their regions) and return if they are equivalent.
static llvm::hash_code directHashValue(Value v)
Helper that can be used with computeHash to compute the hash value of operands/results directly.
static llvm::hash_code computeHash(Operation *op, function_ref< llvm::hash_code(Value)> hashOperands=[](Value v) { return hash_value(v);}, function_ref< llvm::hash_code(Value)> hashResults=[](Value v) { return hash_value(v);}, Flags flags=Flags::None)
Compute a hash for the given operation.