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