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 "mlir/Dialect/Affine/EDSC/Intrinsics.h"
14 #include "mlir/Dialect/Linalg/EDSC/Intrinsics.h"
15 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
16 #include "mlir/Dialect/Linalg/Passes.h"
17 #include "mlir/Dialect/Linalg/Utils/Utils.h"
18 #include "mlir/Dialect/LoopOps/EDSC/Builders.h"
19 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
20 #include "mlir/IR/AffineExpr.h"
21 #include "mlir/IR/AffineExprVisitor.h"
22 #include "mlir/IR/AffineMap.h"
23 #include "mlir/IR/OpImplementation.h"
24 #include "mlir/Pass/Pass.h"
25 #include "mlir/Support/Functional.h"
26 #include "mlir/Support/LLVM.h"
27 #include "mlir/Support/STLExtras.h"
28 #include "mlir/Transforms/FoldUtils.h"
29 
30 #include "llvm/Support/CommandLine.h"
31 
32 using namespace mlir;
33 using namespace mlir::edsc;
34 using namespace mlir::edsc::intrinsics;
35 using namespace mlir::linalg;
36 using namespace mlir::loop;
37 
38 using folded_affine_min = folded::ValueBuilder<AffineMinOp>;
39 
40 #define DEBUG_TYPE "linalg-tiling"
41 
42 static bool isZero(Value v) {
43   return isa_and_nonnull<ConstantIndexOp>(v.getDefiningOp()) &&
44          cast<ConstantIndexOp>(v.getDefiningOp()).getValue() == 0;
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<SubViewOp::Range, 4>, LoopIndexToRangeIndexMap>
59 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
60                     ArrayRef<Value> allViewSizes, ArrayRef<Value> allTileSizes,
61                     OperationFolder *folder) {
62   assert(allTileSizes.size() == map.getNumResults());
63   // Apply `map` to get view sizes in loop order.
64   auto viewSizes = applyMapToValues(b, loc, map, allViewSizes, folder);
65   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
66 
67   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
68   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
69   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
70     if (isZero(tileSizes[idx - zerosCount])) {
71       viewSizes.erase(viewSizes.begin() + idx - zerosCount);
72       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
73       ++zerosCount;
74       continue;
75     }
76     loopIndexToRangeIndex[idx] = idx - zerosCount;
77   }
78 
79   // Create a new range with the applied tile sizes.
80   SmallVector<SubViewOp::Range, 4> res;
81   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx) {
82     res.push_back(SubViewOp::Range{folded_std_constant_index(folder, 0),
83                                    viewSizes[idx], tileSizes[idx]});
84   }
85   return std::make_tuple(res, loopIndexToRangeIndex);
86 }
87 
88 namespace {
89 
90 // Helper visitor to determine whether an AffineExpr is tiled.
91 // This is achieved by traversing every AffineDimExpr with position `pos` and
92 // checking whether the corresponding `tileSizes[pos]` is non-zero.
93 // This also enforces only positive coefficients occur in multiplications.
94 //
95 // Example:
96 //   `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0]
97 //
98 struct TileCheck : public AffineExprVisitor<TileCheck> {
99   TileCheck(ArrayRef<Value> tileSizes) : isTiled(false), tileSizes(tileSizes) {}
100 
101   void visitDimExpr(AffineDimExpr expr) {
102     isTiled |= !isZero(tileSizes[expr.getPosition()]);
103   }
104   void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
105     visit(expr.getLHS());
106     visit(expr.getRHS());
107     if (expr.getKind() == mlir::AffineExprKind::Mul)
108       assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 &&
109              "nonpositive multiplying coefficient");
110   }
111   bool isTiled;
112   ArrayRef<Value> tileSizes;
113 };
114 
115 } // namespace
116 
117 // IndexedGenericOp explicitly uses induction variables in the loop body. The
118 // values of the indices that are used in the loop body for any given access of
119 // input/output memref before `subview` op was applied should be invariant with
120 // respect to tiling.
121 //
122 // Therefore, if the operation is tiled, we have to transform the indices
123 // accordingly, i.e. offset them by the values of the corresponding induction
124 // variables that are captured implicitly in the body of the op.
125 //
126 // Example. `linalg.indexed_generic` before tiling:
127 //
128 // #id_2d = (i, j) -> (i, j)
129 // #pointwise_2d_trait = {
130 //   indexing_maps = [#id_2d, #id_2d],
131 //   iterator_types = ["parallel", "parallel"],
132 //   n_views = [1, 1]
133 // }
134 // linalg.indexed_generic #pointwise_2d_trait %operand, %result {
135 //   ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
136 //     <some operations that use %i, %j>
137 // }: memref<50x100xf32>, memref<50x100xf32>
138 //
139 // After tiling pass with tiles sizes 10 and 25:
140 //
141 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
142 //
143 // %c1 = constant 1 : index
144 // %c0 = constant 0 : index
145 // %c25 = constant 25 : index
146 // %c10 = constant 10 : index
147 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
148 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
149 // loop.for %k = %c0 to operand_dim_0 step %c10 {
150 //   loop.for %l = %c0 to operand_dim_1 step %c25 {
151 //     %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
152 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
153 //     %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1]
154 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
155 //     linalg.indexed_generic pointwise_2d_trait %4, %5 {
156 //     ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
157 //       // Indices `k` and `l` are implicitly captured in the body.
158 //       %transformed_i = addi %i, %k : index // index `i` is offset by %k
159 //       %transformed_j = addi %j, %l : index // index `j` is offset by %l
160 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
161 //       <some operations that use %transformed_i, %transformed_j>
162 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
163 //   }
164 // }
165 //
166 // TODO(pifon, ntv): Investigate whether mixing implicit and explicit indices
167 // does not lead to losing information.
168 static void transformIndexedGenericOpIndices(
169     OpBuilder &b, LinalgOp op, ArrayRef<ValueHandle *> pivs,
170     const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
171   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
172   auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op.getOperation());
173   if (!indexedGenericOp)
174     return;
175 
176   // `linalg.indexed_generic` comes in two flavours. One has a region with a
177   // single block that defines the loop body. The other has a `fun` attribute
178   // that refers to an existing function symbol. The `fun` function call will be
179   // inserted in the loop body in that case.
180   //
181   // TODO(pifon): Add support for `linalg.indexed_generic` with `fun` attribute.
182   auto &region = indexedGenericOp.region();
183   if (region.empty()) {
184     indexedGenericOp.emitOpError("expected a region");
185     return;
186   }
187   auto &block = region.getBlocks().front();
188 
189   OpBuilder::InsertionGuard g(b);
190   b.setInsertionPointToStart(&block);
191   for (unsigned i = 0; i < indexedGenericOp.getNumLoops(); ++i) {
192     auto rangeIndex = loopIndexToRangeIndex.find(i);
193     if (rangeIndex == loopIndexToRangeIndex.end())
194       continue;
195     Value oldIndex = block.getArgument(i);
196     // Offset the index argument `i` by the value of the corresponding induction
197     // variable and replace all uses of the previous value.
198     Value newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex,
199                                       pivs[rangeIndex->second]->getValue());
200     for (auto &use : oldIndex.getUses()) {
201       if (use.getOwner() == newIndex.getDefiningOp())
202         continue;
203       use.set(newIndex);
204     }
205   }
206 }
207 
208 static bool isTiled(AffineExpr expr, ArrayRef<Value> tileSizes) {
209   if (!expr)
210     return false;
211   TileCheck t(tileSizes);
212   t.visit(expr);
213   return t.isTiled;
214 }
215 
216 // Checks whether the view with index `viewIndex` within `linalgOp` varies with
217 // respect to a non-zero `tileSize`.
218 static bool isTiled(AffineMap map, ArrayRef<Value> tileSizes) {
219   if (!map)
220     return false;
221   for (unsigned r = 0; r < map.getNumResults(); ++r)
222     if (isTiled(map.getResult(r), tileSizes))
223       return true;
224   return false;
225 }
226 
227 static SmallVector<Value, 4>
228 makeTiledViews(OpBuilder &b, Location loc, LinalgOp linalgOp,
229                ArrayRef<Value> ivs, ArrayRef<Value> tileSizes,
230                ArrayRef<Value> viewSizes, OperationFolder *folder) {
231   assert(linalgOp.hasBufferSemantics() &&
232          "expected linalg op with buffer semantics");
233   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
234                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
235                            [](Value v) { return !isZero(v); })) &&
236          "expected as many ivs as non-zero sizes");
237 
238   using namespace edsc::op;
239 
240   // Construct (potentially temporary) mins and maxes on which to apply maps
241   // that define tile subviews.
242   SmallVector<Value, 8> lbs, subViewSizes;
243   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
244     bool isTiled = !isZero(tileSizes[idx]);
245     lbs.push_back(isTiled ? ivs[idxIvs++]
246                           : (Value)folded_std_constant_index(folder, 0));
247     subViewSizes.push_back(isTiled ? tileSizes[idx] : viewSizes[idx]);
248   }
249 
250   auto *op = linalgOp.getOperation();
251 
252   SmallVector<Value, 4> res;
253   res.reserve(op->getNumOperands());
254   auto viewIteratorBegin = linalgOp.getInputsAndOutputBuffers().begin();
255   for (unsigned viewIndex = 0; viewIndex < linalgOp.getNumInputsAndOutputs();
256        ++viewIndex) {
257     Value view = *(viewIteratorBegin + viewIndex);
258     auto viewType = view.getType().cast<MemRefType>();
259     unsigned rank = viewType.getRank();
260     auto mapAttr = linalgOp.indexing_maps()[viewIndex];
261     auto map = mapAttr.cast<AffineMapAttr>().getValue();
262     // If the view is not tiled, we can use it as is.
263     if (!isTiled(map, tileSizes)) {
264       res.push_back(view);
265       continue;
266     }
267 
268     // Construct a new subview for the tile.
269     SmallVector<Value, 4> offsets, sizes, strides;
270     offsets.reserve(rank);
271     sizes.reserve(rank);
272     strides.reserve(rank);
273     for (unsigned r = 0; r < rank; ++r) {
274       if (!isTiled(map.getSubMap({r}), tileSizes)) {
275         offsets.push_back(folded_std_constant_index(folder, 0));
276         sizes.push_back(std_dim(view, r));
277         strides.push_back(folded_std_constant_index(folder, 1));
278         continue;
279       }
280 
281       // Tiling creates a new slice at the proper index, the slice step is 1
282       // (i.e. the slice view does not subsample, stepping occurs in the loop).
283       auto m = map.getSubMap({r});
284       auto offset = applyMapToValues(b, loc, m, lbs, folder).front();
285       offsets.push_back(offset);
286       auto size = applyMapToValues(b, loc, m, subViewSizes, folder).front();
287 
288       // The size of the subview should be trimmed to avoid out-of-bounds
289       // accesses, unless we statically know the subview size divides the view
290       // size evenly.
291       int64_t viewSize = viewType.getDimSize(r);
292       auto sizeCst = dyn_cast_or_null<ConstantIndexOp>(size.getDefiningOp());
293       if (ShapedType::isDynamic(viewSize) || !sizeCst ||
294           (viewSize % sizeCst.getValue()) != 0) {
295         // Compute min(size, dim - offset) to avoid out-of-bounds accesses.
296         auto minMap = AffineMap::get(
297             /*dimCount=*/3, /*symbolCount=*/0,
298             {getAffineDimExpr(/*position=*/0, b.getContext()),
299              getAffineDimExpr(/*position=*/1, b.getContext()) -
300                  getAffineDimExpr(/*position=*/2, b.getContext())});
301         auto d = folded_std_dim(folder, view, r);
302         size = folded_affine_min(folder, b.getIndexType(), minMap,
303                                  ValueRange{size, d, offset});
304       }
305 
306       sizes.push_back(size);
307       strides.push_back(folded_std_constant_index(folder, 1));
308     }
309 
310     res.push_back(b.create<SubViewOp>(loc, view, offsets, sizes, strides));
311   }
312 
313   // Traverse the mins/maxes and erase those that don't have uses left.
314   // This is a special type of folding that we only apply when `folder` is
315   // defined.
316   if (folder)
317     for (auto v : llvm::concat<Value>(lbs, subViewSizes))
318       if (v.use_empty())
319         v.getDefiningOp()->erase();
320 
321   return res;
322 }
323 
324 template <typename LoopTy>
325 Optional<TiledLinalgOp> static tileLinalgOpImpl(OpBuilder &b, LinalgOp op,
326                                                 ArrayRef<Value> tileSizes,
327                                                 ArrayRef<unsigned> permutation,
328                                                 OperationFolder *folder) {
329   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
330   // 1. Enforce the convention that "tiling by zero" skips tiling a particular
331   // dimension. This convention is significantly simpler to handle instead of
332   // adjusting affine maps to account for missing dimensions.
333   assert(op.getNumParallelLoops() + op.getNumReductionLoops() +
334                  op.getNumWindowLoops() ==
335              tileSizes.size() &&
336          "expected matching number of tile sizes and loops");
337 
338   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
339     // For conv op only support tiling along batch dimension (which is the first
340     // loop).
341     if (convOp.padding() &&
342         !llvm::all_of(tileSizes.drop_front(),
343                       [](Value val) { return isZero(val); }))
344       return llvm::None;
345   }
346 
347   // If permutation is empty, use the identity. Build the permutation map
348   // otherwise.
349   auto invPermutationMap = AffineMap::getMultiDimIdentityMap(
350       tileSizes.size(), ScopedContext::getContext());
351   if (!permutation.empty())
352     invPermutationMap = inversePermutation(
353         AffineMap::getPermutationMap(permutation, ScopedContext::getContext()));
354 
355   OpBuilder::InsertionGuard g(b);
356   b.setInsertionPoint(op);
357   ScopedContext scope(b, op.getLoc());
358   // 2. Build the tiled loop ranges.
359   auto viewSizes = getViewSizes(b, op);
360   // The flattened loopToOperandRangesMaps is expected to be an invertible
361   // permutation map (asserted in the inverse calculation).
362   auto mapsRange = op.indexing_maps().getAsRange<AffineMapAttr>();
363   auto maps =
364       functional::map([](AffineMapAttr a) { return a.getValue(); }, mapsRange);
365   auto viewSizesToLoopsMap = inversePermutation(concatAffineMaps(maps));
366   assert(viewSizesToLoopsMap && "expected invertible map");
367 
368   SmallVector<SubViewOp::Range, 4> loopRanges;
369   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
370   std::tie(loopRanges, loopIndexToRangeIndex) =
371       makeTiledLoopRanges(b, scope.getLocation(), viewSizesToLoopsMap,
372                           viewSizes, tileSizes, folder);
373   if (!permutation.empty())
374     applyPermutationToVector(loopRanges, permutation);
375 
376   // 3. Create the tiled loops.
377   LinalgOp res = op;
378   auto ivs = ValueHandle::makeIndexHandles(loopRanges.size());
379   auto pivs = makeHandlePointers(MutableArrayRef<ValueHandle>(ivs));
380   // Convert SubViewOp::Range to linalg_range.
381   SmallVector<Value, 4> linalgRanges;
382   for (auto &range : loopRanges) {
383     linalgRanges.push_back(
384         linalg_range(range.offset, range.size, range.stride));
385   }
386   GenericLoopNestRangeBuilder<LoopTy>(pivs, linalgRanges)([&] {
387     auto b = ScopedContext::getBuilder();
388     auto loc = ScopedContext::getLocation();
389     SmallVector<Value, 4> ivValues(ivs.begin(), ivs.end());
390 
391     // If we have to apply a permutation to the tiled loop nest, we have to
392     // reorder the induction variables This permutation is the right one
393     // assuming that loopRanges have previously been permuted by
394     // (i,j,k)->(k,i,j) So this permutation should be the inversePermutation of
395     // that one: (d0,d1,d2)->(d2,d0,d1)
396     if (!permutation.empty())
397       ivValues = applyMapToValues(b, loc, invPermutationMap, ivValues, folder);
398 
399     auto views =
400         makeTiledViews(b, loc, op, ivValues, tileSizes, viewSizes, folder);
401     auto operands = getAssumedNonViewOperands(op);
402     views.append(operands.begin(), operands.end());
403     res = op.clone(b, loc, views);
404   });
405 
406   // 4. Transforms index arguments of `linalg.generic` w.r.t. to the tiling.
407   transformIndexedGenericOpIndices(b, res, pivs, loopIndexToRangeIndex);
408 
409   // 5. Gather the newly created loops and return them with the new op.
410   SmallVector<Operation *, 8> loops;
411   loops.reserve(ivs.size());
412   for (auto iv : ivs)
413     loops.push_back(loop::getForInductionVarOwner(iv));
414 
415   return TiledLinalgOp{res, loops};
416 }
417 
418 template <typename LoopTy>
419 static Optional<TiledLinalgOp>
420 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ArrayRef<int64_t> tileSizes,
421                  ArrayRef<unsigned> permutation, OperationFolder *folder) {
422   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
423   if (tileSizes.empty())
424     return llvm::None;
425 
426   // The following uses the convention that "tiling by zero" skips tiling a
427   // particular dimension. This convention is significantly simpler to handle
428   // instead of adjusting affine maps to account for missing dimensions.
429   auto nLoops = op.getNumParallelLoops() + op.getNumReductionLoops() +
430                 op.getNumWindowLoops();
431   tileSizes = tileSizes.take_front(nLoops);
432   // If only 0 tilings are left, then return.
433   if (llvm::all_of(tileSizes, [](int64_t v) { return v == 0; }))
434     return llvm::None;
435 
436   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
437     // For conv op only support tiling along batch dimension (which is the first
438     // loop).
439     if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(),
440                                           [](int64_t val) { return val == 0; }))
441       return llvm::None;
442   }
443 
444   // Create a builder for tile size constants.
445   OpBuilder::InsertionGuard g(b);
446   b.setInsertionPoint(op);
447   ScopedContext scope(b, op.getLoc());
448 
449   // Materialize concrete tile size values to pass the generic tiling function.
450   SmallVector<Value, 8> tileSizeValues;
451   tileSizeValues.reserve(tileSizes.size());
452   for (auto ts : tileSizes)
453     tileSizeValues.push_back(folded_std_constant_index(folder, ts));
454   // Pad tile sizes with zero values to enforce our convention.
455   if (tileSizeValues.size() < nLoops) {
456     for (unsigned i = tileSizeValues.size(); i < nLoops; ++i)
457       tileSizeValues.push_back(folded_std_constant_index(folder, 0));
458   }
459 
460   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeValues, permutation, folder);
461 }
462 
463 Optional<TiledLinalgOp>
464 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op, ArrayRef<Value> tileSizes,
465                            ArrayRef<unsigned> permutation,
466                            OperationFolder *folder) {
467   return tileLinalgOpImpl<loop::ForOp>(b, op, tileSizes, permutation, folder);
468 }
469 
470 Optional<TiledLinalgOp> mlir::linalg::tileLinalgOpToParallelLoops(
471     OpBuilder &b, LinalgOp op, ArrayRef<Value> tileSizes,
472     ArrayRef<unsigned> permutation, OperationFolder *folder) {
473   return tileLinalgOpImpl<loop::ParallelOp>(b, op, tileSizes, permutation,
474                                             folder);
475 }
476 
477 Optional<TiledLinalgOp> mlir::linalg::tileLinalgOp(
478     OpBuilder &b, LinalgOp op, ArrayRef<int64_t> tileSizes,
479     ArrayRef<unsigned> permutation, OperationFolder *folder) {
480   return tileLinalgOpImpl<loop::ForOp>(b, op, tileSizes, permutation, folder);
481 }
482 
483 Optional<TiledLinalgOp> mlir::linalg::tileLinalgOpToParallelLoops(
484     OpBuilder &b, LinalgOp op, ArrayRef<int64_t> tileSizes,
485     ArrayRef<unsigned> permutation, OperationFolder *folder) {
486   return tileLinalgOpImpl<loop::ParallelOp>(b, op, tileSizes, permutation,
487                                             folder);
488 }
489 
490 template <typename LoopTy>
491 static void tileLinalgOps(FuncOp f, ArrayRef<int64_t> tileSizes) {
492   OpBuilder b(f);
493   OperationFolder folder(f.getContext());
494   f.walk([tileSizes, &b, &folder](LinalgOp op) {
495     if (!op.hasBufferSemantics())
496       return;
497     auto opLoopsPair =
498         tileLinalgOpImpl<LoopTy>(b, op, tileSizes, /*permutation=*/{}, &folder);
499     // If tiling occurred successfully, erase old op.
500     if (opLoopsPair)
501       op.erase();
502   });
503   f.walk([](LinalgOp op) {
504     if (isOpTriviallyDead(op))
505       op.erase();
506   });
507 }
508 
509 namespace {
510 
511 template <typename LoopTy>
512 struct LinalgTilingPass : public FunctionPass<LinalgTilingPass<LoopTy>> {
513   LinalgTilingPass() = default;
514   LinalgTilingPass(const LinalgTilingPass &) {}
515   LinalgTilingPass(ArrayRef<int64_t> sizes) {
516     this->tileSizes->assign(sizes.begin(), sizes.end());
517   }
518 
519   void runOnFunction() override {
520     tileLinalgOps<LoopTy>(this->getFunction(), tileSizes);
521   }
522 
523   Pass::ListOption<int64_t> tileSizes{
524       *this, "linalg-tile-sizes",
525       llvm::cl::desc("Tile sizes by which to tile linalg operations"),
526       llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated};
527 };
528 
529 } // namespace
530 
531 std::unique_ptr<OpPassBase<FuncOp>>
532 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
533   return std::make_unique<LinalgTilingPass<loop::ForOp>>(tileSizes);
534 }
535 
536 std::unique_ptr<OpPassBase<FuncOp>>
537 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
538   return std::make_unique<LinalgTilingPass<loop::ParallelOp>>(tileSizes);
539 }
540 
541 static PassRegistration<LinalgTilingPass<loop::ForOp>>
542     tiling_pass("linalg-tile", "Tile operations in the linalg dialect");
543 
544 static PassRegistration<LinalgTilingPass<loop::ParallelOp>>
545     tiling_to_parallel_loops(
546         "linalg-tile-to-parallel-loops",
547         "Tile operations in the linalg dialect to parallel loops");
548