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 static void transformIndexedGenericOpIndices( 174 OpBuilder &b, LinalgOp op, ArrayRef<ValueHandle *> pivs, 175 const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) { 176 assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics"); 177 auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op.getOperation()); 178 if (!indexedGenericOp) 179 return; 180 181 // `linalg.indexed_generic` comes in two flavours. One has a region with a 182 // single block that defines the loop body. The other has a `fun` attribute 183 // that refers to an existing function symbol. The `fun` function call will be 184 // inserted in the loop body in that case. 185 // 186 // TODO(pifon): Add support for `linalg.indexed_generic` with `fun` attribute. 187 auto ®ion = indexedGenericOp.region(); 188 if (region.empty()) { 189 indexedGenericOp.emitOpError("expected a region"); 190 return; 191 } 192 auto &block = region.getBlocks().front(); 193 194 OpBuilder::InsertionGuard g(b); 195 b.setInsertionPointToStart(&block); 196 for (unsigned i = 0; i < indexedGenericOp.getNumLoops(); ++i) { 197 auto rangeIndex = loopIndexToRangeIndex.find(i); 198 if (rangeIndex == loopIndexToRangeIndex.end()) 199 continue; 200 Value oldIndex = block.getArgument(i); 201 // Offset the index argument `i` by the value of the corresponding induction 202 // variable and replace all uses of the previous value. 203 Value newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex, 204 pivs[rangeIndex->second]->getValue()); 205 for (auto &use : oldIndex.getUses()) { 206 if (use.getOwner() == newIndex.getDefiningOp()) 207 continue; 208 use.set(newIndex); 209 } 210 } 211 } 212 213 static bool isTiled(AffineExpr expr, ArrayRef<Value> tileSizes) { 214 if (!expr) 215 return false; 216 TileCheck t(tileSizes); 217 t.visit(expr); 218 return t.isTiled; 219 } 220 221 // Checks whether the view with index `viewIndex` within `linalgOp` varies with 222 // respect to a non-zero `tileSize`. 223 static bool isTiled(AffineMap map, ArrayRef<Value> tileSizes) { 224 if (!map) 225 return false; 226 for (unsigned r = 0; r < map.getNumResults(); ++r) 227 if (isTiled(map.getResult(r), tileSizes)) 228 return true; 229 return false; 230 } 231 232 static SmallVector<Value, 4> 233 makeTiledViews(OpBuilder &b, Location loc, LinalgOp linalgOp, 234 ArrayRef<Value> ivs, ArrayRef<Value> tileSizes, 235 ArrayRef<Value> viewSizes, OperationFolder *folder) { 236 assert(linalgOp.hasBufferSemantics() && 237 "expected linalg op with buffer semantics"); 238 assert(ivs.size() == static_cast<size_t>(llvm::count_if( 239 llvm::make_range(tileSizes.begin(), tileSizes.end()), 240 [](Value v) { return !isZero(v); })) && 241 "expected as many ivs as non-zero sizes"); 242 243 using edsc::intrinsics::select; 244 using edsc::op::operator+; 245 using edsc::op::operator<; 246 247 // Construct (potentially temporary) mins and maxes on which to apply maps 248 // that define tile subviews. 249 SmallVector<Value, 8> lbs, subViewSizes; 250 for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) { 251 bool isTiled = !isZero(tileSizes[idx]); 252 lbs.push_back(isTiled ? ivs[idxIvs++] : (Value)constant_index(folder, 0)); 253 subViewSizes.push_back(isTiled ? tileSizes[idx] : viewSizes[idx]); 254 } 255 256 auto *op = linalgOp.getOperation(); 257 258 SmallVector<Value, 4> res; 259 res.reserve(op->getNumOperands()); 260 auto viewIteratorBegin = linalgOp.getInputsAndOutputBuffers().begin(); 261 for (unsigned viewIndex = 0; viewIndex < linalgOp.getNumInputsAndOutputs(); 262 ++viewIndex) { 263 Value view = *(viewIteratorBegin + viewIndex); 264 unsigned rank = view.getType().cast<MemRefType>().getRank(); 265 auto map = loopToOperandRangesMaps(linalgOp)[viewIndex]; 266 // If the view is not tiled, we can use it as is. 267 if (!isTiled(map, tileSizes)) { 268 res.push_back(view); 269 continue; 270 } 271 272 // Construct a new subview for the tile. 273 SmallVector<Value, 4> offsets, sizes, strides; 274 offsets.reserve(rank); 275 sizes.reserve(rank); 276 strides.reserve(rank); 277 for (unsigned r = 0; r < rank; ++r) { 278 if (!isTiled(map.getSubMap({r}), tileSizes)) { 279 offsets.push_back(constant_index(folder, 0)); 280 sizes.push_back(dim(view, r)); 281 strides.push_back(constant_index(folder, 1)); 282 continue; 283 } 284 285 // Tiling creates a new slice at the proper index, the slice step is 1 286 // (i.e. the slice view does not subsample, stepping occurs in the loop). 287 auto m = map.getSubMap({r}); 288 auto offset = applyMapToValues(b, loc, m, lbs, folder).front(); 289 offsets.push_back(offset); 290 auto size = applyMapToValues(b, loc, m, subViewSizes, folder).front(); 291 sizes.push_back(size); 292 strides.push_back(constant_index(folder, 1)); 293 } 294 // TODO(b/144419024) Atm std.subview is not guaranteed in-bounds. Depending 295 // on the semantics we attach to it, we may need to use min(size, dim) here 296 // and canonicalize later. 297 res.push_back(b.create<SubViewOp>(loc, view, offsets, sizes, strides)); 298 } 299 300 // Traverse the mins/maxes and erase those that don't have uses left. 301 // This is a special type of folding that we only apply when `folder` is 302 // defined. 303 if (folder) 304 for (auto v : llvm::concat<Value>(lbs, subViewSizes)) 305 if (v.use_empty()) 306 v.getDefiningOp()->erase(); 307 308 return res; 309 } 310 311 Optional<TiledLinalgOp> 312 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op, ArrayRef<Value> tileSizes, 313 ArrayRef<unsigned> permutation, 314 OperationFolder *folder) { 315 assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics"); 316 // 1. Enforce the convention that "tiling by zero" skips tiling a particular 317 // dimension. This convention is significantly simpler to handle instead of 318 // adjusting affine maps to account for missing dimensions. 319 assert(op.getNumParallelLoops() + op.getNumReductionLoops() + 320 op.getNumWindowLoops() == 321 tileSizes.size() && 322 "expected matching number of tile sizes and loops"); 323 324 // If permutation is empty, use the identity. Build the permutation map 325 // otherwise. 326 auto invPermutationMap = AffineMap::getMultiDimIdentityMap( 327 tileSizes.size(), ScopedContext::getContext()); 328 if (!permutation.empty()) 329 invPermutationMap = inversePermutation( 330 AffineMap::getPermutationMap(permutation, ScopedContext::getContext())); 331 332 OpBuilder::InsertionGuard g(b); 333 b.setInsertionPoint(op); 334 ScopedContext scope(b, op.getLoc()); 335 // 2. Build the tiled loop ranges. 336 auto viewSizes = getViewSizes(op); 337 // The flattened loopToOperandRangesMaps is expected to be an invertible 338 // permutation map (asserted in the inverse calculation). 339 auto viewSizesToLoopsMap = 340 inversePermutation(concatAffineMaps(loopToOperandRangesMaps(op))); 341 assert(viewSizesToLoopsMap && "expected invertible map"); 342 343 SmallVector<SubViewOp::Range, 4> loopRanges; 344 LoopIndexToRangeIndexMap loopIndexToRangeIndex; 345 std::tie(loopRanges, loopIndexToRangeIndex) = 346 makeTiledLoopRanges(b, scope.getLocation(), viewSizesToLoopsMap, 347 viewSizes, tileSizes, folder); 348 if (!permutation.empty()) 349 applyPermutationToVector(loopRanges, permutation); 350 351 // 3. Create the tiled loops. 352 LinalgOp res = op; 353 SmallVector<IndexHandle, 4> ivs(loopRanges.size()); 354 auto pivs = makeHandlePointers(MutableArrayRef<IndexHandle>(ivs)); 355 LoopNestRangeBuilder(pivs, loopRanges)([&] { 356 auto b = ScopedContext::getBuilder(); 357 auto loc = ScopedContext::getLocation(); 358 SmallVector<Value, 4> ivValues(ivs.begin(), ivs.end()); 359 360 // If we have to apply a permutation to the tiled loop nest, we have to 361 // reorder the induction variables This permutation is the right one 362 // assuming that loopRanges have previously been permuted by 363 // (i,j,k)->(k,i,j) So this permutation should be the inversePermutation of 364 // that one: (d0,d1,d2)->(d2,d0,d1) 365 if (!permutation.empty()) 366 ivValues = applyMapToValues(b, loc, invPermutationMap, ivValues, folder); 367 368 auto views = 369 makeTiledViews(b, loc, op, ivValues, tileSizes, viewSizes, folder); 370 auto operands = getAssumedNonViewOperands(op); 371 views.append(operands.begin(), operands.end()); 372 res = op.clone(b, loc, views); 373 }); 374 375 // 4. Transforms index arguments of `linalg.generic` w.r.t. to the tiling. 376 transformIndexedGenericOpIndices(b, res, pivs, loopIndexToRangeIndex); 377 378 // 5. Gather the newly created loops and return them with the new op. 379 SmallVector<ForOp, 8> loops; 380 loops.reserve(ivs.size()); 381 for (auto iv : ivs) 382 loops.push_back(loop::getForInductionVarOwner(iv)); 383 384 return TiledLinalgOp{res, loops}; 385 } 386 387 Optional<TiledLinalgOp> mlir::linalg::tileLinalgOp( 388 OpBuilder &b, LinalgOp op, ArrayRef<int64_t> tileSizes, 389 ArrayRef<unsigned> permutation, OperationFolder *folder) { 390 assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics"); 391 if (tileSizes.empty()) 392 return llvm::None; 393 394 // The following uses the convention that "tiling by zero" skips tiling a 395 // particular dimension. This convention is significantly simpler to handle 396 // instead of adjusting affine maps to account for missing dimensions. 397 auto nLoops = op.getNumParallelLoops() + op.getNumReductionLoops() + 398 op.getNumWindowLoops(); 399 tileSizes = tileSizes.take_front(nLoops); 400 // If only 0 tilings are left, then return. 401 if (llvm::all_of(tileSizes, [](int64_t v) { return v == 0; })) 402 return llvm::None; 403 404 // Create a builder for tile size constants. 405 OpBuilder::InsertionGuard g(b); 406 b.setInsertionPoint(op); 407 ScopedContext scope(b, op.getLoc()); 408 409 // Materialize concrete tile size values to pass the generic tiling function. 410 SmallVector<Value, 8> tileSizeValues; 411 tileSizeValues.reserve(tileSizes.size()); 412 for (auto ts : tileSizes) 413 tileSizeValues.push_back(constant_index(folder, ts)); 414 // Pad tile sizes with zero values to enforce our convention. 415 if (tileSizeValues.size() < nLoops) { 416 for (unsigned i = tileSizeValues.size(); i < nLoops; ++i) 417 tileSizeValues.push_back(constant_index(folder, 0)); 418 } 419 420 return tileLinalgOp(b, op, tileSizeValues, permutation, folder); 421 } 422 423 static void tileLinalgOps(FuncOp f, ArrayRef<int64_t> tileSizes) { 424 OpBuilder b(f); 425 OperationFolder folder(f.getContext()); 426 f.walk([tileSizes, &b, &folder](LinalgOp op) { 427 if (!op.hasBufferSemantics()) 428 return; 429 auto opLoopsPair = 430 tileLinalgOp(b, op, tileSizes, /*permutation=*/{}, &folder); 431 // If tiling occurred successfully, erase old op. 432 if (opLoopsPair) 433 op.erase(); 434 }); 435 f.walk([](LinalgOp op) { 436 if (!op.getOperation()->hasNoSideEffect()) 437 return; 438 if (op.getOperation()->use_empty()) 439 op.erase(); 440 }); 441 } 442 443 namespace { 444 struct LinalgTilingPass : public FunctionPass<LinalgTilingPass> { 445 LinalgTilingPass() = default; 446 LinalgTilingPass(ArrayRef<int64_t> sizes); 447 448 void runOnFunction() override { tileLinalgOps(getFunction(), tileSizes); } 449 450 SmallVector<int64_t, 8> tileSizes; 451 }; 452 } // namespace 453 454 LinalgTilingPass::LinalgTilingPass(ArrayRef<int64_t> sizes) { 455 this->tileSizes.assign(sizes.begin(), sizes.end()); 456 } 457 458 std::unique_ptr<OpPassBase<FuncOp>> 459 mlir::linalg::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) { 460 return std::make_unique<LinalgTilingPass>(tileSizes); 461 } 462 463 static PassRegistration<LinalgTilingPass> 464 pass("linalg-tile", "Tile operations in the linalg dialect", [] { 465 auto pass = std::make_unique<LinalgTilingPass>(); 466 pass->tileSizes.assign(clTileSizes.begin(), clTileSizes.end()); 467 return pass; 468 }); 469