1b6281940SNicolas Vasilache //===- Tiling.cpp - Implementation of linalg Tiling -----------------------===//
2b6281940SNicolas Vasilache //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b6281940SNicolas Vasilache //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
8b6281940SNicolas Vasilache //
9b6281940SNicolas Vasilache // This file implements the linalg dialect Tiling pass.
10b6281940SNicolas Vasilache //
11b6281940SNicolas Vasilache //===----------------------------------------------------------------------===//
12b6281940SNicolas Vasilache 
131fc096afSMehdi Amini #include <utility>
141fc096afSMehdi Amini 
151834ad4aSRiver Riddle #include "PassDetail.h"
16297ba167SChristopher Bate #include "mlir/Dialect/Arithmetic/Utils/Utils.h"
173963b4d0SAlex Zinenko #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
18b7f2c108Sgysit #include "mlir/Dialect/Linalg/IR/Linalg.h"
190c8ad3aaSNicolas Vasilache #include "mlir/Dialect/Linalg/Passes.h"
20307cfdf5SNicolas Vasilache #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
210c8ad3aaSNicolas Vasilache #include "mlir/Dialect/Linalg/Utils/Utils.h"
22e2310704SJulian Gross #include "mlir/Dialect/MemRef/IR/MemRef.h"
238b68da2cSAlex Zinenko #include "mlir/Dialect/SCF/Transforms/Transforms.h"
24129d6e55SSean Silva #include "mlir/Dialect/Tensor/IR/Tensor.h"
25f71f9958SDiego Caballero #include "mlir/Dialect/Utils/IndexingUtils.h"
26b6281940SNicolas Vasilache #include "mlir/IR/AffineExpr.h"
27b6281940SNicolas Vasilache #include "mlir/IR/AffineMap.h"
28b6281940SNicolas Vasilache #include "mlir/Transforms/FoldUtils.h"
29b6eb26fdSRiver Riddle #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
30b6281940SNicolas Vasilache 
31b6281940SNicolas Vasilache #include "llvm/Support/CommandLine.h"
32b6281940SNicolas Vasilache 
33b6281940SNicolas Vasilache using namespace mlir;
34b6281940SNicolas Vasilache using namespace mlir::linalg;
35c25b20c0SAlex Zinenko using namespace mlir::scf;
36b6281940SNicolas Vasilache 
37b6281940SNicolas Vasilache #define DEBUG_TYPE "linalg-tiling"
38b6281940SNicolas Vasilache 
isZero(Value v)39e62a6956SRiver Riddle static bool isZero(Value v) {
40a54f4eaeSMogball   if (auto cst = v.getDefiningOp<arith::ConstantIndexOp>())
41a54f4eaeSMogball     return cst.value() == 0;
42004a3d4fSNicolas Vasilache   return false;
43b6281940SNicolas Vasilache }
44b6281940SNicolas Vasilache 
45c9620389SAlexander Belyaev std::tuple<SmallVector<Range, 4>, LoopIndexToRangeIndexMap>
makeTiledLoopRanges(RewriterBase & b,Location loc,AffineMap map,ValueRange allShapeSizes,ValueRange allTileSizes)46c9620389SAlexander Belyaev mlir::linalg::makeTiledLoopRanges(RewriterBase &b, Location loc, AffineMap map,
47c9620389SAlexander Belyaev                                   ValueRange allShapeSizes,
48c9620389SAlexander Belyaev                                   ValueRange allTileSizes) {
49b6281940SNicolas Vasilache   assert(allTileSizes.size() == map.getNumResults());
50a3adcba6SNicolas Vasilache   // Apply `map` to get shape sizes in loop order.
51a3adcba6SNicolas Vasilache   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
52e62a6956SRiver Riddle   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
53b6281940SNicolas Vasilache 
54b6281940SNicolas Vasilache   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
55bae8a7a7SAlexander Belyaev   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
56bae8a7a7SAlexander Belyaev   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
57bae8a7a7SAlexander Belyaev     if (isZero(tileSizes[idx - zerosCount])) {
58a3adcba6SNicolas Vasilache       shapeSizes.erase(shapeSizes.begin() + idx - zerosCount);
59bae8a7a7SAlexander Belyaev       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
60bae8a7a7SAlexander Belyaev       ++zerosCount;
61bae8a7a7SAlexander Belyaev       continue;
62b6281940SNicolas Vasilache     }
63bae8a7a7SAlexander Belyaev     loopIndexToRangeIndex[idx] = idx - zerosCount;
64b6281940SNicolas Vasilache   }
65b6281940SNicolas Vasilache 
66b6281940SNicolas Vasilache   // Create a new range with the applied tile sizes.
67e3de249aSNicolas Vasilache   SmallVector<Range, 4> res;
68004a3d4fSNicolas Vasilache   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx)
69a54f4eaeSMogball     res.push_back(Range{b.create<arith::ConstantIndexOp>(loc, 0),
70a54f4eaeSMogball                         shapeSizes[idx], tileSizes[idx]});
71bae8a7a7SAlexander Belyaev   return std::make_tuple(res, loopIndexToRangeIndex);
72b6281940SNicolas Vasilache }
73b6281940SNicolas Vasilache 
transformIndexOps(RewriterBase & b,LinalgOp op,SmallVectorImpl<Value> & ivs,const LoopIndexToRangeIndexMap & loopIndexToRangeIndex)74c9620389SAlexander Belyaev void mlir::linalg::transformIndexOps(
75c9620389SAlexander Belyaev     RewriterBase &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
768ea5d190STobias Gysi     const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
7790b7817eSTobias Gysi   SmallVector<Value> allIvs(op.getNumLoops(), nullptr);
7890b7817eSTobias Gysi   for (auto &en : enumerate(allIvs)) {
7990b7817eSTobias Gysi     auto rangeIndex = loopIndexToRangeIndex.find(en.index());
808ea5d190STobias Gysi     if (rangeIndex == loopIndexToRangeIndex.end())
818ea5d190STobias Gysi       continue;
8290b7817eSTobias Gysi     en.value() = ivs[rangeIndex->second];
838ea5d190STobias Gysi   }
8481b62f7fSAlex Zinenko   offsetIndices(b, op, allIvs);
858ea5d190STobias Gysi }
868ea5d190STobias Gysi 
873963b4d0SAlex Zinenko /// Asserts that the given index-typed value is strictly positive. If the value
883963b4d0SAlex Zinenko /// is an attribute, asserts at compile time, otherwise emits an assertion
893963b4d0SAlex Zinenko /// checked at runtime.
emitIsPositiveIndexAssertion(ImplicitLocOpBuilder & b,OpFoldResult value)903963b4d0SAlex Zinenko static void emitIsPositiveIndexAssertion(ImplicitLocOpBuilder &b,
913963b4d0SAlex Zinenko                                          OpFoldResult value) {
923963b4d0SAlex Zinenko   if (auto attr = value.dyn_cast<Attribute>()) {
933963b4d0SAlex Zinenko     assert(attr.cast<IntegerAttr>().getValue().isStrictlyPositive() &&
943963b4d0SAlex Zinenko            "expected strictly positive tile size and divisor");
953963b4d0SAlex Zinenko     return;
963963b4d0SAlex Zinenko   }
973963b4d0SAlex Zinenko 
983963b4d0SAlex Zinenko   Value zero = b.create<arith::ConstantIndexOp>(0);
993963b4d0SAlex Zinenko   Value condition = b.create<arith::CmpIOp>(arith::CmpIPredicate::sgt,
1003963b4d0SAlex Zinenko                                             value.get<Value>(), zero);
1013963b4d0SAlex Zinenko   b.create<cf::AssertOp>(
1023963b4d0SAlex Zinenko       condition,
1033963b4d0SAlex Zinenko       b.getStringAttr("expected strictly positive tile size and divisor"));
1043963b4d0SAlex Zinenko }
1053963b4d0SAlex Zinenko 
1063963b4d0SAlex Zinenko FailureOr<MultiSizeSpecification>
computeMultiTileSizes(OpBuilder & builder,LinalgOp op,unsigned dimension,OpFoldResult targetSize,OpFoldResult divisor,bool emitAssertions)1073963b4d0SAlex Zinenko mlir::linalg::computeMultiTileSizes(OpBuilder &builder, LinalgOp op,
1083963b4d0SAlex Zinenko                                     unsigned dimension, OpFoldResult targetSize,
1093963b4d0SAlex Zinenko                                     OpFoldResult divisor, bool emitAssertions) {
1103963b4d0SAlex Zinenko   // Bail out on dimension overflow.
1113963b4d0SAlex Zinenko   if (dimension >= op.getNumLoops())
1123963b4d0SAlex Zinenko     return failure();
1133963b4d0SAlex Zinenko 
1143963b4d0SAlex Zinenko   // The code below works only on values.
1153963b4d0SAlex Zinenko   ImplicitLocOpBuilder b(op.getLoc(), builder);
1163963b4d0SAlex Zinenko   if (emitAssertions) {
1173963b4d0SAlex Zinenko     emitIsPositiveIndexAssertion(b, targetSize);
1183963b4d0SAlex Zinenko     emitIsPositiveIndexAssertion(b, divisor);
1193963b4d0SAlex Zinenko   }
1203963b4d0SAlex Zinenko   Value targetSizeValue = materializeOpFoldResult(b, targetSize);
1213963b4d0SAlex Zinenko   Value divisorValue = materializeOpFoldResult(b, divisor);
1223963b4d0SAlex Zinenko 
1233963b4d0SAlex Zinenko   // Find the trip count of the iteration space dimension for which the tile
1243963b4d0SAlex Zinenko   // sizes are computed.
1253963b4d0SAlex Zinenko   // TODO: update createFlatListOfOperandDims to return OpFoldResults and avoid
1263963b4d0SAlex Zinenko   // littering by useless constant materialization.
1273963b4d0SAlex Zinenko   SmallVector<Value, 4> allShapes =
1283963b4d0SAlex Zinenko       op.createFlatListOfOperandDims(b, b.getLoc());
1293963b4d0SAlex Zinenko   AffineMap shapesToLoops = op.getShapesToLoopsMap();
1303963b4d0SAlex Zinenko   SmallVector<Value, 4> loopRanges =
1313963b4d0SAlex Zinenko       applyMapToValues(b, op.getLoc(), shapesToLoops, allShapes);
1323963b4d0SAlex Zinenko   Value tripCount = loopRanges[dimension];
1333963b4d0SAlex Zinenko 
1343963b4d0SAlex Zinenko   // Compute the tile sizes and the respective numbers of tiles.
1353963b4d0SAlex Zinenko   AffineExpr s0 = b.getAffineSymbolExpr(0);
1363963b4d0SAlex Zinenko   AffineExpr s1 = b.getAffineSymbolExpr(1);
1373963b4d0SAlex Zinenko   AffineExpr s2 = b.getAffineSymbolExpr(2);
1383963b4d0SAlex Zinenko   auto apply = [&](AffineExpr expr, ValueRange values) -> Value {
1393963b4d0SAlex Zinenko     return makeComposedAffineApply(b, b.getLoc(), expr, values);
1403963b4d0SAlex Zinenko   };
1413963b4d0SAlex Zinenko   Value a = apply(s0.floorDiv(s1), {tripCount, divisorValue});
1423963b4d0SAlex Zinenko   Value t = apply((s0 + s1 - 1).floorDiv(s1), {targetSizeValue, divisorValue});
1433963b4d0SAlex Zinenko   Value d = apply((s0 + s1 - 1).floorDiv(s1), {a, t});
1443963b4d0SAlex Zinenko   Value s = apply(s0.floorDiv(s1) * s2, {a, d, divisorValue});
1453963b4d0SAlex Zinenko   Value v = apply(s0 % s1, {a, d});
1463963b4d0SAlex Zinenko   Value u = apply(s0 - s1, {d, v});
1473963b4d0SAlex Zinenko 
1483963b4d0SAlex Zinenko   MultiSizeSpecification spec;
1493963b4d0SAlex Zinenko   spec.lowTileSize = s;
1503963b4d0SAlex Zinenko   spec.highTileSize = apply(s0 + s1, {s, divisorValue});
1513963b4d0SAlex Zinenko   spec.lowTripCount = u;
1523963b4d0SAlex Zinenko   spec.highTripCount = v;
1533963b4d0SAlex Zinenko 
1543963b4d0SAlex Zinenko   // If requested, emit the check that the tile sizes are computed correctly.
1553963b4d0SAlex Zinenko   // For example, for iteration dimension size of 15 and the target size 8 it is
1563963b4d0SAlex Zinenko   // impossible to find two tile sizes both divisible by 8 that fully cover the
1573963b4d0SAlex Zinenko   // original space dimension.
1583963b4d0SAlex Zinenko   if (emitAssertions) {
1593963b4d0SAlex Zinenko     AffineExpr s3 = builder.getAffineSymbolExpr(3);
1603963b4d0SAlex Zinenko     Value coveredSize =
1613963b4d0SAlex Zinenko         apply(s0 * s1 + s2 * s3, {spec.lowTileSize, spec.lowTripCount,
1623963b4d0SAlex Zinenko                                   spec.highTileSize, spec.highTripCount});
1633963b4d0SAlex Zinenko     Value equals = b.create<arith::CmpIOp>(arith::CmpIPredicate::eq,
1643963b4d0SAlex Zinenko                                            coveredSize, tripCount);
1653963b4d0SAlex Zinenko     b.create<cf::AssertOp>(
1663963b4d0SAlex Zinenko         equals, builder.getStringAttr(
1673963b4d0SAlex Zinenko                     "could not compute dynamic multi-size tile shapes"));
1683963b4d0SAlex Zinenko   }
1693963b4d0SAlex Zinenko 
1703963b4d0SAlex Zinenko   return spec;
1713963b4d0SAlex Zinenko }
1723963b4d0SAlex Zinenko 
17318b92c66SNicolas Vasilache /// Given a `subsetExtractOp`, a `source` and a `dest`, create a new
17418b92c66SNicolas Vasilache /// `ParallelInsertSlice` op of `source` into `dest` at the same subset location
17518b92c66SNicolas Vasilache /// as `subsetExtractOp`.
17618b92c66SNicolas Vasilache static void
createMatchingParallelSubsetInsertOp(OpBuilder & b,Location loc,tensor::ExtractSliceOp subsetExtractOp,Value source,Value dest)17718b92c66SNicolas Vasilache createMatchingParallelSubsetInsertOp(OpBuilder &b, Location loc,
17818b92c66SNicolas Vasilache                                      tensor::ExtractSliceOp subsetExtractOp,
17918b92c66SNicolas Vasilache                                      Value source, Value dest) {
18018b92c66SNicolas Vasilache   b.create<tensor::ParallelInsertSliceOp>(
18118b92c66SNicolas Vasilache       loc, source, dest, subsetExtractOp.getMixedOffsets(),
18218b92c66SNicolas Vasilache       subsetExtractOp.getMixedSizes(), subsetExtractOp.getMixedStrides());
18318b92c66SNicolas Vasilache }
18418b92c66SNicolas Vasilache 
18518b92c66SNicolas Vasilache /// Build an `affine_max` of all the `vals`.
buildMax(OpBuilder & b,Location loc,ArrayRef<OpFoldResult> vals)186297ba167SChristopher Bate static OpFoldResult buildMax(OpBuilder &b, Location loc,
187297ba167SChristopher Bate                              ArrayRef<OpFoldResult> vals) {
188297ba167SChristopher Bate   SmallVector<Value> args = getValueOrCreateConstantIndexOp(b, loc, vals);
18918b92c66SNicolas Vasilache   return b.createOrFold<AffineMaxOp>(
19018b92c66SNicolas Vasilache       loc, AffineMap::getMultiDimIdentityMap(vals.size(), loc.getContext()),
191297ba167SChristopher Bate       args);
19218b92c66SNicolas Vasilache }
19318b92c66SNicolas Vasilache 
194297ba167SChristopher Bate /// Returns true if the maximum tile offset `tileSize * numThreads-1` is less
195297ba167SChristopher Bate /// than `iterationSize`.
canOmitTileOffsetInBoundsCheck(OpFoldResult tileSize,OpFoldResult numThreads,OpFoldResult iterationSize)196297ba167SChristopher Bate static bool canOmitTileOffsetInBoundsCheck(OpFoldResult tileSize,
197297ba167SChristopher Bate                                            OpFoldResult numThreads,
198297ba167SChristopher Bate                                            OpFoldResult iterationSize) {
199297ba167SChristopher Bate   Optional<int64_t> tileSizeConst = getConstantIntValue(tileSize);
200297ba167SChristopher Bate   Optional<int64_t> numThreadsConst = getConstantIntValue(numThreads);
201297ba167SChristopher Bate   Optional<int64_t> iterSizeConst = getConstantIntValue(iterationSize);
202297ba167SChristopher Bate   if (!tileSizeConst || !numThreadsConst || !iterSizeConst)
203297ba167SChristopher Bate     return false;
204297ba167SChristopher Bate   return *tileSizeConst * (*numThreadsConst - 1) < *iterSizeConst;
20518b92c66SNicolas Vasilache }
20618b92c66SNicolas Vasilache 
207297ba167SChristopher Bate /// Rewrite a TilingInterface `op` to a tiled `scf.foreach_thread`. The
208297ba167SChristopher Bate /// tiling is specified by the number of tiles/threads `numThreads` and the
209297ba167SChristopher Bate /// optional nominal tile size `nominalTileSizes`. If `nominalTilSizes` is
210297ba167SChristopher Bate /// not specified, then  it is derived from `numThreads` as `ceilDiv(dimSize[i],
211297ba167SChristopher Bate /// numThreads[i])`. If non-empty, the `threadDimMapping` is added as an
212297ba167SChristopher Bate /// attribute to the resulting `scf.foreach_thread`. A zero tile sizes indicate
213297ba167SChristopher Bate /// that the dimension is not tiled, and can be thought of as tiling by the full
214297ba167SChristopher Bate /// size of data.
215297ba167SChristopher Bate /// It is the user's responsibility to ensure that `numThreads` is a valid
216297ba167SChristopher Bate /// tiling specification (i.e. that only tiles parallel dimensions, e.g. in the
217297ba167SChristopher Bate /// Linalg case). If `omitTileOffsetBoundsCheck` is true, then the function will
218297ba167SChristopher Bate /// assume that `tileSize[i] * (numThread[i] -1) <= dimSize[i]` holds.
tileToForeachThreadOpImpl(RewriterBase & b,TilingInterface op,ArrayRef<OpFoldResult> numThreads,Optional<ArrayRef<OpFoldResult>> nominalTileSizes,ArrayRef<int64_t> threadDimMapping,bool omitTileOffsetBoundsCheck)219297ba167SChristopher Bate static FailureOr<ForeachThreadTilingResult> tileToForeachThreadOpImpl(
220297ba167SChristopher Bate     RewriterBase &b, TilingInterface op, ArrayRef<OpFoldResult> numThreads,
221297ba167SChristopher Bate     Optional<ArrayRef<OpFoldResult>> nominalTileSizes,
222297ba167SChristopher Bate     ArrayRef<int64_t> threadDimMapping, bool omitTileOffsetBoundsCheck) {
22318b92c66SNicolas Vasilache   Location loc = op->getLoc();
22418b92c66SNicolas Vasilache   OpBuilder::InsertionGuard g(b);
22518b92c66SNicolas Vasilache   SmallVector<Range> loopRanges = op.getIterationDomain(b);
22618b92c66SNicolas Vasilache   if (loopRanges.empty())
22718b92c66SNicolas Vasilache     return op->emitOpError("expected non-empty loop ranges");
22818b92c66SNicolas Vasilache   auto hasStrideOne = [](Range r) { return !isConstantIntValue(r.stride, 1); };
22918b92c66SNicolas Vasilache   if (llvm::any_of(loopRanges, hasStrideOne))
23018b92c66SNicolas Vasilache     return op->emitOpError("only stride-1 supported atm");
23118b92c66SNicolas Vasilache   // TODO: support `getTiledImplementation` with >1 produced tiled ops.
23218b92c66SNicolas Vasilache   auto destOperands = op.getDestinationOperands(b);
23318b92c66SNicolas Vasilache   if (destOperands.size() != 1)
23418b92c66SNicolas Vasilache     return op->emitOpError("only single dest operand supported atm");
23518b92c66SNicolas Vasilache 
23618b92c66SNicolas Vasilache   SmallVector<OpFoldResult> nonZeroNumThreads =
23718b92c66SNicolas Vasilache       llvm::to_vector(llvm::make_filter_range(numThreads, [](OpFoldResult ofr) {
23818b92c66SNicolas Vasilache         return !isConstantIntValue(ofr, 0);
23918b92c66SNicolas Vasilache       }));
24018b92c66SNicolas Vasilache   SmallVector<Value> materializedNonZeroNumThreads =
24118b92c66SNicolas Vasilache       llvm::to_vector(llvm::map_range(nonZeroNumThreads, [&](OpFoldResult ofr) {
24218b92c66SNicolas Vasilache         ImplicitLocOpBuilder ilocb(loc, b);
24318b92c66SNicolas Vasilache         return materializeOpFoldResult(ilocb, ofr);
24418b92c66SNicolas Vasilache       }));
24518b92c66SNicolas Vasilache 
24618b92c66SNicolas Vasilache   Value zero = b.create<arith::ConstantIndexOp>(loc, 0);
24718b92c66SNicolas Vasilache   Operation *tiledOp = nullptr;
248297ba167SChristopher Bate 
249297ba167SChristopher Bate   // Create the ForeachThreadOp. We don't use the lambda body-builder
250297ba167SChristopher Bate   // version because we require the use of RewriterBase in the body, so we
251297ba167SChristopher Bate   // manually move the insertion point to the body below.
25218b92c66SNicolas Vasilache   scf::ForeachThreadOp foreachThreadOp = b.create<scf::ForeachThreadOp>(
253297ba167SChristopher Bate       loc, op->getResultTypes(), ValueRange(materializedNonZeroNumThreads),
254297ba167SChristopher Bate       threadDimMapping);
255297ba167SChristopher Bate 
256297ba167SChristopher Bate   // Fill out the ForeachThreadOp body.
257297ba167SChristopher Bate   b.setInsertionPointToStart(foreachThreadOp.getBody(0));
258297ba167SChristopher Bate   ValueRange threadIds = foreachThreadOp.getThreadIndices();
25918b92c66SNicolas Vasilache   int64_t nLoops = loopRanges.size();
26018b92c66SNicolas Vasilache   SmallVector<OpFoldResult> tiledOffsets, tiledSizes;
26118b92c66SNicolas Vasilache   tiledOffsets.reserve(nLoops);
26218b92c66SNicolas Vasilache   tiledSizes.reserve(nLoops);
263297ba167SChristopher Bate   for (unsigned loopIdx = 0, threadIdIdx = 0; loopIdx < nLoops; ++loopIdx) {
26418b92c66SNicolas Vasilache     bool overflow = loopIdx >= numThreads.size();
26518b92c66SNicolas Vasilache     bool isZero = !overflow && isConstantIntValue(numThreads[loopIdx], 0);
26618b92c66SNicolas Vasilache     // Degenerate case: take the whole domain.
26718b92c66SNicolas Vasilache     if (overflow || isZero) {
26818b92c66SNicolas Vasilache       tiledOffsets.push_back(loopRanges[loopIdx].offset);
26918b92c66SNicolas Vasilache       tiledSizes.push_back(loopRanges[loopIdx].size);
27018b92c66SNicolas Vasilache       continue;
27118b92c66SNicolas Vasilache     }
27218b92c66SNicolas Vasilache 
27318b92c66SNicolas Vasilache     // Tiled case: compute the offset and size.
27418b92c66SNicolas Vasilache     AffineExpr i, j, M, N, O;
27518b92c66SNicolas Vasilache     bindDims(b.getContext(), i, j);
27618b92c66SNicolas Vasilache     bindSymbols(b.getContext(), M, N, O);
27718b92c66SNicolas Vasilache     Value size = loopRanges[loopIdx].size;
27818b92c66SNicolas Vasilache     Value offset = loopRanges[loopIdx].offset;
27918b92c66SNicolas Vasilache     Value threadId = threadIds[threadIdIdx];
28018b92c66SNicolas Vasilache     // Symbolic fixed max size per thread.
28118b92c66SNicolas Vasilache     // TODO: floor + 0/1 depending on case for better load-balancing.
282297ba167SChristopher Bate     OpFoldResult tileSizePerThread =
283*6fa6901bSKazu Hirata         nominalTileSizes.has_value()
284297ba167SChristopher Bate             ? (*nominalTileSizes)[loopIdx]
285297ba167SChristopher Bate             : makeComposedFoldedAffineApply(
286297ba167SChristopher Bate                   b, loc, M.ceilDiv(N),
287297ba167SChristopher Bate                   ArrayRef<OpFoldResult>{size, nonZeroNumThreads[threadIdIdx]});
288297ba167SChristopher Bate 
28918b92c66SNicolas Vasilache     // Dynamic offset shifted by threadId * maxSizePerThread.
290297ba167SChristopher Bate     OpFoldResult offsetPerThread = makeComposedFoldedAffineApply(
291297ba167SChristopher Bate         b, loc, i + j * M, {offset, threadId, tileSizePerThread});
29218b92c66SNicolas Vasilache     // Dynamic upper-bound depending on the threadId.
293297ba167SChristopher Bate     OpFoldResult residualTileSize = makeComposedFoldedAffineApply(
294297ba167SChristopher Bate         b, loc, i + j * M - N,
295297ba167SChristopher Bate         {offset, nonZeroNumThreads[threadIdIdx], tileSizePerThread, size});
296297ba167SChristopher Bate     if (!isConstantIntValue(residualTileSize, 0)) {
297297ba167SChristopher Bate       OpFoldResult sizeMinusOffsetPerThread = makeComposedFoldedAffineApply(
298297ba167SChristopher Bate           b, loc, -i + M, {offsetPerThread, size});
299297ba167SChristopher Bate       tileSizePerThread = makeComposedFoldedAffineMin(
300297ba167SChristopher Bate           b, loc, AffineMap::getMultiDimIdentityMap(2, b.getContext()),
301297ba167SChristopher Bate           ArrayRef<OpFoldResult>{sizeMinusOffsetPerThread, tileSizePerThread});
302297ba167SChristopher Bate     }
303297ba167SChristopher Bate 
30418b92c66SNicolas Vasilache     tiledOffsets.push_back(offsetPerThread);
30518b92c66SNicolas Vasilache     // TODO: if tileSizePerThread <= 0 early exit.
306297ba167SChristopher Bate     if (!omitTileOffsetBoundsCheck &&
307297ba167SChristopher Bate         !canOmitTileOffsetInBoundsCheck(tileSizePerThread,
308297ba167SChristopher Bate                                         nonZeroNumThreads[threadIdIdx], size))
309297ba167SChristopher Bate       tileSizePerThread = buildMax(b, loc, {zero, tileSizePerThread});
310297ba167SChristopher Bate 
311297ba167SChristopher Bate     tiledSizes.push_back(tileSizePerThread);
31218b92c66SNicolas Vasilache     ++threadIdIdx;
31318b92c66SNicolas Vasilache   }
31418b92c66SNicolas Vasilache 
31518b92c66SNicolas Vasilache   SmallVector<Operation *> tiledOps =
31618b92c66SNicolas Vasilache       op.getTiledImplementation(b, destOperands, tiledOffsets, tiledSizes,
31718b92c66SNicolas Vasilache                                 /*tileDestOperands=*/true);
31818b92c66SNicolas Vasilache   assert(tiledOps.size() == 1 && "expected a single produced tiled op");
31918b92c66SNicolas Vasilache   tiledOp = tiledOps.front();
32018b92c66SNicolas Vasilache 
32118b92c66SNicolas Vasilache   auto tilingInterfaceOp = dyn_cast<TilingInterface>(tiledOp);
322297ba167SChristopher Bate   assert(tilingInterfaceOp && "Tiled op does not implement TilingInterface");
32318b92c66SNicolas Vasilache 
32418b92c66SNicolas Vasilache   auto tiledDestOperands = tilingInterfaceOp.getDestinationOperands(b);
32518b92c66SNicolas Vasilache 
32618b92c66SNicolas Vasilache   // Create terminator with parallel subset insert operations.
327297ba167SChristopher Bate   b.setInsertionPointToStart(foreachThreadOp.getTerminator().getBody());
328297ba167SChristopher Bate   for (auto it : llvm::zip(tiledDestOperands, tilingInterfaceOp->getResults(),
32918b92c66SNicolas Vasilache                            destOperands)) {
33018b92c66SNicolas Vasilache     createMatchingParallelSubsetInsertOp(
331297ba167SChristopher Bate         b, loc, cast<tensor::ExtractSliceOp>(std::get<0>(it).getDefiningOp()),
33218b92c66SNicolas Vasilache         std::get<1>(it), std::get<2>(it));
33318b92c66SNicolas Vasilache   }
33418b92c66SNicolas Vasilache   return ForeachThreadTilingResult{foreachThreadOp, tiledOp};
33518b92c66SNicolas Vasilache }
33618b92c66SNicolas Vasilache 
337297ba167SChristopher Bate FailureOr<ForeachThreadTilingResult>
tileToForeachThreadOp(RewriterBase & b,TilingInterface op,ArrayRef<OpFoldResult> numThreads,ArrayRef<int64_t> threadDimMapping)338297ba167SChristopher Bate linalg::tileToForeachThreadOp(RewriterBase &b, TilingInterface op,
339297ba167SChristopher Bate                               ArrayRef<OpFoldResult> numThreads,
340297ba167SChristopher Bate                               ArrayRef<int64_t> threadDimMapping) {
341297ba167SChristopher Bate   return tileToForeachThreadOpImpl(b, op, numThreads, /*nominalTileSizes=*/None,
342297ba167SChristopher Bate                                    threadDimMapping,
343297ba167SChristopher Bate                                    /*omitTileOffsetBoundsCheck=*/false);
344297ba167SChristopher Bate }
345297ba167SChristopher Bate 
346297ba167SChristopher Bate FailureOr<ForeachThreadTilingResult>
tileToForeachThreadOpUsingTileSizes(RewriterBase & b,TilingInterface op,ArrayRef<OpFoldResult> tileSizes,ArrayRef<int64_t> threadDimMapping)347297ba167SChristopher Bate linalg::tileToForeachThreadOpUsingTileSizes(
348297ba167SChristopher Bate     RewriterBase &b, TilingInterface op, ArrayRef<OpFoldResult> tileSizes,
349297ba167SChristopher Bate     ArrayRef<int64_t> threadDimMapping) {
350297ba167SChristopher Bate   SmallVector<Range> loopRanges = op.getIterationDomain(b);
351297ba167SChristopher Bate   unsigned nLoops = loopRanges.size();
352297ba167SChristopher Bate   SmallVector<OpFoldResult> numThreads;
353297ba167SChristopher Bate   numThreads.reserve(nLoops);
354297ba167SChristopher Bate   AffineExpr s0, s1;
355297ba167SChristopher Bate   bindSymbols(b.getContext(), s0, s1);
356297ba167SChristopher Bate   AffineExpr divExpr = s0.ceilDiv(s1);
357297ba167SChristopher Bate   for (const auto &it : llvm::zip(tileSizes, loopRanges)) {
358297ba167SChristopher Bate     OpFoldResult numTiles = std::get<0>(it);
359297ba167SChristopher Bate     if (!isConstantIntValue(numTiles, 0))
360297ba167SChristopher Bate       numTiles = makeComposedFoldedAffineApply(
361297ba167SChristopher Bate           b, op.getLoc(), divExpr, {std::get<1>(it).size, std::get<0>(it)});
362297ba167SChristopher Bate     numThreads.push_back(numTiles);
363297ba167SChristopher Bate   }
364297ba167SChristopher Bate   return tileToForeachThreadOpImpl(b, op, numThreads,
365297ba167SChristopher Bate                                    /*nominalTileSizes=*/tileSizes,
366297ba167SChristopher Bate                                    threadDimMapping,
367297ba167SChristopher Bate                                    /*omitTileOffsetBoundsCheck=*/true);
368297ba167SChristopher Bate }
369297ba167SChristopher Bate 
3704064b6a3SMatthias Springer // Insert a tile `source` into the destination tensor `dest`. The position at
3714064b6a3SMatthias Springer // which the tile is inserted (as well as size of tile) is taken from a given
3724064b6a3SMatthias Springer // ExtractSliceOp `sliceOp`.
insertSliceIntoTensor(RewriterBase & b,Location loc,tensor::ExtractSliceOp sliceOp,Value source,Value dest)3734a661602SNicolas Vasilache static Value insertSliceIntoTensor(RewriterBase &b, Location loc,
3744064b6a3SMatthias Springer                                    tensor::ExtractSliceOp sliceOp, Value source,
3754064b6a3SMatthias Springer                                    Value dest) {
3764064b6a3SMatthias Springer   return b.create<tensor::InsertSliceOp>(
37704235d07SJacques Pienaar       loc, sliceOp.getSource().getType(), source, dest, sliceOp.getOffsets(),
37804235d07SJacques Pienaar       sliceOp.getSizes(), sliceOp.getStrides(), sliceOp.getStaticOffsets(),
37904235d07SJacques Pienaar       sliceOp.getStaticSizes(), sliceOp.getStaticStrides());
3804064b6a3SMatthias Springer }
3814064b6a3SMatthias Springer 
3820da755dfSAlexander Belyaev template <typename LoopTy>
383489fec27SNicolas Vasilache static FailureOr<TiledLinalgOp>
tileLinalgOpImpl(RewriterBase & b,LinalgOp op,ValueRange tileSizes,const LinalgTilingOptions & options)3844a661602SNicolas Vasilache tileLinalgOpImpl(RewriterBase &b, LinalgOp op, ValueRange tileSizes,
385c694588fSMaheshRavishankar                  const LinalgTilingOptions &options) {
386004a3d4fSNicolas Vasilache   auto nLoops = op.getNumLoops();
387004a3d4fSNicolas Vasilache   // Initial tile sizes may be too big, only take the first nLoops.
388004a3d4fSNicolas Vasilache   tileSizes = tileSizes.take_front(nLoops);
389004a3d4fSNicolas Vasilache 
390526dfe3fSMaheshRavishankar   if (llvm::all_of(tileSizes, isZero)) {
391526dfe3fSMaheshRavishankar     TiledLinalgOp tiledOp;
392526dfe3fSMaheshRavishankar     tiledOp.op = cast<LinalgOp>(b.clone(*op.getOperation()));
393526dfe3fSMaheshRavishankar     tiledOp.tensorResults.assign(tiledOp.op->result_begin(),
394526dfe3fSMaheshRavishankar                                  tiledOp.op->result_end());
395526dfe3fSMaheshRavishankar     return tiledOp;
396526dfe3fSMaheshRavishankar   }
397f60bbb6cSJose Ignacio Gomez 
398c694588fSMaheshRavishankar   // 1. Build the tiled loop ranges.
39901c44185SNicolas Vasilache   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
40001c44185SNicolas Vasilache   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
401a3adcba6SNicolas Vasilache   if (!shapeSizesToLoopsMap)
402489fec27SNicolas Vasilache     return failure();
403bae8a7a7SAlexander Belyaev 
404e3de249aSNicolas Vasilache   SmallVector<Range, 4> loopRanges;
405bae8a7a7SAlexander Belyaev   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
406004a3d4fSNicolas Vasilache   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
407a3adcba6SNicolas Vasilache       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
40842444d0cSMaheshRavishankar 
409c694588fSMaheshRavishankar   SmallVector<Attribute, 4> iteratorTypes;
410e4853be2SMehdi Amini   for (const auto &attr :
411c694588fSMaheshRavishankar        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
412c694588fSMaheshRavishankar     if (loopIndexToRangeIndex.count(attr.index()))
413c694588fSMaheshRavishankar       iteratorTypes.push_back(attr.value());
414c694588fSMaheshRavishankar   }
415c694588fSMaheshRavishankar   // If interchangeVector is empty, use the identity. Build the permutation map
416c694588fSMaheshRavishankar   // otherwise.
417c694588fSMaheshRavishankar   auto invPermutationMap =
418c694588fSMaheshRavishankar       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
419c694588fSMaheshRavishankar   if (!options.interchangeVector.empty()) {
420c694588fSMaheshRavishankar     // Based on the pruned iterations (due to zero tile size), recompute the
421c694588fSMaheshRavishankar     // interchange vector.
422c694588fSMaheshRavishankar     SmallVector<unsigned, 4> interchangeVector;
423c694588fSMaheshRavishankar     interchangeVector.reserve(options.interchangeVector.size());
424c694588fSMaheshRavishankar     for (auto pos : options.interchangeVector) {
425c694588fSMaheshRavishankar       auto it = loopIndexToRangeIndex.find(pos);
426c694588fSMaheshRavishankar       if (it == loopIndexToRangeIndex.end())
427c694588fSMaheshRavishankar         continue;
428c694588fSMaheshRavishankar       interchangeVector.push_back(it->second);
429c694588fSMaheshRavishankar     }
43001c44185SNicolas Vasilache     // Interchange vector is guaranteed to be a permutation,
43101c44185SNicolas Vasilache     // `inversePermutation` must succeed.
432c694588fSMaheshRavishankar     invPermutationMap = inversePermutation(
433c694588fSMaheshRavishankar         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
43401c44185SNicolas Vasilache     assert(invPermutationMap);
4359072f1b5STobias Gysi     SmallVector<int64_t> permutation(interchangeVector.begin(),
4369072f1b5STobias Gysi                                      interchangeVector.end());
4379072f1b5STobias Gysi     applyPermutationToVector(loopRanges, permutation);
4389072f1b5STobias Gysi     applyPermutationToVector(iteratorTypes, permutation);
439c694588fSMaheshRavishankar   }
440b6281940SNicolas Vasilache 
441c694588fSMaheshRavishankar   // 2. Create the tiled loops.
44258ddeba3SAlexander Belyaev   LinalgOp res = op;
443a3adcba6SNicolas Vasilache   SmallVector<Value, 4> ivs, tensorResults;
44416488dc3STobias Gysi   auto tiledLoopBodyBuilder =
4454a661602SNicolas Vasilache       [&](OpBuilder &builder, Location loc, ValueRange localIvs,
44616488dc3STobias Gysi           ValueRange operandValuesToUse) -> scf::ValueVector {
447b4bc72afSAlex Zinenko     ivs.assign(localIvs.begin(), localIvs.end());
448f60bbb6cSJose Ignacio Gomez 
449a3adcba6SNicolas Vasilache     // When an `interchangeVector` is present, it has been applied to the
450a3adcba6SNicolas Vasilache     // loop ranges and the iterator types. Apply its inverse to the
451a3adcba6SNicolas Vasilache     // resulting loop `ivs` to match the op definition.
452a3adcba6SNicolas Vasilache     SmallVector<Value, 4> interchangedIvs;
453004a3d4fSNicolas Vasilache     if (!options.interchangeVector.empty())
454a3adcba6SNicolas Vasilache       interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
455a3adcba6SNicolas Vasilache     else
456a3adcba6SNicolas Vasilache       interchangedIvs.assign(ivs.begin(), ivs.end());
457f60bbb6cSJose Ignacio Gomez 
45816488dc3STobias Gysi     // Tile the `operandValuesToUse` that either match the `op` operands
45916488dc3STobias Gysi     // themselves or the tile loop arguments forwarding them.
46016488dc3STobias Gysi     assert(operandValuesToUse.size() ==
46116488dc3STobias Gysi                static_cast<size_t>(op.getNumInputsAndOutputs()) &&
46216488dc3STobias Gysi            "expect the number of operands and inputs and outputs to match");
46316488dc3STobias Gysi     SmallVector<Value> valuesToTile = operandValuesToUse;
464ddf93abfSLei Zhang     auto sizeBounds =
465ddf93abfSLei Zhang         applyMapToValues(b, loc, shapeSizesToLoopsMap, allShapeSizes);
46665bdeddbSOkwan Kwon     SmallVector<Value, 4> tiledOperands =
46765bdeddbSOkwan Kwon         makeTiledShapes(b, loc, op, valuesToTile, interchangedIvs, tileSizes,
46865bdeddbSOkwan Kwon                         sizeBounds, /*omitPartialTileCheck=*/false);
469a3adcba6SNicolas Vasilache 
470ff6e5508SAlex Zinenko     SmallVector<Type> resultTensorTypes =
471ff6e5508SAlex Zinenko         getTensorOutputTypes(op, tiledOperands);
47258ddeba3SAlexander Belyaev     res = op.clone(b, loc, resultTensorTypes, tiledOperands);
473ff6e5508SAlex Zinenko     tensorResults =
474ff6e5508SAlex Zinenko         insertSlicesBack(builder, loc, op, tiledOperands, res->getResults());
47558ddeba3SAlexander Belyaev     return scf::ValueVector(tensorResults.begin(), tensorResults.end());
47684a880e1SNicolas Vasilache   };
47784a880e1SNicolas Vasilache   GenerateLoopNest<LoopTy>::doit(b, op.getLoc(), loopRanges, op, iteratorTypes,
47874a89cbaSAlexander Belyaev                                  tiledLoopBodyBuilder, options.distribution,
47974a89cbaSAlexander Belyaev                                  options.distributionTypes);
480b6281940SNicolas Vasilache 
481d69bccf1STobias Gysi   // 3. Transform IndexOp results w.r.t. the tiling.
48258ddeba3SAlexander Belyaev   transformIndexOps(b, res, ivs, loopIndexToRangeIndex);
483bae8a7a7SAlexander Belyaev 
484c694588fSMaheshRavishankar   // 4. Gather the newly created loops and return them with the new op.
4850da755dfSAlexander Belyaev   SmallVector<Operation *, 8> loops;
486b6281940SNicolas Vasilache   loops.reserve(ivs.size());
487a5bfd32cSLei Zhang   for (auto iv : ivs) {
48841d41200SMaheshRavishankar     if (iv.isa<BlockArgument>()) {
489a5bfd32cSLei Zhang       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
490a5bfd32cSLei Zhang       assert(loops.back() && "no owner found for induction variable!");
49141d41200SMaheshRavishankar     } else {
49241d41200SMaheshRavishankar       // TODO: Instead of doing this, try to recover the ops used instead of the
49341d41200SMaheshRavishankar       // loop.
49441d41200SMaheshRavishankar       loops.push_back(nullptr);
49541d41200SMaheshRavishankar     }
496a5bfd32cSLei Zhang   }
497a3adcba6SNicolas Vasilache 
498a3adcba6SNicolas Vasilache   // 5. Get the tensor results from the outermost loop if available. Otherwise
499a3adcba6SNicolas Vasilache   // use the previously captured `tensorResults`.
500a3adcba6SNicolas Vasilache   Operation *outermostLoop = nullptr;
501a3adcba6SNicolas Vasilache   for (Operation *loop : loops)
502a3adcba6SNicolas Vasilache     if ((outermostLoop = loop))
503a3adcba6SNicolas Vasilache       break;
504a3adcba6SNicolas Vasilache 
50558ddeba3SAlexander Belyaev   return TiledLinalgOp{
50658ddeba3SAlexander Belyaev       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
507b6281940SNicolas Vasilache }
508b6281940SNicolas Vasilache 
509c694588fSMaheshRavishankar template <typename LoopTy>
tileLinalgOpImpl(RewriterBase & b,LinalgOp op,const LinalgTilingOptions & options)510489fec27SNicolas Vasilache FailureOr<TiledLinalgOp> static tileLinalgOpImpl(
5114a661602SNicolas Vasilache     RewriterBase &b, LinalgOp op, const LinalgTilingOptions &options) {
512c694588fSMaheshRavishankar   OpBuilder::InsertionGuard g(b);
513c694588fSMaheshRavishankar   b.setInsertionPoint(op);
514c694588fSMaheshRavishankar 
5154643fd27SNicolas Vasilache   if (!options.tileSizeComputationFunction)
516489fec27SNicolas Vasilache     return failure();
5174643fd27SNicolas Vasilache 
518c694588fSMaheshRavishankar   // Enforce the convention that "tiling by zero" skips tiling a particular
519c694588fSMaheshRavishankar   // dimension. This convention is significantly simpler to handle instead of
520c694588fSMaheshRavishankar   // adjusting affine maps to account for missing dimensions.
521c694588fSMaheshRavishankar   auto nLoops = op.getNumLoops();
522c694588fSMaheshRavishankar   SmallVector<Value, 4> tileSizeVector =
523c694588fSMaheshRavishankar       options.tileSizeComputationFunction(b, op);
524c694588fSMaheshRavishankar   if (tileSizeVector.size() < nLoops) {
525a54f4eaeSMogball     auto zero = b.create<arith::ConstantIndexOp>(op.getLoc(), 0);
526c694588fSMaheshRavishankar     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
527c694588fSMaheshRavishankar   }
528c694588fSMaheshRavishankar 
529c694588fSMaheshRavishankar   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
530c694588fSMaheshRavishankar }
531c694588fSMaheshRavishankar 
532489fec27SNicolas Vasilache FailureOr<TiledLinalgOp>
tileLinalgOp(RewriterBase & b,LinalgOp op,const LinalgTilingOptions & options)5334a661602SNicolas Vasilache mlir::linalg::tileLinalgOp(RewriterBase &b, LinalgOp op,
534004a3d4fSNicolas Vasilache                            const LinalgTilingOptions &options) {
535c694588fSMaheshRavishankar   switch (options.loopType) {
536c694588fSMaheshRavishankar   case LinalgTilingLoopType::Loops:
537004a3d4fSNicolas Vasilache     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
538c694588fSMaheshRavishankar   case LinalgTilingLoopType::ParallelLoops:
539004a3d4fSNicolas Vasilache     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
540c694588fSMaheshRavishankar   default:;
541c694588fSMaheshRavishankar   }
542489fec27SNicolas Vasilache   return failure();
5430da755dfSAlexander Belyaev }
5440da755dfSAlexander Belyaev 
545fd0c6f53SAlexander Belyaev /// Generate a loop nest around a given tensor::PadOp (for tiling). `newPadOp`
546fd0c6f53SAlexander Belyaev /// and `loopNest` are output parameters that return the new (tiled)
547fd0c6f53SAlexander Belyaev /// tensor::PadOp and the loop nest.
tilePadOp(RewriterBase & builder,tensor::PadOp op,tensor::PadOp & newPadOp,LoopNest & loopNest,const LinalgTilingOptions & options)548fd0c6f53SAlexander Belyaev static LogicalResult tilePadOp(RewriterBase &builder, tensor::PadOp op,
549fd0c6f53SAlexander Belyaev                                tensor::PadOp &newPadOp, LoopNest &loopNest,
5504064b6a3SMatthias Springer                                const LinalgTilingOptions &options) {
5514064b6a3SMatthias Springer   Location loc = op.getLoc();
5524064b6a3SMatthias Springer   OpBuilder::InsertionGuard g(builder);
5534064b6a3SMatthias Springer   builder.setInsertionPoint(op);
5544064b6a3SMatthias Springer 
555fd0c6f53SAlexander Belyaev   // Clone tensor::PadOp so that the existing op can be replaced more easily.
556fd0c6f53SAlexander Belyaev   newPadOp = cast<tensor::PadOp>(builder.clone(*op.getOperation()));
5574064b6a3SMatthias Springer   // Get rank and tile sizes.
5584064b6a3SMatthias Springer   int64_t rank = op.getResultType().getRank();
5594064b6a3SMatthias Springer   SmallVector<Value> tileSizes =
5604064b6a3SMatthias Springer       options.tileSizeComputationFunction(builder, op);
5618a8f0a00SNicolas Vasilache   // Normalize untiled padding dimensions to 0.
5628a8f0a00SNicolas Vasilache   Value zero = builder.create<arith::ConstantIndexOp>(loc, 0);
5638a8f0a00SNicolas Vasilache   tileSizes.append(rank - tileSizes.size(), zero);
5644064b6a3SMatthias Springer   // Compute lower and upper bounds of the loop nest.
565fd0c6f53SAlexander Belyaev   TilingInterface tilingInterface =
566fd0c6f53SAlexander Belyaev       dyn_cast<TilingInterface>(op.getOperation());
567fd0c6f53SAlexander Belyaev   SmallVector<Range> ranges = tilingInterface.getIterationDomain(builder);
568c95a7246SMatthias Springer   SmallVector<Value> lbs, dims, allDims, steps;
5694064b6a3SMatthias Springer   for (int64_t i = 0; i < rank; ++i) {
570c95a7246SMatthias Springer     allDims.push_back(ranges[i].size);
5714064b6a3SMatthias Springer     if (!isZero(tileSizes[i])) {
572ba72cfe7SMaheshRavishankar       lbs.push_back(ranges[i].offset);
573ba72cfe7SMaheshRavishankar       dims.push_back(ranges[i].size);
5744064b6a3SMatthias Springer       steps.push_back(tileSizes[i]);
5754064b6a3SMatthias Springer     }
5764064b6a3SMatthias Springer   }
5774064b6a3SMatthias Springer   // Generate loop nest: One loop per dimension.
578fd0c6f53SAlexander Belyaev   SmallVector<Value> destOperand =
579fd0c6f53SAlexander Belyaev       tilingInterface.getDestinationOperands(builder);
5804064b6a3SMatthias Springer   loopNest = mlir::scf::buildLoopNest(
581b686fdbfSMaheshRavishankar       builder, loc, lbs, /*ubs=*/dims, steps, ValueRange(destOperand),
5824064b6a3SMatthias Springer       [&](OpBuilder &b, Location loc, ValueRange localIvs,
5834064b6a3SMatthias Springer           ValueRange iterArgs) -> scf::ValueVector {
5844064b6a3SMatthias Springer         // Compute offsets and sizes of ExtractSliceOp.
5854064b6a3SMatthias Springer         SmallVector<Value> offsets =
5864064b6a3SMatthias Springer             computeTileOffsets(b, loc, localIvs, tileSizes);
587cf6a7c19SMahesh Ravishankar         SmallVector<Value> sizes = computeTileSizes(b, loc, tileSizes, allDims);
588fd0c6f53SAlexander Belyaev         // Create ExtractSliceOp: Extract a tile from the tensor::PadOp.
589fd0c6f53SAlexander Belyaev         // Note: The tensor::PadOp is located outside of the loop nest. It is
5904064b6a3SMatthias Springer         // later moved inside by ExtractSliceOfPadTensorSwapPattern.
5914064b6a3SMatthias Springer         auto map = AffineMap::getMultiDimIdentityMap(rank, b.getContext());
59265bdeddbSOkwan Kwon         Value tiledOutput = makeTiledShape(
59365bdeddbSOkwan Kwon             b, loc, newPadOp->getResult(0), tileSizes, map, offsets, allDims,
59465bdeddbSOkwan Kwon             sizes, /*omitPartialTileCheck=*/false);
5954064b6a3SMatthias Springer         auto sliceOp = tiledOutput.getDefiningOp<tensor::ExtractSliceOp>();
5964064b6a3SMatthias Springer         assert(sliceOp && "expected ExtractSliceOp");
5974064b6a3SMatthias Springer         // Insert the tile into the output tensor.
5984a661602SNicolas Vasilache         // TODO: Propagate RewriterBase everywhere.
5994a661602SNicolas Vasilache         IRRewriter rewriter(b);
6004064b6a3SMatthias Springer         Value yieldValue =
6014a661602SNicolas Vasilache             insertSliceIntoTensor(rewriter, loc, sliceOp, sliceOp, iterArgs[0]);
6024064b6a3SMatthias Springer         return scf::ValueVector({yieldValue});
6034064b6a3SMatthias Springer       });
6044064b6a3SMatthias Springer   return success();
6054064b6a3SMatthias Springer }
6064064b6a3SMatthias Springer 
6074064b6a3SMatthias Springer namespace {
608fd0c6f53SAlexander Belyaev struct PadOpTilingPattern : public OpRewritePattern<tensor::PadOp> {
PadOpTilingPattern__anon3f60ba290711::PadOpTilingPattern609fd0c6f53SAlexander Belyaev   PadOpTilingPattern(MLIRContext *ctx, LinalgTilingOptions opt)
610fd0c6f53SAlexander Belyaev       : OpRewritePattern<tensor::PadOp>(ctx), options(std::move(opt)) {}
6114064b6a3SMatthias Springer 
matchAndRewrite__anon3f60ba290711::PadOpTilingPattern612fd0c6f53SAlexander Belyaev   LogicalResult matchAndRewrite(tensor::PadOp op,
6134064b6a3SMatthias Springer                                 PatternRewriter &rewriter) const override {
6144064b6a3SMatthias Springer     if (op->hasAttr(LinalgTransforms::kLinalgTransformMarker))
6154064b6a3SMatthias Springer       return failure();
616fd0c6f53SAlexander Belyaev     tensor::PadOp newPadOp;
6174064b6a3SMatthias Springer     LoopNest loopNest;
618fd0c6f53SAlexander Belyaev     if (failed(tilePadOp(rewriter, op, newPadOp, loopNest, options)))
6194064b6a3SMatthias Springer       return failure();
6204064b6a3SMatthias Springer     newPadOp->setAttr(LinalgTransforms::kLinalgTransformMarker,
6214064b6a3SMatthias Springer                       rewriter.getUnitAttr());
622fd0c6f53SAlexander Belyaev     // Replace all uses of the original tensor::PadOp.
6234064b6a3SMatthias Springer     rewriter.replaceOp(op, loopNest.getResults()[0]);
6244064b6a3SMatthias Springer     return success();
6254064b6a3SMatthias Springer   }
6264064b6a3SMatthias Springer 
6274064b6a3SMatthias Springer   LinalgTilingOptions options;
6284064b6a3SMatthias Springer };
6294064b6a3SMatthias Springer } // namespace
6304064b6a3SMatthias Springer 
631004a3d4fSNicolas Vasilache namespace {
632004a3d4fSNicolas Vasilache /// Helper classes for type list expansion.
633004a3d4fSNicolas Vasilache template <typename... OpTypes>
634004a3d4fSNicolas Vasilache class CanonicalizationPatternList;
635004a3d4fSNicolas Vasilache 
636004a3d4fSNicolas Vasilache template <>
637004a3d4fSNicolas Vasilache class CanonicalizationPatternList<> {
638004a3d4fSNicolas Vasilache public:
insert(RewritePatternSet & patterns)639dc4e913bSChris Lattner   static void insert(RewritePatternSet &patterns) {}
640004a3d4fSNicolas Vasilache };
641004a3d4fSNicolas Vasilache 
642004a3d4fSNicolas Vasilache template <typename OpTy, typename... OpTypes>
643004a3d4fSNicolas Vasilache class CanonicalizationPatternList<OpTy, OpTypes...> {
644004a3d4fSNicolas Vasilache public:
insert(RewritePatternSet & patterns)645dc4e913bSChris Lattner   static void insert(RewritePatternSet &patterns) {
6463a506b31SChris Lattner     OpTy::getCanonicalizationPatterns(patterns, patterns.getContext());
6473a506b31SChris Lattner     CanonicalizationPatternList<OpTypes...>::insert(patterns);
648004a3d4fSNicolas Vasilache   }
649004a3d4fSNicolas Vasilache };
650004a3d4fSNicolas Vasilache } // namespace
651004a3d4fSNicolas Vasilache 
652dc4e913bSChris Lattner RewritePatternSet
getLinalgTilingCanonicalizationPatterns(MLIRContext * ctx)653004a3d4fSNicolas Vasilache mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
654dc4e913bSChris Lattner   RewritePatternSet patterns(ctx);
6553a506b31SChris Lattner   populateLinalgTilingCanonicalizationPatterns(patterns);
6562c66b6ecSNicolas Vasilache   return patterns;
6572c66b6ecSNicolas Vasilache }
6582c66b6ecSNicolas Vasilache 
populateLinalgTilingCanonicalizationPatterns(RewritePatternSet & patterns)6592c66b6ecSNicolas Vasilache void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
660dc4e913bSChris Lattner     RewritePatternSet &patterns) {
6613a506b31SChris Lattner   auto *ctx = patterns.getContext();
662004a3d4fSNicolas Vasilache   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
663004a3d4fSNicolas Vasilache   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
664004a3d4fSNicolas Vasilache   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
665004a3d4fSNicolas Vasilache   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
666a54f4eaeSMogball   arith::ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
667a3f42594SLei Zhang 
668a3f42594SLei Zhang   memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx);
669a3f42594SLei Zhang   memref::ViewOp::getCanonicalizationPatterns(patterns, ctx);
670a3f42594SLei Zhang 
671004a3d4fSNicolas Vasilache   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
672004a3d4fSNicolas Vasilache   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
673a3f42594SLei Zhang 
674a3f42594SLei Zhang   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
675060208b4SMatthias Springer   tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, ctx);
676a0e02018SMatthias Springer   tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, ctx);
677a3f42594SLei Zhang 
678a3f42594SLei Zhang   InitTensorOp::getCanonicalizationPatterns(patterns, ctx);
679fd0c6f53SAlexander Belyaev   tensor::PadOp::getCanonicalizationPatterns(patterns, ctx);
68066e27082SRiver Riddle   ctx->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(patterns);
681a3f42594SLei Zhang 
682004a3d4fSNicolas Vasilache   CanonicalizationPatternList<
683004a3d4fSNicolas Vasilache #define GET_OP_LIST
684004a3d4fSNicolas Vasilache #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
6853a506b31SChris Lattner       >::insert(patterns);
686baecae83SAlexander Belyaev }
687baecae83SAlexander Belyaev 
688004a3d4fSNicolas Vasilache /// Populate the given list with patterns that apply Linalg tiling.
insertTilingPatterns(RewritePatternSet & patterns,const LinalgTilingOptions & options)689dc4e913bSChris Lattner static void insertTilingPatterns(RewritePatternSet &patterns,
6903a506b31SChris Lattner                                  const LinalgTilingOptions &options) {
6914a661602SNicolas Vasilache   auto *ctx = patterns.getContext();
6924a661602SNicolas Vasilache   LinalgTransformationFilter f(ArrayRef<StringAttr>{},
6934a661602SNicolas Vasilache                                StringAttr::get(ctx, "tiled"));
6944a661602SNicolas Vasilache   TilingPatterns<GenericOp,
695004a3d4fSNicolas Vasilache #define GET_OP_LIST
696004a3d4fSNicolas Vasilache #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
6974a661602SNicolas Vasilache                  >::insert(patterns, options, f);
698fd0c6f53SAlexander Belyaev   patterns.add<PadOpTilingPattern>(ctx, options);
699a0e02018SMatthias Springer }
700a0e02018SMatthias Springer 
populatePadTensorTilingPatterns(RewritePatternSet & patterns,const LinalgTilingOptions & options)7018a8f0a00SNicolas Vasilache void mlir::linalg::populatePadTensorTilingPatterns(
7028a8f0a00SNicolas Vasilache     RewritePatternSet &patterns, const LinalgTilingOptions &options) {
7038a8f0a00SNicolas Vasilache   auto *ctx = patterns.getContext();
704fd0c6f53SAlexander Belyaev   patterns.add<PadOpTilingPattern>(ctx, options);
7058a8f0a00SNicolas Vasilache }
7068a8f0a00SNicolas Vasilache 
applyExtractSliceOfPadTensorSwapPattern(func::FuncOp funcOp)70758ceae95SRiver Riddle static void applyExtractSliceOfPadTensorSwapPattern(func::FuncOp funcOp) {
708a0e02018SMatthias Springer   MLIRContext *ctx = funcOp.getContext();
709a0e02018SMatthias Springer   RewritePatternSet patterns(ctx);
7104064b6a3SMatthias Springer   patterns.add<ExtractSliceOfPadTensorSwapPattern>(patterns.getContext());
711a0e02018SMatthias Springer   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
712a0e02018SMatthias Springer   (void)applyPatternsAndFoldGreedily(
713a0e02018SMatthias Springer       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
7140da755dfSAlexander Belyaev }
7150da755dfSAlexander Belyaev 
7168dc16ba8SMatthias Springer namespace {
7178dc16ba8SMatthias Springer struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
7188dc16ba8SMatthias Springer   LinalgTilingPass() = default;
LinalgTilingPass__anon3f60ba290911::LinalgTilingPass7191a829d2dSAlexander Belyaev   LinalgTilingPass(ArrayRef<int64_t> tileSizes, LinalgTilingLoopType loopType) {
7208dc16ba8SMatthias Springer     this->tileSizes = tileSizes;
7218dc16ba8SMatthias Springer     this->loopType = "";
7228dc16ba8SMatthias Springer     this->loopTypeEnum = loopType;
7238dc16ba8SMatthias Springer   }
7248dc16ba8SMatthias Springer 
runOnOperation__anon3f60ba290911::LinalgTilingPass72541574554SRiver Riddle   void runOnOperation() override {
72658ceae95SRiver Riddle     func::FuncOp funcOp = getOperation();
7278dc16ba8SMatthias Springer     LinalgTilingLoopType type =
7288dc16ba8SMatthias Springer         llvm::StringSwitch<LinalgTilingLoopType>(loopType)
7298dc16ba8SMatthias Springer             .Case("for", LinalgTilingLoopType::Loops)
7308dc16ba8SMatthias Springer             .Case("affine", LinalgTilingLoopType::AffineLoops)
7318dc16ba8SMatthias Springer             .Case("parallel", LinalgTilingLoopType::ParallelLoops)
7328dc16ba8SMatthias Springer             .Default(loopTypeEnum);
7331a829d2dSAlexander Belyaev     auto options =
7341a829d2dSAlexander Belyaev         LinalgTilingOptions().setTileSizes(tileSizes).setLoopType(type);
735004a3d4fSNicolas Vasilache     MLIRContext *ctx = funcOp.getContext();
736dc4e913bSChris Lattner     RewritePatternSet patterns(ctx);
7373a506b31SChris Lattner     insertTilingPatterns(patterns, options);
738d18ffd61SMatthias Springer     scf::populateSCFForLoopCanonicalizationPatterns(patterns);
739e21adfa3SRiver Riddle     (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
740e21adfa3SRiver Riddle     (void)applyPatternsAndFoldGreedily(
741e21adfa3SRiver Riddle         funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
742004a3d4fSNicolas Vasilache     // Drop the marker.
743004a3d4fSNicolas Vasilache     funcOp.walk([](LinalgOp op) {
744dffc487bSChristian Sigg       op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
745b6281940SNicolas Vasilache     });
746a0e02018SMatthias Springer 
747a0e02018SMatthias Springer     // Apply swap pattern after generating loop nest and running
748a0e02018SMatthias Springer     // canonicalizations.
749a0e02018SMatthias Springer     applyExtractSliceOfPadTensorSwapPattern(funcOp);
750b6281940SNicolas Vasilache   }
751b6281940SNicolas Vasilache 
7528dc16ba8SMatthias Springer   LinalgTilingLoopType loopTypeEnum;
7534b13b758SAlexander Belyaev };
7544b13b758SAlexander Belyaev 
7550da755dfSAlexander Belyaev } // namespace
7560da755dfSAlexander Belyaev 
75758ceae95SRiver Riddle std::unique_ptr<OperationPass<func::FuncOp>>
createLinalgTilingPass(ArrayRef<int64_t> tileSizes,linalg::LinalgTilingLoopType loopType)7588dc16ba8SMatthias Springer mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes,
7591a829d2dSAlexander Belyaev                              linalg::LinalgTilingLoopType loopType) {
7601a829d2dSAlexander Belyaev   return std::make_unique<LinalgTilingPass>(tileSizes, loopType);
7614b13b758SAlexander Belyaev }
762