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   // Skip operations that have no region attached.
133   if (op->getNumRegions() == 0)
134     return;
135   assert(op->getNumRegions() == 1 && op->getRegion(0).getBlocks().size() == 1 &&
136          "expected linalg operation to have one block.");
137   Block &block = op->getRegion(0).front();
138 
139   for (IndexOp indexOp : block.getOps<linalg::IndexOp>()) {
140     auto rangeIndex = loopIndexToRangeIndex.find(indexOp.dim());
141     if (rangeIndex == loopIndexToRangeIndex.end())
142       continue;
143     // Offset the index by the value of the corresponding induction variable and
144     // replace all uses of the previous value.
145     OpBuilder::InsertionGuard g(b);
146     b.setInsertionPointAfter(indexOp);
147     AffineExpr index, iv;
148     bindDims(b.getContext(), index, iv);
149     AffineApplyOp applyOp = b.create<AffineApplyOp>(
150         indexOp.getLoc(), index + iv,
151         ValueRange{indexOp.getResult(), ivs[rangeIndex->second]});
152     indexOp.getResult().replaceAllUsesExcept(applyOp, applyOp);
153   }
154 }
155 
156 // Insert a tile `source` into the destination tensor `dest`. The position at
157 // which the tile is inserted (as well as size of tile) is taken from a given
158 // ExtractSliceOp `sliceOp`.
159 static Value insertSliceIntoTensor(OpBuilder &b, Location loc,
160                                    tensor::ExtractSliceOp sliceOp, Value source,
161                                    Value dest) {
162   return b.create<tensor::InsertSliceOp>(
163       loc, sliceOp.source().getType(), source, dest, sliceOp.offsets(),
164       sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(),
165       sliceOp.static_sizes(), sliceOp.static_strides());
166 }
167 
168 template <typename LoopTy>
169 static Optional<TiledLinalgOp>
170 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
171                  const LinalgTilingOptions &options) {
172   auto nLoops = op.getNumLoops();
173   // Initial tile sizes may be too big, only take the first nLoops.
174   tileSizes = tileSizes.take_front(nLoops);
175 
176   if (llvm::all_of(tileSizes, isZero))
177     return llvm::None;
178 
179   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
180     // For conv op only support tiling along batch dimension (which is the first
181     // loop).
182     if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(), isZero))
183       return llvm::None;
184   }
185 
186   // 1. Build the tiled loop ranges.
187   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
188   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
189   if (!shapeSizesToLoopsMap)
190     return llvm::None;
191 
192   SmallVector<Range, 4> loopRanges;
193   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
194   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
195       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
196 
197   SmallVector<Attribute, 4> iteratorTypes;
198   for (auto attr :
199        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
200     if (loopIndexToRangeIndex.count(attr.index()))
201       iteratorTypes.push_back(attr.value());
202   }
203   // If interchangeVector is empty, use the identity. Build the permutation map
204   // otherwise.
205   auto invPermutationMap =
206       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
207   if (!options.interchangeVector.empty()) {
208     // Based on the pruned iterations (due to zero tile size), recompute the
209     // interchange vector.
210     SmallVector<unsigned, 4> interchangeVector;
211     interchangeVector.reserve(options.interchangeVector.size());
212     for (auto pos : options.interchangeVector) {
213       auto it = loopIndexToRangeIndex.find(pos);
214       if (it == loopIndexToRangeIndex.end())
215         continue;
216       interchangeVector.push_back(it->second);
217     }
218     // Interchange vector is guaranteed to be a permutation,
219     // `inversePermutation` must succeed.
220     invPermutationMap = inversePermutation(
221         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
222     assert(invPermutationMap);
223     applyPermutationToVector(loopRanges, interchangeVector);
224     applyPermutationToVector(iteratorTypes, interchangeVector);
225   }
226 
227   // 2. Create the tiled loops.
228   LinalgOp res = op;
229   SmallVector<Value, 4> ivs, tensorResults;
230   auto tiledLoopBodyBuilder = [&](OpBuilder &b, Location loc,
231                                   ValueRange localIvs,
232                                   ValueRange iterArgs) -> scf::ValueVector {
233     ivs.assign(localIvs.begin(), localIvs.end());
234 
235     // When an `interchangeVector` is present, it has been applied to the
236     // loop ranges and the iterator types. Apply its inverse to the
237     // resulting loop `ivs` to match the op definition.
238     SmallVector<Value, 4> interchangedIvs;
239     if (!options.interchangeVector.empty())
240       interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
241     else
242       interchangedIvs.assign(ivs.begin(), ivs.end());
243 
244     assert(op.getOutputTensorOperands().size() == iterArgs.size() &&
245            "num output tensors must match number of loop iter arguments");
246 
247     SmallVector<Value> operands = op.getInputOperands();
248     SmallVector<Value> outputBuffers = op.getOutputBufferOperands();
249     // TODO: thanks to simplifying assumption we do not need to worry about
250     // order of output buffers and tensors: there is only ever one kind.
251     assert(outputBuffers.empty() || iterArgs.empty());
252     operands.append(outputBuffers.begin(), outputBuffers.end());
253     operands.append(iterArgs.begin(), iterArgs.end());
254     auto sizeBounds =
255         applyMapToValues(b, loc, shapeSizesToLoopsMap, allShapeSizes);
256     SmallVector<Value, 4> tiledOperands = makeTiledShapes(
257         b, loc, op, operands, interchangedIvs, tileSizes, sizeBounds);
258 
259     // TODO: use an interface/adaptor to avoid leaking position in
260     // `tiledOperands`.
261     SmallVector<Type, 4> resultTensorTypes;
262     for (OpOperand *opOperand : op.getOutputTensorOperands())
263       resultTensorTypes.push_back(
264           tiledOperands[opOperand->getOperandNumber()].getType());
265 
266     res = op.clone(b, loc, resultTensorTypes, tiledOperands);
267 
268     // Insert a insert_slice for each output tensor.
269     unsigned resultIdx = 0;
270     for (OpOperand *opOperand : op.getOutputTensorOperands()) {
271       // TODO: use an interface/adaptor to avoid leaking position in
272       // `tiledOperands`.
273       Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
274       if (auto sliceOp = outputTensor.getDefiningOp<tensor::ExtractSliceOp>()) {
275         tensorResults.push_back(insertSliceIntoTensor(
276             b, loc, sliceOp, res->getResult(resultIdx), sliceOp.source()));
277       } else {
278         tensorResults.push_back(res->getResult(resultIdx));
279       }
280       ++resultIdx;
281     }
282     return scf::ValueVector(tensorResults.begin(), tensorResults.end());
283   };
284   GenerateLoopNest<LoopTy>::doit(b, op.getLoc(), loopRanges, op, iteratorTypes,
285                                  tiledLoopBodyBuilder, options.distribution,
286                                  options.distributionTypes);
287 
288   // 3. Transform IndexOp results w.r.t. the tiling.
289   transformIndexOps(b, res, ivs, loopIndexToRangeIndex);
290 
291   // 4. Gather the newly created loops and return them with the new op.
292   SmallVector<Operation *, 8> loops;
293   loops.reserve(ivs.size());
294   for (auto iv : ivs) {
295     if (iv.isa<BlockArgument>()) {
296       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
297       assert(loops.back() && "no owner found for induction variable!");
298     } else {
299       // TODO: Instead of doing this, try to recover the ops used instead of the
300       // loop.
301       loops.push_back(nullptr);
302     }
303   }
304 
305   // 5. Get the tensor results from the outermost loop if available. Otherwise
306   // use the previously captured `tensorResults`.
307   Operation *outermostLoop = nullptr;
308   for (Operation *loop : loops)
309     if ((outermostLoop = loop))
310       break;
311 
312   return TiledLinalgOp{
313       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
314 }
315 
316 template <typename LoopTy>
317 Optional<TiledLinalgOp> static tileLinalgOpImpl(
318     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
319   OpBuilder::InsertionGuard g(b);
320   b.setInsertionPoint(op);
321 
322   if (!options.tileSizeComputationFunction)
323     return llvm::None;
324 
325   // Enforce the convention that "tiling by zero" skips tiling a particular
326   // dimension. This convention is significantly simpler to handle instead of
327   // adjusting affine maps to account for missing dimensions.
328   auto nLoops = op.getNumLoops();
329   SmallVector<Value, 4> tileSizeVector =
330       options.tileSizeComputationFunction(b, op);
331   if (tileSizeVector.size() < nLoops) {
332     auto zero = b.create<ConstantIndexOp>(op.getLoc(), 0);
333     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
334   }
335 
336   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
337 }
338 
339 Optional<TiledLinalgOp>
340 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
341                            const LinalgTilingOptions &options) {
342   switch (options.loopType) {
343   case LinalgTilingLoopType::Loops:
344     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
345   case LinalgTilingLoopType::ParallelLoops:
346     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
347   case LinalgTilingLoopType::TiledLoops:
348     return tileLinalgOpImpl<linalg::TiledLoopOp>(b, op, options);
349   default:;
350   }
351   return llvm::None;
352 }
353 
354 /// Generate a loop nest around a given PadTensorOp (for tiling). `newPadOp`
355 /// and `loopNest` are output parameters that return the new (tiled) PadTensorOp
356 /// and the loop nest.
357 static LogicalResult tilePadTensorOp(OpBuilder &builder, PadTensorOp op,
358                                      PadTensorOp &newPadOp, LoopNest &loopNest,
359                                      const LinalgTilingOptions &options) {
360   // Can tile only PadTensorOp that have an output operand.
361   if (!op.output())
362     return failure();
363 
364   Location loc = op.getLoc();
365   OpBuilder::InsertionGuard g(builder);
366   builder.setInsertionPoint(op);
367 
368   // Clone PadTensorOp so that the existing op can be replaced more easily.
369   newPadOp = cast<PadTensorOp>(builder.clone(*op.getOperation()));
370   // Get rank and tile sizes.
371   int64_t rank = op.getResultType().getRank();
372   SmallVector<Value> tileSizes =
373       options.tileSizeComputationFunction(builder, op);
374   assert(static_cast<int64_t>(tileSizes.size()) == rank);
375   // Compute lower and upper bounds of the loop nest.
376   SmallVector<Value> lbs, dims, steps;
377   for (int64_t i = 0; i < rank; ++i) {
378     if (!isZero(tileSizes[i])) {
379       lbs.push_back(builder.create<ConstantIndexOp>(loc, 0));
380       dims.push_back(builder.create<tensor::DimOp>(loc, op.output(), i));
381       steps.push_back(tileSizes[i]);
382     }
383   }
384   // Generate loop nest: One loop per dimension.
385   loopNest = mlir::scf::buildLoopNest(
386       builder, loc, lbs, /*ubs=*/dims, steps, ValueRange(op.output()),
387       [&](OpBuilder &b, Location loc, ValueRange localIvs,
388           ValueRange iterArgs) -> scf::ValueVector {
389         // Compute offsets and sizes of ExtractSliceOp.
390         SmallVector<Value> offsets =
391             computeTileOffsets(b, loc, localIvs, tileSizes);
392         SmallVector<Value> sizes =
393             computeTileSizes(b, loc, localIvs, tileSizes, dims);
394         // Create ExtractSliceOp: Extract a tile from the PadTensorOp.
395         // Note: The PadTensorOp is located outside of the loop nest. It is
396         // later moved inside by ExtractSliceOfPadTensorSwapPattern.
397         auto map = AffineMap::getMultiDimIdentityMap(rank, b.getContext());
398         Value tiledOutput = makeTiledShape(b, loc, newPadOp->getResult(0),
399                                            tileSizes, map, offsets, sizes);
400         auto sliceOp = tiledOutput.getDefiningOp<tensor::ExtractSliceOp>();
401         assert(sliceOp && "expected ExtractSliceOp");
402         // Insert the tile into the output tensor.
403         Value yieldValue =
404             insertSliceIntoTensor(b, loc, sliceOp, sliceOp, iterArgs[0]);
405         return scf::ValueVector({yieldValue});
406       });
407   return success();
408 }
409 
410 namespace {
411 struct PadTensorOpTilingPattern : public OpRewritePattern<PadTensorOp> {
412   PadTensorOpTilingPattern(MLIRContext *ctx, LinalgTilingOptions opt)
413       : OpRewritePattern<PadTensorOp>(ctx), options(opt) {}
414 
415   LogicalResult matchAndRewrite(PadTensorOp op,
416                                 PatternRewriter &rewriter) const override {
417     if (op->hasAttr(LinalgTransforms::kLinalgTransformMarker))
418       return failure();
419     PadTensorOp newPadOp;
420     LoopNest loopNest;
421     if (failed(tilePadTensorOp(rewriter, op, newPadOp, loopNest, options)))
422       return failure();
423     newPadOp->setAttr(LinalgTransforms::kLinalgTransformMarker,
424                       rewriter.getUnitAttr());
425     // Replace all uses of the original PadTensorOp.
426     rewriter.replaceOp(op, loopNest.getResults()[0]);
427     return success();
428   }
429 
430   LinalgTilingOptions options;
431 };
432 } // namespace
433 
434 namespace {
435 /// Helper classes for type list expansion.
436 template <typename... OpTypes>
437 class CanonicalizationPatternList;
438 
439 template <>
440 class CanonicalizationPatternList<> {
441 public:
442   static void insert(RewritePatternSet &patterns) {}
443 };
444 
445 template <typename OpTy, typename... OpTypes>
446 class CanonicalizationPatternList<OpTy, OpTypes...> {
447 public:
448   static void insert(RewritePatternSet &patterns) {
449     OpTy::getCanonicalizationPatterns(patterns, patterns.getContext());
450     CanonicalizationPatternList<OpTypes...>::insert(patterns);
451   }
452 };
453 
454 /// Helper classes for type list expansion.
455 template <typename... OpTypes>
456 class RewritePatternList;
457 
458 template <>
459 class RewritePatternList<> {
460 public:
461   static void insert(RewritePatternSet &patterns,
462                      const LinalgTilingOptions &options) {}
463 };
464 
465 template <typename OpTy, typename... OpTypes>
466 class RewritePatternList<OpTy, OpTypes...> {
467 public:
468   static void insert(RewritePatternSet &patterns,
469                      const LinalgTilingOptions &options) {
470     auto *ctx = patterns.getContext();
471     patterns.add<LinalgTilingPattern<OpTy>>(
472         ctx, options,
473         LinalgTransformationFilter(ArrayRef<Identifier>{},
474                                    Identifier::get("tiled", ctx)));
475     RewritePatternList<OpTypes...>::insert(patterns, options);
476   }
477 };
478 } // namespace
479 
480 RewritePatternSet
481 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
482   RewritePatternSet patterns(ctx);
483   populateLinalgTilingCanonicalizationPatterns(patterns);
484   return patterns;
485 }
486 
487 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
488     RewritePatternSet &patterns) {
489   auto *ctx = patterns.getContext();
490   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
491   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
492   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
493   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
494   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
495   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
496   ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
497   tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, ctx);
498   tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, ctx);
499   memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx);
500   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
501   memref::ViewOp::getCanonicalizationPatterns(patterns, ctx);
502   PadTensorOp::getCanonicalizationPatterns(patterns, ctx);
503   ctx->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(patterns);
504   CanonicalizationPatternList<
505 #define GET_OP_LIST
506 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
507       >::insert(patterns);
508 }
509 
510 /// Populate the given list with patterns that apply Linalg tiling.
511 static void insertTilingPatterns(RewritePatternSet &patterns,
512                                  const LinalgTilingOptions &options) {
513   RewritePatternList<GenericOp,
514 #define GET_OP_LIST
515 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
516                      >::insert(patterns, options);
517   patterns.add<PadTensorOpTilingPattern>(patterns.getContext(), options);
518 }
519 
520 static void applyExtractSliceOfPadTensorSwapPattern(FuncOp funcOp) {
521   MLIRContext *ctx = funcOp.getContext();
522   RewritePatternSet patterns(ctx);
523   patterns.add<ExtractSliceOfPadTensorSwapPattern>(patterns.getContext());
524   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
525   (void)applyPatternsAndFoldGreedily(
526       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
527 }
528 
529 static void
530 applyTilingToLoopPatterns(LinalgTilingLoopType loopType, FuncOp funcOp,
531                           ArrayRef<int64_t> tileSizes,
532                           ArrayRef<StringRef> distributionTypes = {}) {
533   auto options = LinalgTilingOptions()
534                      .setTileSizes(tileSizes)
535                      .setLoopType(loopType)
536                      .setDistributionTypes(distributionTypes);
537   MLIRContext *ctx = funcOp.getContext();
538   RewritePatternSet patterns(ctx);
539   insertTilingPatterns(patterns, options);
540   scf::populateSCFForLoopCanonicalizationPatterns(patterns);
541   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
542   (void)applyPatternsAndFoldGreedily(
543       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
544   // Drop the marker.
545   funcOp.walk([](LinalgOp op) {
546     op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
547   });
548 
549   // Apply swap pattern after generating loop nest and running
550   // canonicalizations.
551   applyExtractSliceOfPadTensorSwapPattern(funcOp);
552 }
553 
554 namespace {
555 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
556   LinalgTilingPass() = default;
557   LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
558 
559   void runOnFunction() override {
560     applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(),
561                               tileSizes);
562   }
563 };
564 
565 struct LinalgTilingToParallelLoopsPass
566     : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> {
567   LinalgTilingToParallelLoopsPass() = default;
568   LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) {
569     tileSizes = sizes;
570   }
571 
572   void runOnFunction() override {
573     applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops,
574                               getFunction(), tileSizes);
575   }
576 };
577 
578 struct LinalgTilingToTiledLoopsPass
579     : public LinalgTilingToTiledLoopsBase<LinalgTilingToTiledLoopsPass> {
580   LinalgTilingToTiledLoopsPass() = default;
581   LinalgTilingToTiledLoopsPass(ArrayRef<int64_t> sizes,
582                                ArrayRef<StringRef> types) {
583     tileSizes = sizes;
584     distributionTypes = llvm::to_vector<2>(
585         llvm::map_range(types, [](StringRef ref) { return ref.str(); }));
586   }
587 
588   void runOnFunction() override {
589     applyTilingToLoopPatterns(
590         LinalgTilingLoopType::TiledLoops, getFunction(), tileSizes,
591         llvm::to_vector<2>(
592             llvm::map_range(distributionTypes,
593                             [](std::string &str) { return StringRef(str); })));
594   }
595 };
596 
597 } // namespace
598 
599 std::unique_ptr<OperationPass<FuncOp>>
600 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
601   return std::make_unique<LinalgTilingPass>(tileSizes);
602 }
603 
604 std::unique_ptr<OperationPass<FuncOp>>
605 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
606   return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
607 }
608 
609 std::unique_ptr<OperationPass<FuncOp>>
610 mlir::createLinalgTilingToTiledLoopPass(ArrayRef<int64_t> tileSizes,
611                                         ArrayRef<StringRef> distributionTypes) {
612   return std::make_unique<LinalgTilingToTiledLoopsPass>(tileSizes,
613                                                         distributionTypes);
614 }
615