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/Affine/EDSC/Intrinsics.h"
15 #include "mlir/Dialect/Linalg/EDSC/FoldedIntrinsics.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
17 #include "mlir/Dialect/Linalg/Passes.h"
18 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
19 #include "mlir/Dialect/Linalg/Utils/Utils.h"
20 #include "mlir/Dialect/MemRef/EDSC/Intrinsics.h"
21 #include "mlir/Dialect/MemRef/IR/MemRef.h"
22 #include "mlir/Dialect/SCF/EDSC/Builders.h"
23 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
24 #include "mlir/Dialect/Tensor/IR/Tensor.h"
25 #include "mlir/IR/AffineExpr.h"
26 #include "mlir/IR/AffineExprVisitor.h"
27 #include "mlir/IR/AffineMap.h"
28 #include "mlir/Transforms/FoldUtils.h"
29 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
30 
31 #include "llvm/Support/CommandLine.h"
32 
33 using namespace mlir;
34 using namespace mlir::edsc;
35 using namespace mlir::edsc::intrinsics;
36 using namespace mlir::linalg;
37 using namespace mlir::scf;
38 
39 #define DEBUG_TYPE "linalg-tiling"
40 
41 static bool isZero(Value v) {
42   if (auto cst = v.getDefiningOp<ConstantIndexOp>())
43     return cst.getValue() == 0;
44   return false;
45 }
46 
47 using LoopIndexToRangeIndexMap = DenseMap<int, int>;
48 
49 // Creates a number of ranges equal to the number of non-zero in `tileSizes`.
50 // One for each loop of the LinalgOp that is tiled. The `tileSizes` argument has
51 // one entry per surrounding loop. It uses zero as the convention that a
52 // particular loop is not tiled. This convention simplifies implementations by
53 // avoiding affine map manipulations.
54 // The returned ranges correspond to the loop ranges, in the proper order, that
55 // are tiled and for which new loops will be created. Also the function returns
56 // a map from loop indices of the LinalgOp to the corresponding non-empty range
57 // indices of newly created loops.
58 static std::tuple<SmallVector<Range, 4>, LoopIndexToRangeIndexMap>
59 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
60                     ValueRange allShapeSizes, ValueRange allTileSizes) {
61   assert(allTileSizes.size() == map.getNumResults());
62   // Apply `map` to get shape sizes in loop order.
63   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
64   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
65 
66   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
67   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
68   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
69     if (isZero(tileSizes[idx - zerosCount])) {
70       shapeSizes.erase(shapeSizes.begin() + idx - zerosCount);
71       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
72       ++zerosCount;
73       continue;
74     }
75     loopIndexToRangeIndex[idx] = idx - zerosCount;
76   }
77 
78   // Create a new range with the applied tile sizes.
79   SmallVector<Range, 4> res;
80   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx)
81     res.push_back(
82         Range{std_constant_index(0), shapeSizes[idx], tileSizes[idx]});
83   return std::make_tuple(res, loopIndexToRangeIndex);
84 }
85 namespace {
86 
87 // Helper visitor to determine whether an AffineExpr is tiled.
88 // This is achieved by traversing every AffineDimExpr with position `pos` and
89 // checking whether the corresponding `tileSizes[pos]` is non-zero.
90 // This also enforces only positive coefficients occur in multiplications.
91 //
92 // Example:
93 //   `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0]
94 //
95 struct TileCheck : public AffineExprVisitor<TileCheck> {
96   TileCheck(ValueRange tileSizes) : isTiled(false), tileSizes(tileSizes) {}
97 
98   void visitDimExpr(AffineDimExpr expr) {
99     isTiled |= !isZero(tileSizes[expr.getPosition()]);
100   }
101   void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
102     visit(expr.getLHS());
103     visit(expr.getRHS());
104     if (expr.getKind() == mlir::AffineExprKind::Mul)
105       assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 &&
106              "nonpositive multiplying coefficient");
107   }
108   bool isTiled;
109   ValueRange tileSizes;
110 };
111 
112 } // namespace
113 
114 // IndexedGenericOp explicitly uses induction variables in the loop body. The
115 // values of the indices that are used in the loop body for any given access of
116 // input/output memref before `subview` op was applied should be invariant with
117 // respect to tiling.
118 //
119 // Therefore, if the operation is tiled, we have to transform the indices
120 // accordingly, i.e. offset them by the values of the corresponding induction
121 // variables that are captured implicitly in the body of the op.
122 //
123 // Example. `linalg.indexed_generic` before tiling:
124 //
125 // #id_2d = (i, j) -> (i, j)
126 // #pointwise_2d_trait = {
127 //   indexing_maps = [#id_2d, #id_2d],
128 //   iterator_types = ["parallel", "parallel"],
129 //   n_views = [1, 1]
130 // }
131 // linalg.indexed_generic #pointwise_2d_trait %operand, %result {
132 //   ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
133 //     <some operations that use %i, %j>
134 // }: memref<50x100xf32>, memref<50x100xf32>
135 //
136 // After tiling pass with tiles sizes 10 and 25:
137 //
138 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
139 //
140 // %c1 = constant 1 : index
141 // %c0 = constant 0 : index
142 // %c25 = constant 25 : index
143 // %c10 = constant 10 : index
144 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
145 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
146 // scf.for %k = %c0 to operand_dim_0 step %c10 {
147 //   scf.for %l = %c0 to operand_dim_1 step %c25 {
148 //     %4 = memref.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
149 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
150 //     %5 = memref.subview %result[%k, %l][%c10, %c25][%c1, %c1]
151 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
152 //     linalg.indexed_generic pointwise_2d_trait %4, %5 {
153 //     ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
154 //       // Indices `k` and `l` are implicitly captured in the body.
155 //       %transformed_i = addi %i, %k : index // index `i` is offset by %k
156 //       %transformed_j = addi %j, %l : index // index `j` is offset by %l
157 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
158 //       <some operations that use %transformed_i, %transformed_j>
159 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
160 //   }
161 // }
162 //
163 // TODO: Investigate whether mixing implicit and explicit indices
164 // does not lead to losing information.
165 static void transformIndexedGenericOpIndices(
166     OpBuilder &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
167     const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
168   auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op.getOperation());
169   if (!indexedGenericOp)
170     return;
171 
172   // `linalg.indexed_generic` comes in two flavours. One has a region with a
173   // single block that defines the loop body. The other has a `fun` attribute
174   // that refers to an existing function symbol. The `fun` function call will be
175   // inserted in the loop body in that case.
176   //
177   // TODO: Add support for `linalg.indexed_generic` with `fun` attribute.
178   auto &region = indexedGenericOp.region();
179   if (region.empty()) {
180     indexedGenericOp.emitOpError("expected a region");
181     return;
182   }
183   auto &block = region.front();
184 
185   OpBuilder::InsertionGuard g(b);
186   b.setInsertionPointToStart(&block);
187   for (unsigned i = 0; i < indexedGenericOp.getNumLoops(); ++i) {
188     auto rangeIndex = loopIndexToRangeIndex.find(i);
189     if (rangeIndex == loopIndexToRangeIndex.end())
190       continue;
191     Value oldIndex = block.getArgument(i);
192     // Offset the index argument `i` by the value of the corresponding induction
193     // variable and replace all uses of the previous value.
194     Value newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex,
195                                       ivs[rangeIndex->second]);
196     for (auto &use : oldIndex.getUses()) {
197       if (use.getOwner() == newIndex.getDefiningOp())
198         continue;
199       use.set(newIndex);
200     }
201   }
202 }
203 
204 static bool isTiled(AffineExpr expr, ValueRange tileSizes) {
205   if (!expr)
206     return false;
207   TileCheck t(tileSizes);
208   t.visit(expr);
209   return t.isTiled;
210 }
211 
212 // Checks whether the `map  varies with respect to a non-zero `tileSize`.
213 static bool isTiled(AffineMap map, ValueRange tileSizes) {
214   if (!map)
215     return false;
216   for (unsigned r = 0; r < map.getNumResults(); ++r)
217     if (isTiled(map.getResult(r), tileSizes))
218       return true;
219   return false;
220 }
221 
222 static SmallVector<Value, 4>
223 makeTiledShapes(OpBuilder &b, Location loc, LinalgOp linalgOp,
224                 ArrayRef<Value> tiledOperands, AffineMap map, ValueRange ivs,
225                 ValueRange tileSizes, ValueRange allShapeSizes) {
226   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
227                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
228                            [](Value v) { return !isZero(v); })) &&
229          "expected as many ivs as non-zero sizes");
230 
231   using namespace edsc::op;
232 
233   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
234   // Construct (potentially temporary) mins and maxes on which to apply maps
235   // that define tile subshapes.
236   SmallVector<Value, 8> lbs, subShapeSizes;
237   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
238     bool isTiled = !isZero(tileSizes[idx]);
239     lbs.push_back(isTiled ? ivs[idxIvs++] : (Value)std_constant_index(0));
240     // Before composing, we need to make range a closed interval.
241     Value size = isTiled ? tileSizes[idx] : shapeSizes[idx];
242     subShapeSizes.push_back(size - std_constant_index(1));
243   }
244 
245   SmallVector<Value, 4> res;
246   res.reserve(tiledOperands.size());
247   for (auto en : llvm::enumerate(tiledOperands)) {
248     Value shapedOp = en.value();
249     ShapedType shapedType = shapedOp.getType().cast<ShapedType>();
250     unsigned rank = shapedType.getRank();
251     AffineMap map = linalgOp.getIndexingMap(en.index());
252     // If the shape is not tiled, we can use it as is.
253     if (!isTiled(map, tileSizes)) {
254       res.push_back(shapedOp);
255       continue;
256     }
257 
258     // Construct a new subview / subtensor for the tile.
259     SmallVector<OpFoldResult, 4> offsets, sizes, strides;
260     offsets.reserve(rank);
261     sizes.reserve(rank);
262     strides.reserve(rank);
263     for (unsigned r = 0; r < rank; ++r) {
264       if (!isTiled(map.getSubMap({r}), tileSizes)) {
265         offsets.push_back(b.getIndexAttr(0));
266         sizes.push_back(memref_dim(shapedOp, r).value);
267         strides.push_back(b.getIndexAttr(1));
268         continue;
269       }
270 
271       // Tiling creates a new slice at the proper index, the slice step is 1
272       // (i.e. the op does not subsample, stepping occurs in the loop).
273       auto m = map.getSubMap({r});
274       auto offset = applyMapToValues(b, loc, m, lbs).front();
275       offsets.push_back(offset);
276       auto closedIntSize = applyMapToValues(b, loc, m, subShapeSizes).front();
277       // Resulting size needs to be made half open interval again.
278       auto size = closedIntSize + std_constant_index(1);
279 
280       // The size of the subview / subtensor should be trimmed to avoid
281       // out-of-bounds accesses, unless we statically know the subshape size
282       // divides the shape size evenly.
283       int64_t shapeSize = shapedType.getDimSize(r);
284       auto sizeCst = size.getDefiningOp<ConstantIndexOp>();
285       if (ShapedType::isDynamic(shapeSize) || !sizeCst ||
286           (shapeSize % sizeCst.getValue()) != 0) {
287         // Compute min(size, dim - offset) to avoid out-of-bounds accesses.
288         auto minMap = AffineMap::get(
289             /*dimCount=*/3, /*symbolCount=*/0,
290             {getAffineDimExpr(/*position=*/0, b.getContext()),
291              getAffineDimExpr(/*position=*/1, b.getContext()) -
292                  getAffineDimExpr(/*position=*/2, b.getContext())},
293             b.getContext());
294         Value d = memref_dim(shapedOp, r);
295         SmallVector<Value, 4> operands{size, d, offset};
296         fullyComposeAffineMapAndOperands(&minMap, &operands);
297         size = affine_min(b.getIndexType(), minMap, operands);
298       }
299 
300       sizes.push_back(size);
301       strides.push_back(b.getIndexAttr(1));
302     }
303 
304     if (shapedType.isa<MemRefType>())
305       res.push_back(
306           b.create<memref::SubViewOp>(loc, shapedOp, offsets, sizes, strides));
307     else
308       res.push_back(
309           b.create<SubTensorOp>(loc, shapedOp, offsets, sizes, strides));
310   }
311 
312   return res;
313 }
314 
315 template <typename LoopTy>
316 static Optional<TiledLinalgOp>
317 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
318                  const LinalgTilingOptions &options) {
319   auto nLoops = op.getNumLoops();
320   // Initial tile sizes may be too big, only take the first nLoops.
321   tileSizes = tileSizes.take_front(nLoops);
322 
323   if (llvm::all_of(tileSizes, isZero))
324     return llvm::None;
325 
326   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
327     // For conv op only support tiling along batch dimension (which is the first
328     // loop).
329     if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(), isZero))
330       return llvm::None;
331   }
332 
333   // 1. Build the tiled loop ranges.
334   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
335   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
336   if (!shapeSizesToLoopsMap)
337     return llvm::None;
338 
339   SmallVector<Range, 4> loopRanges;
340   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
341   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
342       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
343 
344   SmallVector<Attribute, 4> iteratorTypes;
345   for (auto attr :
346        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
347     if (loopIndexToRangeIndex.count(attr.index()))
348       iteratorTypes.push_back(attr.value());
349   }
350   // If interchangeVector is empty, use the identity. Build the permutation map
351   // otherwise.
352   auto invPermutationMap =
353       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
354   if (!options.interchangeVector.empty()) {
355     // Based on the pruned iterations (due to zero tile size), recompute the
356     // interchange vector.
357     SmallVector<unsigned, 4> interchangeVector;
358     interchangeVector.reserve(options.interchangeVector.size());
359     for (auto pos : options.interchangeVector) {
360       auto it = loopIndexToRangeIndex.find(pos);
361       if (it == loopIndexToRangeIndex.end())
362         continue;
363       interchangeVector.push_back(it->second);
364     }
365     // Interchange vector is guaranteed to be a permutation,
366     // `inversePermutation` must succeed.
367     invPermutationMap = inversePermutation(
368         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
369     assert(invPermutationMap);
370     applyPermutationToVector(loopRanges, interchangeVector);
371     applyPermutationToVector(iteratorTypes, interchangeVector);
372   }
373 
374   // 2. Create the tiled loops.
375   LinalgOp res = op;
376   SmallVector<Value, 4> ivs, tensorResults;
377   auto outputTensors = op.getOutputTensors();
378   GenerateLoopNest<LoopTy>::doit(
379       loopRanges, /*iterArgInitValues*/ outputTensors, iteratorTypes,
380       [&](ValueRange localIvs, ValueRange iterArgs) -> scf::ValueVector {
381         auto &b = ScopedContext::getBuilderRef();
382         auto loc = ScopedContext::getLocation();
383         ivs.assign(localIvs.begin(), localIvs.end());
384 
385         // When an `interchangeVector` is present, it has been applied to the
386         // loop ranges and the iterator types. Apply its inverse to the
387         // resulting loop `ivs` to match the op definition.
388         SmallVector<Value, 4> interchangedIvs;
389         if (!options.interchangeVector.empty())
390           interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
391         else
392           interchangedIvs.assign(ivs.begin(), ivs.end());
393 
394         assert(op.getNumOutputTensors() == iterArgs.size() &&
395                "num output tensors must match number of loop iter arguments");
396 
397         auto operands = llvm::to_vector<4>(op.getInputs());
398         SmallVector<Value, 4> outputBuffers = op.getOutputBuffers();
399         // TODO: thanks to simplifying assumption we do not need to worry about
400         // order of output buffers and tensors: there is only ever one kind.
401         assert(outputBuffers.empty() || iterArgs.empty());
402         operands.append(outputBuffers.begin(), outputBuffers.end());
403         operands.append(iterArgs.begin(), iterArgs.end());
404         SmallVector<Value, 4> tiledOperands =
405             makeTiledShapes(b, loc, op, operands, shapeSizesToLoopsMap,
406                             interchangedIvs, tileSizes, allShapeSizes);
407         auto nonShapedOperands = op.getAssumedNonShapedOperands();
408         tiledOperands.append(nonShapedOperands.begin(),
409                              nonShapedOperands.end());
410 
411         // TODO: use an interface/adaptor to avoid leaking position in
412         // `tiledOperands`.
413         SmallVector<Type, 4> resultTensorTypes;
414         for (OpOperand *opOperand : op.getOutputTensorsOpOperands())
415           resultTensorTypes.push_back(
416               tiledOperands[opOperand->getOperandNumber()].getType());
417 
418         res = op.clone(b, loc, resultTensorTypes, tiledOperands);
419 
420         // Insert a subtensor_insert for each output tensor.
421         unsigned resultIdx = 0;
422         for (OpOperand *opOperand : op.getOutputTensorsOpOperands()) {
423           // TODO: use an interface/adaptor to avoid leaking position in
424           // `tiledOperands`.
425           Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
426           if (auto subtensor = outputTensor.getDefiningOp<SubTensorOp>()) {
427             tensorResults.push_back(b.create<SubTensorInsertOp>(
428                 loc, subtensor.source().getType(), res->getResult(resultIdx),
429                 subtensor.source(), subtensor.offsets(), subtensor.sizes(),
430                 subtensor.strides(), subtensor.static_offsets(),
431                 subtensor.static_sizes(), subtensor.static_strides()));
432           } else {
433             tensorResults.push_back(res->getResult(resultIdx));
434           }
435           ++resultIdx;
436         }
437         return scf::ValueVector(tensorResults.begin(), tensorResults.end());
438       },
439       options.distribution);
440 
441   // 3. Transforms index arguments of `linalg.generic` w.r.t. to the tiling.
442   transformIndexedGenericOpIndices(b, res, ivs, loopIndexToRangeIndex);
443 
444   // 4. Gather the newly created loops and return them with the new op.
445   SmallVector<Operation *, 8> loops;
446   loops.reserve(ivs.size());
447   for (auto iv : ivs) {
448     if (iv.isa<BlockArgument>()) {
449       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
450       assert(loops.back() && "no owner found for induction variable!");
451     } else {
452       // TODO: Instead of doing this, try to recover the ops used instead of the
453       // loop.
454       loops.push_back(nullptr);
455     }
456   }
457 
458   // 5. Get the tensor results from the outermost loop if available. Otherwise
459   // use the previously captured `tensorResults`.
460   Operation *outermostLoop = nullptr;
461   for (Operation *loop : loops)
462     if ((outermostLoop = loop))
463       break;
464 
465   return TiledLinalgOp{
466       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
467 }
468 
469 template <typename LoopTy>
470 Optional<TiledLinalgOp> static tileLinalgOpImpl(
471     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
472   OpBuilder::InsertionGuard g(b);
473   b.setInsertionPoint(op);
474   ScopedContext scope(b, op.getLoc());
475 
476   if (!options.tileSizeComputationFunction)
477     return llvm::None;
478 
479   // Enforce the convention that "tiling by zero" skips tiling a particular
480   // dimension. This convention is significantly simpler to handle instead of
481   // adjusting affine maps to account for missing dimensions.
482   auto nLoops = op.getNumLoops();
483   SmallVector<Value, 4> tileSizeVector =
484       options.tileSizeComputationFunction(b, op);
485   if (tileSizeVector.size() < nLoops) {
486     auto zero = std_constant_index(0);
487     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
488   }
489 
490   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
491 }
492 
493 Optional<TiledLinalgOp>
494 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
495                            const LinalgTilingOptions &options) {
496   switch (options.loopType) {
497   case LinalgTilingLoopType::Loops:
498     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
499   case LinalgTilingLoopType::ParallelLoops:
500     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
501   default:;
502   }
503   return llvm::None;
504 }
505 
506 namespace {
507 /// Helper classes for type list expansion.
508 template <typename... OpTypes>
509 class CanonicalizationPatternList;
510 
511 template <>
512 class CanonicalizationPatternList<> {
513 public:
514   static void insert(OwningRewritePatternList &patterns, MLIRContext *ctx) {}
515 };
516 
517 template <typename OpTy, typename... OpTypes>
518 class CanonicalizationPatternList<OpTy, OpTypes...> {
519 public:
520   static void insert(OwningRewritePatternList &patterns, MLIRContext *ctx) {
521     OpTy::getCanonicalizationPatterns(patterns, ctx);
522     CanonicalizationPatternList<OpTypes...>::insert(patterns, ctx);
523   }
524 };
525 
526 /// Helper classes for type list expansion.
527 template <typename... OpTypes>
528 class RewritePatternList;
529 
530 template <>
531 class RewritePatternList<> {
532 public:
533   static void insert(OwningRewritePatternList &patterns,
534                      const LinalgTilingOptions &options, MLIRContext *ctx) {}
535 };
536 
537 template <typename OpTy, typename... OpTypes>
538 class RewritePatternList<OpTy, OpTypes...> {
539 public:
540   static void insert(OwningRewritePatternList &patterns,
541                      const LinalgTilingOptions &options, MLIRContext *ctx) {
542     patterns.insert<LinalgTilingPattern<OpTy>>(
543         ctx, options,
544         LinalgTransformationFilter(ArrayRef<Identifier>{},
545                                    Identifier::get("tiled", ctx)));
546     RewritePatternList<OpTypes...>::insert(patterns, options, ctx);
547   }
548 };
549 } // namespace
550 
551 OwningRewritePatternList
552 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
553   OwningRewritePatternList patterns;
554   populateLinalgTilingCanonicalizationPatterns(patterns, ctx);
555   return patterns;
556 }
557 
558 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
559     OwningRewritePatternList &patterns, MLIRContext *ctx) {
560   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
561   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
562   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
563   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
564   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
565   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
566   ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
567   SubTensorOp::getCanonicalizationPatterns(patterns, ctx);
568   memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx);
569   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
570   memref::ViewOp::getCanonicalizationPatterns(patterns, ctx);
571   CanonicalizationPatternList<
572 #define GET_OP_LIST
573 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
574       >::insert(patterns, ctx);
575 }
576 
577 /// Populate the given list with patterns that apply Linalg tiling.
578 static void insertTilingPatterns(OwningRewritePatternList &patterns,
579                                  const LinalgTilingOptions &options,
580                                  MLIRContext *ctx) {
581   RewritePatternList<GenericOp, IndexedGenericOp,
582 #define GET_OP_LIST
583 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
584                      >::insert(patterns, options, ctx);
585 }
586 
587 static void applyTilingToLoopPatterns(LinalgTilingLoopType loopType,
588                                       FuncOp funcOp,
589                                       ArrayRef<int64_t> tileSizes) {
590   auto options =
591       LinalgTilingOptions().setTileSizes(tileSizes).setLoopType(loopType);
592   MLIRContext *ctx = funcOp.getContext();
593   OwningRewritePatternList patterns;
594   insertTilingPatterns(patterns, options, ctx);
595   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
596   (void)applyPatternsAndFoldGreedily(
597       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
598   // Drop the marker.
599   funcOp.walk([](LinalgOp op) {
600     op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
601   });
602 }
603 
604 namespace {
605 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
606   LinalgTilingPass() = default;
607   LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
608 
609   void runOnFunction() override {
610     applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(),
611                               tileSizes);
612   }
613 };
614 
615 struct LinalgTilingToParallelLoopsPass
616     : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> {
617   LinalgTilingToParallelLoopsPass() = default;
618   LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) {
619     tileSizes = sizes;
620   }
621 
622   void runOnFunction() override {
623     applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops,
624                               getFunction(), tileSizes);
625   }
626 };
627 
628 } // namespace
629 
630 std::unique_ptr<OperationPass<FuncOp>>
631 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
632   return std::make_unique<LinalgTilingPass>(tileSizes);
633 }
634 
635 std::unique_ptr<OperationPass<FuncOp>>
636 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
637   return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
638 }
639