1 //===- SwapExtractSliceWithFillPatterns.cpp -------------------------------===//
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 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
10 #include "mlir/IR/PatternMatch.h"
11
12 using namespace mlir;
13 using namespace mlir::linalg;
14
15 /// Swaps tensor.extract_slice(linalg.fill(%cst, %init)) into linalg.fill(%cst,
16 /// tensor.extract_slice(%init)) when the linalg.fill op have no other users.
17 /// This helps to reduce the fill footprint.
18 struct SwapExtractSliceOfFill final
19 : public OpRewritePattern<tensor::ExtractSliceOp> {
20 using OpRewritePattern::OpRewritePattern;
21
matchAndRewriteSwapExtractSliceOfFill22 LogicalResult matchAndRewrite(tensor::ExtractSliceOp extractOp,
23 PatternRewriter &rewriter) const override {
24 auto fillOp = extractOp.getSource().getDefiningOp<FillOp>();
25 if (!fillOp || !fillOp->hasOneUse())
26 return failure();
27
28 auto newExtractOp = rewriter.create<tensor::ExtractSliceOp>(
29 extractOp.getLoc(), extractOp.getType(), fillOp.getOutputs()[0],
30 extractOp.getMixedOffsets(), extractOp.getMixedSizes(),
31 extractOp.getMixedStrides());
32 rewriter.replaceOpWithNewOp<FillOp>(extractOp, fillOp.getInputs(),
33 ValueRange{newExtractOp.getResult()});
34 return success();
35 }
36 };
37
populateSwapExtractSliceWithFillPatterns(RewritePatternSet & patterns)38 void mlir::linalg::populateSwapExtractSliceWithFillPatterns(
39 RewritePatternSet &patterns) {
40 patterns.add<SwapExtractSliceOfFill>(patterns.getContext());
41 }
42