1 //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===// 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 the linalg dialect Vectorization transformations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Analysis/SliceAnalysis.h" 14 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.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/Transforms.h" 21 #include "mlir/Dialect/Linalg/Utils/Utils.h" 22 #include "mlir/Dialect/Tensor/IR/Tensor.h" 23 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 24 #include "mlir/Dialect/Vector/IR/VectorOps.h" 25 #include "mlir/Dialect/Vector/Transforms/VectorTransforms.h" 26 #include "mlir/IR/AffineExpr.h" 27 #include "mlir/IR/Matchers.h" 28 #include "mlir/IR/PatternMatch.h" 29 #include "mlir/Pass/Pass.h" 30 #include "mlir/Support/LLVM.h" 31 #include "mlir/Transforms/RegionUtils.h" 32 #include "llvm/ADT/ScopeExit.h" 33 #include "llvm/ADT/Sequence.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/TypeSwitch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <type_traits> 39 40 using namespace mlir; 41 using namespace mlir::linalg; 42 43 #define DEBUG_TYPE "linalg-vectorization" 44 45 #define DBGS() (llvm::dbgs() << '[' << DEBUG_TYPE << "] ") 46 #define LDBG(X) LLVM_DEBUG(DBGS() << X) 47 48 /// Try to vectorize `convOp` as a convolution. 49 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, 50 LinalgOp convOp); 51 52 /// Return the unique instance of OpType in `block` if it is indeed unique. 53 /// Return null if none or more than 1 instances exist. 54 template <typename OpType> 55 static OpType getSingleOpOfType(Block &block) { 56 OpType res; 57 block.walk([&](OpType op) { 58 if (res) { 59 res = nullptr; 60 return WalkResult::interrupt(); 61 } 62 res = op; 63 return WalkResult::advance(); 64 }); 65 return res; 66 } 67 68 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a 69 /// projectedPermutation, compress the unused dimensions to serve as a 70 /// permutation_map for a vector transfer operation. 71 /// For example, given a linalg op such as: 72 /// 73 /// ``` 74 /// %0 = linalg.generic { 75 /// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>, 76 /// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)> 77 /// } 78 /// ins(%0 : tensor<2x3x4xf32>) 79 /// outs(%1 : tensor<5x6xf32>) 80 /// ``` 81 /// 82 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine 83 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second 84 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`. 85 static AffineMap reindexIndexingMap(AffineMap map) { 86 assert(map.isProjectedPermutation(/*allowZeroInResults=*/true) && 87 "expected projected permutation"); 88 auto res = compressUnusedDims(map); 89 assert(res.getNumDims() == res.getNumResults() && 90 "expected reindexed map with same number of dims and results"); 91 return res; 92 } 93 94 /// Helper data structure to represent the result of vectorization. 95 /// In certain specific cases, like terminators, we do not want to propagate/ 96 enum VectorizationStatus { 97 /// Op failed to vectorize. 98 Failure = 0, 99 /// Op vectorized and custom function took care of replacement logic 100 NoReplace, 101 /// Op vectorized into a new Op whose results will replace original Op's 102 /// results. 103 NewOp 104 // TODO: support values if Op vectorized to Many-Ops whose results we need to 105 // aggregate for replacement. 106 }; 107 struct VectorizationResult { 108 /// Return status from vectorizing the current op. 109 enum VectorizationStatus status = VectorizationStatus::Failure; 110 /// New vectorized operation to replace the current op. 111 /// Replacement behavior is specified by `status`. 112 Operation *newOp; 113 }; 114 115 llvm::Optional<vector::CombiningKind> 116 mlir::linalg::getCombinerOpKind(Operation *combinerOp) { 117 using ::mlir::vector::CombiningKind; 118 119 if (!combinerOp) 120 return llvm::None; 121 return llvm::TypeSwitch<Operation *, llvm::Optional<CombiningKind>>( 122 combinerOp) 123 .Case<arith::AddIOp, arith::AddFOp>( 124 [&](auto op) { return CombiningKind::ADD; }) 125 .Case<arith::AndIOp>([&](auto op) { return CombiningKind::AND; }) 126 .Case<arith::MaxSIOp>([&](auto op) { return CombiningKind::MAXSI; }) 127 .Case<arith::MaxFOp>([&](auto op) { return CombiningKind::MAXF; }) 128 .Case<arith::MinSIOp>([&](auto op) { return CombiningKind::MINSI; }) 129 .Case<arith::MinFOp>([&](auto op) { return CombiningKind::MINF; }) 130 .Case<arith::MulIOp, arith::MulFOp>( 131 [&](auto op) { return CombiningKind::MUL; }) 132 .Case<arith::OrIOp>([&](auto op) { return CombiningKind::OR; }) 133 .Case<arith::XOrIOp>([&](auto op) { return CombiningKind::XOR; }) 134 .Default([&](auto op) { return llvm::None; }); 135 } 136 137 /// Check whether `outputOperand` is a reduction with a single combiner 138 /// operation. Return the combiner operation of the reduction. Return 139 /// nullptr otherwise. Multiple reduction operations would impose an 140 /// ordering between reduction dimensions and is currently unsupported in 141 /// Linalg. This limitation is motivated by the fact that e.g. min(max(X)) != 142 /// max(min(X)) 143 // TODO: use in LinalgOp verification, there is a circular dependency atm. 144 static Operation *matchLinalgReduction(OpOperand *outputOperand) { 145 auto linalgOp = cast<LinalgOp>(outputOperand->getOwner()); 146 unsigned outputPos = 147 outputOperand->getOperandNumber() - linalgOp.getNumInputs(); 148 // Only single combiner operations are supported for now. 149 SmallVector<Operation *, 4> combinerOps; 150 if (!matchReduction(linalgOp.getRegionOutputArgs(), outputPos, combinerOps) || 151 combinerOps.size() != 1) 152 return nullptr; 153 154 // Return the combiner operation. 155 return combinerOps[0]; 156 } 157 158 /// Broadcast `value` to a vector of `shape` if possible. Return value 159 /// otherwise. 160 static Value broadcastIfNeeded(OpBuilder &b, Value value, 161 ArrayRef<int64_t> shape) { 162 // If no shape to broadcast to, just return `value`. 163 if (shape.empty()) 164 return value; 165 VectorType targetVectorType = 166 VectorType::get(shape, getElementTypeOrSelf(value)); 167 if (vector::isBroadcastableTo(value.getType(), targetVectorType) != 168 vector::BroadcastableToResult::Success) 169 return value; 170 Location loc = b.getInsertionPoint()->getLoc(); 171 return b.createOrFold<vector::BroadcastOp>(loc, targetVectorType, value); 172 } 173 174 /// Create MultiDimReductionOp to compute the reduction for `reductionOp`. This 175 /// assumes that `reductionOp` has two operands and one of them is the reduction 176 /// initial value. 177 static Value buildMultiDimReduce(OpBuilder &b, Operation *reduceOp, 178 Value valueToReduce, 179 const SmallVector<bool> &reductionMask) { 180 auto maybeKind = getCombinerOpKind(reduceOp); 181 assert(maybeKind && "Failed precondition: could not get reduction kind"); 182 return b.create<vector::MultiDimReductionOp>( 183 reduceOp->getLoc(), valueToReduce, reductionMask, *maybeKind); 184 } 185 186 static SmallVector<bool> getReductionMask(LinalgOp linalgOp) { 187 unsigned idx = 0; 188 SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false); 189 for (auto attr : linalgOp.iterator_types()) { 190 if (isReductionIterator(attr)) 191 reductionMask[idx] = true; 192 ++idx; 193 } 194 return reductionMask; 195 } 196 197 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set 198 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp 199 /// currently being vectorized. If `dest` has null rank, build an memref.store. 200 /// Return the produced value or null if no value is produced. 201 static Value buildVectorWrite(OpBuilder &b, Value value, 202 OpOperand *outputOperand) { 203 Operation *write; 204 Location loc = value.getLoc(); 205 auto linalgOp = cast<LinalgOp>(outputOperand->getOwner()); 206 ArrayRef<int64_t> shape = linalgOp.getShape(outputOperand); 207 auto vectorType = VectorType::get( 208 shape, getElementTypeOrSelf(outputOperand->get().getType())); 209 if (vectorType.getRank() > 0) { 210 // 0-d case is still special: do not invert the reindexing map. 211 AffineMap map = 212 reindexIndexingMap(linalgOp.getTiedIndexingMap(outputOperand)); 213 SmallVector<int64_t> transposeShape = 214 applyPermutationMap(inversePermutation(map), vectorType.getShape()); 215 assert(!transposeShape.empty() && "unexpected empty transpose shape"); 216 vectorType = VectorType::get(transposeShape, vectorType.getElementType()); 217 SmallVector<Value> indices(linalgOp.getRank(outputOperand), 218 b.create<arith::ConstantIndexOp>(loc, 0)); 219 value = broadcastIfNeeded(b, value, vectorType.getShape()); 220 write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(), 221 indices, map); 222 } else { 223 if (!value.getType().isa<VectorType>()) 224 value = b.create<vector::BroadcastOp>(loc, vectorType, value); 225 assert(value.getType() == vectorType && "incorrect type"); 226 write = b.create<vector::TransferWriteOp>(loc, value, outputOperand->get(), 227 ValueRange{}); 228 } 229 LDBG("vectorized op: " << *write); 230 if (!write->getResults().empty()) 231 return write->getResult(0); 232 return Value(); 233 } 234 235 // Custom vectorization function type. Produce a vector form of Operation* 236 // assuming all its vectorized operands are already in the BlockAndValueMapping. 237 // Return nullptr if the Operation cannot be vectorized. 238 using CustomVectorizationHook = std::function<VectorizationResult( 239 Operation *, const BlockAndValueMapping &)>; 240 241 /// Helper function to vectorize the terminator of a `linalgOp`. New result 242 /// vector values are appended to `newResults`. Return 243 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it 244 /// should not try to map produced operations and instead return the results 245 /// using the `newResults` vector making them available to the 246 /// vectorization algorithm for RAUW. This function is meant to be used as a 247 /// CustomVectorizationHook. 248 static VectorizationResult 249 vectorizeLinalgYield(OpBuilder &b, Operation *op, 250 const BlockAndValueMapping &bvm, LinalgOp linalgOp, 251 SmallVectorImpl<Value> &newResults) { 252 auto yieldOp = dyn_cast<linalg::YieldOp>(op); 253 if (!yieldOp) 254 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 255 for (const auto &outputs : llvm::enumerate(yieldOp.values())) { 256 // TODO: Scan for an opportunity for reuse. 257 // TODO: use a map. 258 Value vectorValue = bvm.lookup(outputs.value()); 259 Value newResult = buildVectorWrite( 260 b, vectorValue, linalgOp.getOutputOperand(outputs.index())); 261 if (newResult) 262 newResults.push_back(newResult); 263 } 264 return VectorizationResult{VectorizationStatus::NoReplace, nullptr}; 265 } 266 267 /// Helper function to vectorize the index operations of a `linalgOp`. Return 268 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it 269 /// should map the produced operations. This function is meant to be used as a 270 /// CustomVectorizationHook. 271 static VectorizationResult vectorizeLinalgIndex(OpBuilder &b, Operation *op, 272 LinalgOp linalgOp) { 273 IndexOp indexOp = dyn_cast<linalg::IndexOp>(op); 274 if (!indexOp) 275 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 276 auto loc = indexOp.getLoc(); 277 // Compute the static loop sizes of the index op. 278 auto targetShape = linalgOp.computeStaticLoopSizes(); 279 // Compute a one-dimensional index vector for the index op dimension. 280 SmallVector<int64_t> constantSeq = 281 llvm::to_vector<16>(llvm::seq<int64_t>(0, targetShape[indexOp.dim()])); 282 auto constantOp = 283 b.create<arith::ConstantOp>(loc, b.getIndexVectorAttr(constantSeq)); 284 // Return the one-dimensional index vector if it lives in the trailing 285 // dimension of the iteration space since the vectorization algorithm in this 286 // case can handle the broadcast. 287 if (indexOp.dim() == targetShape.size() - 1) 288 return VectorizationResult{VectorizationStatus::NewOp, constantOp}; 289 // Otherwise permute the targetShape to move the index dimension last, 290 // broadcast the one-dimensional index vector to the permuted shape, and 291 // finally transpose the broadcasted index vector to undo the permutation. 292 std::swap(targetShape[indexOp.dim()], targetShape.back()); 293 auto broadCastOp = b.create<vector::BroadcastOp>( 294 loc, VectorType::get(targetShape, b.getIndexType()), constantOp); 295 SmallVector<int64_t> transposition = 296 llvm::to_vector<16>(llvm::seq<int64_t>(0, linalgOp.getNumLoops())); 297 std::swap(transposition.back(), transposition[indexOp.dim()]); 298 auto transposeOp = 299 b.create<vector::TransposeOp>(loc, broadCastOp, transposition); 300 return VectorizationResult{VectorizationStatus::NewOp, transposeOp}; 301 } 302 303 /// Emit reduction operations if the shapes of the value to reduce is different 304 /// that the result shape. 305 static Operation *reduceIfNeeded(OpBuilder &b, LinalgOp linalgOp, Operation *op, 306 Value reduceValue, Value initialValue, 307 const BlockAndValueMapping &bvm) { 308 Value reduceVec = bvm.lookup(reduceValue); 309 Value outputVec = bvm.lookup(initialValue); 310 auto reduceType = reduceVec.getType().dyn_cast<VectorType>(); 311 auto outputType = outputVec.getType().dyn_cast<VectorType>(); 312 // Reduce only if needed as the value may already have been reduce for 313 // contraction vectorization. 314 if (!reduceType || 315 (outputType && reduceType.getShape() == outputType.getShape())) 316 return nullptr; 317 SmallVector<bool> reductionMask = getReductionMask(linalgOp); 318 Value reduce = buildMultiDimReduce(b, op, reduceVec, reductionMask); 319 return b.create(op->getLoc(), op->getName().getIdentifier(), 320 /*operands=*/{reduce, outputVec}, reduce.getType(), 321 op->getAttrs()); 322 } 323 324 /// Generic vectorization for a single operation `op`, given already vectorized 325 /// operands carried by `bvm`. Vectorization occurs as follows: 326 /// 1. Try to apply any of the `customVectorizationHooks` and return its 327 /// result on success. 328 /// 2. Clone any constant in the current scope without vectorization: each 329 /// consumer of the constant will later determine the shape to which the 330 /// constant needs to be broadcast to. 331 /// 3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose 332 /// of the `customVectorizationHooks` to cover such cases. 333 /// 4. Clone `op` in vector form to a vector of shape prescribed by the first 334 /// operand of maximal rank. Other operands have smaller rank and are 335 /// broadcast accordingly. It is assumed this broadcast is always legal, 336 /// otherwise, it means one of the `customVectorizationHooks` is incorrect. 337 /// 338 /// This function assumes all operands of `op` have been vectorized and are in 339 /// the `bvm` mapping. As a consequence, this function is meant to be called on 340 /// a topologically-sorted list of ops. 341 /// This function does not update `bvm` but returns a VectorizationStatus that 342 /// instructs the caller what `bvm` update needs to occur. 343 static VectorizationResult 344 vectorizeOneOp(OpBuilder &b, LinalgOp linalgOp, Operation *op, 345 const BlockAndValueMapping &bvm, 346 ArrayRef<CustomVectorizationHook> customVectorizationHooks) { 347 LDBG("vectorize op " << *op); 348 349 // 1. Try to apply any CustomVectorizationHook. 350 if (!customVectorizationHooks.empty()) { 351 for (auto &customFunc : customVectorizationHooks) { 352 VectorizationResult result = customFunc(op, bvm); 353 if (result.status == VectorizationStatus::Failure) 354 continue; 355 return result; 356 } 357 } 358 359 // 2. Constant ops don't get vectorized but rather broadcasted at their users. 360 // Clone so that the constant is not confined to the linalgOp block . 361 if (isa<arith::ConstantOp, func::ConstantOp>(op)) 362 return VectorizationResult{VectorizationStatus::NewOp, b.clone(*op)}; 363 364 // 3. Only ElementwiseMappable are allowed in the generic vectorization. 365 if (!OpTrait::hasElementwiseMappableTraits(op)) 366 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 367 368 // 4 . Check if the operation is a reduction. 369 SmallVector<std::pair<Value, Value>> reductionOperands; 370 for (Value operand : op->getOperands()) { 371 auto arg = operand.dyn_cast<BlockArgument>(); 372 if (!arg || arg.getArgNumber() < linalgOp.getNumInputs()) 373 continue; 374 SmallVector<Operation *> reductionOps; 375 Value reduceValue = matchReduction( 376 linalgOp.getRegionOutputArgs(), 377 arg.getArgNumber() - linalgOp.getNumInputs(), reductionOps); 378 if (!reduceValue) 379 continue; 380 reductionOperands.push_back(std::make_pair(reduceValue, operand)); 381 } 382 if (!reductionOperands.empty()) { 383 assert(reductionOperands.size() == 1); 384 Operation *reduceOp = 385 reduceIfNeeded(b, linalgOp, op, reductionOperands[0].first, 386 reductionOperands[0].second, bvm); 387 if (reduceOp) 388 return VectorizationResult{VectorizationStatus::NewOp, reduceOp}; 389 } 390 391 // 5. Generic vectorization path for ElementwiseMappable ops. 392 // a. first get the first max ranked shape. 393 SmallVector<int64_t, 4> firstMaxRankedShape; 394 for (Value operand : op->getOperands()) { 395 auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>(); 396 if (vt && firstMaxRankedShape.size() < vt.getShape().size()) 397 firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end()); 398 } 399 // b. broadcast each op if needed. 400 auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) { 401 return firstMaxRankedShape.empty() 402 ? bvm.lookup(v) 403 : broadcastIfNeeded(b, bvm.lookup(v), firstMaxRankedShape); 404 }); 405 // c. for elementwise, the result is the vector with the firstMaxRankedShape 406 auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) { 407 return firstMaxRankedShape.empty() 408 ? t 409 : VectorType::get(firstMaxRankedShape, t); 410 }); 411 412 // Build and return the new op. 413 return VectorizationResult{ 414 VectorizationStatus::NewOp, 415 b.create(op->getLoc(), op->getName().getIdentifier(), 416 llvm::to_vector<4>(vectorizedOperands), 417 llvm::to_vector<4>(returnTypes), op->getAttrs())}; 418 } 419 420 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp. 421 static bool hasOnlyScalarElementwiseOp(Region &r) { 422 if (!llvm::hasSingleElement(r)) 423 return false; 424 for (Operation &op : r.front()) { 425 if (!(isa<arith::ConstantOp, func::ConstantOp, linalg::YieldOp, 426 linalg::IndexOp>(op) || 427 OpTrait::hasElementwiseMappableTraits(&op)) || 428 llvm::any_of(op.getResultTypes(), 429 [](Type type) { return !type.isIntOrIndexOrFloat(); })) 430 return false; 431 } 432 return true; 433 } 434 435 /// Returns `true` if all indexing maps of the linalg op are projected 436 /// permutations. 437 static bool allIndexingsAreProjectedPermutation(LinalgOp op) { 438 return llvm::all_of(op.getIndexingMaps(), [](AffineMap m) { 439 return m.isProjectedPermutation(/*allowZeroInResults=*/true); 440 }); 441 } 442 443 // Return true if the op is an element-wise linalg op. 444 static bool isElementwise(Operation *op) { 445 auto linalgOp = dyn_cast<linalg::LinalgOp>(op); 446 if (!linalgOp) 447 return false; 448 if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops()) 449 return false; 450 451 if (!allIndexingsAreProjectedPermutation(linalgOp)) 452 return false; 453 454 // TODO: relax the restrictions on indexing map. 455 for (OpOperand *opOperand : linalgOp.getOutputOperands()) { 456 if (!linalgOp.getTiedIndexingMap(opOperand).isPermutation()) 457 return false; 458 } 459 return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0)); 460 } 461 462 /// Generic vectorization function that rewrites the body of a `linalgOp` into 463 /// vector form. Generic vectorization proceeds as follows: 464 /// 1. Verify the `linalgOp` has one non-empty region. 465 /// 2. Values defined above the region are mapped to themselves and will be 466 /// broadcasted on a per-need basis by their consumers. 467 /// 3. Each region argument is vectorized into a vector.transfer_read (or 0-d 468 /// load). 469 /// TODO: Reuse opportunities for RAR dependencies. 470 /// 4a. Register CustomVectorizationHook for YieldOp to capture the results. 471 /// 4b. Register CustomVectorizationHook for IndexOp to access the iteration 472 /// indices. 473 /// 5. Iteratively call vectorizeOneOp on the region operations. 474 /// 475 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is 476 /// performed to the maximal common vector size implied by the `linalgOp` 477 /// iteration space. This eager broadcasting is introduced in the 478 /// permutation_map of the vector.transfer_read operations. The eager 479 /// broadcasting makes it trivial to detrmine where broadcast, transposes and 480 /// reductions should occur, without any bookkeeping. The tradeoff is that, in 481 /// the absence of good canonicalizations, the amount of work increases. 482 /// This is not deemed a problem as we expect canonicalizations and foldings to 483 /// aggressively clean up the useless work. 484 static LogicalResult 485 vectorizeAsLinalgGeneric(OpBuilder &b, LinalgOp linalgOp, 486 SmallVectorImpl<Value> &newResults) { 487 Block *block = linalgOp.getBlock(); 488 489 // 2. Values defined above the region can only be broadcast for now. Make them 490 // map to themselves. 491 BlockAndValueMapping bvm; 492 SetVector<Value> valuesSet; 493 mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet); 494 bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef()); 495 496 if (linalgOp.getNumOutputs() == 0) 497 return failure(); 498 499 // TODO: the common vector shape is equal to the static loop sizes only when 500 // all indexing maps are projected permutations. For convs and stencils the 501 // logic will need to evolve. 502 SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes(); 503 504 // 3. Turn all BBArgs into vector.transfer_read / load. 505 Location loc = linalgOp.getLoc(); 506 Value zero = b.create<arith::ConstantIndexOp>(loc, 0); 507 for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) { 508 BlockArgument bbarg = block->getArgument(opOperand->getOperandNumber()); 509 if (linalgOp.isScalar(opOperand)) { 510 bvm.map(bbarg, opOperand->get()); 511 continue; 512 } 513 VectorType readType; 514 AffineMap map; 515 // TODO: can we keep this simplification? 516 // if (linalgOp.getShape(opOperand).empty()) { 517 // readType = VectorType::get({}, bbarg.getType()); 518 // } else { 519 if (opOperand->getOperandNumber() < linalgOp.getNumInputs()) { 520 map = inverseAndBroadcastProjectedPermutation( 521 linalgOp.getTiedIndexingMap(opOperand)); 522 readType = VectorType::get(commonVectorShape, 523 getElementTypeOrSelf(opOperand->get())); 524 } else { 525 map = inversePermutation( 526 reindexIndexingMap(linalgOp.getTiedIndexingMap(opOperand))); 527 readType = VectorType::get(map.compose(linalgOp.getShape(opOperand)), 528 getElementTypeOrSelf(opOperand->get())); 529 } 530 // } 531 532 auto shape = linalgOp.getShape(opOperand); 533 SmallVector<Value> indices(shape.size(), zero); 534 Value readValue = b.create<vector::TransferReadOp>( 535 loc, readType, opOperand->get(), indices, map); 536 // Not all ops support 0-d vectors, extract the scalar for now. 537 // TODO: remove this. 538 if (readValue.getType().cast<VectorType>().getRank() == 0) 539 readValue = b.create<vector::ExtractElementOp>(loc, readValue); 540 541 LDBG("new vectorized bbarg(" << bbarg.getArgNumber() << "): " << readValue); 542 bvm.map(bbarg, readValue); 543 bvm.map(opOperand->get(), readValue); 544 } 545 546 SmallVector<CustomVectorizationHook> hooks; 547 // 4a. Register CustomVectorizationHook for yieldOp. 548 CustomVectorizationHook vectorizeYield = 549 [&](Operation *op, 550 const BlockAndValueMapping &bvm) -> VectorizationResult { 551 return vectorizeLinalgYield(b, op, bvm, linalgOp, newResults); 552 }; 553 hooks.push_back(vectorizeYield); 554 555 // 4b. Register CustomVectorizationHook for indexOp. 556 CustomVectorizationHook vectorizeIndex = 557 [&](Operation *op, 558 const BlockAndValueMapping &bvm) -> VectorizationResult { 559 return vectorizeLinalgIndex(b, op, linalgOp); 560 }; 561 hooks.push_back(vectorizeIndex); 562 563 // 5. Iteratively call `vectorizeOneOp` to each op in the slice. 564 for (Operation &op : block->getOperations()) { 565 VectorizationResult result = vectorizeOneOp(b, linalgOp, &op, bvm, hooks); 566 if (result.status == VectorizationStatus::Failure) { 567 LDBG("failed to vectorize: " << op); 568 return failure(); 569 } 570 if (result.status == VectorizationStatus::NewOp) { 571 LDBG("new vector op: " << *result.newOp;); 572 bvm.map(op.getResults(), result.newOp->getResults()); 573 } 574 } 575 576 return success(); 577 } 578 579 // TODO: probably need some extra checks for reduction followed by consumer 580 // ops that may not commute (e.g. linear reduction + non-linear instructions). 581 static LogicalResult reductionPreconditions(LinalgOp op) { 582 if (llvm::none_of(op.iterator_types(), isReductionIterator)) { 583 LDBG("reduction precondition failed: no reduction iterator"); 584 return failure(); 585 } 586 for (OpOperand *opOperand : op.getOutputOperands()) { 587 Operation *reduceOp = matchLinalgReduction(opOperand); 588 if (!reduceOp || !getCombinerOpKind(reduceOp)) { 589 LDBG("reduction precondition failed: reduction detection failed"); 590 return failure(); 591 } 592 } 593 return success(); 594 } 595 596 static LogicalResult vectorizeStaticLinalgOpPrecondition(linalg::LinalgOp op) { 597 if (isElementwise(op)) 598 return success(); 599 // TODO: isaConvolutionOpInterface that can also infer from generic features. 600 // But we will still need stride/dilation attributes that will be annoying to 601 // reverse-engineer... 602 if (isa<ConvolutionOpInterface>(op.getOperation())) 603 return success(); 604 // TODO: the common vector shape is equal to the static loop sizes only when 605 // all indexing maps are projected permutations. For convs and stencils the 606 // logic will need to evolve. 607 if (!allIndexingsAreProjectedPermutation(op)) { 608 LDBG("precondition failed: not projected permutations"); 609 return failure(); 610 } 611 if (failed(reductionPreconditions(op))) { 612 LDBG("precondition failed: reduction preconditions"); 613 return failure(); 614 } 615 return success(); 616 } 617 618 static LogicalResult vectorizeLinalgOpPrecondition(LinalgOp linalgOp) { 619 // All types must be static shape to go to vector. 620 if (linalgOp.hasDynamicShape()) { 621 LDBG("precondition failed: dynamic shape"); 622 return failure(); 623 } 624 return vectorizeStaticLinalgOpPrecondition(linalgOp); 625 } 626 627 LogicalResult mlir::linalg::vectorize(RewriterBase &rewriter, 628 LinalgOp linalgOp) { 629 if (failed(vectorizeLinalgOpPrecondition(linalgOp))) 630 return failure(); 631 632 SmallVector<Value> results; 633 // TODO: isaConvolutionOpInterface that can also infer from generic 634 // features. Will require stride/dilation attributes inference. 635 FailureOr<Operation *> convOr = vectorizeConvolution(rewriter, linalgOp); 636 if (succeeded(convOr)) { 637 llvm::append_range(results, (*convOr)->getResults()); 638 } else { 639 if (failed(vectorizeLinalgOpPrecondition(linalgOp))) 640 return failure(); 641 LDBG("Vectorize generic by broadcasting to a common shape: " << linalgOp); 642 if (failed(vectorizeAsLinalgGeneric(rewriter, linalgOp, results))) 643 return failure(); 644 } 645 646 if (!results.empty()) 647 rewriter.replaceOp(linalgOp, results); 648 else 649 rewriter.eraseOp(linalgOp); 650 651 return success(); 652 } 653 654 LogicalResult mlir::linalg::vectorizeCopy(RewriterBase &rewriter, 655 memref::CopyOp copyOp) { 656 657 auto srcType = copyOp.source().getType().cast<MemRefType>(); 658 auto dstType = copyOp.target().getType().cast<MemRefType>(); 659 if (!srcType.hasStaticShape() || !dstType.hasStaticShape()) 660 return failure(); 661 662 auto readType = 663 VectorType::get(srcType.getShape(), getElementTypeOrSelf(srcType)); 664 auto writeType = 665 VectorType::get(dstType.getShape(), getElementTypeOrSelf(dstType)); 666 667 Location loc = copyOp->getLoc(); 668 Value zero = rewriter.create<arith::ConstantIndexOp>(loc, 0); 669 SmallVector<Value> indices(srcType.getRank(), zero); 670 671 Value readValue = rewriter.create<vector::TransferReadOp>( 672 loc, readType, copyOp.source(), indices, 673 rewriter.getMultiDimIdentityMap(srcType.getRank())); 674 if (readValue.getType().cast<VectorType>().getRank() == 0) { 675 readValue = rewriter.create<vector::ExtractElementOp>(loc, readValue); 676 readValue = rewriter.create<vector::BroadcastOp>(loc, writeType, readValue); 677 } 678 Operation *writeValue = rewriter.create<vector::TransferWriteOp>( 679 loc, readValue, copyOp.target(), indices, 680 rewriter.getMultiDimIdentityMap(srcType.getRank())); 681 rewriter.replaceOp(copyOp, writeValue->getResults()); 682 return success(); 683 } 684 685 //----------------------------------------------------------------------------// 686 // Misc. vectorization patterns. 687 //----------------------------------------------------------------------------// 688 689 /// Helper function that retrieves the value of an IntegerAttr. 690 static int64_t getIntFromAttr(Attribute attr) { 691 return attr.cast<IntegerAttr>().getInt(); 692 } 693 694 /// Given an ArrayRef of OpFoldResults, return a vector of Values. 695 /// IntegerAttrs are converted to ConstantIndexOps. Other attribute types are 696 /// not supported. 697 static SmallVector<Value> ofrToIndexValues(OpBuilder &builder, Location loc, 698 ArrayRef<OpFoldResult> ofrs) { 699 SmallVector<Value> result; 700 llvm::for_each(ofrs, [&](auto o) { 701 if (auto val = o.template dyn_cast<Value>()) { 702 result.push_back(val); 703 } else { 704 result.push_back(builder.create<arith::ConstantIndexOp>( 705 loc, getIntFromAttr(o.template get<Attribute>()))); 706 } 707 }); 708 return result; 709 } 710 711 /// Rewrite a tensor::PadOp into a sequence of InitTensorOp, FillOp and 712 /// InsertSliceOp. For now, only constant padding values are supported. 713 /// If there is enough static type information, TransferReadOps and 714 /// TransferWriteOps may be generated instead of InsertSliceOps. 715 struct GenericPadOpVectorizationPattern : public GeneralizePadOpPattern { 716 GenericPadOpVectorizationPattern(MLIRContext *context, 717 PatternBenefit benefit = 1) 718 : GeneralizePadOpPattern(context, tryVectorizeCopy, benefit) {} 719 /// Vectorize the copying of a tensor::PadOp's source. This is possible if 720 /// each dimension size is statically know in the source type or the result 721 /// type (or both). 722 static LogicalResult tryVectorizeCopy(PatternRewriter &rewriter, 723 tensor::PadOp padOp, Value dest) { 724 auto sourceType = padOp.getSourceType(); 725 auto resultType = padOp.getResultType(); 726 727 // Copy cannot be vectorized if pad value is non-constant and source shape 728 // is dynamic. In case of a dynamic source shape, padding must be appended 729 // by TransferReadOp, but TransferReadOp supports only constant padding. 730 auto padValue = padOp.getConstantPaddingValue(); 731 if (!padValue) { 732 if (!sourceType.hasStaticShape()) 733 return failure(); 734 // Create dummy padding value. 735 auto elemType = sourceType.getElementType(); 736 padValue = rewriter.create<arith::ConstantOp>( 737 padOp.getLoc(), elemType, rewriter.getZeroAttr(elemType)); 738 } 739 740 SmallVector<int64_t> vecShape; 741 SmallVector<bool> readInBounds; 742 SmallVector<bool> writeInBounds; 743 for (unsigned i = 0; i < sourceType.getRank(); ++i) { 744 if (!sourceType.isDynamicDim(i)) { 745 vecShape.push_back(sourceType.getDimSize(i)); 746 // Source shape is statically known: Neither read nor write are 747 // out-of- bounds. 748 readInBounds.push_back(true); 749 writeInBounds.push_back(true); 750 } else if (!resultType.isDynamicDim(i)) { 751 // Source shape is not statically known, but result shape is. 752 // Vectorize with size of result shape. This may be larger than the 753 // source size. 754 vecShape.push_back(resultType.getDimSize(i)); 755 // Read may be out-of-bounds because the result size could be larger 756 // than the source size. 757 readInBounds.push_back(false); 758 // Write is out-of-bounds if low padding > 0. 759 writeInBounds.push_back( 760 getConstantIntValue(padOp.getMixedLowPad()[i]) == 761 static_cast<int64_t>(0)); 762 } else { 763 // Neither source nor result dim of padOp is static. Cannot vectorize 764 // the copy. 765 return failure(); 766 } 767 } 768 auto vecType = VectorType::get(vecShape, sourceType.getElementType()); 769 770 // Generate TransferReadOp. 771 SmallVector<Value> readIndices( 772 vecType.getRank(), 773 rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0)); 774 auto read = rewriter.create<vector::TransferReadOp>( 775 padOp.getLoc(), vecType, padOp.source(), readIndices, padValue, 776 ArrayRef<bool>{readInBounds}); 777 778 // If `dest` is a FillOp and the TransferWriteOp would overwrite the 779 // entire tensor, write directly to the FillOp's operand. 780 if (llvm::equal(vecShape, resultType.getShape()) && 781 llvm::all_of(writeInBounds, [](bool b) { return b; })) 782 if (auto fill = dest.getDefiningOp<FillOp>()) 783 dest = fill.output(); 784 785 // Generate TransferWriteOp. 786 auto writeIndices = 787 ofrToIndexValues(rewriter, padOp.getLoc(), padOp.getMixedLowPad()); 788 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>( 789 padOp, read, dest, writeIndices, ArrayRef<bool>{writeInBounds}); 790 791 return success(); 792 } 793 }; 794 795 /// Base pattern for rewriting tensor::PadOps whose result is consumed by a 796 /// given operation type OpTy. 797 template <typename OpTy> 798 struct VectorizePadOpUserPattern : public OpRewritePattern<tensor::PadOp> { 799 using OpRewritePattern<tensor::PadOp>::OpRewritePattern; 800 801 LogicalResult matchAndRewrite(tensor::PadOp padOp, 802 PatternRewriter &rewriter) const final { 803 bool changed = false; 804 // Insert users in vector, because some users may be replaced/removed. 805 for (auto *user : llvm::to_vector<4>(padOp->getUsers())) 806 if (auto op = dyn_cast<OpTy>(user)) 807 changed |= rewriteUser(rewriter, padOp, op).succeeded(); 808 return success(changed); 809 } 810 811 protected: 812 virtual LogicalResult rewriteUser(PatternRewriter &rewriter, 813 tensor::PadOp padOp, OpTy op) const = 0; 814 }; 815 816 /// Rewrite use of tensor::PadOp result in TransferReadOp. E.g.: 817 /// ``` 818 /// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32> 819 /// %r = vector.transfer_read %0[%c0, %c0], %cst 820 /// {in_bounds = [true, true]} : tensor<17x5xf32>, vector<17x5xf32> 821 /// ``` 822 /// is rewritten to: 823 /// ``` 824 /// %r = vector.transfer_read %src[%c0, %c0], %padding 825 /// {in_bounds = [true, true]} 826 /// : tensor<?x?xf32>, vector<17x5xf32> 827 /// ``` 828 /// Note: By restricting this pattern to in-bounds TransferReadOps, we can be 829 /// sure that the original padding value %cst was never used. 830 /// 831 /// This rewrite is possible if: 832 /// - `xferOp` has no out-of-bounds dims or mask. 833 /// - Low padding is static 0. 834 /// - Single, scalar padding value. 835 struct PadOpVectorizationWithTransferReadPattern 836 : public VectorizePadOpUserPattern<vector::TransferReadOp> { 837 using VectorizePadOpUserPattern< 838 vector::TransferReadOp>::VectorizePadOpUserPattern; 839 840 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp, 841 vector::TransferReadOp xferOp) const override { 842 // Low padding must be static 0. 843 if (!padOp.hasZeroLowPad()) 844 return failure(); 845 // Pad value must be a constant. 846 auto padValue = padOp.getConstantPaddingValue(); 847 if (!padValue) 848 return failure(); 849 // Padding value of existing `xferOp` is unused. 850 if (xferOp.hasOutOfBoundsDim() || xferOp.getMask()) 851 return failure(); 852 853 rewriter.updateRootInPlace(xferOp, [&]() { 854 SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false); 855 xferOp->setAttr(xferOp.getInBoundsAttrName(), 856 rewriter.getBoolArrayAttr(inBounds)); 857 xferOp.getSourceMutable().assign(padOp.source()); 858 xferOp.getPaddingMutable().assign(padValue); 859 }); 860 861 return success(); 862 } 863 }; 864 865 /// Rewrite use of tensor::PadOp result in TransferWriteOp. 866 /// This pattern rewrites TransferWriteOps that write to a padded tensor 867 /// value, where the same amount of padding is immediately removed again after 868 /// the write. In such cases, the TransferWriteOp can write to the non-padded 869 /// tensor value and apply out-of-bounds masking. E.g.: 870 /// ``` 871 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1] 872 /// : tensor<...> to tensor<?x?xf32> 873 /// %1 = tensor.pad %0 ... : tensor<?x?xf32> to tensor<17x5xf32> 874 /// %2 = vector.transfer_write %vec, %1[...] 875 /// : vector<17x5xf32>, tensor<17x5xf32> 876 /// %r = tensor.extract_slice %2[0, 0] [%s0, %s1] [1, 1] 877 /// : tensor<17x5xf32> to tensor<?x?xf32> 878 /// ``` 879 /// is rewritten to: 880 /// ``` 881 /// %0 = tensor.extract_slice ...[...] [%s0, %s1] [1, 1] 882 /// : tensor<...> to tensor<?x?xf32> 883 /// %r = vector.transfer_write %vec, %0[...] : vector<17x5xf32>, 884 /// tensor<?x?xf32> 885 /// ``` 886 /// Note: It is important that the ExtractSliceOp %r resizes the result of the 887 /// TransferWriteOp to the same size as the input of the TensorPadOp (or an 888 /// even smaller size). Otherwise, %r's new (dynamic) dimensions would differ 889 /// from %r's old dimensions. 890 /// 891 /// This rewrite is possible if: 892 /// - Low padding is static 0. 893 /// - `xferOp` has exactly one use, which is an ExtractSliceOp. This 894 /// ExtractSliceOp trims the same amount of padding that was added 895 /// beforehand. 896 /// - Single, scalar padding value. 897 struct PadOpVectorizationWithTransferWritePattern 898 : public VectorizePadOpUserPattern<vector::TransferWriteOp> { 899 using VectorizePadOpUserPattern< 900 vector::TransferWriteOp>::VectorizePadOpUserPattern; 901 902 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp, 903 vector::TransferWriteOp xferOp) const override { 904 // TODO: support 0-d corner case. 905 if (xferOp.getTransferRank() == 0) 906 return failure(); 907 908 // Low padding must be static 0. 909 if (!padOp.hasZeroLowPad()) 910 return failure(); 911 // Pad value must be a constant. 912 auto padValue = padOp.getConstantPaddingValue(); 913 if (!padValue) 914 return failure(); 915 // TransferWriteOp result must be directly consumed by an ExtractSliceOp. 916 if (!xferOp->hasOneUse()) 917 return failure(); 918 auto trimPadding = dyn_cast<tensor::ExtractSliceOp>(*xferOp->user_begin()); 919 if (!trimPadding) 920 return failure(); 921 // Only static zero offsets supported when trimming padding. 922 if (!trimPadding.hasZeroOffset()) 923 return failure(); 924 // trimPadding must remove the amount of padding that was added earlier. 925 if (!hasSameTensorSize(padOp.source(), trimPadding)) 926 return failure(); 927 928 // Insert the new TransferWriteOp at position of the old TransferWriteOp. 929 rewriter.setInsertionPoint(xferOp); 930 931 SmallVector<bool> inBounds(xferOp.getVectorType().getRank(), false); 932 auto newXferOp = rewriter.replaceOpWithNewOp<vector::TransferWriteOp>( 933 xferOp, padOp.source().getType(), xferOp.getVector(), padOp.source(), 934 xferOp.getIndices(), xferOp.getPermutationMapAttr(), xferOp.getMask(), 935 rewriter.getBoolArrayAttr(inBounds)); 936 rewriter.replaceOp(trimPadding, newXferOp->getResult(0)); 937 938 return success(); 939 } 940 941 /// Check if `beforePadding` and `afterTrimming` have the same tensor size, 942 /// i.e., same dimensions. 943 /// 944 /// Dimensions may be static, dynamic or mix of both. In case of dynamic 945 /// dimensions, this function tries to infer the (static) tensor size by 946 /// looking at the defining op and utilizing op-specific knowledge. 947 /// 948 /// This is a conservative analysis. In case equal tensor sizes cannot be 949 /// proven statically, this analysis returns `false` even though the tensor 950 /// sizes may turn out to be equal at runtime. 951 bool hasSameTensorSize(Value beforePadding, 952 tensor::ExtractSliceOp afterTrimming) const { 953 // If the input to tensor::PadOp is a CastOp, try with with both CastOp 954 // result and CastOp operand. 955 if (auto castOp = beforePadding.getDefiningOp<tensor::CastOp>()) 956 if (hasSameTensorSize(castOp.source(), afterTrimming)) 957 return true; 958 959 auto t1 = beforePadding.getType().dyn_cast<RankedTensorType>(); 960 auto t2 = afterTrimming.getType().dyn_cast<RankedTensorType>(); 961 // Only RankedTensorType supported. 962 if (!t1 || !t2) 963 return false; 964 // Rank of both values must be the same. 965 if (t1.getRank() != t2.getRank()) 966 return false; 967 968 // All static dimensions must be the same. Mixed cases (e.g., dimension 969 // static in `t1` but dynamic in `t2`) are not supported. 970 for (unsigned i = 0; i < t1.getRank(); ++i) { 971 if (t1.isDynamicDim(i) != t2.isDynamicDim(i)) 972 return false; 973 if (!t1.isDynamicDim(i) && t1.getDimSize(i) != t2.getDimSize(i)) 974 return false; 975 } 976 977 // Nothing more to check if all dimensions are static. 978 if (t1.getNumDynamicDims() == 0) 979 return true; 980 981 // All dynamic sizes must be the same. The only supported case at the 982 // moment is when `beforePadding` is an ExtractSliceOp (or a cast 983 // thereof). 984 985 // Apart from CastOp, only ExtractSliceOp is supported. 986 auto beforeSlice = beforePadding.getDefiningOp<tensor::ExtractSliceOp>(); 987 if (!beforeSlice) 988 return false; 989 990 assert(static_cast<size_t>(t1.getRank()) == 991 beforeSlice.getMixedSizes().size()); 992 assert(static_cast<size_t>(t2.getRank()) == 993 afterTrimming.getMixedSizes().size()); 994 995 for (unsigned i = 0; i < t1.getRank(); ++i) { 996 // Skip static dimensions. 997 if (!t1.isDynamicDim(i)) 998 continue; 999 auto size1 = beforeSlice.getMixedSizes()[i]; 1000 auto size2 = afterTrimming.getMixedSizes()[i]; 1001 1002 // Case 1: Same value or same constant int. 1003 if (isEqualConstantIntOrValue(size1, size2)) 1004 continue; 1005 1006 // Other cases: Take a deeper look at defining ops of values. 1007 auto v1 = size1.dyn_cast<Value>(); 1008 auto v2 = size2.dyn_cast<Value>(); 1009 if (!v1 || !v2) 1010 return false; 1011 1012 // Case 2: Both values are identical AffineMinOps. (Should not happen if 1013 // CSE is run.) 1014 auto minOp1 = v1.getDefiningOp<AffineMinOp>(); 1015 auto minOp2 = v2.getDefiningOp<AffineMinOp>(); 1016 if (minOp1 && minOp2 && minOp1.getAffineMap() == minOp2.getAffineMap() && 1017 minOp1.operands() == minOp2.operands()) 1018 continue; 1019 1020 // Add additional cases as needed. 1021 } 1022 1023 // All tests passed. 1024 return true; 1025 } 1026 }; 1027 1028 /// Rewrite use of tensor::PadOp result in InsertSliceOp. E.g.: 1029 /// ``` 1030 /// %0 = tensor.pad %src ... : tensor<?x?xf32> to tensor<17x5xf32> 1031 /// %r = tensor.insert_slice %0 1032 /// into %dest[%a, %b, 0, 0] [1, 1, 17, 5] [1, 1, 1, 1] 1033 /// : tensor<17x5xf32> into tensor<?x?x17x5xf32> 1034 /// ``` 1035 /// is rewritten to: 1036 /// ``` 1037 /// %0 = vector.transfer_read %src[%c0, %c0], %padding 1038 /// : tensor<?x?xf32>, vector<17x5xf32> 1039 /// %r = vector.transfer_write %0, %dest[%a, %b, %c0, %c0] 1040 /// {in_bounds = [true, true]} : vector<17x5xf32>, tensor<?x?x17x5xf32> 1041 /// ``` 1042 /// 1043 /// This rewrite is possible if: 1044 /// - Low padding is static 0. 1045 /// - `padOp` result shape is static. 1046 /// - The entire padded tensor is inserted. 1047 /// (Implies that sizes of `insertOp` are all static.) 1048 /// - Only unit strides in `insertOp`. 1049 /// - Single, scalar padding value. 1050 /// - `padOp` result not used as destination. 1051 struct PadOpVectorizationWithInsertSlicePattern 1052 : public VectorizePadOpUserPattern<tensor::InsertSliceOp> { 1053 using VectorizePadOpUserPattern< 1054 tensor::InsertSliceOp>::VectorizePadOpUserPattern; 1055 1056 LogicalResult rewriteUser(PatternRewriter &rewriter, tensor::PadOp padOp, 1057 tensor::InsertSliceOp insertOp) const override { 1058 // Low padding must be static 0. 1059 if (!padOp.hasZeroLowPad()) 1060 return failure(); 1061 // Only unit stride supported. 1062 if (!insertOp.hasUnitStride()) 1063 return failure(); 1064 // Pad value must be a constant. 1065 auto padValue = padOp.getConstantPaddingValue(); 1066 if (!padValue) 1067 return failure(); 1068 // Dynamic shapes not supported. 1069 if (!padOp.result().getType().cast<ShapedType>().hasStaticShape()) 1070 return failure(); 1071 // Pad result not used as destination. 1072 if (insertOp.dest() == padOp.result()) 1073 return failure(); 1074 1075 auto vecType = VectorType::get(padOp.getType().getShape(), 1076 padOp.getType().getElementType()); 1077 unsigned vecRank = vecType.getRank(); 1078 unsigned tensorRank = insertOp.getType().getRank(); 1079 1080 // Check if sizes match: Insert the entire tensor into most minor dims. 1081 // (No permutations allowed.) 1082 SmallVector<int64_t> expectedSizes(tensorRank - vecRank, 1); 1083 expectedSizes.append(vecType.getShape().begin(), vecType.getShape().end()); 1084 if (!llvm::all_of( 1085 llvm::zip(insertOp.getMixedSizes(), expectedSizes), [](auto it) { 1086 return getConstantIntValue(std::get<0>(it)) == std::get<1>(it); 1087 })) 1088 return failure(); 1089 1090 // Insert the TransferReadOp and TransferWriteOp at the position of the 1091 // InsertSliceOp. 1092 rewriter.setInsertionPoint(insertOp); 1093 1094 // Generate TransferReadOp: Read entire source tensor and add high 1095 // padding. 1096 SmallVector<Value> readIndices( 1097 vecRank, rewriter.create<arith::ConstantIndexOp>(padOp.getLoc(), 0)); 1098 auto read = rewriter.create<vector::TransferReadOp>( 1099 padOp.getLoc(), vecType, padOp.source(), readIndices, padValue); 1100 1101 // Generate TransferWriteOp: Write to InsertSliceOp's dest tensor at 1102 // specified offsets. Write is fully in-bounds because a InsertSliceOp's 1103 // source must fit into the destination at the specified offsets. 1104 auto writeIndices = 1105 ofrToIndexValues(rewriter, padOp.getLoc(), insertOp.getMixedOffsets()); 1106 SmallVector<bool> inBounds(vecRank, true); 1107 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>( 1108 insertOp, read, insertOp.dest(), writeIndices, 1109 ArrayRef<bool>{inBounds}); 1110 1111 return success(); 1112 } 1113 }; 1114 1115 void mlir::linalg::populatePadOpVectorizationPatterns( 1116 RewritePatternSet &patterns, PatternBenefit baseBenefit) { 1117 patterns.add<GenericPadOpVectorizationPattern>(patterns.getContext(), 1118 baseBenefit); 1119 // Try these specialized patterns first before resorting to the generic one. 1120 patterns.add<PadOpVectorizationWithTransferReadPattern, 1121 PadOpVectorizationWithTransferWritePattern, 1122 PadOpVectorizationWithInsertSlicePattern>( 1123 patterns.getContext(), baseBenefit.getBenefit() + 1); 1124 } 1125 1126 //----------------------------------------------------------------------------// 1127 // Forwarding patterns 1128 //----------------------------------------------------------------------------// 1129 1130 /// Check whether there is any interleaved use of any `values` between 1131 /// `firstOp` and `secondOp`. Conservatively return `true` if any op or value 1132 /// is in a different block. 1133 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp, 1134 ValueRange values) { 1135 if (firstOp->getBlock() != secondOp->getBlock() || 1136 !firstOp->isBeforeInBlock(secondOp)) { 1137 LDBG("interleavedUses precondition failed, firstOp: " 1138 << *firstOp << ", second op: " << *secondOp); 1139 return true; 1140 } 1141 for (auto v : values) { 1142 for (auto &u : v.getUses()) { 1143 Operation *owner = u.getOwner(); 1144 if (owner == firstOp || owner == secondOp) 1145 continue; 1146 // TODO: this is too conservative, use dominance info in the future. 1147 if (owner->getBlock() == firstOp->getBlock() && 1148 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner))) 1149 continue; 1150 LDBG(" found interleaved op " << *owner << ", firstOp: " << *firstOp 1151 << ", second op: " << *secondOp); 1152 return true; 1153 } 1154 } 1155 return false; 1156 } 1157 1158 /// Return the unique subview use of `v` if it is indeed unique, null 1159 /// otherwise. 1160 static memref::SubViewOp getSubViewUseIfUnique(Value v) { 1161 memref::SubViewOp subViewOp; 1162 for (auto &u : v.getUses()) { 1163 if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) { 1164 if (subViewOp) 1165 return memref::SubViewOp(); 1166 subViewOp = newSubViewOp; 1167 } 1168 } 1169 return subViewOp; 1170 } 1171 1172 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 1173 /// when available. 1174 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite( 1175 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const { 1176 1177 // TODO: support mask. 1178 if (xferOp.getMask()) 1179 return failure(); 1180 1181 // Transfer into `view`. 1182 Value viewOrAlloc = xferOp.getSource(); 1183 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 1184 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 1185 return failure(); 1186 1187 LDBG(viewOrAlloc); 1188 1189 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 1190 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 1191 if (!subViewOp) 1192 return failure(); 1193 Value subView = subViewOp.getResult(); 1194 LDBG("with subView " << subView); 1195 1196 // Find the copy into `subView` without interleaved uses. 1197 memref::CopyOp copyOp; 1198 for (auto &u : subView.getUses()) { 1199 if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) { 1200 assert(newCopyOp.target().getType().isa<MemRefType>()); 1201 if (newCopyOp.target() != subView) 1202 continue; 1203 LDBG("copy candidate " << *newCopyOp); 1204 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView})) 1205 continue; 1206 copyOp = newCopyOp; 1207 break; 1208 } 1209 } 1210 if (!copyOp) 1211 return failure(); 1212 LDBG("with copy " << *copyOp); 1213 1214 // Find the fill into `viewOrAlloc` without interleaved uses before the 1215 // copy. 1216 FillOp maybeFillOp; 1217 for (auto &u : viewOrAlloc.getUses()) { 1218 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) { 1219 assert(newFillOp.output().getType().isa<MemRefType>()); 1220 if (newFillOp.output() != viewOrAlloc) 1221 continue; 1222 LDBG("fill candidate " << *newFillOp); 1223 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView})) 1224 continue; 1225 maybeFillOp = newFillOp; 1226 break; 1227 } 1228 } 1229 // Ensure padding matches. 1230 if (maybeFillOp && xferOp.getPadding() != maybeFillOp.value()) 1231 return failure(); 1232 if (maybeFillOp) 1233 LDBG("with maybeFillOp " << *maybeFillOp); 1234 1235 // `in` is the subview that memref.copy reads. Replace it. 1236 Value in = copyOp.source(); 1237 1238 // memref.copy + linalg.fill can be used to create a padded local buffer. 1239 // The `masked` attribute is only valid on this padded buffer. 1240 // When forwarding to vector.transfer_read, the attribute must be reset 1241 // conservatively. 1242 Value res = rewriter.create<vector::TransferReadOp>( 1243 xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.getIndices(), 1244 xferOp.getPermutationMapAttr(), xferOp.getPadding(), xferOp.getMask(), 1245 // in_bounds is explicitly reset 1246 /*inBoundsAttr=*/ArrayAttr()); 1247 1248 if (maybeFillOp) 1249 rewriter.eraseOp(maybeFillOp); 1250 rewriter.eraseOp(copyOp); 1251 rewriter.replaceOp(xferOp, res); 1252 1253 return success(); 1254 } 1255 1256 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 1257 /// when available. 1258 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite( 1259 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const { 1260 // TODO: support mask. 1261 if (xferOp.getMask()) 1262 return failure(); 1263 1264 // Transfer into `viewOrAlloc`. 1265 Value viewOrAlloc = xferOp.getSource(); 1266 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 1267 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 1268 return failure(); 1269 1270 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 1271 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 1272 if (!subViewOp) 1273 return failure(); 1274 Value subView = subViewOp.getResult(); 1275 1276 // Find the copy from `subView` without interleaved uses. 1277 memref::CopyOp copyOp; 1278 for (auto &u : subViewOp.getResult().getUses()) { 1279 if (auto newCopyOp = dyn_cast<memref::CopyOp>(u.getOwner())) { 1280 if (newCopyOp.source() != subView) 1281 continue; 1282 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView})) 1283 continue; 1284 copyOp = newCopyOp; 1285 break; 1286 } 1287 } 1288 if (!copyOp) 1289 return failure(); 1290 1291 // `out` is the subview copied into that we replace. 1292 assert(copyOp.target().getType().isa<MemRefType>()); 1293 Value out = copyOp.target(); 1294 1295 // Forward vector.transfer into copy. 1296 // memref.copy + linalg.fill can be used to create a padded local buffer. 1297 // The `masked` attribute is only valid on this padded buffer. 1298 // When forwarding to vector.transfer_write, the attribute must be reset 1299 // conservatively. 1300 rewriter.create<vector::TransferWriteOp>( 1301 xferOp.getLoc(), xferOp.getVector(), out, xferOp.getIndices(), 1302 xferOp.getPermutationMapAttr(), xferOp.getMask(), 1303 // in_bounds is explicitly reset 1304 /*inBoundsAttr=*/ArrayAttr()); 1305 1306 rewriter.eraseOp(copyOp); 1307 rewriter.eraseOp(xferOp); 1308 1309 return success(); 1310 } 1311 1312 //===----------------------------------------------------------------------===// 1313 // Convolution vectorization patterns 1314 //===----------------------------------------------------------------------===// 1315 1316 template <int N> 1317 static void bindShapeDims(ShapedType shapedType) {} 1318 1319 template <int N, typename IntTy, typename... IntTy2> 1320 static void bindShapeDims(ShapedType shapedType, IntTy &val, IntTy2 &...vals) { 1321 val = shapedType.getShape()[N]; 1322 bindShapeDims<N + 1, IntTy2 &...>(shapedType, vals...); 1323 } 1324 1325 /// Bind a pack of int& to the leading dimensions of shapedType.getShape(). 1326 template <typename... IntTy> 1327 static void bindShapeDims(ShapedType shapedType, IntTy &...vals) { 1328 bindShapeDims<0>(shapedType, vals...); 1329 } 1330 1331 namespace { 1332 /// Generate a vector implementation for either: 1333 /// ``` 1334 /// Op def: ( n, w, c, kw, f ) 1335 /// Iters: ({Par(), Par(), Par(), Red(), Red()}) 1336 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}} 1337 /// ``` 1338 /// kw is unrolled, w is unrolled iff dilationW > 1. 1339 /// 1340 /// or 1341 /// 1342 /// ``` 1343 /// Op def: ( n, w, c, kw ) 1344 /// Iters: ({Par(), Par(), Par(), Red()}) 1345 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}} 1346 /// ``` 1347 /// kw is unrolled, w is unrolled iff dilationW > 1. 1348 struct Conv1DNwcGenerator : public StructuredGenerator<LinalgOp> { 1349 Conv1DNwcGenerator(OpBuilder &builder, LinalgOp linalgOp, int strideW, 1350 int dilationW) 1351 : StructuredGenerator<LinalgOp>(builder, linalgOp), strideW(strideW), 1352 dilationW(dilationW) { 1353 // Determine whether `linalgOp` can be generated with this generator 1354 if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1) 1355 return; 1356 lhsShaped = linalgOp.inputs()[0]; 1357 rhsShaped = linalgOp.inputs()[1]; 1358 resShaped = linalgOp.outputs()[0]; 1359 lhsShapedType = lhsShaped.getType().dyn_cast<ShapedType>(); 1360 rhsShapedType = rhsShaped.getType().dyn_cast<ShapedType>(); 1361 resShapedType = resShaped.getType().dyn_cast<ShapedType>(); 1362 if (!lhsShapedType || !rhsShapedType || !resShapedType) 1363 return; 1364 if (lhsShapedType.getRank() != 3 || 1365 (rhsShapedType.getRank() != 2 && rhsShapedType.getRank() != 3) || 1366 resShapedType.getRank() != 3) 1367 return; 1368 1369 // Check for reduction `add` preceded by `mul`. 1370 Operation *reduceOp = matchLinalgReduction(linalgOp.getOutputOperand(0)); 1371 if (!reduceOp) 1372 return; 1373 llvm::Optional<vector::CombiningKind> maybeKind; 1374 maybeKind = getCombinerOpKind(reduceOp); 1375 if (!maybeKind || *maybeKind != vector::CombiningKind::ADD) 1376 return; 1377 maybeKind = getCombinerOpKind(&(linalgOp->getRegion(0).front().front())); 1378 if (!maybeKind || *maybeKind != vector::CombiningKind::MUL) 1379 return; 1380 1381 // The op is now known to be valid. 1382 valid = true; 1383 } 1384 1385 /// Generate a vector implementation for: 1386 /// ``` 1387 /// Op def: ( n, w, c, kw, f ) 1388 /// Iters: ({Par(), Par(), Par(), Red(), Red()}) 1389 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}} 1390 /// ``` 1391 /// kw is always unrolled. 1392 /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is 1393 /// > 1. 1394 FailureOr<Operation *> conv() { 1395 if (!valid) 1396 return failure(); 1397 1398 int64_t nSize, wSize, cSize, kwSize, fSize; 1399 // kernel{kw, c, f} 1400 bindShapeDims(rhsShapedType, kwSize, cSize, fSize); 1401 // out{n, w, f} 1402 bindShapeDims(resShapedType, nSize, wSize); 1403 1404 vector::TransferWriteOp write; 1405 Value zero = builder.create<arith::ConstantIndexOp>(loc, 0); 1406 1407 // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1. 1408 // When strideW == 1, we can batch the contiguous loads and avoid 1409 // unrolling 1410 int64_t wSizeStep = strideW == 1 ? wSize : 1; 1411 1412 Type lhsEltType = lhsShapedType.getElementType(); 1413 Type rhsEltType = rhsShapedType.getElementType(); 1414 Type resEltType = resShapedType.getElementType(); 1415 VectorType lhsType = VectorType::get( 1416 {nSize, 1417 // iw = ow * sw + kw * dw - 1 1418 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14) 1419 // Perform the proper inclusive -> exclusive -> inclusive. 1420 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1, 1421 cSize}, 1422 lhsEltType); 1423 VectorType rhsType = VectorType::get({kwSize, cSize, fSize}, rhsEltType); 1424 VectorType resType = VectorType::get({nSize, wSize, fSize}, resEltType); 1425 1426 // Read lhs slice of size {w * strideW + kw * dilationW, c, f} @ [0, 0, 1427 // 0]. 1428 Value lhs = builder.create<vector::TransferReadOp>( 1429 loc, lhsType, lhsShaped, ValueRange{zero, zero, zero}); 1430 // Read rhs slice of size {kw, c, f} @ [0, 0, 0]. 1431 Value rhs = builder.create<vector::TransferReadOp>( 1432 loc, rhsType, rhsShaped, ValueRange{zero, zero, zero}); 1433 // Read res slice of size {n, w, f} @ [0, 0, 0]. 1434 Value res = builder.create<vector::TransferReadOp>( 1435 loc, resType, resShaped, ValueRange{zero, zero, zero}); 1436 1437 //===------------------------------------------------------------------===// 1438 // Begin vector-only rewrite part 1439 //===------------------------------------------------------------------===// 1440 // Unroll along kw and read slices of lhs and rhs. 1441 SmallVector<Value> lhsVals, rhsVals, resVals; 1442 // Extract lhs slice of size {n, wSizeStep, c} @ [0, sw * w + dw * kw, 0]. 1443 for (int64_t kw = 0; kw < kwSize; ++kw) { 1444 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1445 lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1446 loc, lhs, 1447 /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0}, 1448 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize}, 1449 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1450 } 1451 } 1452 // Extract rhs slice of size {c, f} @ [kw]. 1453 for (int64_t kw = 0; kw < kwSize; ++kw) { 1454 rhsVals.push_back(builder.create<vector::ExtractOp>( 1455 loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw})); 1456 } 1457 // Extract res slice: {n, wSizeStep, f} @ [0, w, 0]. 1458 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1459 resVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1460 loc, res, 1461 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1462 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, fSize}, 1463 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1464 } 1465 1466 auto linearIndex = [&](int64_t kw, int64_t w) { 1467 return kw * (wSize / wSizeStep) + w; 1468 }; 1469 1470 // Compute contraction: O{n, w, f} += I{n, sw * w + dw * kw, c} * F{c, f} 1471 for (int64_t kw = 0; kw < kwSize; ++kw) { 1472 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1473 resVals[w] = conv1dSliceAsContraction( 1474 builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]); 1475 } 1476 } 1477 1478 // Write back res slice: {n, wSizeStep, f} @ [0, w, 0]. 1479 // This does not depend on kw. 1480 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1481 res = builder.create<vector::InsertStridedSliceOp>( 1482 loc, resVals[w], res, 1483 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1484 /*strides=*/ArrayRef<int64_t>{1, 1, 1}); 1485 } 1486 //===------------------------------------------------------------------===// 1487 // End vector-only rewrite part 1488 //===------------------------------------------------------------------===// 1489 1490 // Write back res slice of size {n, w, f} @ [0, 0, 0]. 1491 return builder 1492 .create<vector::TransferWriteOp>(loc, res, resShaped, 1493 ValueRange{zero, zero, zero}) 1494 .getOperation(); 1495 } 1496 1497 // Create a contraction: lhs{n, w, c} * rhs{c, f} -> res{n, w, f} 1498 Value conv1dSliceAsContraction(OpBuilder &b, Location loc, Value lhs, 1499 Value rhs, Value res) { 1500 StringRef par = Par().strRef, red = Red().strRef; 1501 AffineExpr n, w, f, c; 1502 bindDims(ctx, n, w, f, c); 1503 return builder.create<vector::ContractionOp>( 1504 loc, lhs, rhs, res, 1505 /*indexingMaps=*/MapList{{n, w, c}, {c, f}, {n, w, f}}, 1506 /*iteratorTypes=*/ArrayRef<StringRef>{par, par, par, red}); 1507 } 1508 1509 /// Generate a vector implementation for: 1510 /// ``` 1511 /// Op def: ( n, w, c, kw) 1512 /// Iters: ({Par(), Par(), Par(), Red()}) 1513 /// Layout: {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}} 1514 /// ``` 1515 /// kw is always unrolled. 1516 /// TODO: w (resp. kw) is unrolled when the strideW ( resp. dilationW) is 1517 /// > 1. 1518 FailureOr<Operation *> depthwiseConv() { 1519 if (!valid) 1520 return failure(); 1521 1522 int64_t nSize, wSize, cSize, kwSize; 1523 // kernel{kw, c} 1524 bindShapeDims(rhsShapedType, kwSize, cSize); 1525 // out{n, w, c} 1526 bindShapeDims(resShapedType, nSize, wSize); 1527 1528 vector::TransferWriteOp write; 1529 Value zero = builder.create<arith::ConstantIndexOp>(loc, 0); 1530 1531 // w is unrolled (i.e. wSizeStep == 1) iff strideW > 1. 1532 // When strideW == 1, we can batch the contiguous loads and avoid 1533 // unrolling 1534 int64_t wSizeStep = strideW == 1 ? wSize : 1; 1535 1536 Type lhsEltType = lhsShapedType.getElementType(); 1537 Type rhsEltType = rhsShapedType.getElementType(); 1538 Type resEltType = resShapedType.getElementType(); 1539 VectorType lhsType = VectorType::get( 1540 {nSize, 1541 // iw = ow * sw + kw * dw - 1 1542 // (i.e. 16 convolved with 3 (@stride 1 dilation 1) -> 14) 1543 ((wSize - 1) * strideW + 1) + ((kwSize - 1) * dilationW + 1) - 1, 1544 cSize}, 1545 lhsEltType); 1546 VectorType rhsType = VectorType::get({kwSize, cSize}, rhsEltType); 1547 VectorType resType = VectorType::get({nSize, wSize, cSize}, resEltType); 1548 1549 // Read lhs slice of size {n, w * strideW + kw * dilationW, c} @ [0, 0, 1550 // 0]. 1551 Value lhs = builder.create<vector::TransferReadOp>( 1552 loc, lhsType, lhsShaped, ValueRange{zero, zero, zero}); 1553 // Read rhs slice of size {kw, c} @ [0, 0]. 1554 Value rhs = builder.create<vector::TransferReadOp>(loc, rhsType, rhsShaped, 1555 ValueRange{zero, zero}); 1556 // Read res slice of size {n, w, c} @ [0, 0, 0]. 1557 Value res = builder.create<vector::TransferReadOp>( 1558 loc, resType, resShaped, ValueRange{zero, zero, zero}); 1559 1560 //===------------------------------------------------------------------===// 1561 // Begin vector-only rewrite part 1562 //===------------------------------------------------------------------===// 1563 // Unroll along kw and read slices of lhs and rhs. 1564 SmallVector<Value> lhsVals, rhsVals, resVals; 1565 // Extract lhs slice of size {n, wSizeStep, c} 1566 // @ [0, sw * w + dw * kw, 0]. 1567 for (int64_t kw = 0; kw < kwSize; ++kw) { 1568 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1569 lhsVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1570 loc, lhs, 1571 /*offsets=*/ArrayRef<int64_t>{0, w * strideW + kw * dilationW, 0}, 1572 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize}, 1573 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1574 } 1575 } 1576 // Extract rhs slice of size {c} @ [kw]. 1577 for (int64_t kw = 0; kw < kwSize; ++kw) { 1578 rhsVals.push_back(builder.create<vector::ExtractOp>( 1579 loc, rhs, /*offsets=*/ArrayRef<int64_t>{kw})); 1580 } 1581 // Extract res slice: {n, wSizeStep, c} @ [0, w, 0]. 1582 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1583 resVals.push_back(builder.create<vector::ExtractStridedSliceOp>( 1584 loc, res, 1585 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1586 /*sizes=*/ArrayRef<int64_t>{nSize, wSizeStep, cSize}, 1587 /*strides=*/ArrayRef<int64_t>{1, 1, 1})); 1588 } 1589 1590 auto linearIndex = [&](int64_t kw, int64_t w) { 1591 return kw * (wSize / wSizeStep) + w; 1592 }; 1593 1594 // Compute contraction: O{n, w, c} += I{n, sw * w + dw * kw, c} * F{c} 1595 for (int64_t kw = 0; kw < kwSize; ++kw) { 1596 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1597 resVals[w] = depthwiseConv1dSliceAsFma( 1598 builder, loc, lhsVals[linearIndex(kw, w)], rhsVals[kw], resVals[w]); 1599 } 1600 } 1601 1602 // Write back res slice: {n, wSizeStep, c} @ [0, w, 0]. 1603 // This does not depend on kw. 1604 for (int64_t w = 0; w < wSize; w += wSizeStep) { 1605 res = builder.create<vector::InsertStridedSliceOp>( 1606 loc, resVals[w], res, 1607 /*offsets=*/ArrayRef<int64_t>{0, w, 0}, 1608 /*strides=*/ArrayRef<int64_t>{1, 1, 1}); 1609 } 1610 //===------------------------------------------------------------------===// 1611 // End vector-only rewrite part 1612 //===------------------------------------------------------------------===// 1613 1614 // Write back res slice of size {n, w, c} @ [0, 0, 0]. 1615 return builder 1616 .create<vector::TransferWriteOp>(loc, res, resShaped, 1617 ValueRange{zero, zero, zero}) 1618 .getOperation(); 1619 } 1620 1621 /// Lower lhs{n, w, c} * rhs{c} -> res{n, w, c} to fma. 1622 Value depthwiseConv1dSliceAsFma(OpBuilder &b, Location loc, Value lhs, 1623 Value rhs, Value res) { 1624 Value bcast = builder.create<vector::BroadcastOp>(loc, res.getType(), rhs); 1625 return b.create<vector::FMAOp>(loc, lhs, bcast, res); 1626 } 1627 1628 /// Entry point that transposes into the common form: 1629 /// {{n, strideW * w + dilationW * kw, c}, {kw, c, f}, {n, w, f}} 1630 FailureOr<Operation *> generateConv() { 1631 AffineExpr n, w, f, kw, c; 1632 bindDims(ctx, n, w, f, kw, c); 1633 if (!iters({Par(), Par(), Par(), Red(), Red()})) 1634 return failure(); 1635 1636 // No transposition needed. 1637 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c}, 1638 /*rhsIndex*/ {kw, c, f}, 1639 /*resIndex*/ {n, w, f}})) 1640 return conv(); 1641 return failure(); 1642 } 1643 1644 /// Entry point that transposes into the common form: 1645 /// {{n, strideW * w + dilationW * kw, c}, {kw, c}, {n, w, c}} 1646 FailureOr<Operation *> generateDilatedConv() { 1647 AffineExpr n, w, c, kw; 1648 bindDims(ctx, n, w, c, kw); 1649 if (!iters({Par(), Par(), Par(), Red()})) 1650 return failure(); 1651 1652 // No transposition needed. 1653 if (layout({/*lhsIndex*/ {n, strideW * w + dilationW * kw, c}, 1654 /*rhsIndex*/ {kw, c}, 1655 /*resIndex*/ {n, w, c}})) 1656 return depthwiseConv(); 1657 return failure(); 1658 } 1659 1660 private: 1661 bool valid = false; 1662 int strideW, dilationW; 1663 Value lhsShaped, rhsShaped, resShaped; 1664 ShapedType lhsShapedType, rhsShapedType, resShapedType; 1665 }; 1666 } // namespace 1667 1668 /// Helper function to vectorize a LinalgOp with convolution semantics. 1669 // TODO: extend the generic vectorization to support windows and drop this. 1670 static FailureOr<Operation *> vectorizeConvolution(OpBuilder &b, LinalgOp op) { 1671 // The ConvolutionOpInterface gives us guarantees of existence for 1672 // strides/dilations. However, we do not need to rely on those, we can simply 1673 // use them if present, otherwise use the default and let the generic conv. 1674 // matcher in the ConvGenerator succeed or fail. 1675 auto strides = op->getAttrOfType<DenseIntElementsAttr>("strides"); 1676 auto dilations = op->getAttrOfType<DenseIntElementsAttr>("dilations"); 1677 auto stride = strides ? *strides.getValues<uint64_t>().begin() : 1; 1678 auto dilation = dilations ? *dilations.getValues<uint64_t>().begin() : 1; 1679 Conv1DNwcGenerator e(b, op, stride, dilation); 1680 auto res = e.generateConv(); 1681 if (succeeded(res)) 1682 return res; 1683 return e.generateDilatedConv(); 1684 } 1685 1686 struct VectorizeConvolution : public OpInterfaceRewritePattern<LinalgOp> { 1687 using OpInterfaceRewritePattern::OpInterfaceRewritePattern; 1688 1689 LogicalResult matchAndRewrite(LinalgOp op, 1690 PatternRewriter &rewriter) const override { 1691 FailureOr<Operation *> resultOrFail = vectorizeConvolution(rewriter, op); 1692 if (failed(resultOrFail)) 1693 return failure(); 1694 Operation *newOp = *resultOrFail; 1695 if (newOp->getNumResults() == 0) { 1696 rewriter.eraseOp(op.getOperation()); 1697 return success(); 1698 } 1699 assert(newOp->getNumResults() == 1 && "expected single result"); 1700 rewriter.replaceOp(op.getOperation(), newOp->getResult(0)); 1701 return success(); 1702 } 1703 }; 1704 1705 void mlir::linalg::populateConvolutionVectorizationPatterns( 1706 RewritePatternSet &patterns, PatternBenefit benefit) { 1707 patterns.add<VectorizeConvolution>(patterns.getContext(), benefit); 1708 } 1709