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