1 //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the linalg dialect Vectorization transformations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Analysis/SliceAnalysis.h" 14 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 15 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 16 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 17 #include "mlir/Dialect/Linalg/Utils/Utils.h" 18 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 19 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 20 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 21 #include "mlir/Dialect/Vector/VectorOps.h" 22 #include "mlir/IR/AffineExpr.h" 23 #include "mlir/IR/Matchers.h" 24 #include "mlir/IR/PatternMatch.h" 25 #include "mlir/Pass/Pass.h" 26 #include "mlir/Support/LLVM.h" 27 #include "mlir/Transforms/RegionUtils.h" 28 #include "llvm/ADT/ScopeExit.h" 29 #include "llvm/ADT/TypeSwitch.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <type_traits> 33 34 using namespace mlir; 35 using namespace mlir::edsc; 36 using namespace mlir::edsc::intrinsics; 37 using namespace mlir::linalg; 38 39 using llvm::dbgs; 40 41 #define DEBUG_TYPE "linalg-vectorization" 42 43 /// Return the unique instance of OpType in `block` if it is indeed unique. 44 /// Return null if none or more than 1 instances exist. 45 template <typename OpType> 46 static OpType getSingleOpOfType(Block &block) { 47 OpType res; 48 block.walk([&](OpType op) { 49 if (res) { 50 res = nullptr; 51 return WalkResult::interrupt(); 52 } 53 res = op; 54 return WalkResult::advance(); 55 }); 56 return res; 57 } 58 59 /// Given an indexing `map` coming from a LinalgOp indexing, restricted to a 60 /// projectedPermutation, compress the unused dimensions to serve as a 61 /// permutation_map for a vector transfer operation. 62 /// For example, given a linalg op such as: 63 /// 64 /// ``` 65 /// %0 = linalg.generic { 66 /// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d4, d0, d2)>, 67 /// indexing_maps = affine_map<(d0, d1, d2, d3, d4) -> (d1, d3)> 68 /// } 69 /// ins(%0 : tensor<2x3x4xf32>) 70 /// outs(%1 : tensor<5x6xf32>) 71 /// ``` 72 /// 73 /// the iteration domain size of the linalg op is 3x5x4x6x2. The first affine 74 /// map is reindexed to `affine_map<(d0, d1, d2) -> (d2, d0, d1)>`, the second 75 /// affine map is reindexed to `affine_map<(d0, d1) -> (d0, d1)>`. 76 static AffineMap reindexIndexingMap(AffineMap map) { 77 assert(map.isProjectedPermutation() && "expected projected permutation"); 78 auto res = compressUnusedDims(map); 79 assert(res.getNumDims() == res.getNumResults() && 80 "expected reindexed map with same number of dims and results"); 81 return res; 82 } 83 84 /// Helper data structure to represent the result of vectorization. 85 /// In certain specific cases, like terminators, we do not want to propagate/ 86 enum VectorizationStatus { 87 /// Op failed to vectorize. 88 Failure = 0, 89 /// Op vectorized and custom function took care of replacement logic 90 NoReplace, 91 /// Op vectorized into a new Op whose results will replace original Op's 92 /// results. 93 NewOp 94 // TODO: support values if Op vectorized to Many-Ops whose results we need to 95 // aggregate for replacement. 96 }; 97 struct VectorizationResult { 98 /// Return status from vectorizing the current op. 99 enum VectorizationStatus status = VectorizationStatus::Failure; 100 /// New vectorized operation to replace the current op. 101 /// Replacement behavior is specified by `status`. 102 Operation *newOp; 103 }; 104 105 /// Return a vector type of the same shape and element type as the (assumed) 106 /// ShapedType of `v`. 107 static VectorType extractVectorTypeFromShapedValue(Value v) { 108 auto st = v.getType().cast<ShapedType>(); 109 if (st.isa<MemRefType>() && st.getShape().empty()) 110 return VectorType(); 111 return VectorType::get(st.getShape(), st.getElementType()); 112 } 113 114 /// Given an `outputOperand` of a LinalgOp, compute the intersection of the 115 /// forward slice starting from `outputOperand` and the backward slice 116 /// starting from the corresponding linalg.yield operand. 117 /// This intersection is assumed to have a single binary operation that is 118 /// the reduction operation. Multiple reduction operations would impose an 119 /// ordering between reduction dimensions and is currently unsupported in 120 /// Linalg. This limitation is motivated by the fact that e.g. 121 /// min(max(X)) != max(min(X)) 122 // TODO: use in LinalgOp verification, there is a circular dependency atm. 123 static Operation *getSingleBinaryOpAssumedReduction(OpOperand &outputOperand) { 124 auto linalgOp = cast<LinalgOp>(outputOperand.getOwner()); 125 auto yieldOp = cast<YieldOp>(linalgOp->getRegion(0).front().getTerminator()); 126 unsigned yieldNum = 127 outputOperand.getOperandNumber() - linalgOp.getNumInputs(); 128 llvm::SetVector<Operation *> backwardSlice, forwardSlice; 129 BlockArgument bbArg = linalgOp->getRegion(0).front().getArgument( 130 outputOperand.getOperandNumber()); 131 Value yieldVal = yieldOp->getOperand(yieldNum); 132 getBackwardSlice(yieldVal, &backwardSlice, [&](Operation *op) { 133 return op->getParentOp() == linalgOp; 134 }); 135 backwardSlice.insert(yieldVal.getDefiningOp()); 136 getForwardSlice(bbArg, &forwardSlice, 137 [&](Operation *op) { return op->getParentOp() == linalgOp; }); 138 // Search for the (assumed unique) elementwiseMappable op at the intersection 139 // of forward and backward slices. 140 Operation *reductionOp = nullptr; 141 for (Operation *op : llvm::reverse(backwardSlice)) { 142 if (!forwardSlice.contains(op)) 143 continue; 144 if (OpTrait::hasElementwiseMappableTraits(op)) { 145 if (reductionOp) { 146 // Reduction detection fails: found more than 1 elementwise-mappable op. 147 return nullptr; 148 } 149 reductionOp = op; 150 } 151 } 152 // TODO: also assert no other subsequent ops break the reduction. 153 return reductionOp; 154 } 155 156 /// If `value` of assumed VectorType has a shape different than `shape`, try to 157 /// build and return a new vector.broadcast to `shape`. 158 /// Otherwise, just return `value`. 159 // TODO: this is best effort atm and there is currently no guarantee of 160 // correctness for the broadcast semantics. 161 static Value broadcastIfNeeded(OpBuilder &builder, Value value, 162 ArrayRef<int64_t> shape) { 163 unsigned numDimsGtOne = std::count_if(shape.begin(), shape.end(), 164 [](int64_t val) { return val > 1; }); 165 auto vecType = value.getType().dyn_cast<VectorType>(); 166 if (shape.empty() || 167 (vecType != nullptr && 168 (vecType.getShape() == shape || vecType.getRank() > numDimsGtOne))) 169 return value; 170 auto newVecType = VectorType::get(shape, vecType ? vecType.getElementType() 171 : value.getType()); 172 return builder.create<vector::BroadcastOp>( 173 builder.getInsertionPoint()->getLoc(), newVecType, value); 174 } 175 176 static llvm::Optional<vector::CombiningKind> 177 getKindForOp(Operation *reductionOp) { 178 if (!reductionOp) 179 return llvm::None; 180 return llvm::TypeSwitch<Operation *, llvm::Optional<vector::CombiningKind>>( 181 reductionOp) 182 .Case<AddIOp, AddFOp>([&](auto op) { 183 return llvm::Optional<vector::CombiningKind>{ 184 vector::CombiningKind::ADD}; 185 }) 186 .Default([&](auto op) { return llvm::None; }); 187 } 188 189 /// If value of assumed VectorType has a shape different than `shape`, build and 190 /// return a new vector.broadcast to `shape`. 191 /// Otherwise, just return value. 192 static Value reduceIfNeeded(OpBuilder &builder, VectorType targetVectorType, 193 Value value, OpOperand &outputOperand) { 194 assert(targetVectorType.getShape() == 195 outputOperand.get().getType().cast<ShapedType>().getShape()); 196 auto vecType = value.getType().dyn_cast<VectorType>(); 197 if (!vecType || vecType.getShape() == targetVectorType.getShape()) 198 return value; 199 // At this point, we know we need to reduce. Detect the reduction operator. 200 // TODO: Use the generic reduction detection util. 201 Operation *reductionOp = getSingleBinaryOpAssumedReduction(outputOperand); 202 auto linalgOp = cast<LinalgOp>(outputOperand.getOwner()); 203 unsigned pos = 0; 204 MLIRContext *ctx = builder.getContext(); 205 SmallVector<AffineExpr> exprs; 206 for (auto s : linalgOp.iterator_types()) 207 if (isParallelIterator(s)) 208 exprs.push_back(getAffineDimExpr(pos++, ctx)); 209 auto loc = value.getLoc(); 210 // TODO: reuse common CombiningKing logic and support more than add. 211 auto maybeKind = getKindForOp(reductionOp); 212 assert(maybeKind && "Failed precondition: could not get reduction kind"); 213 unsigned idx = 0; 214 SmallVector<bool> reductionMask(linalgOp.iterator_types().size(), false); 215 for (auto attr : linalgOp.iterator_types()) { 216 if (isReductionIteratorType(attr)) 217 reductionMask[idx] = true; 218 ++idx; 219 } 220 return builder.create<vector::MultiDimReductionOp>(loc, value, reductionMask, 221 *maybeKind); 222 } 223 224 /// Build a vector.transfer_read from `source` at indices set to all `0`. 225 /// If source has rank zero, build an memref.load. 226 /// Return the produced value. 227 static Value buildVectorRead(OpBuilder &builder, Value source, 228 VectorType vectorType, AffineMap map) { 229 edsc::ScopedContext scope(builder); 230 auto shapedType = source.getType().cast<ShapedType>(); 231 SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0)); 232 return vector_transfer_read(vectorType, source, indices, map); 233 } 234 235 /// Build a vector.transfer_write of `value` into `outputOperand` at indices set 236 /// to all `0`; where `outputOperand` is an output operand of the LinalgOp 237 /// currently being vectorized. If `dest` has null rank, build an memref.store. 238 /// Return the produced value or null if no value is produced. 239 static Value buildVectorWrite(OpBuilder &builder, Value value, 240 OpOperand &outputOperand) { 241 edsc::ScopedContext scope(builder); 242 Operation *write; 243 auto shapedType = outputOperand.get().getType().cast<ShapedType>(); 244 if (VectorType vectorType = 245 extractVectorTypeFromShapedValue(outputOperand.get())) { 246 auto linalgOp = cast<LinalgOp>(outputOperand.getOwner()); 247 AffineMap map = reindexIndexingMap( 248 linalgOp.getIndexingMap(outputOperand.getOperandNumber())); 249 SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0)); 250 value = broadcastIfNeeded(builder, value, vectorType.getShape()); 251 value = reduceIfNeeded(builder, vectorType, value, outputOperand); 252 write = vector_transfer_write(value, outputOperand.get(), indices, map); 253 } else { 254 write = memref_store(value, outputOperand.get()); 255 } 256 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorized op: " << *write); 257 if (!write->getResults().empty()) 258 return write->getResult(0); 259 return Value(); 260 } 261 262 // Custom vectorization function type. Produce a vector form of Operation* 263 // assuming all its vectorized operands are already in the BlockAndValueMapping. 264 // Return nullptr if the Operation cannot be vectorized. 265 using CustomVectorizationHook = std::function<VectorizationResult( 266 Operation *, const BlockAndValueMapping &)>; 267 268 /// Helper function to vectorize the terminator of a `linalgOp`. New result 269 /// vector values are appended to `newResults`. Return 270 /// VectorizationStatus::NoReplace to signal the vectorization algorithm that it 271 /// should not try to map produced operations and instead return the results 272 /// using the `newResults` vector making them available to the 273 /// vectorization algorithm for RAUW. This function is meant to be used as a 274 /// CustomVectorizationHook. 275 static VectorizationResult 276 vectorizeLinalgYield(OpBuilder &builder, Operation *op, 277 const BlockAndValueMapping &bvm, LinalgOp linalgOp, 278 SmallVectorImpl<Value> &newResults) { 279 auto yieldOp = dyn_cast<linalg::YieldOp>(op); 280 if (!yieldOp) 281 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 282 for (auto outputs : llvm::enumerate(yieldOp.values())) { 283 // TODO: Scan for an opportunity for reuse. 284 // TODO: use a map. 285 Value vectorValue = bvm.lookup(outputs.value()); 286 Value newResult = buildVectorWrite( 287 builder, vectorValue, linalgOp.getOutputOpOperands()[outputs.index()]); 288 if (newResult) 289 newResults.push_back(newResult); 290 } 291 return VectorizationResult{VectorizationStatus::NoReplace, nullptr}; 292 } 293 294 /// Helper function to vectorize the index operations of a `linalgOp`. Return 295 /// VectorizationStatus::NewOp to signal the vectorization algorithm that it 296 /// should map the produced operations. This function is meant to be used as a 297 /// CustomVectorizationHook. 298 static VectorizationResult 299 vectorizeLinalgIndex(OpBuilder &builder, Operation *op, LinalgOp linalgOp) { 300 IndexOp indexOp = dyn_cast<linalg::IndexOp>(op); 301 if (!indexOp) 302 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 303 auto loc = indexOp.getLoc(); 304 // Compute the static loop sizes of the index op. 305 auto targetShape = linalgOp.computeStaticLoopSizes(); 306 // Compute a one-dimensional index vector for the index op dimension. 307 SmallVector<int64_t> constantSeq( 308 llvm::seq<int64_t>(0, targetShape[indexOp.dim()])); 309 ConstantOp constantOp = 310 builder.create<ConstantOp>(loc, builder.getIndexVectorAttr(constantSeq)); 311 // Return the one-dimensional index vector if it lives in the trailing 312 // dimension of the iteration space since the vectorization algorithm in this 313 // case can handle the broadcast. 314 if (indexOp.dim() == targetShape.size() - 1) 315 return VectorizationResult{VectorizationStatus::NewOp, constantOp}; 316 // Otherwise permute the targetShape to move the index dimension last, 317 // broadcast the one-dimensional index vector to the permuted shape, and 318 // finally transpose the broadcasted index vector to undo the permutation. 319 std::swap(targetShape[indexOp.dim()], targetShape.back()); 320 auto broadCastOp = builder.create<vector::BroadcastOp>( 321 loc, VectorType::get(targetShape, builder.getIndexType()), constantOp); 322 SmallVector<int64_t> transposition( 323 llvm::seq<int64_t>(0, linalgOp.getNumLoops())); 324 std::swap(transposition.back(), transposition[indexOp.dim()]); 325 auto transposeOp = 326 builder.create<vector::TransposeOp>(loc, broadCastOp, transposition); 327 return VectorizationResult{VectorizationStatus::NewOp, transposeOp}; 328 } 329 330 /// Generic vectorization for a single operation `op`, given already vectorized 331 /// operands carried by `bvm`. Vectorization occurs as follows: 332 /// 1. Try to apply any of the `customVectorizationHooks` and return its 333 /// result on success. 334 /// 2. Clone any constant in the current scope without vectorization: each 335 /// consumer of the constant will later determine the shape to which the 336 /// constant needs to be broadcast to. 337 /// 3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose 338 /// of the `customVectorizationHooks` to cover such cases. 339 /// 4. Clone `op` in vector form to a vector of shape prescribed by the first 340 /// operand of maximal rank. Other operands have smaller rank and are 341 /// broadcast accordingly. It is assumed this broadcast is always legal, 342 /// otherwise, it means one of the `customVectorizationHooks` is incorrect. 343 /// 344 /// This function assumes all operands of `op` have been vectorized and are in 345 /// the `bvm` mapping. As a consequence, this function is meant to be called on 346 /// a topologically-sorted list of ops. 347 /// This function does not update `bvm` but returns a VectorizationStatus that 348 /// instructs the caller what `bvm` update needs to occur. 349 static VectorizationResult 350 vectorizeOneOp(OpBuilder &builder, Operation *op, 351 const BlockAndValueMapping &bvm, 352 ArrayRef<CustomVectorizationHook> customVectorizationHooks) { 353 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorize op " << *op); 354 355 // 1. Try to apply any CustomVectorizationHook. 356 if (!customVectorizationHooks.empty()) { 357 for (auto &customFunc : customVectorizationHooks) { 358 VectorizationResult result = customFunc(op, bvm); 359 if (result.status == VectorizationStatus::Failure) 360 continue; 361 return result; 362 } 363 } 364 365 // 2. Constant ops don't get vectorized but rather broadcasted at their users. 366 // Clone so that the constant is not confined to the linalgOp block . 367 if (isa<ConstantOp>(op)) 368 return VectorizationResult{VectorizationStatus::NewOp, builder.clone(*op)}; 369 370 // 3. Only ElementwiseMappable are allowed in the generic vectorization. 371 if (!OpTrait::hasElementwiseMappableTraits(op)) 372 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 373 374 // 4. Generic vectorization path for ElementwiseMappable ops. 375 // a. first get the first max ranked shape. 376 SmallVector<int64_t, 4> firstMaxRankedShape; 377 for (Value operand : op->getOperands()) { 378 auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>(); 379 if (vt && firstMaxRankedShape.size() < vt.getShape().size()) 380 firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end()); 381 } 382 // b. broadcast each op if needed. 383 auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) { 384 return firstMaxRankedShape.empty() 385 ? bvm.lookup(v) 386 : broadcastIfNeeded(builder, bvm.lookup(v), firstMaxRankedShape); 387 }); 388 // c. for elementwise, the result is the vector with the firstMaxRankedShape 389 auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) { 390 return firstMaxRankedShape.empty() 391 ? t 392 : VectorType::get(firstMaxRankedShape, t); 393 }); 394 395 // Build and return the new op. 396 OperationState state(op->getLoc(), op->getName()); 397 state.addAttributes(op->getAttrs()); 398 state.addOperands(llvm::to_vector<4>(vectorizedOperands)); 399 state.addTypes(llvm::to_vector<4>(returnTypes)); 400 return VectorizationResult{VectorizationStatus::NewOp, 401 builder.createOperation(state)}; 402 } 403 404 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp. 405 static bool hasOnlyScalarElementwiseOp(Region &r) { 406 if (!llvm::hasSingleElement(r)) 407 return false; 408 for (Operation &op : r.front()) { 409 if (!(isa<ConstantOp, linalg::YieldOp, linalg::IndexOp>(op) || 410 OpTrait::hasElementwiseMappableTraits(&op)) || 411 llvm::any_of(op.getResultTypes(), 412 [](Type type) { return !type.isIntOrIndexOrFloat(); })) 413 return false; 414 } 415 return true; 416 } 417 418 // Return true if the op is an element-wise linalg op. 419 static bool isElementwise(Operation *op) { 420 auto linalgOp = dyn_cast<linalg::LinalgOp>(op); 421 if (!linalgOp) 422 return false; 423 if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops()) 424 return false; 425 // TODO: relax the restrictions on indexing map. 426 for (unsigned i = 0, e = linalgOp.getNumOutputs(); i < e; i++) { 427 if (!linalgOp.getOutputIndexingMap(i).isIdentity()) 428 return false; 429 } 430 if (linalgOp->getNumRegions() != 1) 431 return false; 432 return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0)); 433 } 434 435 /// Generic vectorization function that rewrites the body of a `linalgOp` into 436 /// vector form. Generic vectorization proceeds as follows: 437 /// 1. Verify the `linalgOp` has one non-empty region. 438 /// 2. Values defined above the region are mapped to themselves and will be 439 /// broadcasted on a per-need basis by their consumers. 440 /// 3. Each region argument is vectorized into a vector.transfer_read (or 0-d 441 /// load). 442 /// TODO: Reuse opportunities for RAR dependencies. 443 /// 4a. Register CustomVectorizationHook for YieldOp to capture the results. 444 /// 4b. Register CustomVectorizationHook for IndexOp to access the iteration 445 /// indices. 446 /// 5. Iteratively call vectorizeOneOp on the region operations. 447 /// 448 /// When `broadcastToMaximalCommonShape` is set to true, eager broadcasting is 449 /// performed to the maximal common vector size implied by the `linalgOp` 450 /// iteration space. This eager broadcasting is introduced in the 451 /// permutation_map of the vector.transfer_read operations. The eager 452 /// broadcasting makes it trivial to detrmine where broadcast, transposes and 453 /// reductions should occur, without any bookkeeping. The tradeoff is that, in 454 /// the absence of good canonicalizations, the amount of work increases. 455 /// This is not deemed a problem as we expect canonicalizations and foldings to 456 /// aggressively clean up the useless work. 457 LogicalResult vectorizeAsLinalgGeneric( 458 OpBuilder &builder, LinalgOp linalgOp, SmallVectorImpl<Value> &newResults, 459 bool broadcastToMaximalCommonShape = false, 460 ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) { 461 // 1. Fail to vectorize if the operation does not have one non-empty region. 462 if (linalgOp->getNumRegions() != 1 || linalgOp->getRegion(0).empty()) 463 return failure(); 464 auto &block = linalgOp->getRegion(0).front(); 465 466 // 2. Values defined above the region can only be broadcast for now. Make them 467 // map to themselves. 468 BlockAndValueMapping bvm; 469 SetVector<Value> valuesSet; 470 mlir::getUsedValuesDefinedAbove(linalgOp->getRegion(0), valuesSet); 471 bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef()); 472 473 if (linalgOp.getNumOutputs() == 0) 474 return failure(); 475 476 // TODO: the common vector shape is equal to the static loop sizes only when 477 // all indexing maps are projected permutations. For convs and stencils the 478 // logic will need to evolve. 479 SmallVector<int64_t> commonVectorShape = linalgOp.computeStaticLoopSizes(); 480 481 // 3. Turn all BBArgs into vector.transfer_read / load. 482 SmallVector<AffineMap> indexings; 483 for (auto bbarg : block.getArguments()) { 484 Value shapedArg = linalgOp.getShapedOperand(bbarg.getArgNumber()); 485 ShapedType shapedType = shapedArg.getType().cast<ShapedType>(); 486 // TODO: 0-d vectors. 487 if (shapedType.getShape().empty()) { 488 Value loaded = 489 builder.create<memref::LoadOp>(linalgOp.getLoc(), shapedArg); 490 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg(" 491 << bbarg.getArgNumber() << "): " << loaded); 492 bvm.map(bbarg, loaded); 493 bvm.map(shapedArg, loaded); 494 continue; 495 } 496 AffineMap map; 497 VectorType vectorType; 498 if (broadcastToMaximalCommonShape) { 499 map = inverseAndBroadcastProjectedPermuation( 500 linalgOp.getIndexingMap(bbarg.getArgNumber())); 501 vectorType = 502 VectorType::get(commonVectorShape, shapedType.getElementType()); 503 } else { 504 map = inversePermutation( 505 reindexIndexingMap(linalgOp.getIndexingMap(bbarg.getArgNumber()))); 506 vectorType = VectorType::get(map.compose(shapedType.getShape()), 507 shapedType.getElementType()); 508 } 509 Value vectorRead = buildVectorRead(builder, shapedArg, vectorType, map); 510 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg(" 511 << bbarg.getArgNumber() << "): " << vectorRead); 512 bvm.map(bbarg, vectorRead); 513 bvm.map(shapedArg, vectorRead); 514 } 515 516 auto hooks = llvm::to_vector<4>(customVectorizationHooks); 517 // 4a. Register CustomVectorizationHook for yieldOp. 518 CustomVectorizationHook vectorizeYield = 519 [&](Operation *op, 520 const BlockAndValueMapping &bvm) -> VectorizationResult { 521 return vectorizeLinalgYield(builder, op, bvm, linalgOp, newResults); 522 }; 523 hooks.push_back(vectorizeYield); 524 525 // 4b. Register CustomVectorizationHook for indexOp. 526 CustomVectorizationHook vectorizeIndex = 527 [&](Operation *op, 528 const BlockAndValueMapping &bvm) -> VectorizationResult { 529 return vectorizeLinalgIndex(builder, op, linalgOp); 530 }; 531 hooks.push_back(vectorizeIndex); 532 533 // 5. Iteratively call `vectorizeOneOp` to each op in the slice. 534 for (Operation &op : block.getOperations()) { 535 VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks); 536 if (result.status == VectorizationStatus::Failure) { 537 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op); 538 return failure(); 539 } 540 if (result.status == VectorizationStatus::NewOp) { 541 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: " 542 << *result.newOp;); 543 bvm.map(op.getResults(), result.newOp->getResults()); 544 } 545 } 546 547 return success(); 548 } 549 550 static LogicalResult vectorizeContraction(OpBuilder &builder, LinalgOp linalgOp, 551 SmallVectorImpl<Value> &newResults) { 552 assert(isaContractionOpInterface(linalgOp) && 553 "expected vectorizeContraction preconditions to be met"); 554 Location loc = linalgOp.getLoc(); 555 // Vectorize other ops as vector contraction. 556 // TODO: interface. 557 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 558 << "Rewrite linalg op as vector.contract: "; 559 linalgOp.dump()); 560 // Special function that describes how to vectorize the multiplication op in a 561 // linalg contraction. 562 CustomVectorizationHook vectorizeContraction = 563 [&](Operation *op, 564 const BlockAndValueMapping &bvm) -> VectorizationResult { 565 if (!isa<MulIOp, MulFOp>(op)) 566 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 567 auto outShape = linalgOp.getOutputShapedType(0).getShape(); 568 auto vType = outShape.empty() 569 ? op->getResult(0).getType() 570 : VectorType::get(outShape, op->getResult(0).getType()); 571 auto zero = 572 builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType)); 573 // Indexing maps at the time of vector.transfer_read are adjusted to order 574 // vector dimensions in the same order as the canonical linalg op iteration 575 // space order. 576 // The indexings for the contraction therefore need to be adjusted. 577 // TODO: consider dropping contraction special casing altogether, this will 578 // require more advanced canonicalizations involving vector.multi_reduction 579 // that are not yet available. 580 SmallVector<AffineMap> indexingMaps{ 581 inversePermutation(reindexIndexingMap(linalgOp.getIndexingMap(0))) 582 .compose(linalgOp.getIndexingMap(0)), 583 inversePermutation(reindexIndexingMap(linalgOp.getIndexingMap(1))) 584 .compose(linalgOp.getIndexingMap(1)), 585 inversePermutation(reindexIndexingMap(linalgOp.getIndexingMap(2))) 586 .compose(linalgOp.getIndexingMap(2))}; 587 Operation *contract = builder.create<vector::ContractionOp>( 588 loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero, 589 builder.getAffineMapArrayAttr(indexingMaps), linalgOp.iterator_types()); 590 return VectorizationResult{VectorizationStatus::NewOp, contract}; 591 }; 592 return vectorizeAsLinalgGeneric(builder, linalgOp, newResults, 593 /*broadcastToMaximalCommonShape=*/false, 594 {vectorizeContraction}); 595 } 596 597 static bool allIndexingsAreProjectedPermutation(LinalgOp op) { 598 return llvm::all_of(op.getIndexingMaps(), 599 [](AffineMap m) { return m.isProjectedPermutation(); }); 600 } 601 602 // TODO: probably need some extra checks for reduction followed by consumer 603 // ops that may not commute (e.g. linear reduction + non-linear instructions). 604 static LogicalResult reductionPreconditions(LinalgOp op) { 605 if (llvm::none_of(op.iterator_types(), isReductionIteratorType)) 606 return failure(); 607 for (auto &operand : op.getOutputOpOperands()) { 608 Operation *reductionOp = getSingleBinaryOpAssumedReduction(operand); 609 if (!getKindForOp(reductionOp)) 610 return failure(); 611 } 612 return success(); 613 } 614 615 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) { 616 auto linalgOp = cast<linalg::LinalgOp>(op); 617 // All types must be static shape to go to vector. 618 for (Value operand : linalgOp.getShapedOperands()) 619 if (!operand.getType().cast<ShapedType>().hasStaticShape()) 620 return failure(); 621 for (Type outputTensorType : linalgOp.getOutputTensorTypes()) 622 if (!outputTensorType.cast<ShapedType>().hasStaticShape()) 623 return failure(); 624 if (isElementwise(op)) 625 return success(); 626 if (isaContractionOpInterface(linalgOp)) 627 return success(); 628 // TODO: the common vector shape is equal to the static loop sizes only when 629 // all indexing maps are projected permutations. For convs and stencils the 630 // logic will need to evolve. 631 if (allIndexingsAreProjectedPermutation(linalgOp) && 632 succeeded(reductionPreconditions(linalgOp))) 633 return success(); 634 return failure(); 635 } 636 637 LogicalResult 638 mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, Operation *op, 639 SmallVectorImpl<Value> &newResults) { 640 if (failed(vectorizeLinalgOpPrecondition(op))) 641 return failure(); 642 643 edsc::ScopedContext scope(builder, op->getLoc()); 644 auto linalgOp = cast<LinalgOp>(op); 645 646 if (isaContractionOpInterface(linalgOp)) 647 return vectorizeContraction(builder, linalgOp, newResults); 648 649 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 650 << "Vectorize linalg op as a generic by broadcasting to " 651 "maximal common shape: " 652 << *op); 653 return vectorizeAsLinalgGeneric(builder, linalgOp, newResults, 654 /*broadcastToMaximalCommonShape=*/true); 655 } 656 657 //----------------------------------------------------------------------------// 658 // Misc. vectorization patterns. 659 //----------------------------------------------------------------------------// 660 661 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, TransferReadOp and 662 /// TransferWriteOp. For now, this only applies when all low and high paddings 663 /// are determined to be zero. 664 LogicalResult PadTensorOpVectorizationPattern::matchAndRewrite( 665 linalg::PadTensorOp padOp, PatternRewriter &rewriter) const { 666 // Helper function to determine whether an OpFoldResult is not a zero Index. 667 auto isNotZeroIndex = [](OpFoldResult ofr) { 668 if (Attribute attr = ofr.dyn_cast<Attribute>()) 669 return attr.cast<IntegerAttr>().getInt() != 0; 670 Value v = ofr.get<Value>(); 671 if (auto constOp = v.getDefiningOp<ConstantOp>()) 672 if (auto intAttr = constOp.getValue().dyn_cast<IntegerAttr>()) 673 return intAttr.getValue().getSExtValue() != 0; 674 return true; 675 }; 676 677 auto resultShapedType = padOp.result().getType().cast<ShapedType>(); 678 // Bail on non-static shapes. 679 if (!resultShapedType.hasStaticShape()) 680 return failure(); 681 682 // If any pad_low is not a static 0, needs a mask. Bail for now. 683 if (llvm::any_of(padOp.getMixedLowPad(), isNotZeroIndex)) 684 return failure(); 685 VectorType vectorType = extractVectorTypeFromShapedValue(padOp.result()); 686 if (!vectorType) 687 return failure(); 688 689 // Only support padding with a constant for now, i.e. either: 690 // 1. A BBarg from a different block. 691 // 2. A value defined outside of the current block. 692 Block &block = padOp.region().front(); 693 auto yieldOp = cast<YieldOp>(block.getTerminator()); 694 assert(yieldOp.getNumOperands() == 1 && "expected single operand yield"); 695 Value padValue = yieldOp.values().front(); 696 Operation *definingOp = padValue.getDefiningOp(); 697 if (definingOp && definingOp->getBlock() == &block) 698 return failure(); 699 if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block) 700 return failure(); 701 702 // TODO: if any pad_high is not a static 0, needs a mask. For now, just bail. 703 if (llvm::any_of(padOp.getMixedHighPad(), 704 [&](OpFoldResult ofr) { return isNotZeroIndex(ofr); })) 705 return failure(); 706 707 // Now we can rewrite as InitTensorOp + TransferReadOp@[0..0] + 708 // TransferWriteOp@[0..0]. 709 SmallVector<Value> indices( 710 resultShapedType.getRank(), 711 rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0)); 712 Value read = rewriter.create<vector::TransferReadOp>( 713 padOp.getLoc(), vectorType, padOp.source(), indices, padValue); 714 Value init = 715 rewriter.create<InitTensorOp>(padOp.getLoc(), resultShapedType.getShape(), 716 resultShapedType.getElementType()); 717 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(padOp, read, init, 718 indices); 719 720 return success(); 721 } 722 723 // TODO: cleanup all the convolution vectorization patterns. 724 template <class ConvOp, int N> 725 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite( 726 ConvOp op, PatternRewriter &rewriter) const { 727 Location loc = op.getLoc(); 728 MLIRContext *context = op.getContext(); 729 edsc::ScopedContext scope(rewriter, loc); 730 731 ShapedType inShapeType = op.getInputShapedType(0); 732 ShapedType kShapeType = op.getInputShapedType(1); 733 734 ArrayRef<int64_t> inShape = inShapeType.getShape(); 735 ArrayRef<int64_t> kShape = kShapeType.getShape(); 736 737 if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape()) 738 return failure(); 739 740 SmallVector<AffineExpr, 4> mapping; 741 SmallVector<int64_t, 4> vectorDims; 742 // Fail to apply when the size of not vectorized dimension is not 1. 743 for (unsigned i = 0; i < N; i++) { 744 if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1)) 745 return failure(); 746 747 if (mask[i] && inShape[i] != kShape[i]) 748 return failure(); 749 750 if (mask[i]) { 751 mapping.push_back(getAffineDimExpr(i, context)); 752 vectorDims.push_back(inShape[i]); 753 } 754 } 755 756 Value input = op.getInput(0); 757 Value kernel = op.getInput(1); 758 Value output = op.getOutputBuffer(0); 759 760 unsigned rank = inShapeType.getRank(); 761 unsigned numDims = mapping.size(); 762 Type elemType = inShapeType.getElementType(); 763 764 auto map = AffineMap::get(rank, 0, mapping, context); 765 SmallVector<Value, 4> zeros(rank, std_constant_index(0)); 766 auto vecType = VectorType::get(vectorDims, elemType); 767 768 auto inputVec = vector_transfer_read(vecType, input, zeros, map); 769 auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map); 770 771 auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType)); 772 773 std::array<AffineMap, 3> indexingMaps{ 774 AffineMap::getMultiDimIdentityMap(numDims, context), 775 AffineMap::getMultiDimIdentityMap(numDims, context), 776 AffineMap::get(numDims, 0, {}, context)}; 777 778 std::vector<StringRef> iteratorTypes(numDims, "reduction"); 779 780 auto result = rewriter.create<vector::ContractionOp>( 781 loc, inputVec, kernelVec, acc, 782 rewriter.getAffineMapArrayAttr(indexingMaps), 783 rewriter.getStrArrayAttr(iteratorTypes)); 784 785 rewriter.create<memref::StoreOp>(loc, result, output, ValueRange(zeros)); 786 rewriter.eraseOp(op); 787 return success(); 788 } 789 790 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>; 791 792 /// Inserts tiling, promotion and vectorization pattern for ConvOp 793 /// conversion into corresponding pattern lists. 794 template <typename ConvOp, unsigned N> 795 static void populateVectorizationPatterns( 796 RewritePatternSet &tilingPatterns, RewritePatternSet &promotionPatterns, 797 RewritePatternSet &vectorizationPatterns, ArrayRef<int64_t> tileSizes) { 798 auto *context = tilingPatterns.getContext(); 799 if (tileSizes.size() < N) 800 return; 801 802 constexpr static StringRef kTiledMarker = "TILED"; 803 constexpr static StringRef kPromotedMarker = "PROMOTED"; 804 tilingPatterns.add<LinalgTilingPattern<ConvOp>>( 805 context, LinalgTilingOptions().setTileSizes(tileSizes), 806 LinalgTransformationFilter(ArrayRef<Identifier>{}, 807 Identifier::get(kTiledMarker, context))); 808 809 promotionPatterns.add<LinalgPromotionPattern<ConvOp>>( 810 context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true), 811 LinalgTransformationFilter(Identifier::get(kTiledMarker, context), 812 Identifier::get(kPromotedMarker, context))); 813 814 SmallVector<bool, 4> mask(N); 815 int offset = tileSizes.size() - N; 816 std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(), 817 [](int64_t i) -> bool { return i > 1; }); 818 819 vectorizationPatterns.add<ConvOpVectorization<ConvOp, N>>(context, mask); 820 } 821 822 void mlir::linalg::populateConvVectorizationPatterns( 823 MLIRContext *context, SmallVectorImpl<RewritePatternSet> &patterns, 824 ArrayRef<int64_t> tileSizes) { 825 RewritePatternSet tiling(context); 826 RewritePatternSet promotion(context); 827 RewritePatternSet vectorization(context); 828 populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization, 829 tileSizes); 830 831 populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization, 832 tileSizes); 833 populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>( 834 tiling, promotion, vectorization, tileSizes); 835 836 populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization, 837 tileSizes); 838 populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>( 839 tiling, promotion, vectorization, tileSizes); 840 841 populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization, 842 tileSizes); 843 844 populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization, 845 tileSizes); 846 populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>( 847 tiling, promotion, vectorization, tileSizes); 848 849 populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization, 850 tileSizes); 851 populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>( 852 tiling, promotion, vectorization, tileSizes); 853 854 populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization, 855 tileSizes); 856 857 populateVectorizationPatterns<ConvNDHWCOp, 5>(tiling, promotion, 858 vectorization, tileSizes); 859 populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>( 860 tiling, promotion, vectorization, tileSizes); 861 862 populateVectorizationPatterns<ConvNCDHWOp, 5>(tiling, promotion, 863 vectorization, tileSizes); 864 populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>( 865 tiling, promotion, vectorization, tileSizes); 866 867 patterns.push_back(std::move(tiling)); 868 patterns.push_back(std::move(promotion)); 869 patterns.push_back(std::move(vectorization)); 870 } 871 872 //----------------------------------------------------------------------------// 873 // Forwarding patterns 874 //----------------------------------------------------------------------------// 875 876 /// Check whether there is any interleaved use of any `values` between `firstOp` 877 /// and `secondOp`. Conservatively return `true` if any op or value is in a 878 /// different block. 879 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp, 880 ValueRange values) { 881 if (firstOp->getBlock() != secondOp->getBlock() || 882 !firstOp->isBeforeInBlock(secondOp)) { 883 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 884 << "interleavedUses precondition failed, firstOp: " 885 << *firstOp << ", second op: " << *secondOp); 886 return true; 887 } 888 for (auto v : values) { 889 for (auto &u : v.getUses()) { 890 Operation *owner = u.getOwner(); 891 if (owner == firstOp || owner == secondOp) 892 continue; 893 // TODO: this is too conservative, use dominance info in the future. 894 if (owner->getBlock() == firstOp->getBlock() && 895 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner))) 896 continue; 897 LLVM_DEBUG(llvm::dbgs() 898 << "\n[" DEBUG_TYPE "]: " 899 << " found interleaved op " << *owner 900 << ", firstOp: " << *firstOp << ", second op: " << *secondOp); 901 return true; 902 } 903 } 904 return false; 905 } 906 907 /// Return the unique subview use of `v` if it is indeed unique, null otherwise. 908 static memref::SubViewOp getSubViewUseIfUnique(Value v) { 909 memref::SubViewOp subViewOp; 910 for (auto &u : v.getUses()) { 911 if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) { 912 if (subViewOp) 913 return memref::SubViewOp(); 914 subViewOp = newSubViewOp; 915 } 916 } 917 return subViewOp; 918 } 919 920 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 921 /// when available. 922 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite( 923 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const { 924 925 // Transfer into `view`. 926 Value viewOrAlloc = xferOp.source(); 927 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 928 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 929 return failure(); 930 931 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc); 932 933 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 934 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 935 if (!subViewOp) 936 return failure(); 937 Value subView = subViewOp.getResult(); 938 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 939 << "with subView " << subView); 940 941 // Find the copy into `subView` without interleaved uses. 942 CopyOp copyOp; 943 for (auto &u : subView.getUses()) { 944 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 945 if (newCopyOp.getOutputBuffer(0) != subView) 946 continue; 947 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 948 << "copy candidate " << *newCopyOp); 949 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView})) 950 continue; 951 copyOp = newCopyOp; 952 break; 953 } 954 } 955 if (!copyOp) 956 return failure(); 957 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 958 << "with copy " << *copyOp); 959 960 // Find the fill into `viewOrAlloc` without interleaved uses before the copy. 961 FillOp maybeFillOp; 962 for (auto &u : viewOrAlloc.getUses()) { 963 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) { 964 if (newFillOp.getOutputBuffer(0) != viewOrAlloc) 965 continue; 966 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 967 << "fill candidate " << *newFillOp); 968 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView})) 969 continue; 970 maybeFillOp = newFillOp; 971 break; 972 } 973 } 974 // Ensure padding matches. 975 if (maybeFillOp && xferOp.padding() != maybeFillOp.value()) 976 return failure(); 977 if (maybeFillOp) 978 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 979 << "with maybeFillOp " << *maybeFillOp); 980 981 // `in` is the subview that linalg.copy reads. Replace it. 982 Value in = copyOp.getInput(0); 983 984 // linalg.copy + linalg.fill can be used to create a padded local buffer. 985 // The `masked` attribute is only valid on this padded buffer. 986 // When forwarding to vector.transfer_read, the attribute must be reset 987 // conservatively. 988 Value res = rewriter.create<vector::TransferReadOp>( 989 xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(), 990 xferOp.permutation_map(), xferOp.padding(), ArrayAttr()); 991 992 if (maybeFillOp) 993 rewriter.eraseOp(maybeFillOp); 994 rewriter.eraseOp(copyOp); 995 rewriter.replaceOp(xferOp, res); 996 997 return success(); 998 } 999 1000 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 1001 /// when available. 1002 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite( 1003 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const { 1004 // Transfer into `viewOrAlloc`. 1005 Value viewOrAlloc = xferOp.source(); 1006 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 1007 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 1008 return failure(); 1009 1010 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 1011 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 1012 if (!subViewOp) 1013 return failure(); 1014 Value subView = subViewOp.getResult(); 1015 1016 // Find the copy from `subView` without interleaved uses. 1017 CopyOp copyOp; 1018 for (auto &u : subViewOp.getResult().getUses()) { 1019 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 1020 if (newCopyOp.getInput(0) != subView) 1021 continue; 1022 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView})) 1023 continue; 1024 copyOp = newCopyOp; 1025 break; 1026 } 1027 } 1028 if (!copyOp) 1029 return failure(); 1030 1031 // `out` is the subview copied into that we replace. 1032 Value out = copyOp.getOutputBuffer(0); 1033 1034 // Forward vector.transfer into copy. 1035 // linalg.copy + linalg.fill can be used to create a padded local buffer. 1036 // The `masked` attribute is only valid on this padded buffer. 1037 // When forwarding to vector.transfer_write, the attribute must be reset 1038 // conservatively. 1039 rewriter.create<vector::TransferWriteOp>( 1040 xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(), 1041 xferOp.permutation_map(), ArrayAttr()); 1042 1043 rewriter.eraseOp(copyOp); 1044 rewriter.eraseOp(xferOp); 1045 1046 return success(); 1047 } 1048