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