I'll create an MLIR optimization pass that fuses compatible linalg operations when they have producer-consumer relationships. This is useful for improving locality and reducing memory traffic.
cpp
//===- LinalgFusionPass.cpp - Linalg fusion pass -----------------------===//
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
using namespace mlir::linalg;
namespace {
struct LinalgFusionPattern : public OpRewritePattern<GenericOp> {
using OpRewritePattern<GenericOp>::OpRewritePattern;
LogicalResult matchAndRewrite(GenericOp consumerOp,
PatternRewriter &rewriter) const override {
// Only handle generic operations with single result
if (consumerOp.getNumResults() != 1)
return failure();
// Find producer op
Value consumerArg = consumerOp.getOperand(0);
GenericOp producerOp = consumerArg.getDefiningOp<GenericOp>();
if (!producerOp)
return failure();
// Check if fusion is legal
if (!isProducerConsumerFusionLegal(producerOp, consumerOp))
return failure();
// Perform the fusion
auto fusedOp = fuseProducerConsumerGenericOps(rewriter, producerOp,
consumerOp);
if (!fusedOp)
return failure();
rewriter.replaceOp(consumerOp, fusedOp->getResults());
return success();
}
private:
bool isProducerConsumerFusionLegal(GenericOp producer,
GenericOp consumer) const {
// Check if producer result is only used by consumer
if (!producer.getResult(0).hasOneUse())
return false;
// Check if operations have compatible iteration spaces
auto producerMap = producer.getIndexingMap(0);
auto consumerMap = consumer.getIndexingMap(0);
return producerMap.isPermutation() &&
consumerMap.isPermutation() &&
producer.getNumParallelLoops() == consumer.getNumParallelLoops();
}
};
struct LinalgFusionPass
: public PassWrapper<LinalgFusionPass, OperationPass<func::FuncOp>> {
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<LinalgDialect>();
}
void runOnOperation() override {
MLIRContext *ctx = &getContext();
RewritePatternSet patterns(ctx);
patterns.add<LinalgFusionPattern>(ctx);
if (failed(applyPatternsAndFoldGreedily(getOperation(),
std::move(patterns)))) {
signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<Pass> createLinalgFusionPass() {
return std::make_unique<LinalgFusionPass>();
}
This pass implements producer-consumer fusion for linalg.generic operations. The optimization is beneficial because:
It reduces memory traffic by eliminating intermediate buffers
Improves data locality by performing computations closer together
Can enable further optimizations like vectorization
Reduces the total number of operations that need to be scheduled
The pass checks for legal fusion opportunities by verifying:
Producer result is only used by the consumer
Operations have compatible iteration spaces
Indexing maps are permutations
Operations have the same number of parallel loops
The example shows fusion of two operations - one doing element-wise addition followed by multiplication. After fusion, the computations are performed in a single operation, eliminating the intermediate tensor allocation.