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