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