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