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/Affine/Utils.h" 16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 17 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 18 #include "mlir/Dialect/Linalg/IR/Linalg.h" 19 #include "mlir/Dialect/Linalg/Transforms/HoistPadding.h" 20 #include "mlir/Dialect/Linalg/Utils/Utils.h" 21 #include "mlir/Dialect/SCF/Transforms.h" 22 #include "mlir/Dialect/Tensor/IR/Tensor.h" 23 #include "mlir/Dialect/Utils/StaticValueUtils.h" 24 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 25 #include "mlir/Dialect/Vector/VectorOps.h" 26 #include "mlir/IR/AffineExpr.h" 27 #include "mlir/IR/Matchers.h" 28 #include "mlir/Pass/Pass.h" 29 #include "mlir/Support/LLVM.h" 30 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 31 #include "llvm/ADT/ScopeExit.h" 32 #include "llvm/ADT/TypeSwitch.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <type_traits> 36 #include <utility> 37 38 #define DEBUG_TYPE "linalg-transforms" 39 40 using namespace mlir; 41 using namespace mlir::linalg; 42 43 #define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE << "]: ") 44 45 //===----------------------------------------------------------------------===// 46 // Transformations exposed as rewrite patterns. 47 //===----------------------------------------------------------------------===// 48 // Marker used as attribute name in generated Linalg rewriting transformations. 49 const StringLiteral mlir::linalg::LinalgTransforms::kLinalgTransformMarker = 50 "__internal_linalg_transform__"; 51 52 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter( 53 ArrayRef<StringAttr> matchDisjunction, Optional<StringAttr> replacement) 54 : matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()), 55 replacement(replacement), matchByDefault(false) {} 56 57 mlir::linalg::LinalgTransformationFilter::LinalgTransformationFilter( 58 const FilterFunction &f, ArrayRef<StringAttr> matchDisjunction, 59 Optional<StringAttr> replacement) 60 : filters(), 61 matchDisjunction(matchDisjunction.begin(), matchDisjunction.end()), 62 replacement(replacement), matchByDefault(false) { 63 if (f) 64 filters.push_back(f); 65 } 66 67 LogicalResult mlir::linalg::LinalgTransformationFilter::checkAndNotify( 68 PatternRewriter &rewriter, Operation *op) const { 69 if (llvm::any_of(filters, 70 [&](const FilterFunction &f) { return failed(f(op)); })) 71 return failure(); 72 73 auto attr = op->template getAttrOfType<StringAttr>( 74 LinalgTransforms::kLinalgTransformMarker); 75 76 if (!attr) { 77 // 1. Has no filter case and matchDisjunction is empty. 78 if (matchDisjunction.empty() || matchByDefault) 79 return success(); 80 81 // 2. Has no filter but was expecting a filter. 82 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) { 83 diag << " does not have any filter from list: "; 84 interleaveComma(matchDisjunction, diag); 85 }); 86 } 87 88 // 4. Match explicit filter. 89 for (auto filter : matchDisjunction) 90 if (attr.getValue() == filter) 91 return success(); 92 93 // 5. Fail to match. 94 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) { 95 diag << " does not have any filter from list: "; 96 interleaveComma(matchDisjunction, diag); 97 }); 98 } 99 100 void mlir::linalg::LinalgTransformationFilter:: 101 replaceLinalgTransformationFilter(PatternRewriter &rewriter, 102 Operation *op) const { 103 if (replacement.hasValue()) 104 op->setAttr(LinalgTransforms::kLinalgTransformMarker, 105 replacement.getValue()); 106 else 107 op->removeAttr( 108 rewriter.getStringAttr(LinalgTransforms::kLinalgTransformMarker)); 109 } 110 111 bool mlir::linalg::LinalgTransformationFilter::hasReplacementFilter( 112 Operation *op) const { 113 if (!replacement) 114 return false; 115 auto attr = op->getAttr(LinalgTransforms::kLinalgTransformMarker) 116 .dyn_cast<StringAttr>(); 117 return attr && attr == replacement.getValue(); 118 } 119 120 LinalgTilingOptions & 121 mlir::linalg::LinalgTilingOptions::setTileSizes(ArrayRef<int64_t> ts) { 122 assert(!tileSizeComputationFunction && "tile sizes already set"); 123 SmallVector<int64_t, 4> tileSizes(ts.begin(), ts.end()); 124 tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) { 125 OpBuilder::InsertionGuard guard(b); 126 b.setInsertionPointToStart( 127 &op->getParentOfType<FuncOp>().getBody().front()); 128 return llvm::to_vector<4>(map_range(tileSizes, [&](int64_t s) { 129 Value v = b.create<arith::ConstantIndexOp>(op->getLoc(), s); 130 return v; 131 })); 132 }; 133 return *this; 134 } 135 136 LinalgTilingOptions &mlir::linalg::LinalgTilingOptions::scalarizeDynamicDims() { 137 assert(!tileSizeComputationFunction && "tile sizes already set"); 138 tileSizeComputationFunction = [](OpBuilder &b, Operation *op) { 139 SmallVector<Value, 4> tileSizes; 140 auto linalgOp = dyn_cast<LinalgOp>(op); 141 if (!linalgOp) 142 return tileSizes; 143 Location loc = linalgOp.getLoc(); 144 auto allShapeSizes = linalgOp.createFlatListOfOperandDims(b, loc); 145 AffineMap map = linalgOp.getShapesToLoopsMap(); 146 if (!map) 147 return tileSizes; 148 auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes); 149 // If the shape size is dynamic, tile by 1. Otherwise, do not tile (tile 150 // size 0). 151 for (Value shapeSize : shapeSizes) 152 tileSizes.push_back(getConstantIntValue(shapeSize).hasValue() 153 ? b.create<arith::ConstantIndexOp>(loc, 0) 154 : b.create<arith::ConstantIndexOp>(loc, 1)); 155 return tileSizes; 156 }; 157 return *this; 158 } 159 160 /// Helper function that tries to pad `opOperand`. Exit early for scalar 161 /// operands, if `paddingFunc` returns failure, or if `opOperand` is not defined 162 /// by an ExtractSliceOp. Otherwise, try to pad the operand even if it already 163 /// has a static shape. Set `result` to the result of the created PadTensorOp or 164 /// and return success if the operand either has been padded to a static shape 165 /// or already had a static shape and failure otherwise. 166 static LogicalResult padOperandToSmallestStaticBoundingBox( 167 OpBuilder &b, linalg::LinalgOp opToPad, OpOperand *opOperand, 168 const PaddingValueComputationFunction &paddingFunc, 169 const PaddingNoFoldComputationFunction &nofoldFunc, Value &result) { 170 // Get the shape of the operand and check if it has a dynamic shape. Only 171 // return failure if the operand is not a scalar and has a dynamic shape. 172 ArrayRef<int64_t> shape = opToPad.getShape(opOperand); 173 bool hasDynamicShape = llvm::is_contained(shape, ShapedType::kDynamicSize); 174 175 // Cannot pad scalar operands. 176 if (shape.empty()) 177 return success(); 178 179 // Cannot pad if the padding value is unknown. 180 FailureOr<Value> paddingValue = paddingFunc(b, *opOperand); 181 if (failed(paddingValue)) 182 return failure(hasDynamicShape); 183 184 // Cannot construct a static bounding box if the operand is not defined by an 185 // ExtractSliceOp. 186 auto sliceOp = opOperand->get().getDefiningOp<tensor::ExtractSliceOp>(); 187 if (!sliceOp) 188 return failure(hasDynamicShape); 189 190 // Compute the dropped dimensions if `sliceOp` is ranke-reducing. 191 llvm::SmallDenseSet<unsigned> droppedDims = sliceOp.getDroppedDims(); 192 193 // Upper bound the `sliceOp` sizes to obtain a static bounding box. 194 SmallVector<int64_t> staticSizes; 195 staticSizes.reserve(shape.size()); 196 auto shapedOp = cast<OffsetSizeAndStrideOpInterface>(sliceOp.getOperation()); 197 for (const auto &en : enumerate(shapedOp.getMixedSizes())) { 198 // Skip dropped dimensions. 199 if (droppedDims.contains(en.index())) 200 continue; 201 // If the size is an attribute add it directly to `staticSizes`. 202 if (en.value().is<Attribute>()) { 203 staticSizes.push_back( 204 en.value().get<Attribute>().dyn_cast<IntegerAttr>().getInt()); 205 continue; 206 } 207 // Otherwise, try to compute a constant upper bound for the size value. 208 FailureOr<int64_t> upperBound = 209 getConstantUpperBoundForIndex(en.value().get<Value>()); 210 if (failed(upperBound)) { 211 LLVM_DEBUG(DBGS() << "No constant bounding box can be found for padding"); 212 return failure(); 213 } 214 staticSizes.push_back(upperBound.getValue()); 215 } 216 assert(staticSizes.size() == shape.size() && 217 "expect the dynamic and static ranks to match"); 218 219 // Pad the operand to the bounding box defined by `staticSizes`. 220 auto staticTensorType = RankedTensorType::get( 221 staticSizes, getElementTypeOrSelf(opOperand->get())); 222 bool nofold = nofoldFunc ? nofoldFunc(*opOperand) : false; 223 result = 224 makeComposedPadHighOp(b, opToPad->getLoc(), staticTensorType, 225 opOperand->get(), paddingValue.getValue(), nofold); 226 return success(); 227 } 228 229 FailureOr<SmallVector<Value>> 230 linalg::rewriteAsPaddedOp(OpBuilder &b, LinalgOp opToPad, 231 const PaddingValueComputationFunction &paddingFunc, 232 const PaddingNoFoldComputationFunction &nofoldFunc, 233 LinalgOp &paddedOp) { 234 Location loc = opToPad->getLoc(); 235 236 // TODO: there are cases where we may still want to pad to larger sizes. 237 assert(opToPad.hasTensorSemantics() && 238 "expected operation to have tensor semantics"); 239 240 OpBuilder::InsertionGuard g(b); 241 // Set IP after op because we also take the dims of the original output. 242 b.setInsertionPointAfter(opToPad); 243 // Make a copy of the shaped operands and update it. 244 SmallVector<Value> newOperands; 245 newOperands.reserve(opToPad.getNumInputsAndOutputs()); 246 for (OpOperand *opOperand : opToPad.getInputAndOutputOperands()) { 247 Value paddedOperand; 248 // If padding was requested but the shape cannot be bounded statically then 249 // the pattern fails to apply. 250 if (failed(padOperandToSmallestStaticBoundingBox( 251 b, opToPad, opOperand, paddingFunc, nofoldFunc, paddedOperand))) 252 return failure(); 253 newOperands.push_back(paddedOperand ? paddedOperand : opOperand->get()); 254 } 255 256 SmallVector<SmallVector<Value>> reifiedResultShapes; 257 if (failed(cast<ReifyRankedShapedTypeOpInterface>(opToPad.getOperation()) 258 .reifyResultShapes(b, reifiedResultShapes))) 259 return failure(); 260 assert(reifiedResultShapes.size() == opToPad->getNumResults() && 261 "expected same number of results"); 262 263 // Clone `opToPad` to operate on the statically padded shapes. 264 auto resultTensorTypes = 265 ValueRange(newOperands).take_back(opToPad.getNumOutputs()).getTypes(); 266 paddedOp = opToPad.clone(b, loc, resultTensorTypes, newOperands); 267 268 // Recover the slice out of the new static results. This keeps the original 269 // linalg op around because it uses the dims of the original results. 270 SmallVector<Value> paddedSubviewResults; 271 paddedSubviewResults.reserve(opToPad->getNumResults()); 272 for (const auto &en : llvm::enumerate(paddedOp->getResults())) { 273 Value paddedResult = en.value(); 274 int64_t resultNumber = en.index(); 275 int64_t rank = paddedResult.getType().cast<RankedTensorType>().getRank(); 276 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 277 SmallVector<OpFoldResult> sizes; 278 for (Value v : reifiedResultShapes[resultNumber]) 279 sizes.push_back(getAsOpFoldResult(v)); 280 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 281 paddedSubviewResults.push_back(b.create<tensor::ExtractSliceOp>( 282 loc, paddedResult, offsets, sizes, strides)); 283 } 284 return paddedSubviewResults; 285 } 286 287 /// Linalg base tiling pattern. 288 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern( 289 StringRef opName, MLIRContext *context, LinalgTilingOptions options, 290 LinalgTransformationFilter filter, PatternBenefit benefit) 291 : RewritePattern(opName, benefit, context), filter(std::move(filter)), 292 options(std::move(options)) {} 293 294 mlir::linalg::LinalgBaseTilingPattern::LinalgBaseTilingPattern( 295 MLIRContext *context, LinalgTilingOptions options, 296 LinalgTransformationFilter filter, PatternBenefit benefit) 297 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), 298 filter(std::move(filter)), options(std::move(options)) {} 299 300 /// Try to peel a loop `op` and return the new result. 301 // TODO: Add support for scf.parallel and affine.for loops. 302 static SmallVector<Value, 4> peelLoop(RewriterBase &rewriter, Operation *op) { 303 return llvm::TypeSwitch<Operation *, SmallVector<Value, 4>>(op) 304 .Case<scf::ForOp>([&](scf::ForOp forOp) { 305 scf::ForOp partialIteration; 306 if (succeeded(scf::peelAndCanonicalizeForLoop(rewriter, forOp, 307 partialIteration))) 308 return partialIteration->getResults(); 309 assert(!partialIteration && "expected that loop was not peeled"); 310 return forOp->getResults(); 311 }) 312 .Default([&](Operation *op) { return op->getResults(); }); 313 } 314 315 /// Try to peel a TiledLoopOp and return the new result. 316 static SmallVector<Value, 4> peelLoop(RewriterBase &rewriter, 317 TiledLoopOp tiledLoop, int64_t idx) { 318 assert(idx < static_cast<int64_t>(tiledLoop.iterator_types().size()) && 319 "requested peeling of non-existing loop"); 320 TiledLoopOp result; 321 if (succeeded(peelAndCanonicalizeTiledLoop(rewriter, tiledLoop, idx, result))) 322 return result->getResults(); 323 assert(!result && "expected that loop was not peeled"); 324 return tiledLoop->getResults(); 325 } 326 327 /// Peel loops after tiling. 328 static void peelLoops(RewriterBase &rewriter, TiledLinalgOp &res, 329 const LinalgTilingOptions &options) { 330 for (int64_t loop : options.peeledLoops) { 331 assert(loop < static_cast<int64_t>(res.loops.size()) && 332 "requested peeling of non-existing loop"); 333 SmallVector<Value, 4> loopResults; 334 Operation *loopOp = res.loops[loop]; 335 if (options.loopType == LinalgTilingLoopType::TiledLoops) { 336 assert(llvm::all_of( 337 res.loops, 338 [&](Operation *op) { return op == res.loops.front(); }) && 339 "expected that all loop ops are the same TiledLoopOp"); 340 auto tiledLoopOp = dyn_cast<TiledLoopOp>(loopOp); 341 assert(tiledLoopOp && "expected TiledLoopOp"); 342 loopResults = peelLoop(rewriter, tiledLoopOp, loop); 343 } else { 344 loopResults = peelLoop(rewriter, loopOp); 345 } 346 347 // The result of the loop nest may change with peeling. 348 if (res.tensorResults.size() == loopOp->getNumResults() && 349 std::equal(res.tensorResults.begin(), res.tensorResults.end(), 350 loopOp->getResults().begin())) 351 res.tensorResults = loopResults; 352 } 353 } 354 355 LogicalResult mlir::linalg::LinalgBaseTilingPattern::matchAndRewriteBase( 356 Operation *op, PatternRewriter &rewriter, TiledLinalgOp &result) const { 357 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 358 if (!linalgOp) 359 return failure(); 360 if (failed(filter.checkAndNotify(rewriter, linalgOp))) 361 return failure(); 362 363 Optional<TiledLinalgOp> res = tileLinalgOp(rewriter, linalgOp, options); 364 365 if (!res) 366 return failure(); 367 // Clear filter to stop recursive pattern application. 368 filter.replaceLinalgTransformationFilter(rewriter, res->op); 369 370 // Peel loops. 371 peelLoops(rewriter, *res, options); 372 373 result = *res; 374 return success(); 375 } 376 377 static ValueRange getTiledOpResult(TiledLinalgOp tiledOp) { 378 if (tiledOp.loops.empty()) 379 return tiledOp.op.getOperation()->getResults(); 380 return tiledOp.loops.front()->getResults(); 381 } 382 383 static ValueRange 384 getTiledAndFusedOpResult(TiledAndFusedLinalgOps tiledAndFusedOp) { 385 if (tiledAndFusedOp.fusedLoops.empty()) 386 return tiledAndFusedOp.op.getOperation()->getResults(); 387 return tiledAndFusedOp.fusedLoops.front()->getResults(); 388 } 389 390 mlir::linalg::LinalgBaseTileAndFusePattern::LinalgBaseTileAndFusePattern( 391 StringRef opName, MLIRContext *context, 392 const LinalgDependenceGraph &dependenceGraph, 393 LinalgTilingOptions tilingOptions, LinalgFusionOptions fusionOptions, 394 LinalgTransformationFilter filter, LinalgTransformationFilter fusedOpMarker, 395 LinalgTransformationFilter originalOpMarker, PatternBenefit benefit) 396 : RewritePattern(opName, benefit, context, {}), 397 dependenceGraph(dependenceGraph), tilingOptions(std::move(tilingOptions)), 398 fusionOptions(std::move(fusionOptions)), filter(std::move(filter)), 399 fusedOpMarker(std::move(fusedOpMarker)), 400 originalOpMarker(std::move(originalOpMarker)) {} 401 402 LogicalResult mlir::linalg::LinalgBaseTileAndFusePattern::matchAndRewrite( 403 Operation *op, PatternRewriter &rewriter) const { 404 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 405 // TODO: remove hasIndexSemantics check once index ops are supported. 406 if (!linalgOp || linalgOp.hasIndexSemantics()) 407 return failure(); 408 if (failed(filter.checkAndNotify(rewriter, linalgOp))) 409 return failure(); 410 411 DenseSet<Operation *> producers; 412 producers.insert(linalgOp); 413 for (auto dependence : dependenceGraph.getDependentOperationsInto(linalgOp)) { 414 Optional<unsigned> operandNumber = dependence.getIndexingOpViewOperandNum(); 415 // When looking at dependences into, indexingOp is always OpOperand. We 416 // could assert, but continue if this is not the case. 417 if (!operandNumber) 418 continue; 419 if (!fusionOptions.indicesToFuse.count(operandNumber.getValue())) 420 continue; 421 if (isa<LinalgOp>(dependence.getDependentOp())) 422 producers.insert(dependence.getDependentOp()); 423 } 424 425 SmallVector<LinalgOp, 1> fusionOps; 426 for (auto it = op->getBlock()->begin(), ie = Block::iterator(op); it != ie; 427 ++it) { 428 auto producerLinalgOp = dyn_cast<LinalgOp>(&(*it)); 429 if (producerLinalgOp && producers.count(producerLinalgOp)) 430 fusionOps.push_back(producerLinalgOp); 431 } 432 fusionOps.push_back(linalgOp); 433 434 SmallVector<Value, 4> tileSizes = 435 tilingOptions.tileSizeComputationFunction(rewriter, op); 436 LinalgTilingOptions instanceTilingOptions = tilingOptions; 437 instanceTilingOptions.setTileSizes(tileSizes); 438 Optional<TiledAndFusedLinalgOps> tiledAndFusedOps = tileAndFuseLinalgOps( 439 rewriter, fusionOps, dependenceGraph, instanceTilingOptions); 440 if (!tiledAndFusedOps) 441 return failure(); 442 443 // Tile the unfused loops; 444 SmallVector<Value, 4> unfusedLoopTileSizes; 445 Value zero = rewriter.create<arith::ConstantIndexOp>(op->getLoc(), 0); 446 for (const auto &tileSize : enumerate(tileSizes)) { 447 if (tiledAndFusedOps->fusedLoopDims.count(tileSize.index())) 448 unfusedLoopTileSizes.push_back(zero); 449 else 450 unfusedLoopTileSizes.push_back(tileSize.value()); 451 } 452 // Tile the loop only if there is a non-zero tile size. 453 if (unfusedLoopTileSizes.size() > linalgOp.getNumLoops()) 454 unfusedLoopTileSizes.resize(linalgOp.getNumLoops()); 455 if (llvm::any_of(unfusedLoopTileSizes, [](Value val) { 456 if (auto cst = val.getDefiningOp<arith::ConstantIndexOp>()) 457 return cst.value() != 0; 458 return true; 459 })) { 460 LinalgTilingOptions unfusedTilingOptions = tilingOptions; 461 unfusedTilingOptions.setTileSizes(unfusedLoopTileSizes); 462 Optional<TiledLinalgOp> unfusedTiledOp = 463 tileLinalgOp(rewriter, tiledAndFusedOps->op, unfusedTilingOptions); 464 if (!unfusedTiledOp) 465 return failure(); 466 rewriter.replaceOp(tiledAndFusedOps->op, 467 getTiledOpResult(unfusedTiledOp.getValue())); 468 tiledAndFusedOps->op = unfusedTiledOp->op; 469 } 470 op->replaceAllUsesWith(getTiledAndFusedOpResult(tiledAndFusedOps.getValue())); 471 472 filter.replaceLinalgTransformationFilter(rewriter, 473 tiledAndFusedOps->op.getOperation()); 474 for (auto fusedOp : tiledAndFusedOps->fusedProducers) { 475 fusedOpMarker.replaceLinalgTransformationFilter(rewriter, 476 fusedOp.getOperation()); 477 } 478 for (auto origProducerOp : ArrayRef<LinalgOp>(fusionOps).drop_back()) { 479 originalOpMarker.replaceLinalgTransformationFilter( 480 rewriter, origProducerOp.getOperation()); 481 } 482 rewriter.updateRootInPlace(op, [&]() { 483 originalOpMarker.replaceLinalgTransformationFilter(rewriter, op); 484 }); 485 return success(); 486 } 487 488 /// Linalg padding pattern. 489 mlir::linalg::LinalgPaddingPattern::LinalgPaddingPattern( 490 MLIRContext *context, LinalgPaddingOptions options, 491 LinalgTransformationFilter filter, PatternBenefit benefit) 492 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), 493 filter(std::move(filter)), options(std::move(options)) {} 494 495 mlir::linalg::LinalgPaddingPattern::LinalgPaddingPattern( 496 StringRef opName, MLIRContext *context, LinalgPaddingOptions options, 497 LinalgTransformationFilter filter, PatternBenefit benefit) 498 : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)), 499 options(std::move(options)) {} 500 501 LogicalResult mlir::linalg::LinalgPaddingPattern::matchAndRewrite( 502 Operation *op, PatternRewriter &rewriter) const { 503 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 504 if (!linalgOp) 505 return failure(); 506 if (!linalgOp.hasTensorSemantics()) 507 return failure(); 508 if (failed(filter.checkAndNotify(rewriter, op))) 509 return failure(); 510 511 // Pad the operation. 512 LinalgOp paddedOp; 513 FailureOr<SmallVector<Value>> newResults = rewriteAsPaddedOp( 514 rewriter, linalgOp, options.paddingValueComputationFunction, 515 options.paddingNoFoldComputationFunction, paddedOp); 516 if (failed(newResults)) 517 return failure(); 518 519 // Compute the desired hoisting depths. 520 SmallVector<int64_t> depths; 521 if (options.paddingHoistComputationFunction) { 522 for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) 523 depths.push_back(options.paddingHoistComputationFunction(*opOperand)); 524 } 525 526 // Hoist the padding. 527 for (const auto &en : enumerate(depths)) { 528 OpOperand &opOperand = paddedOp->getOpOperand(en.index()); 529 auto padTensorOp = opOperand.get().getDefiningOp<PadTensorOp>(); 530 if (!padTensorOp || en.value() == 0) 531 continue; 532 PadTensorOp hoistedOp; 533 FailureOr<Value> newResult = 534 hoistPaddingOnTensors(padTensorOp, en.value(), hoistedOp); 535 if (failed(newResult)) 536 continue; 537 rewriter.replaceOp(padTensorOp, newResult.getValue()); 538 } 539 540 // Replace the original operation to pad. 541 rewriter.replaceOp(op, newResults.getValue()); 542 filter.replaceLinalgTransformationFilter(rewriter, paddedOp); 543 return success(); 544 } 545 546 /// Linalg tile and fuse tensor ops pattern. 547 mlir::linalg::LinalgTileAndFuseTensorOpsPattern:: 548 LinalgTileAndFuseTensorOpsPattern(MLIRContext *context, 549 LinalgTilingAndFusionOptions options, 550 LinalgTransformationFilter filter, 551 PatternBenefit benefit) 552 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), 553 filter(std::move(filter)), options(std::move(options)) {} 554 555 mlir::linalg::LinalgTileAndFuseTensorOpsPattern:: 556 LinalgTileAndFuseTensorOpsPattern(StringRef opName, MLIRContext *context, 557 LinalgTilingAndFusionOptions options, 558 LinalgTransformationFilter filter, 559 PatternBenefit benefit) 560 : RewritePattern(opName, benefit, context), filter(std::move(filter)), 561 options(std::move(options)) {} 562 563 LogicalResult mlir::linalg::LinalgTileAndFuseTensorOpsPattern::matchAndRewrite( 564 Operation *op, PatternRewriter &rewriter) const { 565 LinalgOp rootOp = dyn_cast<LinalgOp>(op); 566 if (!rootOp) 567 return failure(); 568 if (failed(filter.checkAndNotify(rewriter, op))) 569 return failure(); 570 571 // Check `tileSizes` contains a tile size for every `rootOp` loop dimension. 572 if (options.tileSizes.size() < rootOp.getNumLoops()) 573 return rewriter.notifyMatchFailure(op, "expect #tile sizes >= #loops"); 574 575 // Check `tileInterchange` contains no entries or as many as `tileSizes`. 576 if (!options.tileInterchange.empty() && 577 options.tileInterchange.size() != options.tileSizes.size()) 578 return rewriter.notifyMatchFailure( 579 op, "expect the number of tile sizes and interchange dims to match"); 580 581 // Copy the `tileSizes` and `tileInterchange` prefixes needed for `rootOp`. 582 SmallVector<int64_t> rootTileSizes(options.tileSizes.begin(), 583 options.tileSizes.begin() + 584 rootOp.getNumLoops()); 585 SmallVector<int64_t> rootInterchange = 586 options.tileInterchange.empty() 587 ? llvm::to_vector<6>(llvm::seq<int64_t>(0, rootOp.getNumLoops())) 588 : SmallVector<int64_t>(options.tileInterchange.begin(), 589 options.tileInterchange.begin() + 590 rootOp.getNumLoops()); 591 592 // Check `rootInterchange` is a permutation of the `rootOp` loop dimensions. 593 // It has to be a permutation since the tiling cannot tile the same loop 594 // dimension multiple times. 595 if (!isPermutation(rootInterchange)) 596 return rewriter.notifyMatchFailure( 597 op, "expect the tile interchange permutes the root loops"); 598 599 // Tile `rootOp` and fuse its producers. 600 FailureOr<TileLoopNest> tileLoopNest = tileConsumerAndFuseProducers( 601 rewriter, rootOp, rootTileSizes, rootInterchange); 602 if (failed(tileLoopNest)) 603 return rewriter.notifyMatchFailure( 604 op, "tileConsumerAndFuseProducers failed unexpectedly"); 605 606 // Replace all uses of the tiled loop operation. 607 rootOp->replaceAllUsesWith(tileLoopNest->getRootOpReplacementResults()); 608 609 // Apply the filter if specified. 610 for (LinalgOp linalgOp : tileLoopNest->getAllTiledAndFusedOps()) 611 filter.replaceLinalgTransformationFilter(rewriter, linalgOp); 612 return failure(); 613 } 614 615 /// Linalg generic interchange pattern. 616 mlir::linalg::GenericOpInterchangePattern::GenericOpInterchangePattern( 617 MLIRContext *context, ArrayRef<unsigned> interchangeVector, 618 LinalgTransformationFilter filter, PatternBenefit benefit) 619 : OpRewritePattern(context, benefit), filter(std::move(filter)), 620 interchangeVector(interchangeVector.begin(), interchangeVector.end()) {} 621 622 LogicalResult mlir::linalg::GenericOpInterchangePattern::matchAndRewrite( 623 GenericOp genericOp, PatternRewriter &rewriter) const { 624 if (failed(filter.checkAndNotify(rewriter, genericOp))) 625 return failure(); 626 627 FailureOr<GenericOp> transformedOp = 628 interchangeGenericOp(rewriter, genericOp, interchangeVector); 629 if (failed(transformedOp)) 630 return failure(); 631 632 // New filter if specified. 633 filter.replaceLinalgTransformationFilter(rewriter, genericOp); 634 return success(); 635 } 636 637 /// Linalg generalization pattern. 638 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern( 639 MLIRContext *context, LinalgTransformationFilter filter, 640 PatternBenefit benefit) 641 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), 642 filter(std::move(filter)) {} 643 644 mlir::linalg::LinalgGeneralizationPattern::LinalgGeneralizationPattern( 645 StringRef opName, MLIRContext *context, LinalgTransformationFilter filter, 646 PatternBenefit benefit) 647 : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)) {} 648 649 LogicalResult mlir::linalg::LinalgGeneralizationPattern::matchAndRewrite( 650 Operation *op, PatternRewriter &rewriter) const { 651 // TODO: Interface pattern. 652 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 653 if (!linalgOp) 654 return failure(); 655 if (failed(filter.checkAndNotify(rewriter, op))) 656 return failure(); 657 FailureOr<GenericOp> genericOp = generalizeNamedOp(rewriter, linalgOp); 658 if (failed(genericOp)) 659 return failure(); 660 filter.replaceLinalgTransformationFilter(rewriter, *genericOp); 661 return success(); 662 } 663 664 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern( 665 MLIRContext *context, LinalgTransformationFilter filter, 666 LinalgPromotionOptions options, PatternBenefit benefit) 667 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), 668 filter(std::move(filter)), options(std::move(options)) {} 669 670 mlir::linalg::LinalgBasePromotionPattern::LinalgBasePromotionPattern( 671 StringRef opName, MLIRContext *context, LinalgPromotionOptions options, 672 LinalgTransformationFilter filter, PatternBenefit benefit) 673 : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)), 674 options(std::move(options)) {} 675 676 LogicalResult mlir::linalg::LinalgBasePromotionPattern::matchAndRewrite( 677 Operation *op, PatternRewriter &rewriter) const { 678 if (failed(filter.checkAndNotify(rewriter, op))) 679 return failure(); 680 if (failed(promoteSubviewsPrecondition(op, options))) 681 return failure(); 682 683 // TODO: We cannot use root update here. This pattern is creating other ops, 684 // so if the promotion fails, those need to be cleaned up, which doesnt seem 685 // to be happening here. So to fail properly, we should be cloning the op and 686 // deleting the previous op. This needs more investigation. 687 rewriter.startRootUpdate(op); 688 Optional<LinalgOp> promotedOp = promoteSubViews(rewriter, op, options); 689 if (!promotedOp) { 690 rewriter.cancelRootUpdate(op); 691 return op->emitError("subview promotion failed"); 692 } 693 rewriter.finalizeRootUpdate(op); 694 filter.replaceLinalgTransformationFilter(rewriter, op); 695 return success(); 696 } 697 698 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern( 699 MLIRContext *context, LinalgTransformationFilter filter, 700 PatternBenefit benefit) 701 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), 702 filter(std::move(filter)) {} 703 704 mlir::linalg::LinalgBaseVectorizationPattern::LinalgBaseVectorizationPattern( 705 StringRef opName, MLIRContext *context, LinalgTransformationFilter filter, 706 PatternBenefit benefit) 707 : RewritePattern(opName, benefit, context, {}), filter(std::move(filter)) {} 708 709 LogicalResult mlir::linalg::LinalgBaseVectorizationPattern::matchAndRewrite( 710 Operation *op, PatternRewriter &rewriter) const { 711 // TODO: Interface-based rewrite. 712 LinalgOp linalgOp = dyn_cast<LinalgOp>(op); 713 if (!linalgOp) 714 return failure(); 715 if (failed(filter.checkAndNotify(rewriter, op))) 716 return failure(); 717 return vectorize(rewriter, linalgOp); 718 } 719 720 LogicalResult mlir::linalg::applyStagedPatterns( 721 Operation *op, ArrayRef<FrozenRewritePatternSet> stage1Patterns, 722 const FrozenRewritePatternSet &stage2Patterns, 723 function_ref<LogicalResult(Operation *)> stage3Lambda) { 724 unsigned iteration = 0; 725 (void)iteration; 726 for (const auto &patterns : stage1Patterns) { 727 LLVM_DEBUG(DBGS() << "Before 1st stage, iter: " << ++iteration << "\n" 728 << *op); 729 if (failed(applyPatternsAndFoldGreedily(op, patterns))) { 730 LLVM_DEBUG(DBGS() << "Underlying first stage rewrite did not converge"); 731 return failure(); 732 } 733 LLVM_DEBUG(DBGS() << "After 1st stage, iter: " << ++iteration << "\n" 734 << *op); 735 if (failed(applyPatternsAndFoldGreedily(op, stage2Patterns))) { 736 LLVM_DEBUG(DBGS() << "Underlying 2nd stage rewrite did not converge"); 737 return failure(); 738 } 739 LLVM_DEBUG(DBGS() << "After 2nd stage, iter : " << iteration << "\n" 740 << *op); 741 if (stage3Lambda) { 742 if (failed(stage3Lambda(op))) 743 return failure(); 744 LLVM_DEBUG(DBGS() << "After 3rd stage, iter : " << iteration << "\n" 745 << *op); 746 } 747 } 748 return success(); 749 } 750 751 static SmallVector<StringRef> getNParallelLoopsAttrs(unsigned nParallelLoops) { 752 return SmallVector<StringRef>(nParallelLoops, getParallelIteratorTypeName()); 753 } 754 755 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, FillOp (to 756 /// initialize with pad_val) and GenericOp (to copy contents). 757 LogicalResult PadTensorOpTransformationPattern::matchAndRewrite( 758 linalg::PadTensorOp padOp, PatternRewriter &rewriter) const { 759 760 auto inputShapedType = padOp.source().getType().cast<ShapedType>(); 761 auto resultShapedType = padOp.result().getType().cast<ShapedType>(); 762 763 // Bail on non-static shapes. 764 if (!inputShapedType.hasStaticShape()) 765 return failure(); 766 if (!resultShapedType.hasStaticShape()) 767 return failure(); 768 769 // Only support padding with a constant for now, i.e. either: 770 // 1. A BBarg from a different block. 771 // 2. A value defined outside of the current block. 772 Block &block = padOp.region().front(); 773 auto yieldOp = cast<YieldOp>(block.getTerminator()); 774 assert(yieldOp.getNumOperands() == 1 && "expected single operand yield"); 775 Value padValue = yieldOp.values().front(); 776 Operation *definingOp = padValue.getDefiningOp(); 777 if (definingOp && definingOp->getBlock() == &block) 778 return failure(); 779 if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block) 780 return failure(); 781 782 // Create tensor with the padded shape 783 Location loc = padOp.getLoc(); 784 SmallVector<Value> indices(resultShapedType.getRank(), 785 rewriter.create<arith::ConstantIndexOp>(loc, 0)); 786 Value initTensor = rewriter.create<InitTensorOp>( 787 loc, resultShapedType.getShape(), resultShapedType.getElementType()); 788 789 // Initialize tensor with the pad value 790 Value tmpTensor = 791 rewriter.create<linalg::FillOp>(loc, padValue, initTensor).result(); 792 793 // Copy original contents into new tensor 794 // Uses linalg.generic, but could be done with tensor.insert_slice 795 SmallVector<AffineExpr, 4> outputExprs; 796 for (unsigned i = 0; i < resultShapedType.getRank(); ++i) { 797 outputExprs.push_back(getAffineDimExpr(i, rewriter.getContext()) + 798 padOp.static_low()[i].cast<IntegerAttr>().getInt()); 799 } 800 801 SmallVector<AffineMap, 2> transferMaps = { 802 rewriter.getMultiDimIdentityMap(inputShapedType.getRank()), 803 AffineMap::get(resultShapedType.getRank(), 804 /*symbolCount=*/0, outputExprs, rewriter.getContext())}; 805 806 rewriter.replaceOpWithNewOp<linalg::GenericOp>( 807 padOp, resultShapedType, padOp.source(), tmpTensor, transferMaps, 808 getNParallelLoopsAttrs(resultShapedType.getRank()), 809 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) { 810 nestedBuilder.create<linalg::YieldOp>(nestedLoc, args[0]); 811 }); 812 813 return success(); 814 } 815 816 /// Filling `dest` using FillOp constant padding value if possible. 817 /// Otherwise, generate a tensor::GenerateOp. 818 Value GeneralizePadTensorOpPattern::createFillOrGenerateOp( 819 PatternRewriter &rewriter, PadTensorOp padOp, Value dest, 820 const SmallVector<Value> &dynSizes) const { 821 auto padValue = padOp.getConstantPaddingValue(); 822 if (padValue) 823 return rewriter.create<FillOp>(padOp.getLoc(), padValue, dest).result(); 824 825 // Fill could not be optimized: Lower to tensor::GenerateOp with region. 826 auto generateOp = rewriter.create<tensor::GenerateOp>( 827 padOp.getLoc(), padOp.getResultType(), dynSizes); 828 // Copy region to new op. 829 BlockAndValueMapping bvm; 830 padOp.region().cloneInto(&generateOp.getRegion(), bvm); 831 // Rewrite linalg::YieldOp to tensor::YieldOp. 832 OpBuilder::InsertionGuard guard(rewriter); 833 auto yieldOp = 834 dyn_cast<linalg::YieldOp>(generateOp.getRegion().front().getTerminator()); 835 assert(yieldOp && "malformed PadTensorOp: expected YieldOp terminator"); 836 assert(yieldOp.values().size() == 1); 837 rewriter.setInsertionPoint(yieldOp); 838 rewriter.replaceOpWithNewOp<tensor::YieldOp>(yieldOp, yieldOp.values()[0]); 839 return generateOp; 840 } 841 842 LogicalResult 843 GeneralizePadTensorOpPattern::matchAndRewrite(PadTensorOp padOp, 844 PatternRewriter &rewriter) const { 845 // Given an OpFoldResult, return an index-typed value. 846 auto getIdxValue = [&](OpFoldResult ofr) { 847 if (auto val = ofr.dyn_cast<Value>()) 848 return val; 849 return rewriter 850 .create<arith::ConstantIndexOp>( 851 padOp.getLoc(), ofr.get<Attribute>().cast<IntegerAttr>().getInt()) 852 .getResult(); 853 }; 854 855 auto resultType = padOp.getResultType(); 856 // Compute size of InitTensorOp. Any combination of static/dynamic is 857 // supported. 858 SmallVector<Value> dynSizes; 859 SmallVector<int64_t> staticSizes; 860 for (unsigned dim = 0; dim < resultType.getRank(); ++dim) { 861 if (resultType.isDynamicDim(dim)) { 862 auto srcSize = rewriter.createOrFold<tensor::DimOp>(padOp.getLoc(), 863 padOp.source(), dim); 864 // Add low and high padding value. 865 auto plusLow = rewriter.createOrFold<arith::AddIOp>( 866 padOp.getLoc(), srcSize, getIdxValue(padOp.getMixedLowPad()[dim])); 867 auto plusHigh = rewriter.createOrFold<arith::AddIOp>( 868 padOp.getLoc(), plusLow, getIdxValue(padOp.getMixedHighPad()[dim])); 869 dynSizes.push_back(plusHigh); 870 } 871 staticSizes.push_back(resultType.getDimSize(dim)); 872 } 873 874 // Init tensor and fill it with padding. 875 Value init = rewriter.create<InitTensorOp>( 876 padOp.getLoc(), dynSizes, staticSizes, resultType.getElementType()); 877 Value fill = createFillOrGenerateOp(rewriter, padOp, init, dynSizes); 878 879 // Try optimize the copy of source. 880 if (optimizeCopyFn && optimizeCopyFn(rewriter, padOp, fill).succeeded()) 881 return success(); 882 883 // PadTensorOps cannot be optimized. Generate a InsertSliceOp instead 884 // for copying the PadOp source. 885 auto sourceType = padOp.getSourceType(); 886 // Compute size of source of PadTensorOp. 887 SmallVector<OpFoldResult> srcSizes; 888 for (unsigned dim = 0; dim < sourceType.getRank(); ++dim) { 889 if (sourceType.isDynamicDim(dim)) { 890 srcSizes.push_back(rewriter.createOrFold<tensor::DimOp>( 891 padOp.getLoc(), padOp.source(), dim)); 892 } else { 893 srcSizes.push_back(rewriter.getIndexAttr(sourceType.getDimSize(dim))); 894 } 895 } 896 // Strides of InsertSliceOp are all 1. 897 SmallVector<OpFoldResult> strides(sourceType.getRank(), 898 rewriter.getIndexAttr(1)); 899 rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>( 900 padOp, padOp.source(), fill, padOp.getMixedLowPad(), srcSizes, strides); 901 902 return success(); 903 } 904 905 LogicalResult ExtractSliceOfPadTensorSwapPattern::matchAndRewrite( 906 tensor::ExtractSliceOp sliceOp, PatternRewriter &rewriter) const { 907 auto padOp = sliceOp.source().getDefiningOp<PadTensorOp>(); 908 if (!padOp) 909 return failure(); 910 // Only unit stride supported. 911 if (!sliceOp.hasUnitStride()) 912 return failure(); 913 914 Operation *tiledPadOp = 915 padOp 916 .getTiledImplementation( 917 rewriter, /*dest=*/ValueRange{}, sliceOp.getMixedOffsets(), 918 sliceOp.getMixedSizes(), /*tileDestOperands=*/false) 919 .front(); 920 // All shapes are static and the data source is actually used. Rewrite into 921 // pad_tensor(subtensor(x)). 922 rewriter.replaceOp(sliceOp, tiledPadOp->getResults()); 923 return success(); 924 } 925 926 namespace { 927 // The following are patterns for downscaling convolution ops with size-1 928 // window dimensions. 929 // 930 // Note that we'd eventually want to write such transformations in a generic 931 // way, e.g., converting to linalg.generic, removing the size-1 dimensions, 932 // and then turning back to named ops. But for now it's fine to have a few 933 // patterns matching special ops to get started. 934 935 /// Rewrites 2-D convolution ops with size-1 window dimensions into 1-D 936 /// convolution ops. 937 struct DownscaleSizeOneWindowed2DConvolution final 938 : public OpRewritePattern<Conv2DNhwcHwcfOp> { 939 DownscaleSizeOneWindowed2DConvolution( 940 MLIRContext *context, 941 LinalgTransformationFilter filter = LinalgTransformationFilter(), 942 PatternBenefit benefit = 1) 943 : OpRewritePattern<Conv2DNhwcHwcfOp>(context, benefit), 944 filter(std::move(filter)) {} 945 946 LogicalResult matchAndRewrite(linalg::Conv2DNhwcHwcfOp convOp, 947 PatternRewriter &rewriter) const override { 948 if (failed(filter.checkAndNotify(rewriter, convOp))) 949 return failure(); 950 if (convOp.hasBufferSemantics()) 951 return failure(); // To be implemented 952 953 Value input = convOp.inputs().front(); 954 Value kernel = convOp.inputs().back(); 955 Value output = convOp.outputs().front(); 956 957 auto inputType = input.getType().dyn_cast<RankedTensorType>(); 958 auto kernelType = kernel.getType().dyn_cast<RankedTensorType>(); 959 auto outputType = output.getType().dyn_cast<RankedTensorType>(); 960 961 auto kernelShape = kernelType.getShape(); 962 auto outputShape = outputType.getShape(); 963 964 // Only handle the case where at least one of the window dimensions is 965 // of size 1. Other cases can rely on tiling to reduce to such cases. 966 int64_t khSize = kernelShape[0], kwSize = kernelShape[1]; 967 int64_t ohSize = outputShape[1], owSize = outputShape[2]; 968 bool removeH = (khSize == 1 && ohSize == 1); 969 bool removeW = (kwSize == 1 && owSize == 1); 970 if (!removeH && !removeW) 971 return failure(); 972 973 // Get new shapes and types for all operands by removing the size-1 974 // dimension. 975 using RTTBuilder = RankedTensorType::Builder; 976 RankedTensorType newInputType = 977 RTTBuilder(inputType).dropDim((removeH ? 1 : 2)); 978 RankedTensorType newKernelType = 979 RTTBuilder(kernelType).dropDim((removeH ? 0 : 1)); 980 RankedTensorType newOutputType = 981 RTTBuilder(outputType).dropDim(removeH ? 1 : 2); 982 983 // Rank-reduce operands. 984 Location loc = convOp.getLoc(); 985 Value newInput = tensor::createCanonicalRankReducingExtractSliceOp( 986 rewriter, loc, input, newInputType); 987 Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp( 988 rewriter, loc, kernel, newKernelType); 989 Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp( 990 rewriter, loc, output, newOutputType); 991 992 // Rank-reduce strides and dilations too. 993 // TODO: dropDim 1-liner helper. 994 auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>()); 995 strides.erase(strides.begin() + (removeH ? 0 : 1)); 996 auto stridesAttr = rewriter.getI64VectorAttr(strides); 997 998 auto dilations = 999 llvm::to_vector<4>(convOp.dilations().getValues<int64_t>()); 1000 dilations.erase(dilations.begin() + (removeH ? 0 : 1)); 1001 auto dilationsAttr = rewriter.getI64VectorAttr(dilations); 1002 1003 auto conv1DOp = rewriter.create<linalg::Conv1DNwcWcfOp>( 1004 loc, newOutputType, ValueRange{newInput, newKernel}, 1005 ValueRange{newOutput}, stridesAttr, dilationsAttr); 1006 1007 // Insert back. 1008 Value inserted = tensor::createCanonicalRankReducingInsertSliceOp( 1009 rewriter, loc, conv1DOp.getResult(0), output); 1010 rewriter.replaceOp(convOp, inserted); 1011 1012 filter.replaceLinalgTransformationFilter(rewriter, conv1DOp); 1013 return success(); 1014 }; 1015 1016 private: 1017 /// LinalgTransformMarker handles special attribute manipulations. 1018 LinalgTransformationFilter filter; 1019 }; 1020 1021 /// Rewrites 2-D depthwise convolution ops with size-1 (w, kw) or (h, kh) 1022 /// dimensions into 1-D depthwise convolution ops. 1023 struct DownscaleDepthwiseConv2DNhwcHwcOp final 1024 : public OpRewritePattern<DepthwiseConv2DNhwcHwcOp> { 1025 DownscaleDepthwiseConv2DNhwcHwcOp( 1026 MLIRContext *context, 1027 LinalgTransformationFilter filter = LinalgTransformationFilter(), 1028 PatternBenefit benefit = 1) 1029 : OpRewritePattern<DepthwiseConv2DNhwcHwcOp>(context, benefit), 1030 filter(std::move(filter)) {} 1031 1032 LogicalResult matchAndRewrite(DepthwiseConv2DNhwcHwcOp convOp, 1033 PatternRewriter &rewriter) const override { 1034 if (failed(filter.checkAndNotify(rewriter, convOp))) 1035 return failure(); 1036 if (convOp.hasBufferSemantics()) 1037 return failure(); // To be implemented 1038 1039 Value input = convOp.inputs().front(); 1040 Value kernel = convOp.inputs().back(); 1041 Value output = convOp.outputs().front(); 1042 1043 auto inputType = input.getType().dyn_cast<RankedTensorType>(); 1044 auto kernelType = kernel.getType().dyn_cast<RankedTensorType>(); 1045 auto outputType = output.getType().dyn_cast<RankedTensorType>(); 1046 1047 auto kernelShape = kernelType.getShape(); 1048 auto outputShape = outputType.getShape(); 1049 1050 // Only handle the case where at least one of the window dimensions is 1051 // of size 1. Other cases can rely on tiling to reduce to such cases. 1052 int64_t khSize = kernelShape[0], kwSize = kernelShape[1]; 1053 int64_t ohSize = outputShape[1], owSize = outputShape[2]; 1054 bool removeH = (khSize == 1 && ohSize == 1); 1055 bool removeW = (kwSize == 1 && owSize == 1); 1056 if (!removeH && !removeW) 1057 return failure(); 1058 1059 // Get new shapes and types for all operands by removing the size-1 1060 // dimension. 1061 using RTTBuilder = RankedTensorType::Builder; 1062 RankedTensorType newInputType = 1063 RTTBuilder(inputType).dropDim((removeH ? 1 : 2)); 1064 RankedTensorType newKernelType = 1065 RTTBuilder(kernelType).dropDim((removeH ? 0 : 1)); 1066 RankedTensorType newOutputType = 1067 RTTBuilder(outputType).dropDim(removeH ? 1 : 2); 1068 1069 // Rank-reduce operands. 1070 Location loc = convOp.getLoc(); 1071 Value newInput = tensor::createCanonicalRankReducingExtractSliceOp( 1072 rewriter, loc, input, newInputType); 1073 Value newKernel = tensor::createCanonicalRankReducingExtractSliceOp( 1074 rewriter, loc, kernel, newKernelType); 1075 Value newOutput = tensor::createCanonicalRankReducingExtractSliceOp( 1076 rewriter, loc, output, newOutputType); 1077 1078 // Rank-reduce strides and dilations too. 1079 // TODO: dropDim 1-liner helper. 1080 auto strides = llvm::to_vector<4>(convOp.strides().getValues<int64_t>()); 1081 strides.erase(strides.begin() + (removeH ? 0 : 1)); 1082 auto stridesAttr = rewriter.getI64VectorAttr(strides); 1083 1084 auto dilations = 1085 llvm::to_vector<4>(convOp.dilations().getValues<int64_t>()); 1086 dilations.erase(dilations.begin() + (removeH ? 0 : 1)); 1087 auto dilationsAttr = rewriter.getI64VectorAttr(dilations); 1088 1089 auto conv1DOp = rewriter.create<DepthwiseConv1DNwcWcOp>( 1090 loc, newOutputType, ValueRange{newInput, newKernel}, 1091 ValueRange{newOutput}, stridesAttr, dilationsAttr); 1092 1093 // Insert back. 1094 Value inserted = tensor::createCanonicalRankReducingInsertSliceOp( 1095 rewriter, loc, conv1DOp.getResult(0), output); 1096 rewriter.replaceOp(convOp, inserted); 1097 1098 filter.replaceLinalgTransformationFilter(rewriter, conv1DOp); 1099 return success(); 1100 }; 1101 1102 private: 1103 /// LinalgTransformMarker handles special attribute manipulations. 1104 LinalgTransformationFilter filter; 1105 }; 1106 1107 } // namespace 1108 1109 void linalg::populateDecomposeConvolutionPatterns( 1110 RewritePatternSet &patterns, const LinalgTransformationFilter &filter, 1111 PatternBenefit benefit) { 1112 patterns.add<DownscaleSizeOneWindowed2DConvolution, 1113 DownscaleDepthwiseConv2DNhwcHwcOp>(patterns.getContext(), filter, 1114 benefit); 1115 } 1116