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
12using namespace mlir;
13using 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.
18struct SwapExtractSliceOfFill final
19 : public OpRewritePattern<tensor::ExtractSliceOp> {
20 using OpRewritePattern::OpRewritePattern;
21
22 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
38void mlir::linalg::populateSwapExtractSliceWithFillPatterns(
39 RewritePatternSet &patterns) {
40 patterns.add<SwapExtractSliceOfFill>(arg: patterns.getContext());
41}
42

source code of mlir/lib/Dialect/Linalg/Transforms/SwapExtractSliceWithFillPatterns.cpp