1 //===- LinalgTransforms.cpp - Linalg transformations as patterns ----------===// 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 logic and helpers to expose Linalg transforms as rewrite 10 // patterns. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 15 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 17 #include "mlir/Dialect/Linalg/Utils/Utils.h" 18 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 19 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 20 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 21 #include "mlir/Dialect/Vector/VectorOps.h" 22 #include "mlir/IR/AffineExpr.h" 23 #include "mlir/IR/Matchers.h" 24 #include "mlir/Pass/Pass.h" 25 #include "mlir/Support/LLVM.h" 26 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include <type_traits> 30 31 #define DEBUG_TYPE "linalg-transforms" 32 33 using namespace mlir; 34 using namespace mlir::edsc; 35 using namespace mlir::edsc::intrinsics; 36 using namespace mlir::linalg; 37 38 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ") 39 40 //===----------------------------------------------------------------------===// 41 // Transformations exposed as rewrite patterns. 42 //===----------------------------------------------------------------------===// 43 // Marker used as attribute name in generated Linalg rewriting transformations. 44 const StringLiteral mlir::linalg::LinalgTransforms::kLinalgTransformMarker = 45 "__internal_linalg_transform__"; 46 47 mlir::linalg::LinalgMarker::LinalgMarker(ArrayRef<Identifier> matchDisjunction, 48 Optional<Identifier> replacement) 49 : matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()), 50 replacement(replacement) {} 51 52 LogicalResult 53 mlir::linalg::LinalgMarker::checkAndNotify(PatternRewriter &rewriter, 54 Operation *op) const { 55 auto attr = op->template getAttrOfType<StringAttr>( 56 LinalgTransforms::kLinalgTransformMarker); 57 58 if (!attr) { 59 // 1. Has no marker case and matchDisjunction is empty. 60 if (matchDisjunction.empty()) 61 return success(); 62 63 // 2. Has no marker but was expecting a marker. 64 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) { 65 diag << " does not have any marker from list: "; 66 interleaveComma(matchDisjunction, diag); 67 }); 68 } 69 70 // 4. Match explicit marker. 71 for (auto marker : matchDisjunction) 72 if (attr.getValue() == marker) 73 return success(); 74 75 // 5. Fail to match. 76 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) { 77 diag << " does not have any marker from list: "; 78 interleaveComma(matchDisjunction, diag); 79 }); 80 } 81 82 void mlir::linalg::LinalgMarker::replaceLinalgMarker(PatternRewriter &rewriter, 83 Operation *op) const { 84 if (replacement.hasValue()) 85 op->setAttr(LinalgTransforms::kLinalgTransformMarker, 86 rewriter.getStringAttr(replacement.getValue())); 87 else 88 op->removeAttr(Identifier::get(LinalgTransforms::kLinalgTransformMarker, 89 rewriter.getContext())); 90 } 91 92 LinalgTilingOptions & 93 mlir::linalg::LinalgTilingOptions::setTileSizes(ArrayRef<int64_t> ts) { 94 SmallVector<int64_t, 4> tileSizes(ts.begin(), ts.end()); 95 tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) { 96 OpBuilder::InsertionGuard guard(b); 97 b.setInsertionPointToStart( 98 &op->getParentOfType<FuncOp>().getBody().front()); 99 return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) { 100 Value v = b.create<ConstantIndexOp>(op->getLoc(), s); 101 return v; 102 })); 103 }; 104 return *this; 105 } 106 107 /// Linalg base tiling pattern. 108 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern( 109 StringRef opName, MLIRContext *context, LinalgTilingOptions options, 110 LinalgMarker marker, PatternBenefit benefit) 111 : RewritePattern(opName, {}, benefit, context), marker(marker), 112 options(options) {} 113 114 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern( 115 LinalgTilingOptions options, LinalgMarker marker, PatternBenefit benefit) 116 : RewritePattern(benefit, MatchAnyOpTypeTag()), marker(marker), 117 options(options) {} 118 119 LogicalResult mlir::linalg::LinalgBaseTilingPattern::matchAndRewriteBase( 120 Operation *op, PatternRewriter &rewriter, 121 SmallVectorImpl<Value> &tensorResults) const { 122 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 123 if (!linalgOp) 124 return failure(); 125 if (failed(marker.checkAndNotify(rewriter, linalgOp))) 126 return failure(); 127 128 Optional<TiledLinalgOp> res = tileLinalgOp(rewriter, linalgOp, options); 129 130 if (!res) 131 return failure(); 132 133 // Return relevant information to derived pattern. 134 tensorResults = res->tensorResults; 135 136 // New marker if specified. 137 marker.replaceLinalgMarker(rewriter, res->op.getOperation()); 138 return success(); 139 } 140 141 mlir::linalg::LinalgBaseTileAndFusePattern::LinalgBaseTileAndFusePattern( 142 StringRef opName, MLIRContext *context, 143 const LinalgDependenceGraph &dependenceGraph, 144 LinalgTilingOptions tilingOptions, LinalgFusionOptions fusionOptions, 145 LinalgMarker marker, LinalgMarker fusedOpMarker, 146 LinalgMarker originalOpMarker, PatternBenefit benefit) 147 : RewritePattern(opName, {}, benefit, context), 148 dependenceGraph(dependenceGraph), tilingOptions(tilingOptions), 149 fusionOptions(fusionOptions), marker(marker), 150 fusedOpMarker(fusedOpMarker), originalOpMarker(originalOpMarker) {} 151 152 LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite( 153 Operation *op, PatternRewriter &rewriter) const { 154 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 155 if (!linalgOp) 156 return failure(); 157 if (failed(marker.checkAndNotify(rewriter, linalgOp))) 158 return failure(); 159 if (!linalgOp.hasBufferSemantics()) 160 return failure(); 161 162 DenseSet<Operation *> producers; 163 producers.insert(linalgOp); 164 for (auto dependence : dependenceGraph.getDependentOperations(linalgOp)) { 165 if (!fusionOptions.indicesToFuse.count( 166 dependence.indexingOpView->getOperandNumber())) 167 continue; 168 if (isa<LinalgOp>(dependence.dependentOpView->getOwner())) 169 producers.insert(dependence.dependentOpView->getOwner()); 170 } 171 172 SmallVector<LinalgOp, 1> fusionOps; 173 for (auto it = op->getBlock()->begin(), ie = Block::iterator(op); it != ie; 174 ++it) { 175 auto producerLinalgOp = dyn_cast<LinalgOp>(&(*it)); 176 if (producerLinalgOp && producers.count(producerLinalgOp)) 177 fusionOps.push_back(producerLinalgOp); 178 } 179 fusionOps.push_back(linalgOp); 180 181 SmallVector<Value, 4> tileSizes = 182 tilingOptions.tileSizeComputationFunction(rewriter, op); 183 LinalgTilingOptions instanceTilingOptions = tilingOptions; 184 instanceTilingOptions.setTileSizes(tileSizes); 185 Optional<TiledAndFusedLinalgOps> tiledAndFusedOps = tileAndFuseLinalgOps( 186 rewriter, fusionOps, dependenceGraph, instanceTilingOptions); 187 if (!tiledAndFusedOps) 188 return failure(); 189 190 // Tile the unfused loops; 191 SmallVector<Value, 4> unfusedLoopTileSizes; 192 Value zero = rewriter.create<ConstantIndexOp>(op->getLoc(), 0); 193 for (auto tileSize : enumerate(tileSizes)) { 194 if (tiledAndFusedOps->fusedLoopDims.count(tileSize.index())) 195 unfusedLoopTileSizes.push_back(zero); 196 else 197 unfusedLoopTileSizes.push_back(tileSize.value()); 198 } 199 // Tile the loop only if there is a non-zero tile size. 200 if (unfusedLoopTileSizes.size() > linalgOp.getNumLoops()) 201 unfusedLoopTileSizes.resize(linalgOp.getNumLoops()); 202 if (llvm::any_of(unfusedLoopTileSizes, [](Value val) { 203 if (auto cst = val.getDefiningOp<ConstantIndexOp>()) 204 return cst.getValue() != 0; 205 return true; 206 })) { 207 LinalgTilingOptions unfusedTilingOptions = tilingOptions; 208 unfusedTilingOptions.setTileSizes(unfusedLoopTileSizes); 209 Optional<TiledLinalgOp> unfusedTiledOp = 210 tileLinalgOp(rewriter, tiledAndFusedOps->op, unfusedTilingOptions); 211 if (!unfusedTiledOp) 212 return failure(); 213 rewriter.eraseOp(tiledAndFusedOps->op); 214 tiledAndFusedOps->op = unfusedTiledOp->op; 215 } 216 217 marker.replaceLinalgMarker(rewriter, tiledAndFusedOps->op.getOperation()); 218 for (auto fusedOp : tiledAndFusedOps->fusedProducers) { 219 fusedOpMarker.replaceLinalgMarker(rewriter, fusedOp.getOperation()); 220 } 221 for (auto origProducerOp : ArrayRef<LinalgOp>(fusionOps).drop_back()) { 222 originalOpMarker.replaceLinalgMarker(rewriter, 223 origProducerOp.getOperation()); 224 } 225 rewriter.updateRootInPlace( 226 op, [&]() { originalOpMarker.replaceLinalgMarker(rewriter, op); }); 227 return success(); 228 } 229 230 /// Linalg base interchange pattern. 231 mlir::linalg::LinalgBaseInterchangePattern::LinalgBaseInterchangePattern( 232 StringRef opName, MLIRContext *context, 233 ArrayRef<unsigned> interchangeVector, LinalgMarker marker, 234 PatternBenefit benefit) 235 : RewritePattern(opName, {}, benefit, context), marker(marker), 236 interchangeVector(interchangeVector.begin(), interchangeVector.end()) {} 237 238 LogicalResult mlir::linalg::LinalgBaseInterchangePattern::matchAndRewrite( 239 Operation *op, PatternRewriter &rewriter) const { 240 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 241 if (!linalgOp) 242 return failure(); 243 if (failed(marker.checkAndNotify(rewriter, linalgOp))) 244 return failure(); 245 if (failed(interchangeGenericLinalgOpPrecondition(op, interchangeVector))) 246 return failure(); 247 248 // TODO: figure out how this interplays with named ops. In particular this 249 // should break the named op property. 250 rewriter.updateRootInPlace(op, [&]() { 251 interchange(linalgOp, interchangeVector); 252 // New marker if specified. 253 marker.replaceLinalgMarker(rewriter, op); 254 }); 255 return success(); 256 } 257 258 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern( 259 StringRef opName, MLIRContext *context, LinalgPromotionOptions options, 260 LinalgMarker marker, PatternBenefit benefit) 261 : RewritePattern(opName, {}, benefit, context), marker(marker), 262 options(options) {} 263 264 LogicalResult mlir::linalg::LinalgBasePromotionPattern::matchAndRewrite( 265 Operation *op, PatternRewriter &rewriter) const { 266 if (failed(marker.checkAndNotify(rewriter, op))) 267 return failure(); 268 if (failed(promoteSubviewsPrecondition(op, options))) 269 return failure(); 270 271 // TODO: We cannot use root update here. This pattern is creating other ops, 272 // so if the promotion fails, those need to be cleaned up, which doesnt seem 273 // to be happening here. So to fail properly, we should be cloning the op and 274 // deleting the previous op. This needs more investigation. 275 rewriter.startRootUpdate(op); 276 Optional<LinalgOp> promotedOp = promoteSubViews(rewriter, op, options); 277 if (!promotedOp) { 278 rewriter.cancelRootUpdate(op); 279 return op->emitError("subview promotion failed"); 280 } 281 rewriter.finalizeRootUpdate(op); 282 marker.replaceLinalgMarker(rewriter, op); 283 return success(); 284 } 285 286 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern( 287 StringRef opName, MLIRContext *context, LinalgMarker marker, 288 PatternBenefit benefit) 289 : RewritePattern(opName, {}, benefit, context), marker(marker) {} 290 291 LogicalResult mlir::linalg::LinalgBaseVectorizationPattern::matchAndRewrite( 292 Operation *op, PatternRewriter &rewriter) const { 293 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 294 if (!linalgOp) 295 return failure(); 296 if (failed(marker.checkAndNotify(rewriter, linalgOp))) 297 return failure(); 298 if (failed(vectorizeLinalgOpPrecondition(op))) 299 return failure(); 300 vectorizeLinalgOp(rewriter, op); 301 rewriter.eraseOp(op); 302 return success(); 303 } 304 305 LogicalResult mlir::linalg::applyStagedPatterns( 306 Operation *op, ArrayRef<FrozenRewritePatternList> stage1Patterns, 307 const FrozenRewritePatternList &stage2Patterns, 308 function_ref<LogicalResult(Operation *)> stage3Lambda) { 309 unsigned iteration = 0; 310 (void)iteration; 311 for (const auto &patterns : stage1Patterns) { 312 LLVM_DEBUG(DBGS() << "Before 1st stage, iter: " << ++iteration << "\n" 313 << *op); 314 if (failed(applyPatternsAndFoldGreedily(op, patterns))) { 315 LLVM_DEBUG(DBGS() << "Underlying first stage rewrite did not converge"); 316 return failure(); 317 } 318 LLVM_DEBUG(DBGS() << "After 1st stage, iter: " << ++iteration << "\n" 319 << *op); 320 if (failed(applyPatternsAndFoldGreedily(op, stage2Patterns))) { 321 LLVM_DEBUG(DBGS() << "Underlying 2nd stage rewrite did not converge"); 322 return failure(); 323 } 324 LLVM_DEBUG(DBGS() << "After 2nd stage, iter : " << iteration << "\n" 325 << *op); 326 if (stage3Lambda) { 327 if (failed(stage3Lambda(op))) 328 return failure(); 329 LLVM_DEBUG(DBGS() << "After 3rd stage, iter : " << iteration << "\n" 330 << *op); 331 } 332 } 333 return success(); 334 } 335 336 /// Traverse `e` and return an AffineExpr where all occurrences of `dim` have 337 /// been replaced by either: 338 /// - `min` if `positivePath` is true when we reach an occurrence of `dim` 339 /// - `max` if `positivePath` is true when we reach an occurrence of `dim` 340 /// `positivePath` is negated each time we hit a multiplicative or divisive 341 /// binary op with a constant negative coefficient. 342 static AffineExpr substWithMin(AffineExpr e, AffineExpr dim, AffineExpr min, 343 AffineExpr max, bool positivePath = true) { 344 if (e == dim) 345 return positivePath ? min : max; 346 if (auto bin = e.dyn_cast<AffineBinaryOpExpr>()) { 347 AffineExpr lhs = bin.getLHS(); 348 AffineExpr rhs = bin.getRHS(); 349 if (bin.getKind() == mlir::AffineExprKind::Add) 350 return substWithMin(lhs, dim, min, max, positivePath) + 351 substWithMin(rhs, dim, min, max, positivePath); 352 353 auto c1 = bin.getLHS().dyn_cast<AffineConstantExpr>(); 354 auto c2 = bin.getRHS().dyn_cast<AffineConstantExpr>(); 355 if (c1 && c1.getValue() < 0) 356 return getAffineBinaryOpExpr( 357 bin.getKind(), c1, substWithMin(rhs, dim, min, max, !positivePath)); 358 if (c2 && c2.getValue() < 0) 359 return getAffineBinaryOpExpr( 360 bin.getKind(), substWithMin(lhs, dim, min, max, !positivePath), c2); 361 return getAffineBinaryOpExpr( 362 bin.getKind(), substWithMin(lhs, dim, min, max, positivePath), 363 substWithMin(rhs, dim, min, max, positivePath)); 364 } 365 return e; 366 } 367 368 /// Given the `lbVal`, `ubVal` and `stepVal` of a loop, append `lbVal` and 369 /// `ubVal` to `dims` and `stepVal` to `symbols`. 370 /// Create new AffineDimExpr (`%lb` and `%ub`) and AffineSymbolExpr (`%step`) 371 /// with positions matching the newly appended values. Substitute occurrences of 372 /// `dimExpr` by either the min expression (i.e. `%lb`) or the max expression 373 /// (i.e. `%lb + %step * floordiv(%ub -1 - %lb, %step)`), depending on whether 374 /// the induction variable is used with a positive or negative coefficient. 375 static AffineExpr substituteLoopInExpr(AffineExpr expr, AffineExpr dimExpr, 376 Value lbVal, Value ubVal, Value stepVal, 377 SmallVectorImpl<Value> &dims, 378 SmallVectorImpl<Value> &symbols) { 379 MLIRContext *ctx = lbVal.getContext(); 380 AffineExpr lb = getAffineDimExpr(dims.size(), ctx); 381 dims.push_back(lbVal); 382 AffineExpr ub = getAffineDimExpr(dims.size(), ctx); 383 dims.push_back(ubVal); 384 AffineExpr step = getAffineSymbolExpr(symbols.size(), ctx); 385 symbols.push_back(stepVal); 386 LLVM_DEBUG(DBGS() << "Before: " << expr << "\n"); 387 AffineExpr ee = substWithMin(expr, dimExpr, lb, 388 lb + step * ((ub - 1) - lb).floorDiv(step)); 389 LLVM_DEBUG(DBGS() << "After: " << expr << "\n"); 390 return ee; 391 } 392 393 /// Traverse the `dims` and substitute known min or max expressions in place of 394 /// induction variables in `exprs`. 395 static AffineMap substitute(AffineMap map, SmallVectorImpl<Value> &dims, 396 SmallVectorImpl<Value> &symbols) { 397 auto exprs = llvm::to_vector<4>(map.getResults()); 398 for (AffineExpr &expr : exprs) { 399 bool substituted = true; 400 while (substituted) { 401 substituted = false; 402 for (unsigned dimIdx = 0; dimIdx < dims.size(); ++dimIdx) { 403 Value dim = dims[dimIdx]; 404 AffineExpr dimExpr = getAffineDimExpr(dimIdx, expr.getContext()); 405 LLVM_DEBUG(DBGS() << "Subst: " << dim << " @ " << dimExpr << "\n"); 406 AffineExpr substitutedExpr; 407 if (auto forOp = scf::getForInductionVarOwner(dim)) 408 substitutedExpr = substituteLoopInExpr( 409 expr, dimExpr, forOp.lowerBound(), forOp.upperBound(), 410 forOp.step(), dims, symbols); 411 412 if (auto parallelForOp = scf::getParallelForInductionVarOwner(dim)) 413 for (unsigned idx = 0, e = parallelForOp.getNumLoops(); idx < e; 414 ++idx) 415 substitutedExpr = substituteLoopInExpr( 416 expr, dimExpr, parallelForOp.lowerBound()[idx], 417 parallelForOp.upperBound()[idx], parallelForOp.step()[idx], 418 dims, symbols); 419 420 if (!substitutedExpr) 421 continue; 422 423 substituted = (substitutedExpr != expr); 424 expr = substitutedExpr; 425 } 426 } 427 428 // Cleanup and simplify the results. 429 // This needs to happen outside of the loop iterating on dims.size() since 430 // it modifies dims. 431 SmallVector<Value, 4> operands(dims.begin(), dims.end()); 432 operands.append(symbols.begin(), symbols.end()); 433 auto map = AffineMap::get(dims.size(), symbols.size(), exprs, 434 exprs.front().getContext()); 435 436 LLVM_DEBUG(DBGS() << "Map to simplify: " << map << "\n"); 437 438 // Pull in affine.apply operations and compose them fully into the 439 // result. 440 fullyComposeAffineMapAndOperands(&map, &operands); 441 canonicalizeMapAndOperands(&map, &operands); 442 map = simplifyAffineMap(map); 443 // Assign the results. 444 exprs.assign(map.getResults().begin(), map.getResults().end()); 445 dims.assign(operands.begin(), operands.begin() + map.getNumDims()); 446 symbols.assign(operands.begin() + map.getNumDims(), operands.end()); 447 448 LLVM_DEBUG(DBGS() << "Map simplified: " << map << "\n"); 449 } 450 451 assert(!exprs.empty() && "Unexpected empty exprs"); 452 return AffineMap::get(dims.size(), symbols.size(), exprs, map.getContext()); 453 } 454 455 LogicalResult AffineMinSCFCanonicalizationPattern::matchAndRewrite( 456 AffineMinOp minOp, PatternRewriter &rewriter) const { 457 LLVM_DEBUG(DBGS() << "Canonicalize AffineMinSCF: " << *minOp.getOperation() 458 << "\n"); 459 460 SmallVector<Value, 4> dims(minOp.getDimOperands()), 461 symbols(minOp.getSymbolOperands()); 462 AffineMap map = substitute(minOp.getAffineMap(), dims, symbols); 463 464 LLVM_DEBUG(DBGS() << "Resulting map: " << map << "\n"); 465 466 // Check whether any of the expressions, when subtracted from all other 467 // expressions, produces only >= 0 constants. If so, it is the min. 468 for (auto e : minOp.getAffineMap().getResults()) { 469 LLVM_DEBUG(DBGS() << "Candidate min: " << e << "\n"); 470 if (!e.isSymbolicOrConstant()) 471 continue; 472 473 auto isNonPositive = [](AffineExpr e) { 474 if (auto cst = e.dyn_cast<AffineConstantExpr>()) 475 return cst.getValue() < 0; 476 return true; 477 }; 478 479 // Build the subMap and check everything is statically known to be 480 // positive. 481 SmallVector<AffineExpr, 4> subExprs; 482 subExprs.reserve(map.getNumResults()); 483 for (auto ee : map.getResults()) 484 subExprs.push_back(ee - e); 485 MLIRContext *ctx = minOp.getContext(); 486 AffineMap subMap = simplifyAffineMap( 487 AffineMap::get(map.getNumDims(), map.getNumSymbols(), subExprs, ctx)); 488 LLVM_DEBUG(DBGS() << "simplified subMap: " << subMap << "\n"); 489 if (llvm::any_of(subMap.getResults(), isNonPositive)) 490 continue; 491 492 // Static min found. 493 if (auto cst = e.dyn_cast<AffineConstantExpr>()) { 494 rewriter.replaceOpWithNewOp<ConstantIndexOp>(minOp, cst.getValue()); 495 } else { 496 auto resultMap = AffineMap::get(0, map.getNumSymbols(), {e}, ctx); 497 SmallVector<Value, 4> resultOperands = dims; 498 resultOperands.append(symbols.begin(), symbols.end()); 499 canonicalizeMapAndOperands(&resultMap, &resultOperands); 500 resultMap = simplifyAffineMap(resultMap); 501 rewriter.replaceOpWithNewOp<AffineApplyOp>(minOp, resultMap, 502 resultOperands); 503 } 504 return success(); 505 } 506 507 return failure(); 508 } 509