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