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 = inversePermutation( 497 reindexIndexingMap(linalgOp.getIndexingMap(bbarg.getArgNumber()))); 498 VectorType vectorType = VectorType::get(map.compose(shapedType.getShape()), 499 shapedType.getElementType()); 500 if (broadcastToMaximalCommonShape) { 501 map = vector::TransferReadOp::insertBroadcasts(map, vectorType, 502 commonVectorShape); 503 vectorType = 504 VectorType::get(commonVectorShape, vectorType.getElementType()); 505 } 506 Value vectorRead = buildVectorRead(builder, shapedArg, vectorType, map); 507 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg(" 508 << bbarg.getArgNumber() << "): " << vectorRead); 509 bvm.map(bbarg, vectorRead); 510 bvm.map(shapedArg, vectorRead); 511 } 512 513 auto hooks = llvm::to_vector<4>(customVectorizationHooks); 514 // 4a. Register CustomVectorizationHook for yieldOp. 515 CustomVectorizationHook vectorizeYield = 516 [&](Operation *op, 517 const BlockAndValueMapping &bvm) -> VectorizationResult { 518 return vectorizeLinalgYield(builder, op, bvm, linalgOp, newResults); 519 }; 520 hooks.push_back(vectorizeYield); 521 522 // 4b. Register CustomVectorizationHook for indexOp. 523 CustomVectorizationHook vectorizeIndex = 524 [&](Operation *op, 525 const BlockAndValueMapping &bvm) -> VectorizationResult { 526 return vectorizeLinalgIndex(builder, op, linalgOp); 527 }; 528 hooks.push_back(vectorizeIndex); 529 530 // 5. Iteratively call `vectorizeOneOp` to each op in the slice. 531 for (Operation &op : block.getOperations()) { 532 VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks); 533 if (result.status == VectorizationStatus::Failure) { 534 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op); 535 return failure(); 536 } 537 if (result.status == VectorizationStatus::NewOp) { 538 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: " 539 << *result.newOp;); 540 bvm.map(op.getResults(), result.newOp->getResults()); 541 } 542 } 543 544 return success(); 545 } 546 547 static LogicalResult vectorizeContraction(OpBuilder &builder, LinalgOp linalgOp, 548 SmallVectorImpl<Value> &newResults) { 549 assert(isaContractionOpInterface(linalgOp) && 550 "expected vectorizeContraction preconditions to be met"); 551 Location loc = linalgOp.getLoc(); 552 // Vectorize other ops as vector contraction. 553 // TODO: interface. 554 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 555 << "Rewrite linalg op as vector.contract: "; 556 linalgOp.dump()); 557 // Special function that describes how to vectorize the multiplication op in a 558 // linalg contraction. 559 CustomVectorizationHook vectorizeContraction = 560 [&](Operation *op, 561 const BlockAndValueMapping &bvm) -> VectorizationResult { 562 if (!isa<MulIOp, MulFOp>(op)) 563 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 564 auto outShape = linalgOp.getOutputShapedType(0).getShape(); 565 auto vType = outShape.empty() 566 ? op->getResult(0).getType() 567 : VectorType::get(outShape, op->getResult(0).getType()); 568 auto zero = 569 builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType)); 570 // Indexing maps at the time of vector.transfer_read are adjusted to order 571 // vector dimensions in the same order as the canonical linalg op iteration 572 // space order. 573 // The indexings for the contraction therefore need to be adjusted. 574 // TODO: consider dropping contraction special casing altogether, this will 575 // require more advanced canonicalizations involving vector.multi_reduction 576 // that are not yet available. 577 SmallVector<AffineMap> indexingMaps{ 578 inversePermutation(reindexIndexingMap(linalgOp.getIndexingMap(0))) 579 .compose(linalgOp.getIndexingMap(0)), 580 inversePermutation(reindexIndexingMap(linalgOp.getIndexingMap(1))) 581 .compose(linalgOp.getIndexingMap(1)), 582 inversePermutation(reindexIndexingMap(linalgOp.getIndexingMap(2))) 583 .compose(linalgOp.getIndexingMap(2))}; 584 Operation *contract = builder.create<vector::ContractionOp>( 585 loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero, 586 builder.getAffineMapArrayAttr(indexingMaps), linalgOp.iterator_types()); 587 return VectorizationResult{VectorizationStatus::NewOp, contract}; 588 }; 589 return vectorizeAsLinalgGeneric(builder, linalgOp, newResults, 590 /*broadcastToMaximalCommonShape=*/false, 591 {vectorizeContraction}); 592 } 593 594 static bool allIndexingsAreProjectedPermutation(LinalgOp op) { 595 return llvm::all_of(op.getIndexingMaps(), 596 [](AffineMap m) { return m.isProjectedPermutation(); }); 597 } 598 599 // TODO: probably need some extra checks for reduction followed by consumer 600 // ops that may not commute (e.g. linear reduction + non-linear instructions). 601 static LogicalResult reductionPreconditions(LinalgOp op) { 602 if (llvm::none_of(op.iterator_types(), isReductionIteratorType)) 603 return failure(); 604 for (auto &operand : op.getOutputOpOperands()) { 605 Operation *reductionOp = getSingleBinaryOpAssumedReduction(operand); 606 if (!getKindForOp(reductionOp)) 607 return failure(); 608 } 609 return success(); 610 } 611 612 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) { 613 auto linalgOp = cast<linalg::LinalgOp>(op); 614 // All types must be static shape to go to vector. 615 for (Value operand : linalgOp.getShapedOperands()) 616 if (!operand.getType().cast<ShapedType>().hasStaticShape()) 617 return failure(); 618 for (Type outputTensorType : linalgOp.getOutputTensorTypes()) 619 if (!outputTensorType.cast<ShapedType>().hasStaticShape()) 620 return failure(); 621 if (isElementwise(op)) 622 return success(); 623 if (isaContractionOpInterface(linalgOp)) 624 return success(); 625 // TODO: the common vector shape is equal to the static loop sizes only when 626 // all indexing maps are projected permutations. For convs and stencils the 627 // logic will need to evolve. 628 if (allIndexingsAreProjectedPermutation(linalgOp) && 629 succeeded(reductionPreconditions(linalgOp))) 630 return success(); 631 return failure(); 632 } 633 634 LogicalResult 635 mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, Operation *op, 636 SmallVectorImpl<Value> &newResults) { 637 if (failed(vectorizeLinalgOpPrecondition(op))) 638 return failure(); 639 640 edsc::ScopedContext scope(builder, op->getLoc()); 641 auto linalgOp = cast<LinalgOp>(op); 642 643 if (isaContractionOpInterface(linalgOp)) 644 return vectorizeContraction(builder, linalgOp, newResults); 645 646 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 647 << "Vectorize linalg op as a generic by broadcasting to " 648 "maximal common shape: " 649 << *op); 650 return vectorizeAsLinalgGeneric(builder, linalgOp, newResults, 651 /*broadcastToMaximalCommonShape=*/true); 652 } 653 654 //----------------------------------------------------------------------------// 655 // Misc. vectorization patterns. 656 //----------------------------------------------------------------------------// 657 658 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, TransferReadOp and 659 /// TransferWriteOp. For now, this only applies when all low and high paddings 660 /// are determined to be zero. 661 LogicalResult PadTensorOpVectorizationPattern::matchAndRewrite( 662 linalg::PadTensorOp padOp, PatternRewriter &rewriter) const { 663 // Helper function to determine whether an OpFoldResult is not a zero Index. 664 auto isNotZeroIndex = [](OpFoldResult ofr) { 665 if (Attribute attr = ofr.dyn_cast<Attribute>()) 666 return attr.cast<IntegerAttr>().getInt() != 0; 667 Value v = ofr.get<Value>(); 668 if (auto constOp = v.getDefiningOp<ConstantOp>()) 669 if (auto intAttr = constOp.getValue().dyn_cast<IntegerAttr>()) 670 return intAttr.getValue().getSExtValue() != 0; 671 return true; 672 }; 673 674 auto resultShapedType = padOp.result().getType().cast<ShapedType>(); 675 // Bail on non-static shapes. 676 if (!resultShapedType.hasStaticShape()) 677 return failure(); 678 679 // If any pad_low is not a static 0, needs a mask. Bail for now. 680 if (llvm::any_of(padOp.getMixedLowPad(), isNotZeroIndex)) 681 return failure(); 682 VectorType vectorType = extractVectorTypeFromShapedValue(padOp.result()); 683 if (!vectorType) 684 return failure(); 685 686 // Only support padding with a constant for now, i.e. either: 687 // 1. A BBarg from a different block. 688 // 2. A value defined outside of the current block. 689 Block &block = padOp.region().front(); 690 auto yieldOp = cast<YieldOp>(block.getTerminator()); 691 assert(yieldOp.getNumOperands() == 1 && "expected single operand yield"); 692 Value padValue = yieldOp.values().front(); 693 Operation *definingOp = padValue.getDefiningOp(); 694 if (definingOp && definingOp->getBlock() == &block) 695 return failure(); 696 if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block) 697 return failure(); 698 699 // TODO: if any pad_high is not a static 0, needs a mask. For now, just bail. 700 if (llvm::any_of(padOp.getMixedHighPad(), 701 [&](OpFoldResult ofr) { return isNotZeroIndex(ofr); })) 702 return failure(); 703 704 // Now we can rewrite as InitTensorOp + TransferReadOp@[0..0] + 705 // TransferWriteOp@[0..0]. 706 SmallVector<Value> indices( 707 resultShapedType.getRank(), 708 rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0)); 709 Value read = rewriter.create<vector::TransferReadOp>( 710 padOp.getLoc(), vectorType, padOp.source(), indices, padValue); 711 Value init = 712 rewriter.create<InitTensorOp>(padOp.getLoc(), resultShapedType.getShape(), 713 resultShapedType.getElementType()); 714 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(padOp, read, init, 715 indices); 716 717 return success(); 718 } 719 720 // TODO: cleanup all the convolution vectorization patterns. 721 template <class ConvOp, int N> 722 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite( 723 ConvOp op, PatternRewriter &rewriter) const { 724 Location loc = op.getLoc(); 725 MLIRContext *context = op.getContext(); 726 edsc::ScopedContext scope(rewriter, loc); 727 728 ShapedType inShapeType = op.getInputShapedType(0); 729 ShapedType kShapeType = op.getInputShapedType(1); 730 731 ArrayRef<int64_t> inShape = inShapeType.getShape(); 732 ArrayRef<int64_t> kShape = kShapeType.getShape(); 733 734 if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape()) 735 return failure(); 736 737 SmallVector<AffineExpr, 4> mapping; 738 SmallVector<int64_t, 4> vectorDims; 739 // Fail to apply when the size of not vectorized dimension is not 1. 740 for (unsigned i = 0; i < N; i++) { 741 if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1)) 742 return failure(); 743 744 if (mask[i] && inShape[i] != kShape[i]) 745 return failure(); 746 747 if (mask[i]) { 748 mapping.push_back(getAffineDimExpr(i, context)); 749 vectorDims.push_back(inShape[i]); 750 } 751 } 752 753 Value input = op.getInput(0); 754 Value kernel = op.getInput(1); 755 Value output = op.getOutputBuffer(0); 756 757 unsigned rank = inShapeType.getRank(); 758 unsigned numDims = mapping.size(); 759 Type elemType = inShapeType.getElementType(); 760 761 auto map = AffineMap::get(rank, 0, mapping, context); 762 SmallVector<Value, 4> zeros(rank, std_constant_index(0)); 763 auto vecType = VectorType::get(vectorDims, elemType); 764 765 auto inputVec = vector_transfer_read(vecType, input, zeros, map); 766 auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map); 767 768 auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType)); 769 770 std::array<AffineMap, 3> indexingMaps{ 771 AffineMap::getMultiDimIdentityMap(numDims, context), 772 AffineMap::getMultiDimIdentityMap(numDims, context), 773 AffineMap::get(numDims, 0, {}, context)}; 774 775 std::vector<StringRef> iteratorTypes(numDims, "reduction"); 776 777 auto result = rewriter.create<vector::ContractionOp>( 778 loc, inputVec, kernelVec, acc, 779 rewriter.getAffineMapArrayAttr(indexingMaps), 780 rewriter.getStrArrayAttr(iteratorTypes)); 781 782 rewriter.create<memref::StoreOp>(loc, result, output, ValueRange(zeros)); 783 rewriter.eraseOp(op); 784 return success(); 785 } 786 787 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>; 788 789 /// Inserts tiling, promotion and vectorization pattern for ConvOp 790 /// conversion into corresponding pattern lists. 791 template <typename ConvOp, unsigned N> 792 static void populateVectorizationPatterns( 793 RewritePatternSet &tilingPatterns, RewritePatternSet &promotionPatterns, 794 RewritePatternSet &vectorizationPatterns, ArrayRef<int64_t> tileSizes) { 795 auto *context = tilingPatterns.getContext(); 796 if (tileSizes.size() < N) 797 return; 798 799 constexpr static StringRef kTiledMarker = "TILED"; 800 constexpr static StringRef kPromotedMarker = "PROMOTED"; 801 tilingPatterns.add<LinalgTilingPattern<ConvOp>>( 802 context, LinalgTilingOptions().setTileSizes(tileSizes), 803 LinalgTransformationFilter(ArrayRef<Identifier>{}, 804 Identifier::get(kTiledMarker, context))); 805 806 promotionPatterns.add<LinalgPromotionPattern<ConvOp>>( 807 context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true), 808 LinalgTransformationFilter(Identifier::get(kTiledMarker, context), 809 Identifier::get(kPromotedMarker, context))); 810 811 SmallVector<bool, 4> mask(N); 812 int offset = tileSizes.size() - N; 813 std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(), 814 [](int64_t i) -> bool { return i > 1; }); 815 816 vectorizationPatterns.add<ConvOpVectorization<ConvOp, N>>(context, mask); 817 } 818 819 void mlir::linalg::populateConvVectorizationPatterns( 820 MLIRContext *context, SmallVectorImpl<RewritePatternSet> &patterns, 821 ArrayRef<int64_t> tileSizes) { 822 RewritePatternSet tiling(context); 823 RewritePatternSet promotion(context); 824 RewritePatternSet vectorization(context); 825 populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization, 826 tileSizes); 827 828 populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization, 829 tileSizes); 830 populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>( 831 tiling, promotion, vectorization, tileSizes); 832 833 populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization, 834 tileSizes); 835 populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>( 836 tiling, promotion, vectorization, tileSizes); 837 838 populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization, 839 tileSizes); 840 841 populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization, 842 tileSizes); 843 populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>( 844 tiling, promotion, vectorization, tileSizes); 845 846 populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization, 847 tileSizes); 848 populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>( 849 tiling, promotion, vectorization, tileSizes); 850 851 populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization, 852 tileSizes); 853 854 populateVectorizationPatterns<ConvNDHWCOp, 5>(tiling, promotion, 855 vectorization, tileSizes); 856 populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>( 857 tiling, promotion, vectorization, tileSizes); 858 859 populateVectorizationPatterns<ConvNCDHWOp, 5>(tiling, promotion, 860 vectorization, tileSizes); 861 populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>( 862 tiling, promotion, vectorization, tileSizes); 863 864 patterns.push_back(std::move(tiling)); 865 patterns.push_back(std::move(promotion)); 866 patterns.push_back(std::move(vectorization)); 867 } 868 869 //----------------------------------------------------------------------------// 870 // Forwarding patterns 871 //----------------------------------------------------------------------------// 872 873 /// Check whether there is any interleaved use of any `values` between `firstOp` 874 /// and `secondOp`. Conservatively return `true` if any op or value is in a 875 /// different block. 876 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp, 877 ValueRange values) { 878 if (firstOp->getBlock() != secondOp->getBlock() || 879 !firstOp->isBeforeInBlock(secondOp)) { 880 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 881 << "interleavedUses precondition failed, firstOp: " 882 << *firstOp << ", second op: " << *secondOp); 883 return true; 884 } 885 for (auto v : values) { 886 for (auto &u : v.getUses()) { 887 Operation *owner = u.getOwner(); 888 if (owner == firstOp || owner == secondOp) 889 continue; 890 // TODO: this is too conservative, use dominance info in the future. 891 if (owner->getBlock() == firstOp->getBlock() && 892 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner))) 893 continue; 894 LLVM_DEBUG(llvm::dbgs() 895 << "\n[" DEBUG_TYPE "]: " 896 << " found interleaved op " << *owner 897 << ", firstOp: " << *firstOp << ", second op: " << *secondOp); 898 return true; 899 } 900 } 901 return false; 902 } 903 904 /// Return the unique subview use of `v` if it is indeed unique, null otherwise. 905 static memref::SubViewOp getSubViewUseIfUnique(Value v) { 906 memref::SubViewOp subViewOp; 907 for (auto &u : v.getUses()) { 908 if (auto newSubViewOp = dyn_cast<memref::SubViewOp>(u.getOwner())) { 909 if (subViewOp) 910 return memref::SubViewOp(); 911 subViewOp = newSubViewOp; 912 } 913 } 914 return subViewOp; 915 } 916 917 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 918 /// when available. 919 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite( 920 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const { 921 922 // Transfer into `view`. 923 Value viewOrAlloc = xferOp.source(); 924 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 925 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 926 return failure(); 927 928 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc); 929 930 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 931 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 932 if (!subViewOp) 933 return failure(); 934 Value subView = subViewOp.getResult(); 935 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 936 << "with subView " << subView); 937 938 // Find the copy into `subView` without interleaved uses. 939 CopyOp copyOp; 940 for (auto &u : subView.getUses()) { 941 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 942 if (newCopyOp.getOutputBuffer(0) != subView) 943 continue; 944 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 945 << "copy candidate " << *newCopyOp); 946 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView})) 947 continue; 948 copyOp = newCopyOp; 949 break; 950 } 951 } 952 if (!copyOp) 953 return failure(); 954 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 955 << "with copy " << *copyOp); 956 957 // Find the fill into `viewOrAlloc` without interleaved uses before the copy. 958 FillOp maybeFillOp; 959 for (auto &u : viewOrAlloc.getUses()) { 960 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) { 961 if (newFillOp.getOutputBuffer(0) != viewOrAlloc) 962 continue; 963 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 964 << "fill candidate " << *newFillOp); 965 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView})) 966 continue; 967 maybeFillOp = newFillOp; 968 break; 969 } 970 } 971 // Ensure padding matches. 972 if (maybeFillOp && xferOp.padding() != maybeFillOp.value()) 973 return failure(); 974 if (maybeFillOp) 975 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 976 << "with maybeFillOp " << *maybeFillOp); 977 978 // `in` is the subview that linalg.copy reads. Replace it. 979 Value in = copyOp.getInput(0); 980 981 // linalg.copy + linalg.fill can be used to create a padded local buffer. 982 // The `masked` attribute is only valid on this padded buffer. 983 // When forwarding to vector.transfer_read, the attribute must be reset 984 // conservatively. 985 Value res = rewriter.create<vector::TransferReadOp>( 986 xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(), 987 xferOp.permutation_map(), xferOp.padding(), ArrayAttr()); 988 989 if (maybeFillOp) 990 rewriter.eraseOp(maybeFillOp); 991 rewriter.eraseOp(copyOp); 992 rewriter.replaceOp(xferOp, res); 993 994 return success(); 995 } 996 997 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 998 /// when available. 999 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite( 1000 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const { 1001 // Transfer into `viewOrAlloc`. 1002 Value viewOrAlloc = xferOp.source(); 1003 if (!viewOrAlloc.getDefiningOp<memref::ViewOp>() && 1004 !viewOrAlloc.getDefiningOp<memref::AllocOp>()) 1005 return failure(); 1006 1007 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 1008 memref::SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 1009 if (!subViewOp) 1010 return failure(); 1011 Value subView = subViewOp.getResult(); 1012 1013 // Find the copy from `subView` without interleaved uses. 1014 CopyOp copyOp; 1015 for (auto &u : subViewOp.getResult().getUses()) { 1016 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 1017 if (newCopyOp.getInput(0) != subView) 1018 continue; 1019 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView})) 1020 continue; 1021 copyOp = newCopyOp; 1022 break; 1023 } 1024 } 1025 if (!copyOp) 1026 return failure(); 1027 1028 // `out` is the subview copied into that we replace. 1029 Value out = copyOp.getOutputBuffer(0); 1030 1031 // Forward vector.transfer into copy. 1032 // linalg.copy + linalg.fill can be used to create a padded local buffer. 1033 // The `masked` attribute is only valid on this padded buffer. 1034 // When forwarding to vector.transfer_write, the attribute must be reset 1035 // conservatively. 1036 rewriter.create<vector::TransferWriteOp>( 1037 xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(), 1038 xferOp.permutation_map(), ArrayAttr()); 1039 1040 rewriter.eraseOp(copyOp); 1041 rewriter.eraseOp(xferOp); 1042 1043 return success(); 1044 } 1045