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