24#include "llvm/Support/Debug.h"
25#include "llvm/Support/DebugLog.h"
26#include "llvm/Support/raw_ostream.h"
29#define DEBUG_TYPE "affine-fusion-utils"
39 if (
auto loadOp = dyn_cast<AffineReadOpInterface>(op)) {
40 if (values.count(loadOp.getMemRef()) == 0)
41 values[loadOp.getMemRef()] =
false;
42 }
else if (
auto storeOp = dyn_cast<AffineWriteOpInterface>(op)) {
43 values[storeOp.getMemRef()] =
true;
53 if (
auto loadOp = dyn_cast<AffineReadOpInterface>(op))
54 return values.count(loadOp.getMemRef()) > 0 && values[loadOp.getMemRef()];
55 if (
auto storeOp = dyn_cast<AffineWriteOpInterface>(op))
56 return values.count(storeOp.getMemRef()) > 0;
104 if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op)) {
116 if (llvm::is_contained(loops, cast<AffineForOp>(opB))) {
134 AffineForOp dstForOp) {
135 bool isSrcForOpBeforeDstForOp = srcForOp->isBeforeInBlock(dstForOp);
136 auto forOpA = isSrcForOpBeforeDstForOp ? srcForOp : dstForOp;
137 auto forOpB = isSrcForOpBeforeDstForOp ? dstForOp : srcForOp;
155 if (firstDepOpA->
isBeforeInBlock(lastDepOpB) || firstDepOpA == lastDepOpB)
173 bool hasIfOp =
false;
175 if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op))
176 loadAndStoreOps.push_back(op);
177 else if (isa<AffineIfOp>(op))
200 auto loadOp = dyn_cast<AffineReadOpInterface>(dstOp);
202 : cast<AffineWriteOpInterface>(dstOp).getMemRef();
203 if (producerConsumerMemrefs.count(
memref) > 0)
204 targetDstOps.push_back(dstOp);
207 assert(!targetDstOps.empty() &&
208 "No dependences between 'srcForOp' and 'dstForOp'?");
214 if (all_of(targetDstOps, llvm::IsaPred<AffineReadOpInterface>))
219 for (
unsigned i = 0, e = targetDstOps.size(); i < e; ++i) {
222 for (
unsigned j = 0;
j < e; ++
j) {
223 auto *dstOpInst = targetDstOps[
j];
226 unsigned numCommonLoops =
228 for (
unsigned d = 1; d <= numCommonLoops + 1; ++d) {
235 loopDepth = std::min(loopDepth, d - 1);
251 unsigned numCommonLoops,
252 bool isBackwardSlice,
254 auto isLoadFromMemRef = [&](
Operation *op) {
255 auto load = dyn_cast<AffineReadOpInterface>(op);
259 std::optional<ComputationSliceState> validSlice;
261 for (
Operation *a : llvm::make_filter_range(opsA, isLoadFromMemRef)) {
262 for (
Operation *
b : llvm::make_filter_range(opsB, isLoadFromMemRef)) {
265 a,
b, dstLoopDepth, numCommonLoops, isBackwardSlice, &
slice);
272 if (
slice.isMaximal().value_or(
false)) {
282 LDBG() <<
"No valid sibling fusion slice";
285 *srcSlice = *validSlice;
293 AffineForOp dstForOp,
294 unsigned dstLoopDepth,
298 if (dstLoopDepth == 0) {
299 LDBG() <<
"Cannot fuse loop nests at depth 0";
303 auto *block = srcForOp->getBlock();
304 if (block != dstForOp->getBlock()) {
305 LDBG() <<
"Cannot fuse loop nests in different blocks";
312 LDBG() <<
"Fusion would violate dependences in block";
317 bool isSrcForOpBeforeDstForOp = srcForOp->isBeforeInBlock(dstForOp);
319 auto forOpA = isSrcForOpBeforeDstForOp ? srcForOp : dstForOp;
320 auto forOpB = isSrcForOpBeforeDstForOp ? dstForOp : srcForOp;
325 LDBG() <<
"Fusing loops with affine.if unsupported";
332 LDBG() <<
"Fusing loops with affine.if unsupported";
342 assert(isSrcForOpBeforeDstForOp &&
"Unexpected forward slice fusion");
344 LDBG() <<
"Fusion would violate loop dependences";
350 unsigned numCommonLoops =
360 strategyOpsA.append(opsA.begin(), opsA.end());
366 if (isa<AffineWriteOpInterface>(op))
367 strategyOpsA.push_back(op);
375 numCommonLoops, isSrcForOpBeforeDstForOp, srcSlice);
381 strategyOpsA, opsB, dstLoopDepth, numCommonLoops,
382 isSrcForOpBeforeDstForOp, srcSlice);
384 LDBG() <<
"computeSliceUnion failed";
387 if (sliceComputationResult.
value ==
389 LDBG() <<
"Incorrect slice computation";
399 bool siblingFusionUser) {
401 std::optional<APInt> tripCount = forOp.getStaticTripCount();
402 if (!tripCount || *tripCount != 1)
404 auto *parentOp = forOp->getParentOp();
405 if (!isa<AffineForOp>(parentOp))
408 llvm::append_range(newOperands,
409 forOp.getBody()->getTerminator()->getOperands());
411 int64_t parentOpNumResults = parentOp->getNumResults();
413 AffineForOp parentForOp = forOp->getParentOfType<AffineForOp>();
414 AffineForOp newLoop =
415 cast<AffineForOp>(*parentForOp.replaceWithAdditionalYields(
416 rewriter, forOp.getInits(),
false,
426 if (siblingFusionUser) {
427 for (
unsigned i = 0, e = forOp.getNumResults(); i != e; ++i) {
430 forwardSlice.set_union(tmpForwardSlice);
434 for (
unsigned i = 0, e = forOp.getNumResults(); i != e; ++i) {
435 forOp.getResult(i).replaceAllUsesWith(
436 newLoop.getResult(i + parentOpNumResults));
440 if (siblingFusionUser) {
442 for (
Operation *op : llvm::reverse(forwardSlice))
443 op->moveAfter(newLoop);
446 auto iv = forOp.getInductionVar();
447 iv.replaceAllUsesWith(newLoop.getInductionVar());
449 auto forOpIterArgs = forOp.getRegionIterArgs();
450 for (
auto it : llvm::zip(forOpIterArgs, newLoop.getRegionIterArgs().take_back(
451 forOpIterArgs.size()))) {
452 std::get<0>(it).replaceAllUsesWith(std::get<1>(it));
456 forOp.getBody()->back().erase();
457 auto *parentBlock = forOp->getBlock();
459 forOp.getBody()->getOperations());
468 bool isInnermostSiblingInsertion) {
472 b.clone(*srcForOp, mapper);
476 for (
unsigned i = 0, e = srcSlice.
ivs.size(); i < e; ++i) {
481 sliceLoops.push_back(forOp);
485 forOp.setLowerBound(lbOperands, lbMap);
490 forOp.setUpperBound(ubOperands, ubMap);
494 llvm::SmallDenseMap<Operation *, uint64_t, 8> sliceTripCountMap;
495 auto srcIsUnitSlice = [&]() {
500 for (AffineForOp forOp : sliceLoops) {
502 isInnermostSiblingInsertion && srcIsUnitSlice())
517 auto walkResult = forOpRoot.walk([&](AffineForOp forOp) {
518 auto *childForOp = forOp.getOperation();
519 auto *parentForOp = forOp->getParentOp();
520 if (forOp != forOpRoot) {
521 if (!isa<AffineForOp>(parentForOp)) {
522 LDBG() <<
"Expected parent AffineForOp";
526 stats->
loopMap[parentForOp].push_back(forOp);
532 for (
auto &op : *forOp.getBody()) {
533 if (!isa<AffineForOp, AffineIfOp>(op))
540 std::optional<APInt> maybeConstTripCount = forOp.getStaticTripCount();
541 if (!maybeConstTripCount) {
543 LDBG() <<
"Non-constant trip count unsupported";
547 stats->
tripCountMap[childForOp] = maybeConstTripCount->getZExtValue();
550 return !walkResult.wasInterrupted();
570 llvm::SmallDenseMap<Operation *, uint64_t, 8> *tripCountOverrideMap,
575 if (stats.
loopMap.count(forOp) > 0) {
576 for (
auto childForOp : stats.
loopMap[forOp]) {
582 if (computeCostMap) {
583 auto it = computeCostMap->find(forOp);
584 if (it != computeCostMap->end()) {
585 opCount += it->second;
590 if (tripCountOverrideMap) {
591 auto it = tripCountOverrideMap->find(forOp);
592 if (it != tripCountOverrideMap->end()) {
593 tripCount = it->second;
597 return tripCount * opCount;
617 AffineForOp dstForOp,
621 llvm::SmallDenseMap<Operation *, uint64_t, 8> sliceTripCountMap;
631 if (sliceIterationCount == 0)
633 bool storeLoadFwdGuaranteed = (sliceIterationCount == 1);
634 auto *insertPointParent =
slice.insertPoint->getParentOp();
637 if (storeLoadFwdGuaranteed) {
641 llvm::SmallDenseSet<Value, 4> storeMemrefs;
642 srcForOp.walk([&](AffineWriteOpInterface storeOp) {
643 storeMemrefs.insert(storeOp.getMemRef());
648 computeCostMap[insertPointParent] = -storeCount;
653 if (!isa<AffineReadOpInterface>(user))
659 if (llvm::is_contained(loops, cast<AffineForOp>(insertPointParent))) {
660 if (
auto forOp = dyn_cast_or_null<AffineForOp>(user->getParentOp()))
661 --computeCostMap[forOp];
669 srcForOp, srcStats, &sliceTripCountMap, &computeCostMap);
672 computeCostMap[insertPointParent] = sliceComputeCost;
676 nullptr, &computeCostMap);
689 if (
auto storeOp = dyn_cast<AffineWriteOpInterface>(op))
690 srcStoreMemRefs.insert(storeOp.getMemRef());
695 if (
auto loadOp = dyn_cast<AffineReadOpInterface>(op))
696 if (srcStoreMemRefs.count(loadOp.getMemRef()) > 0)
697 producerConsumerMemrefs.insert(loadOp.getMemRef());
static Operation * getFirstDependentOpInRange(Operation *opA, Operation *opB)
static Operation * getFusedLoopNestInsertionPoint(AffineForOp srcForOp, AffineForOp dstForOp)
static void getLoadAndStoreMemRefAccesses(Operation *opA, DenseMap< Value, bool > &values)
static bool gatherLoadsAndStores(AffineForOp forOp, SmallVectorImpl< Operation * > &loadAndStoreOps)
static int64_t getComputeCostHelper(Operation *forOp, LoopNestStats &stats, llvm::SmallDenseMap< Operation *, uint64_t, 8 > *tripCountOverrideMap, DenseMap< Operation *, int64_t > *computeCostMap)
static bool isDependentLoadOrStoreOp(Operation *op, DenseMap< Value, bool > &values)
Returns true if 'op' is a load or store operation which access a memref accessed 'values' and at leas...
static LogicalResult promoteSingleIterReductionLoop(AffineForOp forOp, bool siblingFusionUser)
Patch the loop body of a forOp that is a single iteration reduction loop into its containing block.
static Operation * getLastDependentOpInRange(Operation *opA, Operation *opB)
static unsigned getMaxLoopDepth(ArrayRef< Operation * > srcOps, ArrayRef< Operation * > dstOps)
Returns the maximum loop depth at which we could fuse producer loop 'srcForOp' into consumer loop 'ds...
static FusionResult computeSiblingSlice(ArrayRef< Operation * > opsA, ArrayRef< Operation * > opsB, Value memref, unsigned dstLoopDepth, unsigned numCommonLoops, bool isBackwardSlice, ComputationSliceState *srcSlice)
Computes in 'srcSlice' the sibling fusion slice from a single pair of loads to 'memref' in 'opsA' and...
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
OpListType::iterator iterator
OpListType::reverse_iterator reverse_iterator
This is a utility class for mapping one set of IR entities to another.
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
Operation is the basic unit of execution within MLIR.
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
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),...
user_range getUsers()
Returns a range of all users.
result_range getResults()
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
static WalkResult advance()
static WalkResult interrupt()
Describes the fusion strategy to be used in the Affine loop fusion utilities.
StrategyEnum getStrategy() const
Returns the fusion strategy.
Value getSiblingFusionMemRef() const
Returns the memref attached to this sibling fusion strategy.
LogicalResult promoteIfSingleIteration(AffineForOp forOp)
Promotes the loop body of a AffineForOp to its containing block if the loop was known to have a singl...
bool getFusionComputeCost(AffineForOp srcForOp, LoopNestStats &srcStats, AffineForOp dstForOp, LoopNestStats &dstStats, const ComputationSliceState &slice, int64_t *computeCost)
Computes and returns in 'computeCost', the total compute cost of fusing the 'slice' of the loop nest ...
SliceComputationResult computeSliceUnion(ArrayRef< Operation * > opsA, ArrayRef< Operation * > opsB, unsigned loopDepth, unsigned numCommonLoops, bool isBackwardSlice, ComputationSliceState *sliceUnion)
Computes in 'sliceUnion' the union of all slice bounds computed at 'loopDepth' between all dependent ...
bool isLoopParallelAndContainsReduction(AffineForOp forOp)
Returns whether a loop is a parallel loop and contains a reduction loop.
unsigned getNumCommonSurroundingLoops(Operation &a, Operation &b)
Returns the number of surrounding loops common to both A and B.
void gatherProducerConsumerMemrefs(ArrayRef< Operation * > srcOps, ArrayRef< Operation * > dstOps, DenseSet< Value > &producerConsumerMemrefs)
Returns in 'producerConsumerMemrefs' the memrefs involved in a producer-consumer dependence between w...
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
DependenceResult checkMemrefAccessDependence(const MemRefAccess &srcAccess, const MemRefAccess &dstAccess, unsigned loopDepth, FlatAffineValueConstraints *dependenceConstraints=nullptr, SmallVector< DependenceComponent, 2 > *dependenceComponents=nullptr, bool allowRAR=false)
void canonicalizeMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands)
Modifies both map and operands in-place so as to:
int64_t getComputeCost(AffineForOp forOp, LoopNestStats &stats)
Computes the total cost of the loop nest rooted at 'forOp' using 'stats'.
void fuseLoops(AffineForOp srcForOp, AffineForOp dstForOp, const ComputationSliceState &srcSlice, bool isInnermostSiblingInsertionFusion=false)
Fuses 'srcForOp' into 'dstForOp' with destination loop block insertion point and source slice loop bo...
void getAffineForIVs(Operation &op, SmallVectorImpl< AffineForOp > *loops)
Populates 'loops' with IVs of the affine.for ops surrounding 'op' ordered from the outermost 'affine....
unsigned getInnermostCommonLoopDepth(ArrayRef< Operation * > ops, SmallVectorImpl< AffineForOp > *surroundingLoops=nullptr)
Returns the innermost common loop depth for the set of operations in 'ops'.
bool getLoopNestStats(AffineForOp forOp, LoopNestStats *stats)
Collect loop nest statistics (eg.
bool hasDependence(DependenceResult result)
Utility function that returns true if the provided DependenceResult corresponds to a dependence resul...
uint64_t getSliceIterationCount(const llvm::SmallDenseMap< Operation *, uint64_t, 8 > &sliceTripCountMap)
Return the number of iterations for the slicetripCountMap provided.
FusionResult canFuseLoops(AffineForOp srcForOp, AffineForOp dstForOp, unsigned dstLoopDepth, ComputationSliceState *srcSlice, FusionStrategy fusionStrategy=FusionStrategy::Generic)
Checks the feasibility of fusing the loop nest rooted at 'srcForOp' into the loop nest rooted at 'dst...
bool buildSliceTripCountMap(const ComputationSliceState &slice, llvm::SmallDenseMap< Operation *, uint64_t, 8 > *tripCountMap)
Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop nest surrounding represe...
Include the generated interface declarations.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
llvm::SetVector< T, Vector, Set, N > SetVector
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
SetVector< Operation * > topologicalSort(const SetVector< Operation * > &toSort)
Sorts all operations in toSort topologically while also considering region semantics.
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.
ComputationSliceState aggregates loop IVs, loop bound AffineMaps and their associated operands for a ...
SmallVector< Value, 4 > ivs
std::vector< SmallVector< Value, 4 > > ubOperands
SmallVector< AffineMap, 4 > ubs
SmallVector< AffineMap, 4 > lbs
Block::iterator insertPoint
std::vector< SmallVector< Value, 4 > > lbOperands
Checks whether two accesses to the same memref access the same element.
LoopNestStats aggregates various per-loop statistics (eg.
DenseMap< Operation *, uint64_t > opCountMap
Map from AffineForOp to count of operations in its loop body.
DenseMap< Operation *, SmallVector< AffineForOp, 2 > > loopMap
Map from AffineForOp to immediate child AffineForOps in its loop body.
DenseMap< Operation *, uint64_t > tripCountMap
Map from AffineForOp to its constant trip count.
Encapsulates a memref load or store access information.
Enumerates different result statuses of slice computation by computeSliceUnion
enum mlir::affine::SliceComputationResult::ResultEnum value
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.