1 //===- VectorToSCF.cpp - Conversion from Vector to mix of SCF and Std -----===// 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 target-dependent lowering of vector transfer operations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include <type_traits> 14 15 #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" 16 #include "mlir/Dialect/Affine/EDSC/Intrinsics.h" 17 #include "mlir/Dialect/SCF/EDSC/Builders.h" 18 #include "mlir/Dialect/SCF/EDSC/Intrinsics.h" 19 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 20 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 21 #include "mlir/Dialect/Vector/VectorOps.h" 22 #include "mlir/Dialect/Vector/VectorUtils.h" 23 #include "mlir/IR/AffineExpr.h" 24 #include "mlir/IR/AffineMap.h" 25 #include "mlir/IR/Attributes.h" 26 #include "mlir/IR/Builders.h" 27 #include "mlir/IR/Location.h" 28 #include "mlir/IR/Matchers.h" 29 #include "mlir/IR/OperationSupport.h" 30 #include "mlir/IR/PatternMatch.h" 31 #include "mlir/IR/Types.h" 32 33 using namespace mlir; 34 using namespace mlir::edsc; 35 using namespace mlir::edsc::intrinsics; 36 using vector::TransferReadOp; 37 using vector::TransferWriteOp; 38 39 namespace { 40 /// Helper class captures the common information needed to lower N>1-D vector 41 /// transfer operations (read and write). 42 /// On construction, this class opens an edsc::ScopedContext for simpler IR 43 /// manipulation. 44 /// In pseudo-IR, for an n-D vector_transfer_read such as: 45 /// 46 /// ``` 47 /// vector_transfer_read(%m, %offsets, identity_map, %fill) : 48 /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 49 /// vector<(major_dims) x (minor_dims) x type> 50 /// ``` 51 /// 52 /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or 53 /// higher). 54 /// 55 /// This is the entry point to emitting pseudo-IR resembling: 56 /// 57 /// ``` 58 /// %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>> 59 /// for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest 60 /// if (any_of(%ivs_major + %offsets, <, major_dims)) { 61 /// %v = vector_transfer_read( 62 /// {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor}, 63 /// %ivs_minor): 64 /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 65 /// vector<(minor_dims) x type>; 66 /// store(%v, %tmp); 67 /// } else { 68 /// %v = splat(vector<(minor_dims) x type>, %fill) 69 /// store(%v, %tmp, %ivs_major); 70 /// } 71 /// } 72 /// %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>): 73 // vector<(major_dims) x (minor_dims) x type> 74 /// ``` 75 /// 76 template <typename ConcreteOp> 77 class NDTransferOpHelper { 78 public: 79 NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp, 80 const VectorTransferToSCFOptions &options) 81 : rewriter(rewriter), options(options), loc(xferOp.getLoc()), 82 scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp), 83 op(xferOp.getOperation()) { 84 vectorType = xferOp.getVectorType(); 85 // TODO(ntv, ajcbik): when we go to k > 1-D vectors adapt minorRank. 86 minorRank = 1; 87 majorRank = vectorType.getRank() - minorRank; 88 leadingRank = xferOp.getMemRefType().getRank() - (majorRank + minorRank); 89 majorVectorType = 90 VectorType::get(vectorType.getShape().take_front(majorRank), 91 vectorType.getElementType()); 92 minorVectorType = 93 VectorType::get(vectorType.getShape().take_back(minorRank), 94 vectorType.getElementType()); 95 /// Memref of minor vector type is used for individual transfers. 96 memRefMinorVectorType = 97 MemRefType::get(majorVectorType.getShape(), minorVectorType, {}, 98 xferOp.getMemRefType().getMemorySpace()); 99 } 100 101 LogicalResult doReplace(); 102 103 private: 104 /// Creates the loop nest on the "major" dimensions and calls the 105 /// `loopBodyBuilder` lambda in the context of the loop nest. 106 template <typename Lambda> 107 void emitLoops(Lambda loopBodyBuilder); 108 109 /// Operate within the body of `emitLoops` to: 110 /// 1. Compute the indexings `majorIvs + majorOffsets` and save them in 111 /// `majorIvsPlusOffsets`. 112 /// 2. Return a boolean that determines whether the first `majorIvs.rank()` 113 /// dimensions `majorIvs + majorOffsets` are all within `memrefBounds`. 114 Value emitInBoundsCondition(ValueRange majorIvs, ValueRange majorOffsets, 115 MemRefBoundsCapture &memrefBounds, 116 SmallVectorImpl<Value> &majorIvsPlusOffsets); 117 118 /// Common state to lower vector transfer ops. 119 PatternRewriter &rewriter; 120 const VectorTransferToSCFOptions &options; 121 Location loc; 122 std::unique_ptr<ScopedContext> scope; 123 ConcreteOp xferOp; 124 Operation *op; 125 // A vector transfer copies data between: 126 // - memref<(leading_dims) x (major_dims) x (minor_dims) x type> 127 // - vector<(major_dims) x (minor_dims) x type> 128 unsigned minorRank; // for now always 1 129 unsigned majorRank; // vector rank - minorRank 130 unsigned leadingRank; // memref rank - vector rank 131 VectorType vectorType; // vector<(major_dims) x (minor_dims) x type> 132 VectorType majorVectorType; // vector<(major_dims) x type> 133 VectorType minorVectorType; // vector<(minor_dims) x type> 134 MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>> 135 }; 136 137 template <typename ConcreteOp> 138 template <typename Lambda> 139 void NDTransferOpHelper<ConcreteOp>::emitLoops(Lambda loopBodyBuilder) { 140 /// Loop nest operates on the major dimensions 141 MemRefBoundsCapture memrefBoundsCapture(xferOp.memref()); 142 143 if (options.unroll) { 144 auto shape = majorVectorType.getShape(); 145 auto strides = computeStrides(shape); 146 unsigned numUnrolledInstances = computeMaxLinearIndex(shape); 147 ValueRange indices(xferOp.indices()); 148 for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) { 149 SmallVector<int64_t, 4> offsets = delinearize(strides, idx); 150 SmallVector<Value, 4> offsetValues = 151 llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value { 152 return std_constant_index(off); 153 })); 154 loopBodyBuilder(offsetValues, indices.take_front(leadingRank), 155 indices.drop_front(leadingRank).take_front(majorRank), 156 indices.take_back(minorRank), memrefBoundsCapture); 157 } 158 } else { 159 VectorBoundsCapture vectorBoundsCapture(majorVectorType); 160 auto majorLbs = vectorBoundsCapture.getLbs(); 161 auto majorUbs = vectorBoundsCapture.getUbs(); 162 auto majorSteps = vectorBoundsCapture.getSteps(); 163 SmallVector<Value, 8> majorIvs(vectorBoundsCapture.rank()); 164 AffineLoopNestBuilder(majorIvs, majorLbs, majorUbs, majorSteps)([&] { 165 ValueRange indices(xferOp.indices()); 166 loopBodyBuilder(majorIvs, indices.take_front(leadingRank), 167 indices.drop_front(leadingRank).take_front(majorRank), 168 indices.take_back(minorRank), memrefBoundsCapture); 169 }); 170 } 171 } 172 173 template <typename ConcreteOp> 174 Value NDTransferOpHelper<ConcreteOp>::emitInBoundsCondition( 175 ValueRange majorIvs, ValueRange majorOffsets, 176 MemRefBoundsCapture &memrefBounds, 177 SmallVectorImpl<Value> &majorIvsPlusOffsets) { 178 Value inBoundsCondition; 179 majorIvsPlusOffsets.reserve(majorIvs.size()); 180 unsigned idx = 0; 181 for (auto it : llvm::zip(majorIvs, majorOffsets, memrefBounds.getUbs())) { 182 Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it); 183 using namespace mlir::edsc::op; 184 majorIvsPlusOffsets.push_back(iv + off); 185 if (xferOp.isMaskedDim(leadingRank + idx)) { 186 Value inBounds = majorIvsPlusOffsets.back() < ub; 187 inBoundsCondition = 188 (inBoundsCondition) ? (inBoundsCondition && inBounds) : inBounds; 189 } 190 ++idx; 191 } 192 return inBoundsCondition; 193 } 194 195 template <> 196 LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() { 197 Value alloc, result; 198 if (options.unroll) 199 result = std_splat(vectorType, xferOp.padding()); 200 else 201 alloc = std_alloc(memRefMinorVectorType); 202 203 emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 204 ValueRange majorOffsets, ValueRange minorOffsets, 205 MemRefBoundsCapture &memrefBounds) { 206 /// Lambda to load 1-D vector in the current loop ivs + offset context. 207 auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value { 208 SmallVector<Value, 8> indexing; 209 indexing.reserve(leadingRank + majorRank + minorRank); 210 indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 211 indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 212 indexing.append(minorOffsets.begin(), minorOffsets.end()); 213 Value memref = xferOp.memref(); 214 auto map = TransferReadOp::getTransferMinorIdentityMap( 215 xferOp.getMemRefType(), minorVectorType); 216 ArrayAttr masked; 217 if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 218 OpBuilder &b = ScopedContext::getBuilderRef(); 219 masked = b.getBoolArrayAttr({true}); 220 } 221 return vector_transfer_read(minorVectorType, memref, indexing, 222 AffineMapAttr::get(map), xferOp.padding(), 223 masked); 224 }; 225 226 // 1. Compute the inBoundsCondition in the current loops ivs + offset 227 // context. 228 SmallVector<Value, 4> majorIvsPlusOffsets; 229 Value inBoundsCondition = emitInBoundsCondition( 230 majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 231 232 if (inBoundsCondition) { 233 // 2. If the condition is not null, we need an IfOp, which may yield 234 // if `options.unroll` is true. 235 SmallVector<Type, 1> resultType; 236 if (options.unroll) 237 resultType.push_back(vectorType); 238 auto ifOp = ScopedContext::getBuilderRef().create<scf::IfOp>( 239 ScopedContext::getLocation(), resultType, inBoundsCondition, 240 /*withElseRegion=*/true); 241 242 // 3.a. If in-bounds, progressively lower to a 1-D transfer read. 243 BlockBuilder(&ifOp.thenRegion().front(), Append())([&] { 244 Value vector = load1DVector(majorIvsPlusOffsets); 245 // 3.a.i. If `options.unroll` is true, insert the 1-D vector in the 246 // aggregate. We must yield and merge with the `else` branch. 247 if (options.unroll) { 248 vector = vector_insert(vector, result, majorIvs); 249 (loop_yield(vector)); 250 return; 251 } 252 // 3.a.ii. Otherwise, just go through the temporary `alloc`. 253 std_store(vector, alloc, majorIvs); 254 }); 255 256 // 3.b. If not in-bounds, splat a 1-D vector. 257 BlockBuilder(&ifOp.elseRegion().front(), Append())([&] { 258 Value vector = std_splat(minorVectorType, xferOp.padding()); 259 // 3.a.i. If `options.unroll` is true, insert the 1-D vector in the 260 // aggregate. We must yield and merge with the `then` branch. 261 if (options.unroll) { 262 vector = vector_insert(vector, result, majorIvs); 263 (loop_yield(vector)); 264 return; 265 } 266 // 3.b.ii. Otherwise, just go through the temporary `alloc`. 267 std_store(vector, alloc, majorIvs); 268 }); 269 if (!resultType.empty()) 270 result = *ifOp.results().begin(); 271 } else { 272 // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read. 273 Value loaded1D = load1DVector(majorIvsPlusOffsets); 274 // 5.a. If `options.unroll` is true, insert the 1-D vector in the 275 // aggregate. 276 if (options.unroll) 277 result = vector_insert(loaded1D, result, majorIvs); 278 // 5.b. Otherwise, just go through the temporary `alloc`. 279 else 280 std_store(loaded1D, alloc, majorIvs); 281 } 282 }); 283 284 assert((!options.unroll ^ result) && "Expected resulting Value iff unroll"); 285 if (!result) 286 result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc)); 287 rewriter.replaceOp(op, result); 288 289 return success(); 290 } 291 292 template <> 293 LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() { 294 Value alloc; 295 if (!options.unroll) { 296 alloc = std_alloc(memRefMinorVectorType); 297 std_store(xferOp.vector(), 298 vector_type_cast(MemRefType::get({}, vectorType), alloc)); 299 } 300 301 emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 302 ValueRange majorOffsets, ValueRange minorOffsets, 303 MemRefBoundsCapture &memrefBounds) { 304 // Lower to 1-D vector_transfer_write and let recursion handle it. 305 auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) { 306 SmallVector<Value, 8> indexing; 307 indexing.reserve(leadingRank + majorRank + minorRank); 308 indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 309 indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 310 indexing.append(minorOffsets.begin(), minorOffsets.end()); 311 Value result; 312 // If `options.unroll` is true, extract the 1-D vector from the 313 // aggregate. 314 if (options.unroll) 315 result = vector_extract(xferOp.vector(), majorIvs); 316 else 317 result = std_load(alloc, majorIvs); 318 auto map = TransferWriteOp::getTransferMinorIdentityMap( 319 xferOp.getMemRefType(), minorVectorType); 320 ArrayAttr masked; 321 if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 322 OpBuilder &b = ScopedContext::getBuilderRef(); 323 masked = b.getBoolArrayAttr({true}); 324 } 325 vector_transfer_write(result, xferOp.memref(), indexing, 326 AffineMapAttr::get(map), masked); 327 }; 328 329 // 1. Compute the inBoundsCondition in the current loops ivs + offset 330 // context. 331 SmallVector<Value, 4> majorIvsPlusOffsets; 332 Value inBoundsCondition = emitInBoundsCondition( 333 majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 334 335 if (inBoundsCondition) { 336 // 2.a. If the condition is not null, we need an IfOp, to write 337 // conditionally. Progressively lower to a 1-D transfer write. 338 auto ifOp = ScopedContext::getBuilderRef().create<scf::IfOp>( 339 ScopedContext::getLocation(), TypeRange{}, inBoundsCondition, 340 /*withElseRegion=*/false); 341 BlockBuilder(&ifOp.thenRegion().front(), 342 Append())([&] { emitTransferWrite(majorIvsPlusOffsets); }); 343 } else { 344 // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write. 345 emitTransferWrite(majorIvsPlusOffsets); 346 } 347 }); 348 349 rewriter.eraseOp(op); 350 351 return success(); 352 } 353 354 } // namespace 355 356 /// Analyzes the `transfer` to find an access dimension along the fastest remote 357 /// MemRef dimension. If such a dimension with coalescing properties is found, 358 /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of 359 /// LoopNestBuilder captures it in the innermost loop. 360 template <typename TransferOpTy> 361 static int computeCoalescedIndex(TransferOpTy transfer) { 362 // rank of the remote memory access, coalescing behavior occurs on the 363 // innermost memory dimension. 364 auto remoteRank = transfer.getMemRefType().getRank(); 365 // Iterate over the results expressions of the permutation map to determine 366 // the loop order for creating pointwise copies between remote and local 367 // memories. 368 int coalescedIdx = -1; 369 auto exprs = transfer.permutation_map().getResults(); 370 for (auto en : llvm::enumerate(exprs)) { 371 auto dim = en.value().template dyn_cast<AffineDimExpr>(); 372 if (!dim) { 373 continue; 374 } 375 auto memRefDim = dim.getPosition(); 376 if (memRefDim == remoteRank - 1) { 377 // memRefDim has coalescing properties, it should be swapped in the last 378 // position. 379 assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices"); 380 coalescedIdx = en.index(); 381 } 382 } 383 return coalescedIdx; 384 } 385 386 /// Emits remote memory accesses that are clipped to the boundaries of the 387 /// MemRef. 388 template <typename TransferOpTy> 389 static SmallVector<Value, 8> 390 clip(TransferOpTy transfer, MemRefBoundsCapture &bounds, ArrayRef<Value> ivs) { 391 using namespace mlir::edsc; 392 393 Value zero(std_constant_index(0)), one(std_constant_index(1)); 394 SmallVector<Value, 8> memRefAccess(transfer.indices()); 395 SmallVector<Value, 8> clippedScalarAccessExprs(memRefAccess.size()); 396 // Indices accessing to remote memory are clipped and their expressions are 397 // returned in clippedScalarAccessExprs. 398 for (unsigned memRefDim = 0; memRefDim < clippedScalarAccessExprs.size(); 399 ++memRefDim) { 400 // Linear search on a small number of entries. 401 int loopIndex = -1; 402 auto exprs = transfer.permutation_map().getResults(); 403 for (auto en : llvm::enumerate(exprs)) { 404 auto expr = en.value(); 405 auto dim = expr.template dyn_cast<AffineDimExpr>(); 406 // Sanity check. 407 assert( 408 (dim || expr.template cast<AffineConstantExpr>().getValue() == 0) && 409 "Expected dim or 0 in permutationMap"); 410 if (dim && memRefDim == dim.getPosition()) { 411 loopIndex = en.index(); 412 break; 413 } 414 } 415 416 // We cannot distinguish atm between unrolled dimensions that implement 417 // the "always full" tile abstraction and need clipping from the other 418 // ones. So we conservatively clip everything. 419 using namespace edsc::op; 420 auto N = bounds.ub(memRefDim); 421 auto i = memRefAccess[memRefDim]; 422 if (loopIndex < 0) { 423 auto N_minus_1 = N - one; 424 auto select_1 = std_select(i < N, i, N_minus_1); 425 clippedScalarAccessExprs[memRefDim] = 426 std_select(i < zero, zero, select_1); 427 } else { 428 auto ii = ivs[loopIndex]; 429 auto i_plus_ii = i + ii; 430 auto N_minus_1 = N - one; 431 auto select_1 = std_select(i_plus_ii < N, i_plus_ii, N_minus_1); 432 clippedScalarAccessExprs[memRefDim] = 433 std_select(i_plus_ii < zero, zero, select_1); 434 } 435 } 436 437 return clippedScalarAccessExprs; 438 } 439 440 template <typename TransferOpTy> 441 VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter( 442 VectorTransferToSCFOptions options, MLIRContext *context) 443 : RewritePattern(TransferOpTy::getOperationName(), 1, context), 444 options(options) {} 445 446 /// Used for staging the transfer in a local buffer. 447 template <typename TransferOpTy> 448 MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType( 449 TransferOpTy transfer) const { 450 auto vectorType = transfer.getVectorType(); 451 return MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {}, 452 0); 453 } 454 455 /// Lowers TransferReadOp into a combination of: 456 /// 1. local memory allocation; 457 /// 2. perfect loop nest over: 458 /// a. scalar load from local buffers (viewed as a scalar memref); 459 /// a. scalar store to original memref (with clipping). 460 /// 3. vector_load from local buffer (viewed as a memref<1 x vector>); 461 /// 4. local memory deallocation. 462 /// 463 /// Lowers the data transfer part of a TransferReadOp while ensuring no 464 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 465 /// clipping. This means that a given value in memory can be read multiple 466 /// times and concurrently. 467 /// 468 /// Important notes about clipping and "full-tiles only" abstraction: 469 /// ================================================================= 470 /// When using clipping for dealing with boundary conditions, the same edge 471 /// value will appear multiple times (a.k.a edge padding). This is fine if the 472 /// subsequent vector operations are all data-parallel but **is generally 473 /// incorrect** in the presence of reductions or extract operations. 474 /// 475 /// More generally, clipping is a scalar abstraction that is expected to work 476 /// fine as a baseline for CPUs and GPUs but not for vector_load and DMAs. 477 /// To deal with real vector_load and DMAs, a "padded allocation + view" 478 /// abstraction with the ability to read out-of-memref-bounds (but still within 479 /// the allocated region) is necessary. 480 /// 481 /// Whether using scalar loops or vector_load/DMAs to perform the transfer, 482 /// junk values will be materialized in the vectors and generally need to be 483 /// filtered out and replaced by the "neutral element". This neutral element is 484 /// op-dependent so, in the future, we expect to create a vector filter and 485 /// apply it to a splatted constant vector with the proper neutral element at 486 /// each ssa-use. This filtering is not necessary for pure data-parallel 487 /// operations. 488 /// 489 /// In the case of vector_store/DMAs, Read-Modify-Write will be required, which 490 /// also have concurrency implications. Note that by using clipped scalar stores 491 /// in the presence of data-parallel only operations, we generate code that 492 /// writes the same value multiple time on the edge locations. 493 /// 494 /// TODO(ntv): implement alternatives to clipping. 495 /// TODO(ntv): support non-data-parallel operations. 496 497 /// Performs the rewrite. 498 template <> 499 LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite( 500 Operation *op, PatternRewriter &rewriter) const { 501 using namespace mlir::edsc::op; 502 503 TransferReadOp transfer = cast<TransferReadOp>(op); 504 if (AffineMap::isMinorIdentity(transfer.permutation_map())) { 505 // If > 1D, emit a bunch of loops around 1-D vector transfers. 506 if (transfer.getVectorType().getRank() > 1) 507 return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options) 508 .doReplace(); 509 // If 1-D this is now handled by the target-specific lowering. 510 if (transfer.getVectorType().getRank() == 1) 511 return failure(); 512 } 513 514 // Conservative lowering to scalar load / stores. 515 // 1. Setup all the captures. 516 ScopedContext scope(rewriter, transfer.getLoc()); 517 StdIndexedValue remote(transfer.memref()); 518 MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 519 VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 520 int coalescedIdx = computeCoalescedIndex(transfer); 521 // Swap the vectorBoundsCapture which will reorder loop bounds. 522 if (coalescedIdx >= 0) 523 vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 524 coalescedIdx); 525 526 auto lbs = vectorBoundsCapture.getLbs(); 527 auto ubs = vectorBoundsCapture.getUbs(); 528 SmallVector<Value, 8> steps; 529 steps.reserve(vectorBoundsCapture.getSteps().size()); 530 for (auto step : vectorBoundsCapture.getSteps()) 531 steps.push_back(std_constant_index(step)); 532 533 // 2. Emit alloc-copy-load-dealloc. 534 Value tmp = std_alloc(tmpMemRefType(transfer)); 535 StdIndexedValue local(tmp); 536 Value vec = vector_type_cast(tmp); 537 loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 538 auto ivs = llvm::to_vector<8>(loopIvs); 539 // Swap the ivs which will reorder memory accesses. 540 if (coalescedIdx >= 0) 541 std::swap(ivs.back(), ivs[coalescedIdx]); 542 // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 543 local(ivs) = remote(clip(transfer, memRefBoundsCapture, ivs)); 544 }); 545 Value vectorValue = std_load(vec); 546 (std_dealloc(tmp)); // vexing parse 547 548 // 3. Propagate. 549 rewriter.replaceOp(op, vectorValue); 550 return success(); 551 } 552 553 /// Lowers TransferWriteOp into a combination of: 554 /// 1. local memory allocation; 555 /// 2. vector_store to local buffer (viewed as a memref<1 x vector>); 556 /// 3. perfect loop nest over: 557 /// a. scalar load from local buffers (viewed as a scalar memref); 558 /// a. scalar store to original memref (with clipping). 559 /// 4. local memory deallocation. 560 /// 561 /// More specifically, lowers the data transfer part while ensuring no 562 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 563 /// clipping. This means that a given value in memory can be written to multiple 564 /// times and concurrently. 565 /// 566 /// See `Important notes about clipping and full-tiles only abstraction` in the 567 /// description of `readClipped` above. 568 /// 569 /// TODO(ntv): implement alternatives to clipping. 570 /// TODO(ntv): support non-data-parallel operations. 571 template <> 572 LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite( 573 Operation *op, PatternRewriter &rewriter) const { 574 using namespace edsc::op; 575 576 TransferWriteOp transfer = cast<TransferWriteOp>(op); 577 if (AffineMap::isMinorIdentity(transfer.permutation_map())) { 578 // If > 1D, emit a bunch of loops around 1-D vector transfers. 579 if (transfer.getVectorType().getRank() > 1) 580 return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options) 581 .doReplace(); 582 // If 1-D this is now handled by the target-specific lowering. 583 if (transfer.getVectorType().getRank() == 1) 584 return failure(); 585 } 586 587 // 1. Setup all the captures. 588 ScopedContext scope(rewriter, transfer.getLoc()); 589 StdIndexedValue remote(transfer.memref()); 590 MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 591 Value vectorValue(transfer.vector()); 592 VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 593 int coalescedIdx = computeCoalescedIndex(transfer); 594 // Swap the vectorBoundsCapture which will reorder loop bounds. 595 if (coalescedIdx >= 0) 596 vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 597 coalescedIdx); 598 599 auto lbs = vectorBoundsCapture.getLbs(); 600 auto ubs = vectorBoundsCapture.getUbs(); 601 SmallVector<Value, 8> steps; 602 steps.reserve(vectorBoundsCapture.getSteps().size()); 603 for (auto step : vectorBoundsCapture.getSteps()) 604 steps.push_back(std_constant_index(step)); 605 606 // 2. Emit alloc-store-copy-dealloc. 607 Value tmp = std_alloc(tmpMemRefType(transfer)); 608 StdIndexedValue local(tmp); 609 Value vec = vector_type_cast(tmp); 610 std_store(vectorValue, vec); 611 loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 612 auto ivs = llvm::to_vector<8>(loopIvs); 613 // Swap the ivs which will reorder memory accesses. 614 if (coalescedIdx >= 0) 615 std::swap(ivs.back(), ivs[coalescedIdx]); 616 // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 617 remote(clip(transfer, memRefBoundsCapture, ivs)) = local(ivs); 618 }); 619 (std_dealloc(tmp)); // vexing parse... 620 621 rewriter.eraseOp(op); 622 return success(); 623 } 624 625 void mlir::populateVectorToSCFConversionPatterns( 626 OwningRewritePatternList &patterns, MLIRContext *context, 627 const VectorTransferToSCFOptions &options) { 628 patterns.insert<VectorTransferRewriter<vector::TransferReadOp>, 629 VectorTransferRewriter<vector::TransferWriteOp>>(options, 630 context); 631 } 632