1 //===- Tiling.cpp - Implementation of linalg Tiling -----------------------===//
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 // This file implements the linalg dialect Tiling pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
15 #include "mlir/Dialect/Linalg/Passes.h"
16 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
17 #include "mlir/Dialect/Linalg/Utils/Utils.h"
18 #include "mlir/Dialect/MemRef/IR/MemRef.h"
19 #include "mlir/Dialect/SCF/Transforms.h"
20 #include "mlir/Dialect/Tensor/IR/Tensor.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/AffineMap.h"
23 #include "mlir/Transforms/FoldUtils.h"
24 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
25 
26 #include "llvm/Support/CommandLine.h"
27 
28 using namespace mlir;
29 using namespace mlir::linalg;
30 using namespace mlir::scf;
31 
32 #define DEBUG_TYPE "linalg-tiling"
33 
34 static bool isZero(Value v) {
35   if (auto cst = v.getDefiningOp<ConstantIndexOp>())
36     return cst.getValue() == 0;
37   return false;
38 }
39 
40 using LoopIndexToRangeIndexMap = DenseMap<int, int>;
41 
42 // Creates a number of ranges equal to the number of non-zero in `tileSizes`.
43 // One for each loop of the LinalgOp that is tiled. The `tileSizes` argument has
44 // one entry per surrounding loop. It uses zero as the convention that a
45 // particular loop is not tiled. This convention simplifies implementations by
46 // avoiding affine map manipulations.
47 // The returned ranges correspond to the loop ranges, in the proper order, that
48 // are tiled and for which new loops will be created. Also the function returns
49 // a map from loop indices of the LinalgOp to the corresponding non-empty range
50 // indices of newly created loops.
51 static std::tuple<SmallVector<Range, 4>, LoopIndexToRangeIndexMap>
52 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
53                     ValueRange allShapeSizes, ValueRange allTileSizes) {
54   assert(allTileSizes.size() == map.getNumResults());
55   // Apply `map` to get shape sizes in loop order.
56   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
57   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
58 
59   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
60   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
61   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
62     if (isZero(tileSizes[idx - zerosCount])) {
63       shapeSizes.erase(shapeSizes.begin() + idx - zerosCount);
64       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
65       ++zerosCount;
66       continue;
67     }
68     loopIndexToRangeIndex[idx] = idx - zerosCount;
69   }
70 
71   // Create a new range with the applied tile sizes.
72   SmallVector<Range, 4> res;
73   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx)
74     res.push_back(Range{b.create<ConstantIndexOp>(loc, 0), shapeSizes[idx],
75                         tileSizes[idx]});
76   return std::make_tuple(res, loopIndexToRangeIndex);
77 }
78 
79 // All indices returned by IndexOp should be invariant with respect to tiling.
80 // Therefore, if an operation is tiled, we have to transform the indices
81 // accordingly, i.e. offset them by the values of the corresponding induction
82 // variables that are captured implicitly in the body of the op.
83 //
84 // Example. `linalg.generic` before tiling:
85 //
86 // #id_2d = (i, j) -> (i, j)
87 // #pointwise_2d_trait = {
88 //   indexing_maps = [#id_2d, #id_2d],
89 //   iterator_types = ["parallel", "parallel"]
90 // }
91 // linalg.generic #pointwise_2d_trait %operand, %result {
92 //   ^bb0(%operand_in: f32, %result_in: f32):
93 //     %i = linalg.index 0 : index
94 //     %j = linalg.index 1 : index
95 //     <some operations that use %i, %j>
96 // }: memref<50x100xf32>, memref<50x100xf32>
97 //
98 // After tiling pass with tiles sizes 10 and 25:
99 //
100 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
101 //
102 // %c1 = constant 1 : index
103 // %c0 = constant 0 : index
104 // %c25 = constant 25 : index
105 // %c10 = constant 10 : index
106 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
107 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
108 // scf.for %k = %c0 to operand_dim_0 step %c10 {
109 //   scf.for %l = %c0 to operand_dim_1 step %c25 {
110 //     %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
111 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
112 //     %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1]
113 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
114 //     linalg.generic pointwise_2d_trait %4, %5 {
115 //     ^bb0(%operand_in: f32, %result_in: f32):
116 //       %i = linalg.index 0 : index
117 //       %j = linalg.index 1 : index
118 //       // Indices `k` and `l` are implicitly captured in the body.
119 //       %transformed_i = addi %i, %k : index // index `i` is offset by %k
120 //       %transformed_j = addi %j, %l : index // index `j` is offset by %l
121 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
122 //       <some operations that use %transformed_i, %transformed_j>
123 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
124 //   }
125 // }
126 //
127 // TODO: Investigate whether mixing implicit and explicit indices
128 // does not lead to losing information.
129 static void
130 transformIndexOps(OpBuilder &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
131                   const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
132   SmallVector<Value> allIvs(op.getNumLoops(), nullptr);
133   for (auto &en : enumerate(allIvs)) {
134     auto rangeIndex = loopIndexToRangeIndex.find(en.index());
135     if (rangeIndex == loopIndexToRangeIndex.end())
136       continue;
137     en.value() = ivs[rangeIndex->second];
138   }
139   addTileLoopIvsToIndexOpResults(b, op, allIvs);
140 }
141 
142 // Insert a tile `source` into the destination tensor `dest`. The position at
143 // which the tile is inserted (as well as size of tile) is taken from a given
144 // ExtractSliceOp `sliceOp`.
145 static Value insertSliceIntoTensor(OpBuilder &b, Location loc,
146                                    tensor::ExtractSliceOp sliceOp, Value source,
147                                    Value dest) {
148   return b.create<tensor::InsertSliceOp>(
149       loc, sliceOp.source().getType(), source, dest, sliceOp.offsets(),
150       sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(),
151       sliceOp.static_sizes(), sliceOp.static_strides());
152 }
153 
154 template <typename LoopTy>
155 static Optional<TiledLinalgOp>
156 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
157                  const LinalgTilingOptions &options) {
158   auto nLoops = op.getNumLoops();
159   // Initial tile sizes may be too big, only take the first nLoops.
160   tileSizes = tileSizes.take_front(nLoops);
161 
162   if (llvm::all_of(tileSizes, isZero))
163     return llvm::None;
164 
165   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
166     // For conv op only support tiling along batch dimension (which is the first
167     // loop).
168     if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(), isZero))
169       return llvm::None;
170   }
171 
172   // 1. Build the tiled loop ranges.
173   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
174   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
175   if (!shapeSizesToLoopsMap)
176     return llvm::None;
177 
178   SmallVector<Range, 4> loopRanges;
179   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
180   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
181       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
182 
183   SmallVector<Attribute, 4> iteratorTypes;
184   for (auto attr :
185        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
186     if (loopIndexToRangeIndex.count(attr.index()))
187       iteratorTypes.push_back(attr.value());
188   }
189   // If interchangeVector is empty, use the identity. Build the permutation map
190   // otherwise.
191   auto invPermutationMap =
192       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
193   if (!options.interchangeVector.empty()) {
194     // Based on the pruned iterations (due to zero tile size), recompute the
195     // interchange vector.
196     SmallVector<unsigned, 4> interchangeVector;
197     interchangeVector.reserve(options.interchangeVector.size());
198     for (auto pos : options.interchangeVector) {
199       auto it = loopIndexToRangeIndex.find(pos);
200       if (it == loopIndexToRangeIndex.end())
201         continue;
202       interchangeVector.push_back(it->second);
203     }
204     // Interchange vector is guaranteed to be a permutation,
205     // `inversePermutation` must succeed.
206     invPermutationMap = inversePermutation(
207         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
208     assert(invPermutationMap);
209     SmallVector<int64_t> permutation(interchangeVector.begin(),
210                                      interchangeVector.end());
211     applyPermutationToVector(loopRanges, permutation);
212     applyPermutationToVector(iteratorTypes, permutation);
213   }
214 
215   // 2. Create the tiled loops.
216   LinalgOp res = op;
217   SmallVector<Value, 4> ivs, tensorResults;
218   auto tiledLoopBodyBuilder =
219       [&](OpBuilder &b, Location loc, ValueRange localIvs,
220           ValueRange operandValuesToUse) -> scf::ValueVector {
221     ivs.assign(localIvs.begin(), localIvs.end());
222 
223     // When an `interchangeVector` is present, it has been applied to the
224     // loop ranges and the iterator types. Apply its inverse to the
225     // resulting loop `ivs` to match the op definition.
226     SmallVector<Value, 4> interchangedIvs;
227     if (!options.interchangeVector.empty())
228       interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
229     else
230       interchangedIvs.assign(ivs.begin(), ivs.end());
231 
232     // Tile the `operandValuesToUse` that either match the `op` operands
233     // themselves or the tile loop arguments forwarding them.
234     assert(operandValuesToUse.size() ==
235                static_cast<size_t>(op.getNumInputsAndOutputs()) &&
236            "expect the number of operands and inputs and outputs to match");
237     SmallVector<Value> valuesToTile = operandValuesToUse;
238     auto sizeBounds =
239         applyMapToValues(b, loc, shapeSizesToLoopsMap, allShapeSizes);
240     SmallVector<Value, 4> tiledOperands = makeTiledShapes(
241         b, loc, op, valuesToTile, interchangedIvs, tileSizes, sizeBounds);
242 
243     // TODO: use an interface/adaptor to avoid leaking position in
244     // `tiledOperands`.
245     SmallVector<Type, 4> resultTensorTypes;
246     for (OpOperand *opOperand : op.getOutputTensorOperands())
247       resultTensorTypes.push_back(
248           tiledOperands[opOperand->getOperandNumber()].getType());
249 
250     res = op.clone(b, loc, resultTensorTypes, tiledOperands);
251 
252     // Insert a insert_slice for each output tensor.
253     unsigned resultIdx = 0;
254     for (OpOperand *opOperand : op.getOutputTensorOperands()) {
255       // TODO: use an interface/adaptor to avoid leaking position in
256       // `tiledOperands`.
257       Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
258       if (auto sliceOp = outputTensor.getDefiningOp<tensor::ExtractSliceOp>()) {
259         tensorResults.push_back(insertSliceIntoTensor(
260             b, loc, sliceOp, res->getResult(resultIdx), sliceOp.source()));
261       } else {
262         tensorResults.push_back(res->getResult(resultIdx));
263       }
264       ++resultIdx;
265     }
266     return scf::ValueVector(tensorResults.begin(), tensorResults.end());
267   };
268   GenerateLoopNest<LoopTy>::doit(b, op.getLoc(), loopRanges, op, iteratorTypes,
269                                  tiledLoopBodyBuilder, options.distribution,
270                                  options.distributionTypes);
271 
272   // 3. Transform IndexOp results w.r.t. the tiling.
273   transformIndexOps(b, res, ivs, loopIndexToRangeIndex);
274 
275   // 4. Gather the newly created loops and return them with the new op.
276   SmallVector<Operation *, 8> loops;
277   loops.reserve(ivs.size());
278   for (auto iv : ivs) {
279     if (iv.isa<BlockArgument>()) {
280       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
281       assert(loops.back() && "no owner found for induction variable!");
282     } else {
283       // TODO: Instead of doing this, try to recover the ops used instead of the
284       // loop.
285       loops.push_back(nullptr);
286     }
287   }
288 
289   // 5. Get the tensor results from the outermost loop if available. Otherwise
290   // use the previously captured `tensorResults`.
291   Operation *outermostLoop = nullptr;
292   for (Operation *loop : loops)
293     if ((outermostLoop = loop))
294       break;
295 
296   return TiledLinalgOp{
297       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
298 }
299 
300 template <typename LoopTy>
301 Optional<TiledLinalgOp> static tileLinalgOpImpl(
302     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
303   OpBuilder::InsertionGuard g(b);
304   b.setInsertionPoint(op);
305 
306   if (!options.tileSizeComputationFunction)
307     return llvm::None;
308 
309   // Enforce the convention that "tiling by zero" skips tiling a particular
310   // dimension. This convention is significantly simpler to handle instead of
311   // adjusting affine maps to account for missing dimensions.
312   auto nLoops = op.getNumLoops();
313   SmallVector<Value, 4> tileSizeVector =
314       options.tileSizeComputationFunction(b, op);
315   if (tileSizeVector.size() < nLoops) {
316     auto zero = b.create<ConstantIndexOp>(op.getLoc(), 0);
317     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
318   }
319 
320   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
321 }
322 
323 Optional<TiledLinalgOp>
324 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
325                            const LinalgTilingOptions &options) {
326   switch (options.loopType) {
327   case LinalgTilingLoopType::Loops:
328     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
329   case LinalgTilingLoopType::ParallelLoops:
330     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
331   case LinalgTilingLoopType::TiledLoops:
332     return tileLinalgOpImpl<linalg::TiledLoopOp>(b, op, options);
333   default:;
334   }
335   return llvm::None;
336 }
337 
338 /// Generate a loop nest around a given PadTensorOp (for tiling). `newPadOp`
339 /// and `loopNest` are output parameters that return the new (tiled) PadTensorOp
340 /// and the loop nest.
341 static LogicalResult tilePadTensorOp(OpBuilder &builder, PadTensorOp op,
342                                      PadTensorOp &newPadOp, LoopNest &loopNest,
343                                      const LinalgTilingOptions &options) {
344   Location loc = op.getLoc();
345   OpBuilder::InsertionGuard g(builder);
346   builder.setInsertionPoint(op);
347 
348   // Clone PadTensorOp so that the existing op can be replaced more easily.
349   newPadOp = cast<PadTensorOp>(builder.clone(*op.getOperation()));
350   // Get rank and tile sizes.
351   int64_t rank = op.getResultType().getRank();
352   SmallVector<Value> tileSizes =
353       options.tileSizeComputationFunction(builder, op);
354   assert(static_cast<int64_t>(tileSizes.size()) == rank);
355   // Compute lower and upper bounds of the loop nest.
356   SmallVector<Range> ranges = op.getLoopBounds(builder);
357   SmallVector<Value> lbs, dims, allDims, steps;
358   for (int64_t i = 0; i < rank; ++i) {
359     allDims.push_back(ranges[i].size);
360     if (!isZero(tileSizes[i])) {
361       lbs.push_back(ranges[i].offset);
362       dims.push_back(ranges[i].size);
363       steps.push_back(tileSizes[i]);
364     }
365   }
366   // Generate loop nest: One loop per dimension.
367   SmallVector<Value> destOperand = op.getDestinationOperands(builder);
368   loopNest = mlir::scf::buildLoopNest(
369       builder, loc, lbs, /*ubs=*/dims, steps, ValueRange(destOperand),
370       [&](OpBuilder &b, Location loc, ValueRange localIvs,
371           ValueRange iterArgs) -> scf::ValueVector {
372         // Compute offsets and sizes of ExtractSliceOp.
373         SmallVector<Value> offsets =
374             computeTileOffsets(b, loc, localIvs, tileSizes);
375         SmallVector<Value> sizes =
376             computeTileSizes(b, loc, localIvs, tileSizes, allDims);
377         // Create ExtractSliceOp: Extract a tile from the PadTensorOp.
378         // Note: The PadTensorOp is located outside of the loop nest. It is
379         // later moved inside by ExtractSliceOfPadTensorSwapPattern.
380         auto map = AffineMap::getMultiDimIdentityMap(rank, b.getContext());
381         Value tiledOutput =
382             makeTiledShape(b, loc, newPadOp->getResult(0), tileSizes, map,
383                            offsets, allDims, sizes);
384         auto sliceOp = tiledOutput.getDefiningOp<tensor::ExtractSliceOp>();
385         assert(sliceOp && "expected ExtractSliceOp");
386         // Insert the tile into the output tensor.
387         Value yieldValue =
388             insertSliceIntoTensor(b, loc, sliceOp, sliceOp, iterArgs[0]);
389         return scf::ValueVector({yieldValue});
390       });
391   return success();
392 }
393 
394 namespace {
395 struct PadTensorOpTilingPattern : public OpRewritePattern<PadTensorOp> {
396   PadTensorOpTilingPattern(MLIRContext *ctx, LinalgTilingOptions opt)
397       : OpRewritePattern<PadTensorOp>(ctx), options(opt) {}
398 
399   LogicalResult matchAndRewrite(PadTensorOp op,
400                                 PatternRewriter &rewriter) const override {
401     if (op->hasAttr(LinalgTransforms::kLinalgTransformMarker))
402       return failure();
403     PadTensorOp newPadOp;
404     LoopNest loopNest;
405     if (failed(tilePadTensorOp(rewriter, op, newPadOp, loopNest, options)))
406       return failure();
407     newPadOp->setAttr(LinalgTransforms::kLinalgTransformMarker,
408                       rewriter.getUnitAttr());
409     // Replace all uses of the original PadTensorOp.
410     rewriter.replaceOp(op, loopNest.getResults()[0]);
411     return success();
412   }
413 
414   LinalgTilingOptions options;
415 };
416 } // namespace
417 
418 namespace {
419 /// Helper classes for type list expansion.
420 template <typename... OpTypes>
421 class CanonicalizationPatternList;
422 
423 template <>
424 class CanonicalizationPatternList<> {
425 public:
426   static void insert(RewritePatternSet &patterns) {}
427 };
428 
429 template <typename OpTy, typename... OpTypes>
430 class CanonicalizationPatternList<OpTy, OpTypes...> {
431 public:
432   static void insert(RewritePatternSet &patterns) {
433     OpTy::getCanonicalizationPatterns(patterns, patterns.getContext());
434     CanonicalizationPatternList<OpTypes...>::insert(patterns);
435   }
436 };
437 
438 /// Helper classes for type list expansion.
439 template <typename... OpTypes>
440 class RewritePatternList;
441 
442 template <>
443 class RewritePatternList<> {
444 public:
445   static void insert(RewritePatternSet &patterns,
446                      const LinalgTilingOptions &options) {}
447 };
448 
449 template <typename OpTy, typename... OpTypes>
450 class RewritePatternList<OpTy, OpTypes...> {
451 public:
452   static void insert(RewritePatternSet &patterns,
453                      const LinalgTilingOptions &options) {
454     auto *ctx = patterns.getContext();
455     patterns.add<LinalgTilingPattern<OpTy>>(
456         ctx, options,
457         LinalgTransformationFilter(ArrayRef<Identifier>{},
458                                    Identifier::get("tiled", ctx)));
459     RewritePatternList<OpTypes...>::insert(patterns, options);
460   }
461 };
462 } // namespace
463 
464 RewritePatternSet
465 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
466   RewritePatternSet patterns(ctx);
467   populateLinalgTilingCanonicalizationPatterns(patterns);
468   return patterns;
469 }
470 
471 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
472     RewritePatternSet &patterns) {
473   auto *ctx = patterns.getContext();
474   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
475   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
476   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
477   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
478   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
479   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
480   ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
481   tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, ctx);
482   tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, ctx);
483   memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx);
484   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
485   memref::ViewOp::getCanonicalizationPatterns(patterns, ctx);
486   PadTensorOp::getCanonicalizationPatterns(patterns, ctx);
487   ctx->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(patterns);
488   CanonicalizationPatternList<
489 #define GET_OP_LIST
490 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
491       >::insert(patterns);
492 }
493 
494 /// Populate the given list with patterns that apply Linalg tiling.
495 static void insertTilingPatterns(RewritePatternSet &patterns,
496                                  const LinalgTilingOptions &options) {
497   RewritePatternList<GenericOp,
498 #define GET_OP_LIST
499 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
500                      >::insert(patterns, options);
501   patterns.add<PadTensorOpTilingPattern>(patterns.getContext(), options);
502 }
503 
504 static void applyExtractSliceOfPadTensorSwapPattern(FuncOp funcOp) {
505   MLIRContext *ctx = funcOp.getContext();
506   RewritePatternSet patterns(ctx);
507   patterns.add<ExtractSliceOfPadTensorSwapPattern>(patterns.getContext());
508   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
509   (void)applyPatternsAndFoldGreedily(
510       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
511 }
512 
513 static void
514 applyTilingToLoopPatterns(LinalgTilingLoopType loopType, FuncOp funcOp,
515                           ArrayRef<int64_t> tileSizes,
516                           ArrayRef<StringRef> distributionTypes = {}) {
517   auto options = LinalgTilingOptions()
518                      .setTileSizes(tileSizes)
519                      .setLoopType(loopType)
520                      .setDistributionTypes(distributionTypes);
521   MLIRContext *ctx = funcOp.getContext();
522   RewritePatternSet patterns(ctx);
523   insertTilingPatterns(patterns, options);
524   scf::populateSCFForLoopCanonicalizationPatterns(patterns);
525   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
526   (void)applyPatternsAndFoldGreedily(
527       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
528   // Drop the marker.
529   funcOp.walk([](LinalgOp op) {
530     op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
531   });
532 
533   // Apply swap pattern after generating loop nest and running
534   // canonicalizations.
535   applyExtractSliceOfPadTensorSwapPattern(funcOp);
536 }
537 
538 namespace {
539 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
540   LinalgTilingPass() = default;
541   LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
542 
543   void runOnFunction() override {
544     applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(),
545                               tileSizes);
546   }
547 };
548 
549 struct LinalgTilingToParallelLoopsPass
550     : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> {
551   LinalgTilingToParallelLoopsPass() = default;
552   LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) {
553     tileSizes = sizes;
554   }
555 
556   void runOnFunction() override {
557     applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops,
558                               getFunction(), tileSizes);
559   }
560 };
561 
562 struct LinalgTilingToTiledLoopsPass
563     : public LinalgTilingToTiledLoopsBase<LinalgTilingToTiledLoopsPass> {
564   LinalgTilingToTiledLoopsPass() = default;
565   LinalgTilingToTiledLoopsPass(ArrayRef<int64_t> sizes,
566                                ArrayRef<StringRef> types) {
567     tileSizes = sizes;
568     distributionTypes = llvm::to_vector<2>(
569         llvm::map_range(types, [](StringRef ref) { return ref.str(); }));
570   }
571 
572   void runOnFunction() override {
573     applyTilingToLoopPatterns(
574         LinalgTilingLoopType::TiledLoops, getFunction(), tileSizes,
575         llvm::to_vector<2>(
576             llvm::map_range(distributionTypes,
577                             [](std::string &str) { return StringRef(str); })));
578   }
579 };
580 
581 } // namespace
582 
583 std::unique_ptr<OperationPass<FuncOp>>
584 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
585   return std::make_unique<LinalgTilingPass>(tileSizes);
586 }
587 
588 std::unique_ptr<OperationPass<FuncOp>>
589 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
590   return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
591 }
592 
593 std::unique_ptr<OperationPass<FuncOp>>
594 mlir::createLinalgTilingToTiledLoopPass(ArrayRef<int64_t> tileSizes,
595                                         ArrayRef<StringRef> distributionTypes) {
596   return std::make_unique<LinalgTilingToTiledLoopsPass>(tileSizes,
597                                                         distributionTypes);
598 }
599