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