14ead2cf7SAlex Zinenko //===- VectorToSCF.cpp - Conversion from Vector to mix of SCF and Std -----===//
24ead2cf7SAlex Zinenko //
34ead2cf7SAlex Zinenko // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
44ead2cf7SAlex Zinenko // See https://llvm.org/LICENSE.txt for license information.
54ead2cf7SAlex Zinenko // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64ead2cf7SAlex Zinenko //
74ead2cf7SAlex Zinenko //===----------------------------------------------------------------------===//
84ead2cf7SAlex Zinenko //
94ead2cf7SAlex Zinenko // This file implements target-dependent lowering of vector transfer operations.
104ead2cf7SAlex Zinenko //
114ead2cf7SAlex Zinenko //===----------------------------------------------------------------------===//
124ead2cf7SAlex Zinenko 
134ead2cf7SAlex Zinenko #include <type_traits>
144ead2cf7SAlex Zinenko 
154ead2cf7SAlex Zinenko #include "mlir/Conversion/VectorToSCF/VectorToSCF.h"
165f9e0466SNicolas Vasilache 
175f9e0466SNicolas Vasilache #include "../PassDetail.h"
184ead2cf7SAlex Zinenko #include "mlir/Dialect/Affine/EDSC/Intrinsics.h"
19e2310704SJulian Gross #include "mlir/Dialect/MemRef/EDSC/Intrinsics.h"
204ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Builders.h"
214ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Intrinsics.h"
224ead2cf7SAlex Zinenko #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
234ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
244ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/VectorOps.h"
257c3c5b11SNicolas Vasilache #include "mlir/Dialect/Vector/VectorUtils.h"
264ead2cf7SAlex Zinenko #include "mlir/IR/AffineExpr.h"
274ead2cf7SAlex Zinenko #include "mlir/IR/AffineMap.h"
284ead2cf7SAlex Zinenko #include "mlir/IR/Builders.h"
294ead2cf7SAlex Zinenko #include "mlir/IR/Matchers.h"
305f9e0466SNicolas Vasilache #include "mlir/Pass/Pass.h"
31b6eb26fdSRiver Riddle #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
325f9e0466SNicolas Vasilache #include "mlir/Transforms/Passes.h"
334ead2cf7SAlex Zinenko 
344ead2cf7SAlex Zinenko using namespace mlir;
354ead2cf7SAlex Zinenko using namespace mlir::edsc;
364ead2cf7SAlex Zinenko using namespace mlir::edsc::intrinsics;
374ead2cf7SAlex Zinenko using vector::TransferReadOp;
384ead2cf7SAlex Zinenko using vector::TransferWriteOp;
394ead2cf7SAlex Zinenko 
40af5be38aSNicolas Vasilache // Return a list of Values that correspond to multiple AffineApplyOp, one for
41af5be38aSNicolas Vasilache // each result of `map`. Each `expr` in `map` is canonicalized and folded
42af5be38aSNicolas Vasilache // greedily according to its operands.
43af5be38aSNicolas Vasilache // TODO: factor out in a common location that both linalg and vector can use.
44af5be38aSNicolas Vasilache static SmallVector<Value, 4>
45af5be38aSNicolas Vasilache applyMapToValues(OpBuilder &b, Location loc, AffineMap map, ValueRange values) {
46af5be38aSNicolas Vasilache   SmallVector<Value, 4> res;
47af5be38aSNicolas Vasilache   res.reserve(map.getNumResults());
48af5be38aSNicolas Vasilache   unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols();
49af5be38aSNicolas Vasilache   // For each `expr` in `map`, applies the `expr` to the values extracted from
50af5be38aSNicolas Vasilache   // ranges. If the resulting application can be folded into a Value, the
51af5be38aSNicolas Vasilache   // folding occurs eagerly. Otherwise, an affine.apply operation is emitted.
52af5be38aSNicolas Vasilache   for (auto expr : map.getResults()) {
53af5be38aSNicolas Vasilache     AffineMap map = AffineMap::get(numDims, numSym, expr);
54af5be38aSNicolas Vasilache     SmallVector<Value, 4> operands(values.begin(), values.end());
55af5be38aSNicolas Vasilache     fullyComposeAffineMapAndOperands(&map, &operands);
56af5be38aSNicolas Vasilache     canonicalizeMapAndOperands(&map, &operands);
57af5be38aSNicolas Vasilache     res.push_back(b.createOrFold<AffineApplyOp>(loc, map, operands));
58af5be38aSNicolas Vasilache   }
59af5be38aSNicolas Vasilache   return res;
60af5be38aSNicolas Vasilache }
61af5be38aSNicolas Vasilache 
62350dadaaSBenjamin Kramer namespace {
634ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector
644ead2cf7SAlex Zinenko /// transfer operations (read and write).
654ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR
664ead2cf7SAlex Zinenko /// manipulation.
674ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as:
684ead2cf7SAlex Zinenko ///
694ead2cf7SAlex Zinenko /// ```
704ead2cf7SAlex Zinenko ///   vector_transfer_read(%m, %offsets, identity_map, %fill) :
714ead2cf7SAlex Zinenko ///     memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
724ead2cf7SAlex Zinenko ///     vector<(major_dims) x (minor_dims) x type>
734ead2cf7SAlex Zinenko /// ```
744ead2cf7SAlex Zinenko ///
754ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or
764ead2cf7SAlex Zinenko /// higher).
774ead2cf7SAlex Zinenko ///
784ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling:
794ead2cf7SAlex Zinenko ///
804ead2cf7SAlex Zinenko /// ```
814ead2cf7SAlex Zinenko ///   %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>>
824ead2cf7SAlex Zinenko ///   for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest
834ead2cf7SAlex Zinenko ///     if (any_of(%ivs_major + %offsets, <, major_dims)) {
844ead2cf7SAlex Zinenko ///       %v = vector_transfer_read(
854ead2cf7SAlex Zinenko ///         {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor},
864ead2cf7SAlex Zinenko ///          %ivs_minor):
874ead2cf7SAlex Zinenko ///         memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
884ead2cf7SAlex Zinenko ///         vector<(minor_dims) x type>;
894ead2cf7SAlex Zinenko ///       store(%v, %tmp);
904ead2cf7SAlex Zinenko ///     } else {
914ead2cf7SAlex Zinenko ///       %v = splat(vector<(minor_dims) x type>, %fill)
924ead2cf7SAlex Zinenko ///       store(%v, %tmp, %ivs_major);
934ead2cf7SAlex Zinenko ///     }
944ead2cf7SAlex Zinenko ///   }
954ead2cf7SAlex Zinenko ///   %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>):
964ead2cf7SAlex Zinenko //      vector<(major_dims) x (minor_dims) x type>
974ead2cf7SAlex Zinenko /// ```
984ead2cf7SAlex Zinenko ///
994ead2cf7SAlex Zinenko template <typename ConcreteOp>
1004ead2cf7SAlex Zinenko class NDTransferOpHelper {
1014ead2cf7SAlex Zinenko public:
1027c3c5b11SNicolas Vasilache   NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp,
1037c3c5b11SNicolas Vasilache                      const VectorTransferToSCFOptions &options)
1047c3c5b11SNicolas Vasilache       : rewriter(rewriter), options(options), loc(xferOp.getLoc()),
1054ead2cf7SAlex Zinenko         scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp),
1064ead2cf7SAlex Zinenko         op(xferOp.getOperation()) {
1074ead2cf7SAlex Zinenko     vectorType = xferOp.getVectorType();
1089db53a18SRiver Riddle     // TODO: when we go to k > 1-D vectors adapt minorRank.
1094ead2cf7SAlex Zinenko     minorRank = 1;
1104ead2cf7SAlex Zinenko     majorRank = vectorType.getRank() - minorRank;
11126c8f908SThomas Raoux     leadingRank = xferOp.getLeadingShapedRank();
1124ead2cf7SAlex Zinenko     majorVectorType =
1134ead2cf7SAlex Zinenko         VectorType::get(vectorType.getShape().take_front(majorRank),
1144ead2cf7SAlex Zinenko                         vectorType.getElementType());
1154ead2cf7SAlex Zinenko     minorVectorType =
1164ead2cf7SAlex Zinenko         VectorType::get(vectorType.getShape().take_back(minorRank),
1174ead2cf7SAlex Zinenko                         vectorType.getElementType());
1184ead2cf7SAlex Zinenko     /// Memref of minor vector type is used for individual transfers.
11937eca08eSVladislav Vinogradov     memRefMinorVectorType =
12037eca08eSVladislav Vinogradov         MemRefType::get(majorVectorType.getShape(), minorVectorType, {},
12137eca08eSVladislav Vinogradov                         xferOp.getShapedType()
12237eca08eSVladislav Vinogradov                             .template cast<MemRefType>()
12337eca08eSVladislav Vinogradov                             .getMemorySpaceAsInt());
1244ead2cf7SAlex Zinenko   }
1254ead2cf7SAlex Zinenko 
1264ead2cf7SAlex Zinenko   LogicalResult doReplace();
1274ead2cf7SAlex Zinenko 
1284ead2cf7SAlex Zinenko private:
1294ead2cf7SAlex Zinenko   /// Creates the loop nest on the "major" dimensions and calls the
1304ead2cf7SAlex Zinenko   /// `loopBodyBuilder` lambda in the context of the loop nest.
131307dc7b2SBenjamin Kramer   void
132307dc7b2SBenjamin Kramer   emitLoops(llvm::function_ref<void(ValueRange, ValueRange, ValueRange,
133307dc7b2SBenjamin Kramer                                     ValueRange, const MemRefBoundsCapture &)>
134307dc7b2SBenjamin Kramer                 loopBodyBuilder);
1354ead2cf7SAlex Zinenko 
1364ead2cf7SAlex Zinenko   /// Common state to lower vector transfer ops.
1374ead2cf7SAlex Zinenko   PatternRewriter &rewriter;
1387c3c5b11SNicolas Vasilache   const VectorTransferToSCFOptions &options;
1394ead2cf7SAlex Zinenko   Location loc;
1404ead2cf7SAlex Zinenko   std::unique_ptr<ScopedContext> scope;
1414ead2cf7SAlex Zinenko   ConcreteOp xferOp;
1424ead2cf7SAlex Zinenko   Operation *op;
1434ead2cf7SAlex Zinenko   // A vector transfer copies data between:
1444ead2cf7SAlex Zinenko   //   - memref<(leading_dims) x (major_dims) x (minor_dims) x type>
1454ead2cf7SAlex Zinenko   //   - vector<(major_dims) x (minor_dims) x type>
1464ead2cf7SAlex Zinenko   unsigned minorRank;         // for now always 1
1474ead2cf7SAlex Zinenko   unsigned majorRank;         // vector rank - minorRank
1484ead2cf7SAlex Zinenko   unsigned leadingRank;       // memref rank - vector rank
1494ead2cf7SAlex Zinenko   VectorType vectorType;      // vector<(major_dims) x (minor_dims) x type>
1504ead2cf7SAlex Zinenko   VectorType majorVectorType; // vector<(major_dims) x type>
1514ead2cf7SAlex Zinenko   VectorType minorVectorType; // vector<(minor_dims) x type>
1524ead2cf7SAlex Zinenko   MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>>
1534ead2cf7SAlex Zinenko };
1544ead2cf7SAlex Zinenko 
1554ead2cf7SAlex Zinenko template <typename ConcreteOp>
156307dc7b2SBenjamin Kramer void NDTransferOpHelper<ConcreteOp>::emitLoops(
157307dc7b2SBenjamin Kramer     llvm::function_ref<void(ValueRange, ValueRange, ValueRange, ValueRange,
158307dc7b2SBenjamin Kramer                             const MemRefBoundsCapture &)>
159307dc7b2SBenjamin Kramer         loopBodyBuilder) {
1604ead2cf7SAlex Zinenko   /// Loop nest operates on the major dimensions
16126c8f908SThomas Raoux   MemRefBoundsCapture memrefBoundsCapture(xferOp.source());
1627c3c5b11SNicolas Vasilache 
1637c3c5b11SNicolas Vasilache   if (options.unroll) {
1647c3c5b11SNicolas Vasilache     auto shape = majorVectorType.getShape();
1657c3c5b11SNicolas Vasilache     auto strides = computeStrides(shape);
1667c3c5b11SNicolas Vasilache     unsigned numUnrolledInstances = computeMaxLinearIndex(shape);
1677c3c5b11SNicolas Vasilache     ValueRange indices(xferOp.indices());
1687c3c5b11SNicolas Vasilache     for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) {
1697c3c5b11SNicolas Vasilache       SmallVector<int64_t, 4> offsets = delinearize(strides, idx);
1707c3c5b11SNicolas Vasilache       SmallVector<Value, 4> offsetValues =
1717c3c5b11SNicolas Vasilache           llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value {
1727c3c5b11SNicolas Vasilache             return std_constant_index(off);
1737c3c5b11SNicolas Vasilache           }));
1747c3c5b11SNicolas Vasilache       loopBodyBuilder(offsetValues, indices.take_front(leadingRank),
1757c3c5b11SNicolas Vasilache                       indices.drop_front(leadingRank).take_front(majorRank),
1767c3c5b11SNicolas Vasilache                       indices.take_back(minorRank), memrefBoundsCapture);
1777c3c5b11SNicolas Vasilache     }
1787c3c5b11SNicolas Vasilache   } else {
1794ead2cf7SAlex Zinenko     VectorBoundsCapture vectorBoundsCapture(majorVectorType);
1804ead2cf7SAlex Zinenko     auto majorLbs = vectorBoundsCapture.getLbs();
1814ead2cf7SAlex Zinenko     auto majorUbs = vectorBoundsCapture.getUbs();
1824ead2cf7SAlex Zinenko     auto majorSteps = vectorBoundsCapture.getSteps();
1833f5bd53eSAlex Zinenko     affineLoopNestBuilder(
1843f5bd53eSAlex Zinenko         majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) {
1854ead2cf7SAlex Zinenko           ValueRange indices(xferOp.indices());
1864ead2cf7SAlex Zinenko           loopBodyBuilder(majorIvs, indices.take_front(leadingRank),
1874ead2cf7SAlex Zinenko                           indices.drop_front(leadingRank).take_front(majorRank),
1884ead2cf7SAlex Zinenko                           indices.take_back(minorRank), memrefBoundsCapture);
1894ead2cf7SAlex Zinenko         });
1904ead2cf7SAlex Zinenko   }
1917c3c5b11SNicolas Vasilache }
1924ead2cf7SAlex Zinenko 
193bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) {
194bd87c6bcSNicolas Vasilache   if (auto cstOp = v.getDefiningOp<ConstantIndexOp>())
195bd87c6bcSNicolas Vasilache     return cstOp.getValue();
196bd87c6bcSNicolas Vasilache   if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>())
197bd87c6bcSNicolas Vasilache     if (affineApplyOp.getAffineMap().isSingleConstant())
198bd87c6bcSNicolas Vasilache       return affineApplyOp.getAffineMap().getSingleConstantResult();
199bd87c6bcSNicolas Vasilache   return None;
200bd87c6bcSNicolas Vasilache }
201bd87c6bcSNicolas Vasilache 
202bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding
203bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go
204bd87c6bcSNicolas Vasilache // away once scf.if folds properly.
205bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) {
206bd87c6bcSNicolas Vasilache   using namespace mlir::edsc::op;
207bd87c6bcSNicolas Vasilache   auto maybeCstV = extractConstantIndex(v);
208bd87c6bcSNicolas Vasilache   auto maybeCstUb = extractConstantIndex(ub);
209bd87c6bcSNicolas Vasilache   if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb)
210bd87c6bcSNicolas Vasilache     return Value();
211bd87c6bcSNicolas Vasilache   return slt(v, ub);
212bd87c6bcSNicolas Vasilache }
213bd87c6bcSNicolas Vasilache 
214239eff50SBenjamin Kramer ///   1. Compute the indexings `majorIvs + majorOffsets` and save them in
215239eff50SBenjamin Kramer ///      `majorIvsPlusOffsets`.
216af5be38aSNicolas Vasilache ///   2. Return a value of i1 that determines whether the first
217af5be38aSNicolas Vasilache ///   `majorIvs.rank()`
218239eff50SBenjamin Kramer ///      dimensions `majorIvs + majorOffsets` are all within `memrefBounds`.
219239eff50SBenjamin Kramer static Value
220239eff50SBenjamin Kramer emitInBoundsCondition(PatternRewriter &rewriter,
221239eff50SBenjamin Kramer                       VectorTransferOpInterface xferOp, unsigned leadingRank,
2224ead2cf7SAlex Zinenko                       ValueRange majorIvs, ValueRange majorOffsets,
223307dc7b2SBenjamin Kramer                       const MemRefBoundsCapture &memrefBounds,
2247c3c5b11SNicolas Vasilache                       SmallVectorImpl<Value> &majorIvsPlusOffsets) {
2257c3c5b11SNicolas Vasilache   Value inBoundsCondition;
2264ead2cf7SAlex Zinenko   majorIvsPlusOffsets.reserve(majorIvs.size());
2271870e787SNicolas Vasilache   unsigned idx = 0;
2288dace28fSJakub Lichman   SmallVector<Value, 4> bounds =
229af5be38aSNicolas Vasilache       applyMapToValues(rewriter, xferOp.getLoc(), xferOp.permutation_map(),
230af5be38aSNicolas Vasilache                        memrefBounds.getUbs());
2318dace28fSJakub Lichman   for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) {
2324ead2cf7SAlex Zinenko     Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it);
2334ead2cf7SAlex Zinenko     using namespace mlir::edsc::op;
2344ead2cf7SAlex Zinenko     majorIvsPlusOffsets.push_back(iv + off);
2351870e787SNicolas Vasilache     if (xferOp.isMaskedDim(leadingRank + idx)) {
236bd87c6bcSNicolas Vasilache       Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub);
237bd87c6bcSNicolas Vasilache       if (inBoundsCond)
238bd87c6bcSNicolas Vasilache         inBoundsCondition = (inBoundsCondition)
239bd87c6bcSNicolas Vasilache                                 ? (inBoundsCondition && inBoundsCond)
240bd87c6bcSNicolas Vasilache                                 : inBoundsCond;
2411870e787SNicolas Vasilache     }
2421870e787SNicolas Vasilache     ++idx;
2434ead2cf7SAlex Zinenko   }
2447c3c5b11SNicolas Vasilache   return inBoundsCondition;
2454ead2cf7SAlex Zinenko }
2464ead2cf7SAlex Zinenko 
247247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations.
248247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType,
249247e185dSNicolas Vasilache                                      Operation *op) {
250247e185dSNicolas Vasilache   auto &b = ScopedContext::getBuilderRef();
251247e185dSNicolas Vasilache   OpBuilder::InsertionGuard guard(b);
252a4b8c2deSJakub Lichman   Operation *scope =
253a4b8c2deSJakub Lichman       op->getParentWithTrait<OpTrait::AutomaticAllocationScope>();
254a4b8c2deSJakub Lichman   assert(scope && "Expected op to be inside automatic allocation scope");
255a4b8c2deSJakub Lichman   b.setInsertionPointToStart(&scope->getRegion(0).front());
256e2310704SJulian Gross   Value res = memref_alloca(memRefMinorVectorType);
257247e185dSNicolas Vasilache   return res;
258247e185dSNicolas Vasilache }
259247e185dSNicolas Vasilache 
2604ead2cf7SAlex Zinenko template <>
2614ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() {
2627c3c5b11SNicolas Vasilache   Value alloc, result;
2637c3c5b11SNicolas Vasilache   if (options.unroll)
2647c3c5b11SNicolas Vasilache     result = std_splat(vectorType, xferOp.padding());
2657c3c5b11SNicolas Vasilache   else
266247e185dSNicolas Vasilache     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
2674ead2cf7SAlex Zinenko 
2684ead2cf7SAlex Zinenko   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
2694ead2cf7SAlex Zinenko                 ValueRange majorOffsets, ValueRange minorOffsets,
270307dc7b2SBenjamin Kramer                 const MemRefBoundsCapture &memrefBounds) {
2717c3c5b11SNicolas Vasilache     /// Lambda to load 1-D vector in the current loop ivs + offset context.
2727c3c5b11SNicolas Vasilache     auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value {
2734ead2cf7SAlex Zinenko       SmallVector<Value, 8> indexing;
2744ead2cf7SAlex Zinenko       indexing.reserve(leadingRank + majorRank + minorRank);
2754ead2cf7SAlex Zinenko       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
2764ead2cf7SAlex Zinenko       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
2774ead2cf7SAlex Zinenko       indexing.append(minorOffsets.begin(), minorOffsets.end());
27826c8f908SThomas Raoux       Value memref = xferOp.source();
27947cbd9f9SNicolas Vasilache       auto map =
28026c8f908SThomas Raoux           getTransferMinorIdentityMap(xferOp.getShapedType(), minorVectorType);
2811870e787SNicolas Vasilache       ArrayAttr masked;
282cc0a58d7SNicolas Vasilache       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
2831870e787SNicolas Vasilache         OpBuilder &b = ScopedContext::getBuilderRef();
284cc0a58d7SNicolas Vasilache         masked = b.getBoolArrayAttr({false});
2851870e787SNicolas Vasilache       }
2867c3c5b11SNicolas Vasilache       return vector_transfer_read(minorVectorType, memref, indexing,
2877c3c5b11SNicolas Vasilache                                   AffineMapAttr::get(map), xferOp.padding(),
2887c3c5b11SNicolas Vasilache                                   masked);
2894ead2cf7SAlex Zinenko     };
2907c3c5b11SNicolas Vasilache 
2917c3c5b11SNicolas Vasilache     // 1. Compute the inBoundsCondition in the current loops ivs + offset
2927c3c5b11SNicolas Vasilache     // context.
2937c3c5b11SNicolas Vasilache     SmallVector<Value, 4> majorIvsPlusOffsets;
2947c3c5b11SNicolas Vasilache     Value inBoundsCondition = emitInBoundsCondition(
295239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
296239eff50SBenjamin Kramer         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
2977c3c5b11SNicolas Vasilache 
2987c3c5b11SNicolas Vasilache     if (inBoundsCondition) {
2997c3c5b11SNicolas Vasilache       // 2. If the condition is not null, we need an IfOp, which may yield
3007c3c5b11SNicolas Vasilache       // if `options.unroll` is true.
3017c3c5b11SNicolas Vasilache       SmallVector<Type, 1> resultType;
3027c3c5b11SNicolas Vasilache       if (options.unroll)
3037c3c5b11SNicolas Vasilache         resultType.push_back(vectorType);
3047c3c5b11SNicolas Vasilache 
305cadb7ccfSAlex Zinenko       // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise
306cadb7ccfSAlex Zinenko       // splat a 1-D vector.
307cadb7ccfSAlex Zinenko       ValueRange ifResults = conditionBuilder(
308cadb7ccfSAlex Zinenko           resultType, inBoundsCondition,
309cadb7ccfSAlex Zinenko           [&]() -> scf::ValueVector {
3107c3c5b11SNicolas Vasilache             Value vector = load1DVector(majorIvsPlusOffsets);
311cadb7ccfSAlex Zinenko             // 3.a. If `options.unroll` is true, insert the 1-D vector in the
3127c3c5b11SNicolas Vasilache             // aggregate. We must yield and merge with the `else` branch.
3137c3c5b11SNicolas Vasilache             if (options.unroll) {
3147c3c5b11SNicolas Vasilache               vector = vector_insert(vector, result, majorIvs);
315cadb7ccfSAlex Zinenko               return {vector};
3167c3c5b11SNicolas Vasilache             }
317cadb7ccfSAlex Zinenko             // 3.b. Otherwise, just go through the temporary `alloc`.
318e2310704SJulian Gross             memref_store(vector, alloc, majorIvs);
319cadb7ccfSAlex Zinenko             return {};
320cadb7ccfSAlex Zinenko           },
321cadb7ccfSAlex Zinenko           [&]() -> scf::ValueVector {
3227c3c5b11SNicolas Vasilache             Value vector = std_splat(minorVectorType, xferOp.padding());
323cadb7ccfSAlex Zinenko             // 3.c. If `options.unroll` is true, insert the 1-D vector in the
3247c3c5b11SNicolas Vasilache             // aggregate. We must yield and merge with the `then` branch.
3257c3c5b11SNicolas Vasilache             if (options.unroll) {
3267c3c5b11SNicolas Vasilache               vector = vector_insert(vector, result, majorIvs);
327cadb7ccfSAlex Zinenko               return {vector};
3287c3c5b11SNicolas Vasilache             }
329cadb7ccfSAlex Zinenko             // 3.d. Otherwise, just go through the temporary `alloc`.
330e2310704SJulian Gross             memref_store(vector, alloc, majorIvs);
331cadb7ccfSAlex Zinenko             return {};
3327c3c5b11SNicolas Vasilache           });
333cadb7ccfSAlex Zinenko 
3347c3c5b11SNicolas Vasilache       if (!resultType.empty())
335cadb7ccfSAlex Zinenko         result = *ifResults.begin();
3367c3c5b11SNicolas Vasilache     } else {
3377c3c5b11SNicolas Vasilache       // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read.
3387c3c5b11SNicolas Vasilache       Value loaded1D = load1DVector(majorIvsPlusOffsets);
3397c3c5b11SNicolas Vasilache       // 5.a. If `options.unroll` is true, insert the 1-D vector in the
3407c3c5b11SNicolas Vasilache       // aggregate.
3417c3c5b11SNicolas Vasilache       if (options.unroll)
3427c3c5b11SNicolas Vasilache         result = vector_insert(loaded1D, result, majorIvs);
3437c3c5b11SNicolas Vasilache       // 5.b. Otherwise, just go through the temporary `alloc`.
3447c3c5b11SNicolas Vasilache       else
345e2310704SJulian Gross         memref_store(loaded1D, alloc, majorIvs);
3467c3c5b11SNicolas Vasilache     }
3477c3c5b11SNicolas Vasilache   });
3487c3c5b11SNicolas Vasilache 
349a9b5edc5SBenjamin Kramer   assert((!options.unroll ^ (bool)result) &&
350a9b5edc5SBenjamin Kramer          "Expected resulting Value iff unroll");
3517c3c5b11SNicolas Vasilache   if (!result)
352e2310704SJulian Gross     result =
353e2310704SJulian Gross         memref_load(vector_type_cast(MemRefType::get({}, vectorType), alloc));
3547c3c5b11SNicolas Vasilache   rewriter.replaceOp(op, result);
3554ead2cf7SAlex Zinenko 
3564ead2cf7SAlex Zinenko   return success();
3574ead2cf7SAlex Zinenko }
3584ead2cf7SAlex Zinenko 
3594ead2cf7SAlex Zinenko template <>
3604ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() {
3617c3c5b11SNicolas Vasilache   Value alloc;
3627c3c5b11SNicolas Vasilache   if (!options.unroll) {
363247e185dSNicolas Vasilache     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
364e2310704SJulian Gross     memref_store(xferOp.vector(),
3654ead2cf7SAlex Zinenko                  vector_type_cast(MemRefType::get({}, vectorType), alloc));
3667c3c5b11SNicolas Vasilache   }
3674ead2cf7SAlex Zinenko 
3684ead2cf7SAlex Zinenko   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
3694ead2cf7SAlex Zinenko                 ValueRange majorOffsets, ValueRange minorOffsets,
370307dc7b2SBenjamin Kramer                 const MemRefBoundsCapture &memrefBounds) {
3717c3c5b11SNicolas Vasilache     // Lower to 1-D vector_transfer_write and let recursion handle it.
3727c3c5b11SNicolas Vasilache     auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) {
3734ead2cf7SAlex Zinenko       SmallVector<Value, 8> indexing;
3744ead2cf7SAlex Zinenko       indexing.reserve(leadingRank + majorRank + minorRank);
3754ead2cf7SAlex Zinenko       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
3764ead2cf7SAlex Zinenko       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
3774ead2cf7SAlex Zinenko       indexing.append(minorOffsets.begin(), minorOffsets.end());
3787c3c5b11SNicolas Vasilache       Value result;
3797c3c5b11SNicolas Vasilache       // If `options.unroll` is true, extract the 1-D vector from the
3807c3c5b11SNicolas Vasilache       // aggregate.
3817c3c5b11SNicolas Vasilache       if (options.unroll)
3827c3c5b11SNicolas Vasilache         result = vector_extract(xferOp.vector(), majorIvs);
3837c3c5b11SNicolas Vasilache       else
384e2310704SJulian Gross         result = memref_load(alloc, majorIvs);
38547cbd9f9SNicolas Vasilache       auto map =
38626c8f908SThomas Raoux           getTransferMinorIdentityMap(xferOp.getShapedType(), minorVectorType);
3871870e787SNicolas Vasilache       ArrayAttr masked;
388cc0a58d7SNicolas Vasilache       if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
3891870e787SNicolas Vasilache         OpBuilder &b = ScopedContext::getBuilderRef();
390cc0a58d7SNicolas Vasilache         masked = b.getBoolArrayAttr({false});
3911870e787SNicolas Vasilache       }
39226c8f908SThomas Raoux       vector_transfer_write(result, xferOp.source(), indexing,
3931870e787SNicolas Vasilache                             AffineMapAttr::get(map), masked);
3944ead2cf7SAlex Zinenko     };
3957c3c5b11SNicolas Vasilache 
3967c3c5b11SNicolas Vasilache     // 1. Compute the inBoundsCondition in the current loops ivs + offset
3977c3c5b11SNicolas Vasilache     // context.
3987c3c5b11SNicolas Vasilache     SmallVector<Value, 4> majorIvsPlusOffsets;
3997c3c5b11SNicolas Vasilache     Value inBoundsCondition = emitInBoundsCondition(
400239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
401239eff50SBenjamin Kramer         leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
4027c3c5b11SNicolas Vasilache 
4037c3c5b11SNicolas Vasilache     if (inBoundsCondition) {
4047c3c5b11SNicolas Vasilache       // 2.a. If the condition is not null, we need an IfOp, to write
4057c3c5b11SNicolas Vasilache       // conditionally. Progressively lower to a 1-D transfer write.
406cadb7ccfSAlex Zinenko       conditionBuilder(inBoundsCondition,
407cadb7ccfSAlex Zinenko                        [&] { emitTransferWrite(majorIvsPlusOffsets); });
4087c3c5b11SNicolas Vasilache     } else {
4097c3c5b11SNicolas Vasilache       // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write.
4107c3c5b11SNicolas Vasilache       emitTransferWrite(majorIvsPlusOffsets);
4117c3c5b11SNicolas Vasilache     }
4124ead2cf7SAlex Zinenko   });
4134ead2cf7SAlex Zinenko 
4144ead2cf7SAlex Zinenko   rewriter.eraseOp(op);
4154ead2cf7SAlex Zinenko 
4164ead2cf7SAlex Zinenko   return success();
4174ead2cf7SAlex Zinenko }
4184ead2cf7SAlex Zinenko 
419df63eedeSBenjamin Kramer } // namespace
420df63eedeSBenjamin Kramer 
4214ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote
4224ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found,
4234ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of
4244ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop.
4254ead2cf7SAlex Zinenko template <typename TransferOpTy>
4264ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) {
4274ead2cf7SAlex Zinenko   // rank of the remote memory access, coalescing behavior occurs on the
4284ead2cf7SAlex Zinenko   // innermost memory dimension.
42926c8f908SThomas Raoux   auto remoteRank = transfer.getShapedType().getRank();
4304ead2cf7SAlex Zinenko   // Iterate over the results expressions of the permutation map to determine
4314ead2cf7SAlex Zinenko   // the loop order for creating pointwise copies between remote and local
4324ead2cf7SAlex Zinenko   // memories.
4334ead2cf7SAlex Zinenko   int coalescedIdx = -1;
4344ead2cf7SAlex Zinenko   auto exprs = transfer.permutation_map().getResults();
4354ead2cf7SAlex Zinenko   for (auto en : llvm::enumerate(exprs)) {
4364ead2cf7SAlex Zinenko     auto dim = en.value().template dyn_cast<AffineDimExpr>();
4374ead2cf7SAlex Zinenko     if (!dim) {
4384ead2cf7SAlex Zinenko       continue;
4394ead2cf7SAlex Zinenko     }
4404ead2cf7SAlex Zinenko     auto memRefDim = dim.getPosition();
4414ead2cf7SAlex Zinenko     if (memRefDim == remoteRank - 1) {
4424ead2cf7SAlex Zinenko       // memRefDim has coalescing properties, it should be swapped in the last
4434ead2cf7SAlex Zinenko       // position.
4444ead2cf7SAlex Zinenko       assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices");
4454ead2cf7SAlex Zinenko       coalescedIdx = en.index();
4464ead2cf7SAlex Zinenko     }
4474ead2cf7SAlex Zinenko   }
4484ead2cf7SAlex Zinenko   return coalescedIdx;
4494ead2cf7SAlex Zinenko }
4504ead2cf7SAlex Zinenko 
4514ead2cf7SAlex Zinenko template <typename TransferOpTy>
4523393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter(
4537c3c5b11SNicolas Vasilache     VectorTransferToSCFOptions options, MLIRContext *context)
4547c3c5b11SNicolas Vasilache     : RewritePattern(TransferOpTy::getOperationName(), 1, context),
4557c3c5b11SNicolas Vasilache       options(options) {}
4564ead2cf7SAlex Zinenko 
4577c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer.
4587c3c5b11SNicolas Vasilache template <typename TransferOpTy>
4593393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType(
4607c3c5b11SNicolas Vasilache     TransferOpTy transfer) const {
4614ead2cf7SAlex Zinenko   auto vectorType = transfer.getVectorType();
4628d64df9fSNicolas Vasilache   return MemRefType::get(vectorType.getShape().drop_back(),
4638d64df9fSNicolas Vasilache                          VectorType::get(vectorType.getShape().take_back(),
4648d64df9fSNicolas Vasilache                                          vectorType.getElementType()),
4658d64df9fSNicolas Vasilache                          {}, 0);
4664ead2cf7SAlex Zinenko }
4674ead2cf7SAlex Zinenko 
468239eff50SBenjamin Kramer static void emitWithBoundsChecks(
469239eff50SBenjamin Kramer     PatternRewriter &rewriter, VectorTransferOpInterface transfer,
470307dc7b2SBenjamin Kramer     ValueRange ivs, const MemRefBoundsCapture &memRefBoundsCapture,
471239eff50SBenjamin Kramer     function_ref<void(ArrayRef<Value>)> inBoundsFun,
472239eff50SBenjamin Kramer     function_ref<void(ArrayRef<Value>)> outOfBoundsFun = nullptr) {
473239eff50SBenjamin Kramer   // Permute the incoming indices according to the permutation map.
474239eff50SBenjamin Kramer   SmallVector<Value, 4> indices =
475af5be38aSNicolas Vasilache       applyMapToValues(rewriter, transfer.getLoc(), transfer.permutation_map(),
476af5be38aSNicolas Vasilache                        transfer.indices());
477239eff50SBenjamin Kramer 
478239eff50SBenjamin Kramer   // Generate a bounds check if necessary.
479239eff50SBenjamin Kramer   SmallVector<Value, 4> majorIvsPlusOffsets;
480239eff50SBenjamin Kramer   Value inBoundsCondition =
481239eff50SBenjamin Kramer       emitInBoundsCondition(rewriter, transfer, 0, ivs, indices,
482239eff50SBenjamin Kramer                             memRefBoundsCapture, majorIvsPlusOffsets);
483239eff50SBenjamin Kramer 
484239eff50SBenjamin Kramer   // Apply the permutation map to the ivs. The permutation map may not use all
485239eff50SBenjamin Kramer   // the inputs.
486239eff50SBenjamin Kramer   SmallVector<Value, 4> scalarAccessExprs(transfer.indices().size());
487239eff50SBenjamin Kramer   for (unsigned memRefDim = 0; memRefDim < transfer.indices().size();
488239eff50SBenjamin Kramer        ++memRefDim) {
489239eff50SBenjamin Kramer     // Linear search on a small number of entries.
490239eff50SBenjamin Kramer     int loopIndex = -1;
491239eff50SBenjamin Kramer     auto exprs = transfer.permutation_map().getResults();
492239eff50SBenjamin Kramer     for (auto en : llvm::enumerate(exprs)) {
493239eff50SBenjamin Kramer       auto expr = en.value();
494239eff50SBenjamin Kramer       auto dim = expr.dyn_cast<AffineDimExpr>();
495239eff50SBenjamin Kramer       // Sanity check.
496239eff50SBenjamin Kramer       assert((dim || expr.cast<AffineConstantExpr>().getValue() == 0) &&
497239eff50SBenjamin Kramer              "Expected dim or 0 in permutationMap");
498239eff50SBenjamin Kramer       if (dim && memRefDim == dim.getPosition()) {
499239eff50SBenjamin Kramer         loopIndex = en.index();
500239eff50SBenjamin Kramer         break;
501239eff50SBenjamin Kramer       }
502239eff50SBenjamin Kramer     }
503239eff50SBenjamin Kramer 
504239eff50SBenjamin Kramer     using namespace edsc::op;
505239eff50SBenjamin Kramer     auto i = transfer.indices()[memRefDim];
506239eff50SBenjamin Kramer     scalarAccessExprs[memRefDim] = loopIndex < 0 ? i : i + ivs[loopIndex];
507239eff50SBenjamin Kramer   }
508239eff50SBenjamin Kramer 
509239eff50SBenjamin Kramer   if (inBoundsCondition)
510239eff50SBenjamin Kramer     conditionBuilder(
511239eff50SBenjamin Kramer         /* scf.if */ inBoundsCondition, // {
512239eff50SBenjamin Kramer         [&] { inBoundsFun(scalarAccessExprs); },
513239eff50SBenjamin Kramer         // } else {
514239eff50SBenjamin Kramer         outOfBoundsFun ? [&] { outOfBoundsFun(scalarAccessExprs); }
515239eff50SBenjamin Kramer                        : function_ref<void()>()
516239eff50SBenjamin Kramer         // }
517239eff50SBenjamin Kramer     );
518239eff50SBenjamin Kramer   else
519239eff50SBenjamin Kramer     inBoundsFun(scalarAccessExprs);
520239eff50SBenjamin Kramer }
521239eff50SBenjamin Kramer 
52251d30c34SBenjamin Kramer namespace mlir {
52351d30c34SBenjamin Kramer 
5244ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of:
5254ead2cf7SAlex Zinenko ///   1. local memory allocation;
5264ead2cf7SAlex Zinenko ///   2. perfect loop nest over:
5274ead2cf7SAlex Zinenko ///      a. scalar load from local buffers (viewed as a scalar memref);
528307dc7b2SBenjamin Kramer ///      a. scalar store to original memref (with padding).
5294ead2cf7SAlex Zinenko ///   3. vector_load from local buffer (viewed as a memref<1 x vector>);
5304ead2cf7SAlex Zinenko ///   4. local memory deallocation.
5314ead2cf7SAlex Zinenko ///
5324ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no
5334ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
534307dc7b2SBenjamin Kramer /// padding.
5354ead2cf7SAlex Zinenko 
5364ead2cf7SAlex Zinenko /// Performs the rewrite.
5374ead2cf7SAlex Zinenko template <>
5383393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite(
5394ead2cf7SAlex Zinenko     Operation *op, PatternRewriter &rewriter) const {
5404ead2cf7SAlex Zinenko   using namespace mlir::edsc::op;
5414ead2cf7SAlex Zinenko 
5424ead2cf7SAlex Zinenko   TransferReadOp transfer = cast<TransferReadOp>(op);
54326c8f908SThomas Raoux   auto memRefType = transfer.getShapedType().dyn_cast<MemRefType>();
54426c8f908SThomas Raoux   if (!memRefType)
54526c8f908SThomas Raoux     return failure();
546dfb7b3feSBenjamin Kramer   // Fall back to a loop if the fastest varying stride is not 1 or it is
547dfb7b3feSBenjamin Kramer   // permuted.
548dfb7b3feSBenjamin Kramer   int64_t offset;
549dfb7b3feSBenjamin Kramer   SmallVector<int64_t, 4> strides;
55026c8f908SThomas Raoux   auto successStrides = getStridesAndOffset(memRefType, strides, offset);
551dfb7b3feSBenjamin Kramer   if (succeeded(successStrides) && strides.back() == 1 &&
552dfb7b3feSBenjamin Kramer       transfer.permutation_map().isMinorIdentity()) {
5534ead2cf7SAlex Zinenko     // If > 1D, emit a bunch of loops around 1-D vector transfers.
5544ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() > 1)
5557c3c5b11SNicolas Vasilache       return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options)
5567c3c5b11SNicolas Vasilache           .doReplace();
5574ead2cf7SAlex Zinenko     // If 1-D this is now handled by the target-specific lowering.
5584ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() == 1)
5594ead2cf7SAlex Zinenko       return failure();
5604ead2cf7SAlex Zinenko   }
5614ead2cf7SAlex Zinenko 
5624ead2cf7SAlex Zinenko   // Conservative lowering to scalar load / stores.
5634ead2cf7SAlex Zinenko   // 1. Setup all the captures.
5644ead2cf7SAlex Zinenko   ScopedContext scope(rewriter, transfer.getLoc());
565e2310704SJulian Gross   MemRefIndexedValue remote(transfer.source());
56626c8f908SThomas Raoux   MemRefBoundsCapture memRefBoundsCapture(transfer.source());
5674ead2cf7SAlex Zinenko   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
5684ead2cf7SAlex Zinenko   int coalescedIdx = computeCoalescedIndex(transfer);
5694ead2cf7SAlex Zinenko   // Swap the vectorBoundsCapture which will reorder loop bounds.
5704ead2cf7SAlex Zinenko   if (coalescedIdx >= 0)
5714ead2cf7SAlex Zinenko     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
5724ead2cf7SAlex Zinenko                                    coalescedIdx);
5734ead2cf7SAlex Zinenko 
5744ead2cf7SAlex Zinenko   auto lbs = vectorBoundsCapture.getLbs();
5754ead2cf7SAlex Zinenko   auto ubs = vectorBoundsCapture.getUbs();
5764ead2cf7SAlex Zinenko   SmallVector<Value, 8> steps;
5774ead2cf7SAlex Zinenko   steps.reserve(vectorBoundsCapture.getSteps().size());
5784ead2cf7SAlex Zinenko   for (auto step : vectorBoundsCapture.getSteps())
5794ead2cf7SAlex Zinenko     steps.push_back(std_constant_index(step));
5804ead2cf7SAlex Zinenko 
5814ead2cf7SAlex Zinenko   // 2. Emit alloc-copy-load-dealloc.
5829be61784SNicolas Vasilache   MLIRContext *ctx = op->getContext();
5838d64df9fSNicolas Vasilache   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
584e2310704SJulian Gross   MemRefIndexedValue local(tmp);
585d1560f39SAlex Zinenko   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
586239eff50SBenjamin Kramer     auto ivsStorage = llvm::to_vector<8>(loopIvs);
5874ead2cf7SAlex Zinenko     // Swap the ivs which will reorder memory accesses.
5884ead2cf7SAlex Zinenko     if (coalescedIdx >= 0)
589239eff50SBenjamin Kramer       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
590239eff50SBenjamin Kramer 
591239eff50SBenjamin Kramer     ArrayRef<Value> ivs(ivsStorage);
5921b97cdf8SRiver Riddle     Value pos = std_index_cast(IntegerType::get(ctx, 32), ivs.back());
593239eff50SBenjamin Kramer     Value inVector = local(ivs.drop_back());
594239eff50SBenjamin Kramer     auto loadValue = [&](ArrayRef<Value> indices) {
595239eff50SBenjamin Kramer       Value vector = vector_insert_element(remote(indices), inVector, pos);
596239eff50SBenjamin Kramer       local(ivs.drop_back()) = vector;
597239eff50SBenjamin Kramer     };
598239eff50SBenjamin Kramer     auto loadPadding = [&](ArrayRef<Value>) {
599239eff50SBenjamin Kramer       Value vector = vector_insert_element(transfer.padding(), inVector, pos);
600239eff50SBenjamin Kramer       local(ivs.drop_back()) = vector;
601239eff50SBenjamin Kramer     };
602239eff50SBenjamin Kramer     emitWithBoundsChecks(
603239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
604239eff50SBenjamin Kramer         memRefBoundsCapture, loadValue, loadPadding);
6054ead2cf7SAlex Zinenko   });
606e2310704SJulian Gross   Value vectorValue = memref_load(vector_type_cast(tmp));
6074ead2cf7SAlex Zinenko 
6084ead2cf7SAlex Zinenko   // 3. Propagate.
6094ead2cf7SAlex Zinenko   rewriter.replaceOp(op, vectorValue);
6104ead2cf7SAlex Zinenko   return success();
6114ead2cf7SAlex Zinenko }
6124ead2cf7SAlex Zinenko 
6134ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of:
6144ead2cf7SAlex Zinenko ///   1. local memory allocation;
6154ead2cf7SAlex Zinenko ///   2. vector_store to local buffer (viewed as a memref<1 x vector>);
6164ead2cf7SAlex Zinenko ///   3. perfect loop nest over:
6174ead2cf7SAlex Zinenko ///      a. scalar load from local buffers (viewed as a scalar memref);
618307dc7b2SBenjamin Kramer ///      a. scalar store to original memref (if in bounds).
6194ead2cf7SAlex Zinenko ///   4. local memory deallocation.
6204ead2cf7SAlex Zinenko ///
6214ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no
622307dc7b2SBenjamin Kramer /// out-of-bounds accesses are possible.
6234ead2cf7SAlex Zinenko template <>
6243393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite(
6254ead2cf7SAlex Zinenko     Operation *op, PatternRewriter &rewriter) const {
6264ead2cf7SAlex Zinenko   using namespace edsc::op;
6274ead2cf7SAlex Zinenko 
6284ead2cf7SAlex Zinenko   TransferWriteOp transfer = cast<TransferWriteOp>(op);
62926c8f908SThomas Raoux   auto memRefType = transfer.getShapedType().template dyn_cast<MemRefType>();
63026c8f908SThomas Raoux   if (!memRefType)
63126c8f908SThomas Raoux     return failure();
632dfb7b3feSBenjamin Kramer 
633dfb7b3feSBenjamin Kramer   // Fall back to a loop if the fastest varying stride is not 1 or it is
634dfb7b3feSBenjamin Kramer   // permuted.
635dfb7b3feSBenjamin Kramer   int64_t offset;
636dfb7b3feSBenjamin Kramer   SmallVector<int64_t, 4> strides;
63726c8f908SThomas Raoux   auto successStrides = getStridesAndOffset(memRefType, strides, offset);
638dfb7b3feSBenjamin Kramer   if (succeeded(successStrides) && strides.back() == 1 &&
639dfb7b3feSBenjamin Kramer       transfer.permutation_map().isMinorIdentity()) {
6404ead2cf7SAlex Zinenko     // If > 1D, emit a bunch of loops around 1-D vector transfers.
6414ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() > 1)
6427c3c5b11SNicolas Vasilache       return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options)
6434ead2cf7SAlex Zinenko           .doReplace();
6444ead2cf7SAlex Zinenko     // If 1-D this is now handled by the target-specific lowering.
6454ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() == 1)
6464ead2cf7SAlex Zinenko       return failure();
6474ead2cf7SAlex Zinenko   }
6484ead2cf7SAlex Zinenko 
6494ead2cf7SAlex Zinenko   // 1. Setup all the captures.
6504ead2cf7SAlex Zinenko   ScopedContext scope(rewriter, transfer.getLoc());
651e2310704SJulian Gross   MemRefIndexedValue remote(transfer.source());
65226c8f908SThomas Raoux   MemRefBoundsCapture memRefBoundsCapture(transfer.source());
6534ead2cf7SAlex Zinenko   Value vectorValue(transfer.vector());
6544ead2cf7SAlex Zinenko   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
6554ead2cf7SAlex Zinenko   int coalescedIdx = computeCoalescedIndex(transfer);
6564ead2cf7SAlex Zinenko   // Swap the vectorBoundsCapture which will reorder loop bounds.
6574ead2cf7SAlex Zinenko   if (coalescedIdx >= 0)
6584ead2cf7SAlex Zinenko     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
6594ead2cf7SAlex Zinenko                                    coalescedIdx);
6604ead2cf7SAlex Zinenko 
6614ead2cf7SAlex Zinenko   auto lbs = vectorBoundsCapture.getLbs();
6624ead2cf7SAlex Zinenko   auto ubs = vectorBoundsCapture.getUbs();
6634ead2cf7SAlex Zinenko   SmallVector<Value, 8> steps;
6644ead2cf7SAlex Zinenko   steps.reserve(vectorBoundsCapture.getSteps().size());
6654ead2cf7SAlex Zinenko   for (auto step : vectorBoundsCapture.getSteps())
6664ead2cf7SAlex Zinenko     steps.push_back(std_constant_index(step));
6674ead2cf7SAlex Zinenko 
6684ead2cf7SAlex Zinenko   // 2. Emit alloc-store-copy-dealloc.
6698d64df9fSNicolas Vasilache   Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer);
670e2310704SJulian Gross   MemRefIndexedValue local(tmp);
6714ead2cf7SAlex Zinenko   Value vec = vector_type_cast(tmp);
672e2310704SJulian Gross   memref_store(vectorValue, vec);
673d1560f39SAlex Zinenko   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
674239eff50SBenjamin Kramer     auto ivsStorage = llvm::to_vector<8>(loopIvs);
675239eff50SBenjamin Kramer     // Swap the ivsStorage which will reorder memory accesses.
6764ead2cf7SAlex Zinenko     if (coalescedIdx >= 0)
677239eff50SBenjamin Kramer       std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]);
678239eff50SBenjamin Kramer 
679239eff50SBenjamin Kramer     ArrayRef<Value> ivs(ivsStorage);
6808d64df9fSNicolas Vasilache     Value pos =
6811b97cdf8SRiver Riddle         std_index_cast(IntegerType::get(op->getContext(), 32), ivs.back());
682239eff50SBenjamin Kramer     auto storeValue = [&](ArrayRef<Value> indices) {
683239eff50SBenjamin Kramer       Value scalar = vector_extract_element(local(ivs.drop_back()), pos);
6848d64df9fSNicolas Vasilache       remote(indices) = scalar;
685239eff50SBenjamin Kramer     };
686239eff50SBenjamin Kramer     emitWithBoundsChecks(
687239eff50SBenjamin Kramer         rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs,
688239eff50SBenjamin Kramer         memRefBoundsCapture, storeValue);
6894ead2cf7SAlex Zinenko   });
6904ead2cf7SAlex Zinenko 
6918d64df9fSNicolas Vasilache   // 3. Erase.
6924ead2cf7SAlex Zinenko   rewriter.eraseOp(op);
6934ead2cf7SAlex Zinenko   return success();
6944ead2cf7SAlex Zinenko }
6954ead2cf7SAlex Zinenko 
6963393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns(
697*dc4e913bSChris Lattner     RewritePatternSet &patterns, const VectorTransferToSCFOptions &options) {
698*dc4e913bSChris Lattner   patterns.add<VectorTransferRewriter<vector::TransferReadOp>,
6993a506b31SChris Lattner                VectorTransferRewriter<vector::TransferWriteOp>>(
7003a506b31SChris Lattner       options, patterns.getContext());
7014ead2cf7SAlex Zinenko }
7023393cc4cSNicolas Vasilache 
7033393cc4cSNicolas Vasilache } // namespace mlir
7043393cc4cSNicolas Vasilache 
7055f9e0466SNicolas Vasilache namespace {
7065f9e0466SNicolas Vasilache 
7075f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass
7085f9e0466SNicolas Vasilache     : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
7095f9e0466SNicolas Vasilache   ConvertVectorToSCFPass() = default;
7105f9e0466SNicolas Vasilache   ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
7115f9e0466SNicolas Vasilache     this->fullUnroll = options.unroll;
7125f9e0466SNicolas Vasilache   }
7135f9e0466SNicolas Vasilache 
7145f9e0466SNicolas Vasilache   void runOnFunction() override {
715*dc4e913bSChris Lattner     RewritePatternSet patterns(getFunction().getContext());
7165f9e0466SNicolas Vasilache     populateVectorToSCFConversionPatterns(
7173a506b31SChris Lattner         patterns, VectorTransferToSCFOptions().setUnroll(fullUnroll));
718e21adfa3SRiver Riddle     (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns));
7195f9e0466SNicolas Vasilache   }
7205f9e0466SNicolas Vasilache };
7215f9e0466SNicolas Vasilache 
7225f9e0466SNicolas Vasilache } // namespace
7235f9e0466SNicolas Vasilache 
7245f9e0466SNicolas Vasilache std::unique_ptr<Pass>
7255f9e0466SNicolas Vasilache mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
7265f9e0466SNicolas Vasilache   return std::make_unique<ConvertVectorToSCFPass>(options);
7275f9e0466SNicolas Vasilache }
728