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 
17 #include "../PassDetail.h"
18 #include "mlir/Dialect/Affine/EDSC/Intrinsics.h"
19 #include "mlir/Dialect/Linalg/Utils/Utils.h"
20 #include "mlir/Dialect/SCF/EDSC/Builders.h"
21 #include "mlir/Dialect/SCF/EDSC/Intrinsics.h"
22 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
23 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
24 #include "mlir/Dialect/Vector/VectorOps.h"
25 #include "mlir/Dialect/Vector/VectorUtils.h"
26 #include "mlir/IR/AffineExpr.h"
27 #include "mlir/IR/AffineMap.h"
28 #include "mlir/IR/Attributes.h"
29 #include "mlir/IR/Builders.h"
30 #include "mlir/IR/Location.h"
31 #include "mlir/IR/Matchers.h"
32 #include "mlir/IR/OperationSupport.h"
33 #include "mlir/IR/PatternMatch.h"
34 #include "mlir/IR/Types.h"
35 #include "mlir/Pass/Pass.h"
36 #include "mlir/Transforms/Passes.h"
37 
38 using namespace mlir;
39 using namespace mlir::edsc;
40 using namespace mlir::edsc::intrinsics;
41 using vector::TransferReadOp;
42 using vector::TransferWriteOp;
43 
44 namespace {
45 /// Helper class captures the common information needed to lower N>1-D vector
46 /// transfer operations (read and write).
47 /// On construction, this class opens an edsc::ScopedContext for simpler IR
48 /// manipulation.
49 /// In pseudo-IR, for an n-D vector_transfer_read such as:
50 ///
51 /// ```
52 ///   vector_transfer_read(%m, %offsets, identity_map, %fill) :
53 ///     memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
54 ///     vector<(major_dims) x (minor_dims) x type>
55 /// ```
56 ///
57 /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or
58 /// higher).
59 ///
60 /// This is the entry point to emitting pseudo-IR resembling:
61 ///
62 /// ```
63 ///   %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>>
64 ///   for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest
65 ///     if (any_of(%ivs_major + %offsets, <, major_dims)) {
66 ///       %v = vector_transfer_read(
67 ///         {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor},
68 ///          %ivs_minor):
69 ///         memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
70 ///         vector<(minor_dims) x type>;
71 ///       store(%v, %tmp);
72 ///     } else {
73 ///       %v = splat(vector<(minor_dims) x type>, %fill)
74 ///       store(%v, %tmp, %ivs_major);
75 ///     }
76 ///   }
77 ///   %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>):
78 //      vector<(major_dims) x (minor_dims) x type>
79 /// ```
80 ///
81 template <typename ConcreteOp>
82 class NDTransferOpHelper {
83 public:
84   NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp,
85                      const VectorTransferToSCFOptions &options)
86       : rewriter(rewriter), options(options), loc(xferOp.getLoc()),
87         scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp),
88         op(xferOp.getOperation()) {
89     vectorType = xferOp.getVectorType();
90     // TODO: when we go to k > 1-D vectors adapt minorRank.
91     minorRank = 1;
92     majorRank = vectorType.getRank() - minorRank;
93     leadingRank = xferOp.getLeadingMemRefRank();
94     majorVectorType =
95         VectorType::get(vectorType.getShape().take_front(majorRank),
96                         vectorType.getElementType());
97     minorVectorType =
98         VectorType::get(vectorType.getShape().take_back(minorRank),
99                         vectorType.getElementType());
100     /// Memref of minor vector type is used for individual transfers.
101     memRefMinorVectorType =
102         MemRefType::get(majorVectorType.getShape(), minorVectorType, {},
103                         xferOp.getMemRefType().getMemorySpace());
104   }
105 
106   LogicalResult doReplace();
107 
108 private:
109   /// Creates the loop nest on the "major" dimensions and calls the
110   /// `loopBodyBuilder` lambda in the context of the loop nest.
111   void
112   emitLoops(llvm::function_ref<void(ValueRange, ValueRange, ValueRange,
113                                     ValueRange, const MemRefBoundsCapture &)>
114                 loopBodyBuilder);
115 
116   /// Common state to lower vector transfer ops.
117   PatternRewriter &rewriter;
118   const VectorTransferToSCFOptions &options;
119   Location loc;
120   std::unique_ptr<ScopedContext> scope;
121   ConcreteOp xferOp;
122   Operation *op;
123   // A vector transfer copies data between:
124   //   - memref<(leading_dims) x (major_dims) x (minor_dims) x type>
125   //   - vector<(major_dims) x (minor_dims) x type>
126   unsigned minorRank;         // for now always 1
127   unsigned majorRank;         // vector rank - minorRank
128   unsigned leadingRank;       // memref rank - vector rank
129   VectorType vectorType;      // vector<(major_dims) x (minor_dims) x type>
130   VectorType majorVectorType; // vector<(major_dims) x type>
131   VectorType minorVectorType; // vector<(minor_dims) x type>
132   MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>>
133 };
134 
135 template <typename ConcreteOp>
136 void NDTransferOpHelper<ConcreteOp>::emitLoops(
137     llvm::function_ref<void(ValueRange, ValueRange, ValueRange, ValueRange,
138                             const MemRefBoundsCapture &)>
139         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     affineLoopNestBuilder(
164         majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) {
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 static Optional<int64_t> extractConstantIndex(Value v) {
174   if (auto cstOp = v.getDefiningOp<ConstantIndexOp>())
175     return cstOp.getValue();
176   if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>())
177     if (affineApplyOp.getAffineMap().isSingleConstant())
178       return affineApplyOp.getAffineMap().getSingleConstantResult();
179   return None;
180 }
181 
182 // Missing foldings of scf.if make it necessary to perform poor man's folding
183 // eagerly, especially in the case of unrolling. In the future, this should go
184 // away once scf.if folds properly.
185 static Value onTheFlyFoldSLT(Value v, Value ub) {
186   using namespace mlir::edsc::op;
187   auto maybeCstV = extractConstantIndex(v);
188   auto maybeCstUb = extractConstantIndex(ub);
189   if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb)
190     return Value();
191   return slt(v, ub);
192 }
193 
194 ///   1. Compute the indexings `majorIvs + majorOffsets` and save them in
195 ///      `majorIvsPlusOffsets`.
196 ///   2. Return a value of i1 that determines whether the first `majorIvs.rank()`
197 ///      dimensions `majorIvs + majorOffsets` are all within `memrefBounds`.
198 static Value
199 emitInBoundsCondition(PatternRewriter &rewriter,
200                       VectorTransferOpInterface xferOp, unsigned leadingRank,
201                       ValueRange majorIvs, ValueRange majorOffsets,
202                       const MemRefBoundsCapture &memrefBounds,
203                       SmallVectorImpl<Value> &majorIvsPlusOffsets) {
204   Value inBoundsCondition;
205   majorIvsPlusOffsets.reserve(majorIvs.size());
206   unsigned idx = 0;
207   SmallVector<Value, 4> bounds =
208       linalg::applyMapToValues(rewriter, xferOp.getLoc(),
209                                xferOp.permutation_map(), memrefBounds.getUbs());
210   for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) {
211     Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it);
212     using namespace mlir::edsc::op;
213     majorIvsPlusOffsets.push_back(iv + off);
214     if (xferOp.isMaskedDim(leadingRank + idx)) {
215       Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub);
216       if (inBoundsCond)
217         inBoundsCondition = (inBoundsCondition)
218                                 ? (inBoundsCondition && inBoundsCond)
219                                 : inBoundsCond;
220     }
221     ++idx;
222   }
223   return inBoundsCondition;
224 }
225 
226 // TODO: Parallelism and threadlocal considerations.
227 static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType,
228                                      Operation *op) {
229   auto &b = ScopedContext::getBuilderRef();
230   OpBuilder::InsertionGuard guard(b);
231   Operation *scope =
232       op->getParentWithTrait<OpTrait::AutomaticAllocationScope>();
233   assert(scope && "Expected op to be inside automatic allocation scope");
234   b.setInsertionPointToStart(&scope->getRegion(0).front());
235   Value res = std_alloca(memRefMinorVectorType);
236   return res;
237 }
238 
239 template <>
240 LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() {
241   Value alloc, result;
242   if (options.unroll)
243     result = std_splat(vectorType, xferOp.padding());
244   else
245     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
246 
247   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
248                 ValueRange majorOffsets, ValueRange minorOffsets,
249                 const MemRefBoundsCapture &memrefBounds) {
250     /// Lambda to load 1-D vector in the current loop ivs + offset context.
251     auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value {
252       SmallVector<Value, 8> indexing;
253       indexing.reserve(leadingRank + majorRank + minorRank);
254       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
255       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
256       indexing.append(minorOffsets.begin(), minorOffsets.end());
257       Value memref = xferOp.memref();
258       auto map =
259           getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType);
260       ArrayAttr masked;
261       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
262         OpBuilder &b = ScopedContext::getBuilderRef();
263         masked = b.getBoolArrayAttr({false});
264       }
265       return vector_transfer_read(minorVectorType, memref, indexing,
266                                   AffineMapAttr::get(map), xferOp.padding(),
267                                   masked);
268     };
269 
270     // 1. Compute the inBoundsCondition in the current loops ivs + offset
271     // context.
272     SmallVector<Value, 4> majorIvsPlusOffsets;
273     Value inBoundsCondition = emitInBoundsCondition(
274         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
275         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
276 
277     if (inBoundsCondition) {
278       // 2. If the condition is not null, we need an IfOp, which may yield
279       // if `options.unroll` is true.
280       SmallVector<Type, 1> resultType;
281       if (options.unroll)
282         resultType.push_back(vectorType);
283 
284       // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise
285       // splat a 1-D vector.
286       ValueRange ifResults = conditionBuilder(
287           resultType, inBoundsCondition,
288           [&]() -> scf::ValueVector {
289             Value vector = load1DVector(majorIvsPlusOffsets);
290             // 3.a. If `options.unroll` is true, insert the 1-D vector in the
291             // aggregate. We must yield and merge with the `else` branch.
292             if (options.unroll) {
293               vector = vector_insert(vector, result, majorIvs);
294               return {vector};
295             }
296             // 3.b. Otherwise, just go through the temporary `alloc`.
297             std_store(vector, alloc, majorIvs);
298             return {};
299           },
300           [&]() -> scf::ValueVector {
301             Value vector = std_splat(minorVectorType, xferOp.padding());
302             // 3.c. If `options.unroll` is true, insert the 1-D vector in the
303             // aggregate. We must yield and merge with the `then` branch.
304             if (options.unroll) {
305               vector = vector_insert(vector, result, majorIvs);
306               return {vector};
307             }
308             // 3.d. Otherwise, just go through the temporary `alloc`.
309             std_store(vector, alloc, majorIvs);
310             return {};
311           });
312 
313       if (!resultType.empty())
314         result = *ifResults.begin();
315     } else {
316       // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read.
317       Value loaded1D = load1DVector(majorIvsPlusOffsets);
318       // 5.a. If `options.unroll` is true, insert the 1-D vector in the
319       // aggregate.
320       if (options.unroll)
321         result = vector_insert(loaded1D, result, majorIvs);
322       // 5.b. Otherwise, just go through the temporary `alloc`.
323       else
324         std_store(loaded1D, alloc, majorIvs);
325     }
326   });
327 
328   assert((!options.unroll ^ (bool)result) &&
329          "Expected resulting Value iff unroll");
330   if (!result)
331     result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc));
332   rewriter.replaceOp(op, result);
333 
334   return success();
335 }
336 
337 template <>
338 LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() {
339   Value alloc;
340   if (!options.unroll) {
341     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
342     std_store(xferOp.vector(),
343               vector_type_cast(MemRefType::get({}, vectorType), alloc));
344   }
345 
346   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
347                 ValueRange majorOffsets, ValueRange minorOffsets,
348                 const MemRefBoundsCapture &memrefBounds) {
349     // Lower to 1-D vector_transfer_write and let recursion handle it.
350     auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) {
351       SmallVector<Value, 8> indexing;
352       indexing.reserve(leadingRank + majorRank + minorRank);
353       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
354       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
355       indexing.append(minorOffsets.begin(), minorOffsets.end());
356       Value result;
357       // If `options.unroll` is true, extract the 1-D vector from the
358       // aggregate.
359       if (options.unroll)
360         result = vector_extract(xferOp.vector(), majorIvs);
361       else
362         result = std_load(alloc, majorIvs);
363       auto map =
364           getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType);
365       ArrayAttr masked;
366       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
367         OpBuilder &b = ScopedContext::getBuilderRef();
368         masked = b.getBoolArrayAttr({false});
369       }
370       vector_transfer_write(result, xferOp.memref(), indexing,
371                             AffineMapAttr::get(map), masked);
372     };
373 
374     // 1. Compute the inBoundsCondition in the current loops ivs + offset
375     // context.
376     SmallVector<Value, 4> majorIvsPlusOffsets;
377     Value inBoundsCondition = emitInBoundsCondition(
378         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
379         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
380 
381     if (inBoundsCondition) {
382       // 2.a. If the condition is not null, we need an IfOp, to write
383       // conditionally. Progressively lower to a 1-D transfer write.
384       conditionBuilder(inBoundsCondition,
385                        [&] { emitTransferWrite(majorIvsPlusOffsets); });
386     } else {
387       // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write.
388       emitTransferWrite(majorIvsPlusOffsets);
389     }
390   });
391 
392   rewriter.eraseOp(op);
393 
394   return success();
395 }
396 
397 } // namespace
398 
399 /// Analyzes the `transfer` to find an access dimension along the fastest remote
400 /// MemRef dimension. If such a dimension with coalescing properties is found,
401 /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of
402 /// LoopNestBuilder captures it in the innermost loop.
403 template <typename TransferOpTy>
404 static int computeCoalescedIndex(TransferOpTy transfer) {
405   // rank of the remote memory access, coalescing behavior occurs on the
406   // innermost memory dimension.
407   auto remoteRank = transfer.getMemRefType().getRank();
408   // Iterate over the results expressions of the permutation map to determine
409   // the loop order for creating pointwise copies between remote and local
410   // memories.
411   int coalescedIdx = -1;
412   auto exprs = transfer.permutation_map().getResults();
413   for (auto en : llvm::enumerate(exprs)) {
414     auto dim = en.value().template dyn_cast<AffineDimExpr>();
415     if (!dim) {
416       continue;
417     }
418     auto memRefDim = dim.getPosition();
419     if (memRefDim == remoteRank - 1) {
420       // memRefDim has coalescing properties, it should be swapped in the last
421       // position.
422       assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices");
423       coalescedIdx = en.index();
424     }
425   }
426   return coalescedIdx;
427 }
428 
429 template <typename TransferOpTy>
430 VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter(
431     VectorTransferToSCFOptions options, MLIRContext *context)
432     : RewritePattern(TransferOpTy::getOperationName(), 1, context),
433       options(options) {}
434 
435 /// Used for staging the transfer in a local buffer.
436 template <typename TransferOpTy>
437 MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType(
438     TransferOpTy transfer) const {
439   auto vectorType = transfer.getVectorType();
440   return MemRefType::get(vectorType.getShape().drop_back(),
441                          VectorType::get(vectorType.getShape().take_back(),
442                                          vectorType.getElementType()),
443                          {}, 0);
444 }
445 
446 static void emitWithBoundsChecks(
447     PatternRewriter &rewriter, VectorTransferOpInterface transfer,
448     ValueRange ivs, const MemRefBoundsCapture &memRefBoundsCapture,
449     function_ref<void(ArrayRef<Value>)> inBoundsFun,
450     function_ref<void(ArrayRef<Value>)> outOfBoundsFun = nullptr) {
451   // Permute the incoming indices according to the permutation map.
452   SmallVector<Value, 4> indices =
453       linalg::applyMapToValues(rewriter, transfer.getLoc(),
454                                transfer.permutation_map(), transfer.indices());
455 
456   // Generate a bounds check if necessary.
457   SmallVector<Value, 4> majorIvsPlusOffsets;
458   Value inBoundsCondition =
459       emitInBoundsCondition(rewriter, transfer, 0, ivs, indices,
460                             memRefBoundsCapture, majorIvsPlusOffsets);
461 
462   // Apply the permutation map to the ivs. The permutation map may not use all
463   // the inputs.
464   SmallVector<Value, 4> scalarAccessExprs(transfer.indices().size());
465   for (unsigned memRefDim = 0; memRefDim < transfer.indices().size();
466        ++memRefDim) {
467     // Linear search on a small number of entries.
468     int loopIndex = -1;
469     auto exprs = transfer.permutation_map().getResults();
470     for (auto en : llvm::enumerate(exprs)) {
471       auto expr = en.value();
472       auto dim = expr.dyn_cast<AffineDimExpr>();
473       // Sanity check.
474       assert((dim || expr.cast<AffineConstantExpr>().getValue() == 0) &&
475              "Expected dim or 0 in permutationMap");
476       if (dim && memRefDim == dim.getPosition()) {
477         loopIndex = en.index();
478         break;
479       }
480     }
481 
482     using namespace edsc::op;
483     auto i = transfer.indices()[memRefDim];
484     scalarAccessExprs[memRefDim] = loopIndex < 0 ? i : i + ivs[loopIndex];
485   }
486 
487   if (inBoundsCondition)
488     conditionBuilder(
489         /* scf.if */ inBoundsCondition, // {
490         [&] { inBoundsFun(scalarAccessExprs); },
491         // } else {
492         outOfBoundsFun ? [&] { outOfBoundsFun(scalarAccessExprs); }
493                        : function_ref<void()>()
494         // }
495     );
496   else
497     inBoundsFun(scalarAccessExprs);
498 }
499 
500 namespace mlir {
501 
502 /// Lowers TransferReadOp into a combination of:
503 ///   1. local memory allocation;
504 ///   2. perfect loop nest over:
505 ///      a. scalar load from local buffers (viewed as a scalar memref);
506 ///      a. scalar store to original memref (with padding).
507 ///   3. vector_load from local buffer (viewed as a memref<1 x vector>);
508 ///   4. local memory deallocation.
509 ///
510 /// Lowers the data transfer part of a TransferReadOp while ensuring no
511 /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
512 /// padding.
513 
514 /// Performs the rewrite.
515 template <>
516 LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite(
517     Operation *op, PatternRewriter &rewriter) const {
518   using namespace mlir::edsc::op;
519 
520   TransferReadOp transfer = cast<TransferReadOp>(op);
521 
522   // Fall back to a loop if the fastest varying stride is not 1 or it is
523   // permuted.
524   int64_t offset;
525   SmallVector<int64_t, 4> strides;
526   auto successStrides =
527       getStridesAndOffset(transfer.getMemRefType(), strides, offset);
528   if (succeeded(successStrides) && strides.back() == 1 &&
529       transfer.permutation_map().isMinorIdentity()) {
530     // If > 1D, emit a bunch of loops around 1-D vector transfers.
531     if (transfer.getVectorType().getRank() > 1)
532       return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options)
533           .doReplace();
534     // If 1-D this is now handled by the target-specific lowering.
535     if (transfer.getVectorType().getRank() == 1)
536       return failure();
537   }
538 
539   // Conservative lowering to scalar load / stores.
540   // 1. Setup all the captures.
541   ScopedContext scope(rewriter, transfer.getLoc());
542   StdIndexedValue remote(transfer.memref());
543   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
544   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
545   int coalescedIdx = computeCoalescedIndex(transfer);
546   // Swap the vectorBoundsCapture which will reorder loop bounds.
547   if (coalescedIdx >= 0)
548     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
549                                    coalescedIdx);
550 
551   auto lbs = vectorBoundsCapture.getLbs();
552   auto ubs = vectorBoundsCapture.getUbs();
553   SmallVector<Value, 8> steps;
554   steps.reserve(vectorBoundsCapture.getSteps().size());
555   for (auto step : vectorBoundsCapture.getSteps())
556     steps.push_back(std_constant_index(step));
557 
558   // 2. Emit alloc-copy-load-dealloc.
559   MLIRContext *ctx = op->getContext();
560   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
561   StdIndexedValue local(tmp);
562   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
563     auto ivsStorage = llvm::to_vector<8>(loopIvs);
564     // Swap the ivs which will reorder memory accesses.
565     if (coalescedIdx >= 0)
566       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
567 
568     ArrayRef<Value> ivs(ivsStorage);
569     Value pos = std_index_cast(IntegerType::get(32, ctx), ivs.back());
570     Value inVector = local(ivs.drop_back());
571     auto loadValue = [&](ArrayRef<Value> indices) {
572       Value vector = vector_insert_element(remote(indices), inVector, pos);
573       local(ivs.drop_back()) = vector;
574     };
575     auto loadPadding = [&](ArrayRef<Value>) {
576       Value vector = vector_insert_element(transfer.padding(), inVector, pos);
577       local(ivs.drop_back()) = vector;
578     };
579     emitWithBoundsChecks(
580         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
581         memRefBoundsCapture, loadValue, loadPadding);
582   });
583   Value vectorValue = std_load(vector_type_cast(tmp));
584 
585   // 3. Propagate.
586   rewriter.replaceOp(op, vectorValue);
587   return success();
588 }
589 
590 /// Lowers TransferWriteOp into a combination of:
591 ///   1. local memory allocation;
592 ///   2. vector_store to local buffer (viewed as a memref<1 x vector>);
593 ///   3. perfect loop nest over:
594 ///      a. scalar load from local buffers (viewed as a scalar memref);
595 ///      a. scalar store to original memref (if in bounds).
596 ///   4. local memory deallocation.
597 ///
598 /// More specifically, lowers the data transfer part while ensuring no
599 /// out-of-bounds accesses are possible.
600 template <>
601 LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite(
602     Operation *op, PatternRewriter &rewriter) const {
603   using namespace edsc::op;
604 
605   TransferWriteOp transfer = cast<TransferWriteOp>(op);
606 
607   // Fall back to a loop if the fastest varying stride is not 1 or it is
608   // permuted.
609   int64_t offset;
610   SmallVector<int64_t, 4> strides;
611   auto successStrides =
612       getStridesAndOffset(transfer.getMemRefType(), strides, offset);
613   if (succeeded(successStrides) && strides.back() == 1 &&
614       transfer.permutation_map().isMinorIdentity()) {
615     // If > 1D, emit a bunch of loops around 1-D vector transfers.
616     if (transfer.getVectorType().getRank() > 1)
617       return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options)
618           .doReplace();
619     // If 1-D this is now handled by the target-specific lowering.
620     if (transfer.getVectorType().getRank() == 1)
621       return failure();
622   }
623 
624   // 1. Setup all the captures.
625   ScopedContext scope(rewriter, transfer.getLoc());
626   StdIndexedValue remote(transfer.memref());
627   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
628   Value vectorValue(transfer.vector());
629   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
630   int coalescedIdx = computeCoalescedIndex(transfer);
631   // Swap the vectorBoundsCapture which will reorder loop bounds.
632   if (coalescedIdx >= 0)
633     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
634                                    coalescedIdx);
635 
636   auto lbs = vectorBoundsCapture.getLbs();
637   auto ubs = vectorBoundsCapture.getUbs();
638   SmallVector<Value, 8> steps;
639   steps.reserve(vectorBoundsCapture.getSteps().size());
640   for (auto step : vectorBoundsCapture.getSteps())
641     steps.push_back(std_constant_index(step));
642 
643   // 2. Emit alloc-store-copy-dealloc.
644   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
645   StdIndexedValue local(tmp);
646   Value vec = vector_type_cast(tmp);
647   std_store(vectorValue, vec);
648   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
649     auto ivsStorage = llvm::to_vector<8>(loopIvs);
650     // Swap the ivsStorage which will reorder memory accesses.
651     if (coalescedIdx >= 0)
652       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
653 
654     ArrayRef<Value> ivs(ivsStorage);
655     Value pos =
656         std_index_cast(IntegerType::get(32, op->getContext()), ivs.back());
657     auto storeValue = [&](ArrayRef<Value> indices) {
658       Value scalar = vector_extract_element(local(ivs.drop_back()), pos);
659       remote(indices) = scalar;
660     };
661     emitWithBoundsChecks(
662         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
663         memRefBoundsCapture, storeValue);
664   });
665 
666   // 3. Erase.
667   rewriter.eraseOp(op);
668   return success();
669 }
670 
671 void populateVectorToSCFConversionPatterns(
672     OwningRewritePatternList &patterns, MLIRContext *context,
673     const VectorTransferToSCFOptions &options) {
674   patterns.insert<VectorTransferRewriter<vector::TransferReadOp>,
675                   VectorTransferRewriter<vector::TransferWriteOp>>(options,
676                                                                    context);
677 }
678 
679 } // namespace mlir
680 
681 namespace {
682 
683 struct ConvertVectorToSCFPass
684     : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
685   ConvertVectorToSCFPass() = default;
686   ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
687     this->fullUnroll = options.unroll;
688   }
689 
690   void runOnFunction() override {
691     OwningRewritePatternList patterns;
692     auto *context = getFunction().getContext();
693     populateVectorToSCFConversionPatterns(
694         patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll));
695     applyPatternsAndFoldGreedily(getFunction(), patterns);
696   }
697 };
698 
699 } // namespace
700 
701 std::unique_ptr<Pass>
702 mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
703   return std::make_unique<ConvertVectorToSCFPass>(options);
704 }
705