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"
194ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Builders.h"
204ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Intrinsics.h"
214ead2cf7SAlex Zinenko #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
224ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/EDSC/Intrinsics.h"
234ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/VectorOps.h"
247c3c5b11SNicolas Vasilache #include "mlir/Dialect/Vector/VectorUtils.h"
254ead2cf7SAlex Zinenko #include "mlir/IR/AffineExpr.h"
264ead2cf7SAlex Zinenko #include "mlir/IR/AffineMap.h"
274ead2cf7SAlex Zinenko #include "mlir/IR/Attributes.h"
284ead2cf7SAlex Zinenko #include "mlir/IR/Builders.h"
294ead2cf7SAlex Zinenko #include "mlir/IR/Location.h"
304ead2cf7SAlex Zinenko #include "mlir/IR/Matchers.h"
314ead2cf7SAlex Zinenko #include "mlir/IR/OperationSupport.h"
324ead2cf7SAlex Zinenko #include "mlir/IR/PatternMatch.h"
334ead2cf7SAlex Zinenko #include "mlir/IR/Types.h"
345f9e0466SNicolas Vasilache #include "mlir/Pass/Pass.h"
355f9e0466SNicolas Vasilache #include "mlir/Transforms/Passes.h"
364ead2cf7SAlex Zinenko 
374ead2cf7SAlex Zinenko using namespace mlir;
384ead2cf7SAlex Zinenko using namespace mlir::edsc;
394ead2cf7SAlex Zinenko using namespace mlir::edsc::intrinsics;
404ead2cf7SAlex Zinenko using vector::TransferReadOp;
414ead2cf7SAlex Zinenko using vector::TransferWriteOp;
424ead2cf7SAlex Zinenko 
43350dadaaSBenjamin Kramer namespace {
444ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector
454ead2cf7SAlex Zinenko /// transfer operations (read and write).
464ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR
474ead2cf7SAlex Zinenko /// manipulation.
484ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as:
494ead2cf7SAlex Zinenko ///
504ead2cf7SAlex Zinenko /// ```
514ead2cf7SAlex Zinenko ///   vector_transfer_read(%m, %offsets, identity_map, %fill) :
524ead2cf7SAlex Zinenko ///     memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
534ead2cf7SAlex Zinenko ///     vector<(major_dims) x (minor_dims) x type>
544ead2cf7SAlex Zinenko /// ```
554ead2cf7SAlex Zinenko ///
564ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or
574ead2cf7SAlex Zinenko /// higher).
584ead2cf7SAlex Zinenko ///
594ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling:
604ead2cf7SAlex Zinenko ///
614ead2cf7SAlex Zinenko /// ```
624ead2cf7SAlex Zinenko ///   %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>>
634ead2cf7SAlex Zinenko ///   for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest
644ead2cf7SAlex Zinenko ///     if (any_of(%ivs_major + %offsets, <, major_dims)) {
654ead2cf7SAlex Zinenko ///       %v = vector_transfer_read(
664ead2cf7SAlex Zinenko ///         {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor},
674ead2cf7SAlex Zinenko ///          %ivs_minor):
684ead2cf7SAlex Zinenko ///         memref<(leading_dims) x (major_dims) x (minor_dims) x type>,
694ead2cf7SAlex Zinenko ///         vector<(minor_dims) x type>;
704ead2cf7SAlex Zinenko ///       store(%v, %tmp);
714ead2cf7SAlex Zinenko ///     } else {
724ead2cf7SAlex Zinenko ///       %v = splat(vector<(minor_dims) x type>, %fill)
734ead2cf7SAlex Zinenko ///       store(%v, %tmp, %ivs_major);
744ead2cf7SAlex Zinenko ///     }
754ead2cf7SAlex Zinenko ///   }
764ead2cf7SAlex Zinenko ///   %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>):
774ead2cf7SAlex Zinenko //      vector<(major_dims) x (minor_dims) x type>
784ead2cf7SAlex Zinenko /// ```
794ead2cf7SAlex Zinenko ///
804ead2cf7SAlex Zinenko template <typename ConcreteOp>
814ead2cf7SAlex Zinenko class NDTransferOpHelper {
824ead2cf7SAlex Zinenko public:
837c3c5b11SNicolas Vasilache   NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp,
847c3c5b11SNicolas Vasilache                      const VectorTransferToSCFOptions &options)
857c3c5b11SNicolas Vasilache       : rewriter(rewriter), options(options), loc(xferOp.getLoc()),
864ead2cf7SAlex Zinenko         scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp),
874ead2cf7SAlex Zinenko         op(xferOp.getOperation()) {
884ead2cf7SAlex Zinenko     vectorType = xferOp.getVectorType();
899db53a18SRiver Riddle     // TODO: when we go to k > 1-D vectors adapt minorRank.
904ead2cf7SAlex Zinenko     minorRank = 1;
914ead2cf7SAlex Zinenko     majorRank = vectorType.getRank() - minorRank;
92*ec2f2cecSNicolas Vasilache     leadingRank = xferOp.getLeadingMemRefRank();
934ead2cf7SAlex Zinenko     majorVectorType =
944ead2cf7SAlex Zinenko         VectorType::get(vectorType.getShape().take_front(majorRank),
954ead2cf7SAlex Zinenko                         vectorType.getElementType());
964ead2cf7SAlex Zinenko     minorVectorType =
974ead2cf7SAlex Zinenko         VectorType::get(vectorType.getShape().take_back(minorRank),
984ead2cf7SAlex Zinenko                         vectorType.getElementType());
994ead2cf7SAlex Zinenko     /// Memref of minor vector type is used for individual transfers.
1004ead2cf7SAlex Zinenko     memRefMinorVectorType =
1014ead2cf7SAlex Zinenko         MemRefType::get(majorVectorType.getShape(), minorVectorType, {},
1024ead2cf7SAlex Zinenko                         xferOp.getMemRefType().getMemorySpace());
1034ead2cf7SAlex Zinenko   }
1044ead2cf7SAlex Zinenko 
1054ead2cf7SAlex Zinenko   LogicalResult doReplace();
1064ead2cf7SAlex Zinenko 
1074ead2cf7SAlex Zinenko private:
1084ead2cf7SAlex Zinenko   /// Creates the loop nest on the "major" dimensions and calls the
1094ead2cf7SAlex Zinenko   /// `loopBodyBuilder` lambda in the context of the loop nest.
1104ead2cf7SAlex Zinenko   template <typename Lambda>
1114ead2cf7SAlex Zinenko   void emitLoops(Lambda loopBodyBuilder);
1124ead2cf7SAlex Zinenko 
1134ead2cf7SAlex Zinenko   /// Operate within the body of `emitLoops` to:
1147c3c5b11SNicolas Vasilache   ///   1. Compute the indexings `majorIvs + majorOffsets` and save them in
1157c3c5b11SNicolas Vasilache   ///      `majorIvsPlusOffsets`.
1167c3c5b11SNicolas Vasilache   ///   2. Return a boolean that determines whether the first `majorIvs.rank()`
1174ead2cf7SAlex Zinenko   ///      dimensions `majorIvs + majorOffsets` are all within `memrefBounds`.
1187c3c5b11SNicolas Vasilache   Value emitInBoundsCondition(ValueRange majorIvs, ValueRange majorOffsets,
1194ead2cf7SAlex Zinenko                               MemRefBoundsCapture &memrefBounds,
1207c3c5b11SNicolas Vasilache                               SmallVectorImpl<Value> &majorIvsPlusOffsets);
1214ead2cf7SAlex Zinenko 
1224ead2cf7SAlex Zinenko   /// Common state to lower vector transfer ops.
1234ead2cf7SAlex Zinenko   PatternRewriter &rewriter;
1247c3c5b11SNicolas Vasilache   const VectorTransferToSCFOptions &options;
1254ead2cf7SAlex Zinenko   Location loc;
1264ead2cf7SAlex Zinenko   std::unique_ptr<ScopedContext> scope;
1274ead2cf7SAlex Zinenko   ConcreteOp xferOp;
1284ead2cf7SAlex Zinenko   Operation *op;
1294ead2cf7SAlex Zinenko   // A vector transfer copies data between:
1304ead2cf7SAlex Zinenko   //   - memref<(leading_dims) x (major_dims) x (minor_dims) x type>
1314ead2cf7SAlex Zinenko   //   - vector<(major_dims) x (minor_dims) x type>
1324ead2cf7SAlex Zinenko   unsigned minorRank;         // for now always 1
1334ead2cf7SAlex Zinenko   unsigned majorRank;         // vector rank - minorRank
1344ead2cf7SAlex Zinenko   unsigned leadingRank;       // memref rank - vector rank
1354ead2cf7SAlex Zinenko   VectorType vectorType;      // vector<(major_dims) x (minor_dims) x type>
1364ead2cf7SAlex Zinenko   VectorType majorVectorType; // vector<(major_dims) x type>
1374ead2cf7SAlex Zinenko   VectorType minorVectorType; // vector<(minor_dims) x type>
1384ead2cf7SAlex Zinenko   MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>>
1394ead2cf7SAlex Zinenko };
1404ead2cf7SAlex Zinenko 
1414ead2cf7SAlex Zinenko template <typename ConcreteOp>
1424ead2cf7SAlex Zinenko template <typename Lambda>
1434ead2cf7SAlex Zinenko void NDTransferOpHelper<ConcreteOp>::emitLoops(Lambda loopBodyBuilder) {
1444ead2cf7SAlex Zinenko   /// Loop nest operates on the major dimensions
1454ead2cf7SAlex Zinenko   MemRefBoundsCapture memrefBoundsCapture(xferOp.memref());
1467c3c5b11SNicolas Vasilache 
1477c3c5b11SNicolas Vasilache   if (options.unroll) {
1487c3c5b11SNicolas Vasilache     auto shape = majorVectorType.getShape();
1497c3c5b11SNicolas Vasilache     auto strides = computeStrides(shape);
1507c3c5b11SNicolas Vasilache     unsigned numUnrolledInstances = computeMaxLinearIndex(shape);
1517c3c5b11SNicolas Vasilache     ValueRange indices(xferOp.indices());
1527c3c5b11SNicolas Vasilache     for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) {
1537c3c5b11SNicolas Vasilache       SmallVector<int64_t, 4> offsets = delinearize(strides, idx);
1547c3c5b11SNicolas Vasilache       SmallVector<Value, 4> offsetValues =
1557c3c5b11SNicolas Vasilache           llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value {
1567c3c5b11SNicolas Vasilache             return std_constant_index(off);
1577c3c5b11SNicolas Vasilache           }));
1587c3c5b11SNicolas Vasilache       loopBodyBuilder(offsetValues, indices.take_front(leadingRank),
1597c3c5b11SNicolas Vasilache                       indices.drop_front(leadingRank).take_front(majorRank),
1607c3c5b11SNicolas Vasilache                       indices.take_back(minorRank), memrefBoundsCapture);
1617c3c5b11SNicolas Vasilache     }
1627c3c5b11SNicolas Vasilache   } else {
1634ead2cf7SAlex Zinenko     VectorBoundsCapture vectorBoundsCapture(majorVectorType);
1644ead2cf7SAlex Zinenko     auto majorLbs = vectorBoundsCapture.getLbs();
1654ead2cf7SAlex Zinenko     auto majorUbs = vectorBoundsCapture.getUbs();
1664ead2cf7SAlex Zinenko     auto majorSteps = vectorBoundsCapture.getSteps();
1673f5bd53eSAlex Zinenko     affineLoopNestBuilder(
1683f5bd53eSAlex Zinenko         majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) {
1694ead2cf7SAlex Zinenko           ValueRange indices(xferOp.indices());
1704ead2cf7SAlex Zinenko           loopBodyBuilder(majorIvs, indices.take_front(leadingRank),
1714ead2cf7SAlex Zinenko                           indices.drop_front(leadingRank).take_front(majorRank),
1724ead2cf7SAlex Zinenko                           indices.take_back(minorRank), memrefBoundsCapture);
1734ead2cf7SAlex Zinenko         });
1744ead2cf7SAlex Zinenko   }
1757c3c5b11SNicolas Vasilache }
1764ead2cf7SAlex Zinenko 
177bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) {
178bd87c6bcSNicolas Vasilache   if (auto cstOp = v.getDefiningOp<ConstantIndexOp>())
179bd87c6bcSNicolas Vasilache     return cstOp.getValue();
180bd87c6bcSNicolas Vasilache   if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>())
181bd87c6bcSNicolas Vasilache     if (affineApplyOp.getAffineMap().isSingleConstant())
182bd87c6bcSNicolas Vasilache       return affineApplyOp.getAffineMap().getSingleConstantResult();
183bd87c6bcSNicolas Vasilache   return None;
184bd87c6bcSNicolas Vasilache }
185bd87c6bcSNicolas Vasilache 
186bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding
187bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go
188bd87c6bcSNicolas Vasilache // away once scf.if folds properly.
189bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) {
190bd87c6bcSNicolas Vasilache   using namespace mlir::edsc::op;
191bd87c6bcSNicolas Vasilache   auto maybeCstV = extractConstantIndex(v);
192bd87c6bcSNicolas Vasilache   auto maybeCstUb = extractConstantIndex(ub);
193bd87c6bcSNicolas Vasilache   if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb)
194bd87c6bcSNicolas Vasilache     return Value();
195bd87c6bcSNicolas Vasilache   return slt(v, ub);
196bd87c6bcSNicolas Vasilache }
197bd87c6bcSNicolas Vasilache 
1984ead2cf7SAlex Zinenko template <typename ConcreteOp>
1997c3c5b11SNicolas Vasilache Value NDTransferOpHelper<ConcreteOp>::emitInBoundsCondition(
2004ead2cf7SAlex Zinenko     ValueRange majorIvs, ValueRange majorOffsets,
2017c3c5b11SNicolas Vasilache     MemRefBoundsCapture &memrefBounds,
2027c3c5b11SNicolas Vasilache     SmallVectorImpl<Value> &majorIvsPlusOffsets) {
2037c3c5b11SNicolas Vasilache   Value inBoundsCondition;
2044ead2cf7SAlex Zinenko   majorIvsPlusOffsets.reserve(majorIvs.size());
2051870e787SNicolas Vasilache   unsigned idx = 0;
2064ead2cf7SAlex Zinenko   for (auto it : llvm::zip(majorIvs, majorOffsets, memrefBounds.getUbs())) {
2074ead2cf7SAlex Zinenko     Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it);
2084ead2cf7SAlex Zinenko     using namespace mlir::edsc::op;
2094ead2cf7SAlex Zinenko     majorIvsPlusOffsets.push_back(iv + off);
2101870e787SNicolas Vasilache     if (xferOp.isMaskedDim(leadingRank + idx)) {
211bd87c6bcSNicolas Vasilache       Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub);
212bd87c6bcSNicolas Vasilache       if (inBoundsCond)
213bd87c6bcSNicolas Vasilache         inBoundsCondition = (inBoundsCondition)
214bd87c6bcSNicolas Vasilache                                 ? (inBoundsCondition && inBoundsCond)
215bd87c6bcSNicolas Vasilache                                 : inBoundsCond;
2161870e787SNicolas Vasilache     }
2171870e787SNicolas Vasilache     ++idx;
2184ead2cf7SAlex Zinenko   }
2197c3c5b11SNicolas Vasilache   return inBoundsCondition;
2204ead2cf7SAlex Zinenko }
2214ead2cf7SAlex Zinenko 
222247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations.
223247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType,
224247e185dSNicolas Vasilache                                      Operation *op) {
225247e185dSNicolas Vasilache   auto &b = ScopedContext::getBuilderRef();
226247e185dSNicolas Vasilache   OpBuilder::InsertionGuard guard(b);
227247e185dSNicolas Vasilache   b.setInsertionPointToStart(&op->getParentOfType<FuncOp>().front());
228247e185dSNicolas Vasilache   Value res =
229247e185dSNicolas Vasilache       std_alloca(memRefMinorVectorType, ValueRange{}, b.getI64IntegerAttr(128));
230247e185dSNicolas Vasilache   return res;
231247e185dSNicolas Vasilache }
232247e185dSNicolas Vasilache 
2334ead2cf7SAlex Zinenko template <>
2344ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() {
2357c3c5b11SNicolas Vasilache   Value alloc, result;
2367c3c5b11SNicolas Vasilache   if (options.unroll)
2377c3c5b11SNicolas Vasilache     result = std_splat(vectorType, xferOp.padding());
2387c3c5b11SNicolas Vasilache   else
239247e185dSNicolas Vasilache     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
2404ead2cf7SAlex Zinenko 
2414ead2cf7SAlex Zinenko   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
2424ead2cf7SAlex Zinenko                 ValueRange majorOffsets, ValueRange minorOffsets,
2434ead2cf7SAlex Zinenko                 MemRefBoundsCapture &memrefBounds) {
2447c3c5b11SNicolas Vasilache     /// Lambda to load 1-D vector in the current loop ivs + offset context.
2457c3c5b11SNicolas Vasilache     auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value {
2464ead2cf7SAlex Zinenko       SmallVector<Value, 8> indexing;
2474ead2cf7SAlex Zinenko       indexing.reserve(leadingRank + majorRank + minorRank);
2484ead2cf7SAlex Zinenko       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
2494ead2cf7SAlex Zinenko       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
2504ead2cf7SAlex Zinenko       indexing.append(minorOffsets.begin(), minorOffsets.end());
25136cdc17fSNicolas Vasilache       Value memref = xferOp.memref();
25236cdc17fSNicolas Vasilache       auto map = TransferReadOp::getTransferMinorIdentityMap(
25336cdc17fSNicolas Vasilache           xferOp.getMemRefType(), minorVectorType);
2541870e787SNicolas Vasilache       ArrayAttr masked;
2551870e787SNicolas Vasilache       if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
2561870e787SNicolas Vasilache         OpBuilder &b = ScopedContext::getBuilderRef();
2571870e787SNicolas Vasilache         masked = b.getBoolArrayAttr({true});
2581870e787SNicolas Vasilache       }
2597c3c5b11SNicolas Vasilache       return vector_transfer_read(minorVectorType, memref, indexing,
2607c3c5b11SNicolas Vasilache                                   AffineMapAttr::get(map), xferOp.padding(),
2617c3c5b11SNicolas Vasilache                                   masked);
2624ead2cf7SAlex Zinenko     };
2637c3c5b11SNicolas Vasilache 
2647c3c5b11SNicolas Vasilache     // 1. Compute the inBoundsCondition in the current loops ivs + offset
2657c3c5b11SNicolas Vasilache     // context.
2667c3c5b11SNicolas Vasilache     SmallVector<Value, 4> majorIvsPlusOffsets;
2677c3c5b11SNicolas Vasilache     Value inBoundsCondition = emitInBoundsCondition(
2687c3c5b11SNicolas Vasilache         majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
2697c3c5b11SNicolas Vasilache 
2707c3c5b11SNicolas Vasilache     if (inBoundsCondition) {
2717c3c5b11SNicolas Vasilache       // 2. If the condition is not null, we need an IfOp, which may yield
2727c3c5b11SNicolas Vasilache       // if `options.unroll` is true.
2737c3c5b11SNicolas Vasilache       SmallVector<Type, 1> resultType;
2747c3c5b11SNicolas Vasilache       if (options.unroll)
2757c3c5b11SNicolas Vasilache         resultType.push_back(vectorType);
2767c3c5b11SNicolas Vasilache 
277cadb7ccfSAlex Zinenko       // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise
278cadb7ccfSAlex Zinenko       // splat a 1-D vector.
279cadb7ccfSAlex Zinenko       ValueRange ifResults = conditionBuilder(
280cadb7ccfSAlex Zinenko           resultType, inBoundsCondition,
281cadb7ccfSAlex Zinenko           [&]() -> scf::ValueVector {
2827c3c5b11SNicolas Vasilache             Value vector = load1DVector(majorIvsPlusOffsets);
283cadb7ccfSAlex Zinenko             // 3.a. If `options.unroll` is true, insert the 1-D vector in the
2847c3c5b11SNicolas Vasilache             // aggregate. We must yield and merge with the `else` branch.
2857c3c5b11SNicolas Vasilache             if (options.unroll) {
2867c3c5b11SNicolas Vasilache               vector = vector_insert(vector, result, majorIvs);
287cadb7ccfSAlex Zinenko               return {vector};
2887c3c5b11SNicolas Vasilache             }
289cadb7ccfSAlex Zinenko             // 3.b. Otherwise, just go through the temporary `alloc`.
2904ead2cf7SAlex Zinenko             std_store(vector, alloc, majorIvs);
291cadb7ccfSAlex Zinenko             return {};
292cadb7ccfSAlex Zinenko           },
293cadb7ccfSAlex Zinenko           [&]() -> scf::ValueVector {
2947c3c5b11SNicolas Vasilache             Value vector = std_splat(minorVectorType, xferOp.padding());
295cadb7ccfSAlex Zinenko             // 3.c. If `options.unroll` is true, insert the 1-D vector in the
2967c3c5b11SNicolas Vasilache             // aggregate. We must yield and merge with the `then` branch.
2977c3c5b11SNicolas Vasilache             if (options.unroll) {
2987c3c5b11SNicolas Vasilache               vector = vector_insert(vector, result, majorIvs);
299cadb7ccfSAlex Zinenko               return {vector};
3007c3c5b11SNicolas Vasilache             }
301cadb7ccfSAlex Zinenko             // 3.d. Otherwise, just go through the temporary `alloc`.
3027c3c5b11SNicolas Vasilache             std_store(vector, alloc, majorIvs);
303cadb7ccfSAlex Zinenko             return {};
3047c3c5b11SNicolas Vasilache           });
305cadb7ccfSAlex Zinenko 
3067c3c5b11SNicolas Vasilache       if (!resultType.empty())
307cadb7ccfSAlex Zinenko         result = *ifResults.begin();
3087c3c5b11SNicolas Vasilache     } else {
3097c3c5b11SNicolas Vasilache       // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read.
3107c3c5b11SNicolas Vasilache       Value loaded1D = load1DVector(majorIvsPlusOffsets);
3117c3c5b11SNicolas Vasilache       // 5.a. If `options.unroll` is true, insert the 1-D vector in the
3127c3c5b11SNicolas Vasilache       // aggregate.
3137c3c5b11SNicolas Vasilache       if (options.unroll)
3147c3c5b11SNicolas Vasilache         result = vector_insert(loaded1D, result, majorIvs);
3157c3c5b11SNicolas Vasilache       // 5.b. Otherwise, just go through the temporary `alloc`.
3167c3c5b11SNicolas Vasilache       else
3177c3c5b11SNicolas Vasilache         std_store(loaded1D, alloc, majorIvs);
3187c3c5b11SNicolas Vasilache     }
3197c3c5b11SNicolas Vasilache   });
3207c3c5b11SNicolas Vasilache 
321a9b5edc5SBenjamin Kramer   assert((!options.unroll ^ (bool)result) &&
322a9b5edc5SBenjamin Kramer          "Expected resulting Value iff unroll");
3237c3c5b11SNicolas Vasilache   if (!result)
3247c3c5b11SNicolas Vasilache     result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc));
3257c3c5b11SNicolas Vasilache   rewriter.replaceOp(op, result);
3264ead2cf7SAlex Zinenko 
3274ead2cf7SAlex Zinenko   return success();
3284ead2cf7SAlex Zinenko }
3294ead2cf7SAlex Zinenko 
3304ead2cf7SAlex Zinenko template <>
3314ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() {
3327c3c5b11SNicolas Vasilache   Value alloc;
3337c3c5b11SNicolas Vasilache   if (!options.unroll) {
334247e185dSNicolas Vasilache     alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op);
3354ead2cf7SAlex Zinenko     std_store(xferOp.vector(),
3364ead2cf7SAlex Zinenko               vector_type_cast(MemRefType::get({}, vectorType), alloc));
3377c3c5b11SNicolas Vasilache   }
3384ead2cf7SAlex Zinenko 
3394ead2cf7SAlex Zinenko   emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets,
3404ead2cf7SAlex Zinenko                 ValueRange majorOffsets, ValueRange minorOffsets,
3414ead2cf7SAlex Zinenko                 MemRefBoundsCapture &memrefBounds) {
3427c3c5b11SNicolas Vasilache     // Lower to 1-D vector_transfer_write and let recursion handle it.
3437c3c5b11SNicolas Vasilache     auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) {
3444ead2cf7SAlex Zinenko       SmallVector<Value, 8> indexing;
3454ead2cf7SAlex Zinenko       indexing.reserve(leadingRank + majorRank + minorRank);
3464ead2cf7SAlex Zinenko       indexing.append(leadingOffsets.begin(), leadingOffsets.end());
3474ead2cf7SAlex Zinenko       indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end());
3484ead2cf7SAlex Zinenko       indexing.append(minorOffsets.begin(), minorOffsets.end());
3497c3c5b11SNicolas Vasilache       Value result;
3507c3c5b11SNicolas Vasilache       // If `options.unroll` is true, extract the 1-D vector from the
3517c3c5b11SNicolas Vasilache       // aggregate.
3527c3c5b11SNicolas Vasilache       if (options.unroll)
3537c3c5b11SNicolas Vasilache         result = vector_extract(xferOp.vector(), majorIvs);
3547c3c5b11SNicolas Vasilache       else
3557c3c5b11SNicolas Vasilache         result = std_load(alloc, majorIvs);
35636cdc17fSNicolas Vasilache       auto map = TransferWriteOp::getTransferMinorIdentityMap(
35736cdc17fSNicolas Vasilache           xferOp.getMemRefType(), minorVectorType);
3581870e787SNicolas Vasilache       ArrayAttr masked;
3591870e787SNicolas Vasilache       if (xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) {
3601870e787SNicolas Vasilache         OpBuilder &b = ScopedContext::getBuilderRef();
3611870e787SNicolas Vasilache         masked = b.getBoolArrayAttr({true});
3621870e787SNicolas Vasilache       }
3637c3c5b11SNicolas Vasilache       vector_transfer_write(result, xferOp.memref(), indexing,
3641870e787SNicolas Vasilache                             AffineMapAttr::get(map), masked);
3654ead2cf7SAlex Zinenko     };
3667c3c5b11SNicolas Vasilache 
3677c3c5b11SNicolas Vasilache     // 1. Compute the inBoundsCondition in the current loops ivs + offset
3687c3c5b11SNicolas Vasilache     // context.
3697c3c5b11SNicolas Vasilache     SmallVector<Value, 4> majorIvsPlusOffsets;
3707c3c5b11SNicolas Vasilache     Value inBoundsCondition = emitInBoundsCondition(
3717c3c5b11SNicolas Vasilache         majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets);
3727c3c5b11SNicolas Vasilache 
3737c3c5b11SNicolas Vasilache     if (inBoundsCondition) {
3747c3c5b11SNicolas Vasilache       // 2.a. If the condition is not null, we need an IfOp, to write
3757c3c5b11SNicolas Vasilache       // conditionally. Progressively lower to a 1-D transfer write.
376cadb7ccfSAlex Zinenko       conditionBuilder(inBoundsCondition,
377cadb7ccfSAlex Zinenko                        [&] { emitTransferWrite(majorIvsPlusOffsets); });
3787c3c5b11SNicolas Vasilache     } else {
3797c3c5b11SNicolas Vasilache       // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write.
3807c3c5b11SNicolas Vasilache       emitTransferWrite(majorIvsPlusOffsets);
3817c3c5b11SNicolas Vasilache     }
3824ead2cf7SAlex Zinenko   });
3834ead2cf7SAlex Zinenko 
3844ead2cf7SAlex Zinenko   rewriter.eraseOp(op);
3854ead2cf7SAlex Zinenko 
3864ead2cf7SAlex Zinenko   return success();
3874ead2cf7SAlex Zinenko }
3884ead2cf7SAlex Zinenko 
389da95a0d8SNicolas Vasilache } // namespace
390da95a0d8SNicolas Vasilache 
3914ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote
3924ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found,
3934ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of
3944ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop.
3954ead2cf7SAlex Zinenko template <typename TransferOpTy>
3964ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) {
3974ead2cf7SAlex Zinenko   // rank of the remote memory access, coalescing behavior occurs on the
3984ead2cf7SAlex Zinenko   // innermost memory dimension.
3994ead2cf7SAlex Zinenko   auto remoteRank = transfer.getMemRefType().getRank();
4004ead2cf7SAlex Zinenko   // Iterate over the results expressions of the permutation map to determine
4014ead2cf7SAlex Zinenko   // the loop order for creating pointwise copies between remote and local
4024ead2cf7SAlex Zinenko   // memories.
4034ead2cf7SAlex Zinenko   int coalescedIdx = -1;
4044ead2cf7SAlex Zinenko   auto exprs = transfer.permutation_map().getResults();
4054ead2cf7SAlex Zinenko   for (auto en : llvm::enumerate(exprs)) {
4064ead2cf7SAlex Zinenko     auto dim = en.value().template dyn_cast<AffineDimExpr>();
4074ead2cf7SAlex Zinenko     if (!dim) {
4084ead2cf7SAlex Zinenko       continue;
4094ead2cf7SAlex Zinenko     }
4104ead2cf7SAlex Zinenko     auto memRefDim = dim.getPosition();
4114ead2cf7SAlex Zinenko     if (memRefDim == remoteRank - 1) {
4124ead2cf7SAlex Zinenko       // memRefDim has coalescing properties, it should be swapped in the last
4134ead2cf7SAlex Zinenko       // position.
4144ead2cf7SAlex Zinenko       assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices");
4154ead2cf7SAlex Zinenko       coalescedIdx = en.index();
4164ead2cf7SAlex Zinenko     }
4174ead2cf7SAlex Zinenko   }
4184ead2cf7SAlex Zinenko   return coalescedIdx;
4194ead2cf7SAlex Zinenko }
4204ead2cf7SAlex Zinenko 
4214ead2cf7SAlex Zinenko /// Emits remote memory accesses that are clipped to the boundaries of the
4224ead2cf7SAlex Zinenko /// MemRef.
4234ead2cf7SAlex Zinenko template <typename TransferOpTy>
4244ead2cf7SAlex Zinenko static SmallVector<Value, 8>
4254ead2cf7SAlex Zinenko clip(TransferOpTy transfer, MemRefBoundsCapture &bounds, ArrayRef<Value> ivs) {
4264ead2cf7SAlex Zinenko   using namespace mlir::edsc;
4274ead2cf7SAlex Zinenko 
4284ead2cf7SAlex Zinenko   Value zero(std_constant_index(0)), one(std_constant_index(1));
4294ead2cf7SAlex Zinenko   SmallVector<Value, 8> memRefAccess(transfer.indices());
4304ead2cf7SAlex Zinenko   SmallVector<Value, 8> clippedScalarAccessExprs(memRefAccess.size());
4314ead2cf7SAlex Zinenko   // Indices accessing to remote memory are clipped and their expressions are
4324ead2cf7SAlex Zinenko   // returned in clippedScalarAccessExprs.
4334ead2cf7SAlex Zinenko   for (unsigned memRefDim = 0; memRefDim < clippedScalarAccessExprs.size();
4344ead2cf7SAlex Zinenko        ++memRefDim) {
4354ead2cf7SAlex Zinenko     // Linear search on a small number of entries.
4364ead2cf7SAlex Zinenko     int loopIndex = -1;
4374ead2cf7SAlex Zinenko     auto exprs = transfer.permutation_map().getResults();
4384ead2cf7SAlex Zinenko     for (auto en : llvm::enumerate(exprs)) {
4394ead2cf7SAlex Zinenko       auto expr = en.value();
4404ead2cf7SAlex Zinenko       auto dim = expr.template dyn_cast<AffineDimExpr>();
4414ead2cf7SAlex Zinenko       // Sanity check.
4424ead2cf7SAlex Zinenko       assert(
4434ead2cf7SAlex Zinenko           (dim || expr.template cast<AffineConstantExpr>().getValue() == 0) &&
4444ead2cf7SAlex Zinenko           "Expected dim or 0 in permutationMap");
4454ead2cf7SAlex Zinenko       if (dim && memRefDim == dim.getPosition()) {
4464ead2cf7SAlex Zinenko         loopIndex = en.index();
4474ead2cf7SAlex Zinenko         break;
4484ead2cf7SAlex Zinenko       }
4494ead2cf7SAlex Zinenko     }
4504ead2cf7SAlex Zinenko 
4514ead2cf7SAlex Zinenko     // We cannot distinguish atm between unrolled dimensions that implement
4524ead2cf7SAlex Zinenko     // the "always full" tile abstraction and need clipping from the other
4534ead2cf7SAlex Zinenko     // ones. So we conservatively clip everything.
4544ead2cf7SAlex Zinenko     using namespace edsc::op;
4554ead2cf7SAlex Zinenko     auto N = bounds.ub(memRefDim);
4564ead2cf7SAlex Zinenko     auto i = memRefAccess[memRefDim];
4574ead2cf7SAlex Zinenko     if (loopIndex < 0) {
4584ead2cf7SAlex Zinenko       auto N_minus_1 = N - one;
45925055a4fSAdam D Straw       auto select_1 = std_select(slt(i, N), i, N_minus_1);
4604ead2cf7SAlex Zinenko       clippedScalarAccessExprs[memRefDim] =
46125055a4fSAdam D Straw           std_select(slt(i, zero), zero, select_1);
4624ead2cf7SAlex Zinenko     } else {
4634ead2cf7SAlex Zinenko       auto ii = ivs[loopIndex];
4644ead2cf7SAlex Zinenko       auto i_plus_ii = i + ii;
4654ead2cf7SAlex Zinenko       auto N_minus_1 = N - one;
46625055a4fSAdam D Straw       auto select_1 = std_select(slt(i_plus_ii, N), i_plus_ii, N_minus_1);
4674ead2cf7SAlex Zinenko       clippedScalarAccessExprs[memRefDim] =
46825055a4fSAdam D Straw           std_select(slt(i_plus_ii, zero), zero, select_1);
4694ead2cf7SAlex Zinenko     }
4704ead2cf7SAlex Zinenko   }
4714ead2cf7SAlex Zinenko 
4724ead2cf7SAlex Zinenko   return clippedScalarAccessExprs;
4734ead2cf7SAlex Zinenko }
4744ead2cf7SAlex Zinenko 
4753393cc4cSNicolas Vasilache namespace mlir {
4763393cc4cSNicolas Vasilache 
4774ead2cf7SAlex Zinenko template <typename TransferOpTy>
4783393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter(
4797c3c5b11SNicolas Vasilache     VectorTransferToSCFOptions options, MLIRContext *context)
4807c3c5b11SNicolas Vasilache     : RewritePattern(TransferOpTy::getOperationName(), 1, context),
4817c3c5b11SNicolas Vasilache       options(options) {}
4824ead2cf7SAlex Zinenko 
4837c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer.
4847c3c5b11SNicolas Vasilache template <typename TransferOpTy>
4853393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType(
4867c3c5b11SNicolas Vasilache     TransferOpTy transfer) const {
4874ead2cf7SAlex Zinenko   auto vectorType = transfer.getVectorType();
4887c3c5b11SNicolas Vasilache   return MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {},
4897c3c5b11SNicolas Vasilache                          0);
4904ead2cf7SAlex Zinenko }
4914ead2cf7SAlex Zinenko 
4924ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of:
4934ead2cf7SAlex Zinenko ///   1. local memory allocation;
4944ead2cf7SAlex Zinenko ///   2. perfect loop nest over:
4954ead2cf7SAlex Zinenko ///      a. scalar load from local buffers (viewed as a scalar memref);
4964ead2cf7SAlex Zinenko ///      a. scalar store to original memref (with clipping).
4974ead2cf7SAlex Zinenko ///   3. vector_load from local buffer (viewed as a memref<1 x vector>);
4984ead2cf7SAlex Zinenko ///   4. local memory deallocation.
4994ead2cf7SAlex Zinenko ///
5004ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no
5014ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
5024ead2cf7SAlex Zinenko /// clipping. This means that a given value in memory can be read multiple
5034ead2cf7SAlex Zinenko /// times and concurrently.
5044ead2cf7SAlex Zinenko ///
5054ead2cf7SAlex Zinenko /// Important notes about clipping and "full-tiles only" abstraction:
5064ead2cf7SAlex Zinenko /// =================================================================
5074ead2cf7SAlex Zinenko /// When using clipping for dealing with boundary conditions, the same edge
5084ead2cf7SAlex Zinenko /// value will appear multiple times (a.k.a edge padding). This is fine if the
5094ead2cf7SAlex Zinenko /// subsequent vector operations are all data-parallel but **is generally
5104ead2cf7SAlex Zinenko /// incorrect** in the presence of reductions or extract operations.
5114ead2cf7SAlex Zinenko ///
5124ead2cf7SAlex Zinenko /// More generally, clipping is a scalar abstraction that is expected to work
5134ead2cf7SAlex Zinenko /// fine as a baseline for CPUs and GPUs but not for vector_load and DMAs.
5144ead2cf7SAlex Zinenko /// To deal with real vector_load and DMAs, a "padded allocation + view"
5154ead2cf7SAlex Zinenko /// abstraction with the ability to read out-of-memref-bounds (but still within
5164ead2cf7SAlex Zinenko /// the allocated region) is necessary.
5174ead2cf7SAlex Zinenko ///
5184ead2cf7SAlex Zinenko /// Whether using scalar loops or vector_load/DMAs to perform the transfer,
5194ead2cf7SAlex Zinenko /// junk values will be materialized in the vectors and generally need to be
5204ead2cf7SAlex Zinenko /// filtered out and replaced by the "neutral element". This neutral element is
5214ead2cf7SAlex Zinenko /// op-dependent so, in the future, we expect to create a vector filter and
5224ead2cf7SAlex Zinenko /// apply it to a splatted constant vector with the proper neutral element at
5234ead2cf7SAlex Zinenko /// each ssa-use. This filtering is not necessary for pure data-parallel
5244ead2cf7SAlex Zinenko /// operations.
5254ead2cf7SAlex Zinenko ///
5264ead2cf7SAlex Zinenko /// In the case of vector_store/DMAs, Read-Modify-Write will be required, which
5274ead2cf7SAlex Zinenko /// also have concurrency implications. Note that by using clipped scalar stores
5284ead2cf7SAlex Zinenko /// in the presence of data-parallel only operations, we generate code that
5294ead2cf7SAlex Zinenko /// writes the same value multiple time on the edge locations.
5304ead2cf7SAlex Zinenko ///
5319db53a18SRiver Riddle /// TODO: implement alternatives to clipping.
5329db53a18SRiver Riddle /// TODO: support non-data-parallel operations.
5334ead2cf7SAlex Zinenko 
5344ead2cf7SAlex Zinenko /// Performs the rewrite.
5354ead2cf7SAlex Zinenko template <>
5363393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite(
5374ead2cf7SAlex Zinenko     Operation *op, PatternRewriter &rewriter) const {
5384ead2cf7SAlex Zinenko   using namespace mlir::edsc::op;
5394ead2cf7SAlex Zinenko 
5404ead2cf7SAlex Zinenko   TransferReadOp transfer = cast<TransferReadOp>(op);
541*ec2f2cecSNicolas Vasilache   if (transfer.permutation_map().isMinorIdentity()) {
5424ead2cf7SAlex Zinenko     // If > 1D, emit a bunch of loops around 1-D vector transfers.
5434ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() > 1)
5447c3c5b11SNicolas Vasilache       return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options)
5457c3c5b11SNicolas Vasilache           .doReplace();
5464ead2cf7SAlex Zinenko     // If 1-D this is now handled by the target-specific lowering.
5474ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() == 1)
5484ead2cf7SAlex Zinenko       return failure();
5494ead2cf7SAlex Zinenko   }
5504ead2cf7SAlex Zinenko 
5514ead2cf7SAlex Zinenko   // Conservative lowering to scalar load / stores.
5524ead2cf7SAlex Zinenko   // 1. Setup all the captures.
5534ead2cf7SAlex Zinenko   ScopedContext scope(rewriter, transfer.getLoc());
5544ead2cf7SAlex Zinenko   StdIndexedValue remote(transfer.memref());
5554ead2cf7SAlex Zinenko   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
5564ead2cf7SAlex Zinenko   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
5574ead2cf7SAlex Zinenko   int coalescedIdx = computeCoalescedIndex(transfer);
5584ead2cf7SAlex Zinenko   // Swap the vectorBoundsCapture which will reorder loop bounds.
5594ead2cf7SAlex Zinenko   if (coalescedIdx >= 0)
5604ead2cf7SAlex Zinenko     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
5614ead2cf7SAlex Zinenko                                    coalescedIdx);
5624ead2cf7SAlex Zinenko 
5634ead2cf7SAlex Zinenko   auto lbs = vectorBoundsCapture.getLbs();
5644ead2cf7SAlex Zinenko   auto ubs = vectorBoundsCapture.getUbs();
5654ead2cf7SAlex Zinenko   SmallVector<Value, 8> steps;
5664ead2cf7SAlex Zinenko   steps.reserve(vectorBoundsCapture.getSteps().size());
5674ead2cf7SAlex Zinenko   for (auto step : vectorBoundsCapture.getSteps())
5684ead2cf7SAlex Zinenko     steps.push_back(std_constant_index(step));
5694ead2cf7SAlex Zinenko 
5704ead2cf7SAlex Zinenko   // 2. Emit alloc-copy-load-dealloc.
5714ead2cf7SAlex Zinenko   Value tmp = std_alloc(tmpMemRefType(transfer));
5724ead2cf7SAlex Zinenko   StdIndexedValue local(tmp);
5734ead2cf7SAlex Zinenko   Value vec = vector_type_cast(tmp);
574d1560f39SAlex Zinenko   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
575d1560f39SAlex Zinenko     auto ivs = llvm::to_vector<8>(loopIvs);
5764ead2cf7SAlex Zinenko     // Swap the ivs which will reorder memory accesses.
5774ead2cf7SAlex Zinenko     if (coalescedIdx >= 0)
5784ead2cf7SAlex Zinenko       std::swap(ivs.back(), ivs[coalescedIdx]);
5794ead2cf7SAlex Zinenko     // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist).
5804ead2cf7SAlex Zinenko     local(ivs) = remote(clip(transfer, memRefBoundsCapture, ivs));
5814ead2cf7SAlex Zinenko   });
5824ead2cf7SAlex Zinenko   Value vectorValue = std_load(vec);
5834ead2cf7SAlex Zinenko   (std_dealloc(tmp)); // vexing parse
5844ead2cf7SAlex Zinenko 
5854ead2cf7SAlex Zinenko   // 3. Propagate.
5864ead2cf7SAlex Zinenko   rewriter.replaceOp(op, vectorValue);
5874ead2cf7SAlex Zinenko   return success();
5884ead2cf7SAlex Zinenko }
5894ead2cf7SAlex Zinenko 
5904ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of:
5914ead2cf7SAlex Zinenko ///   1. local memory allocation;
5924ead2cf7SAlex Zinenko ///   2. vector_store to local buffer (viewed as a memref<1 x vector>);
5934ead2cf7SAlex Zinenko ///   3. perfect loop nest over:
5944ead2cf7SAlex Zinenko ///      a. scalar load from local buffers (viewed as a scalar memref);
5954ead2cf7SAlex Zinenko ///      a. scalar store to original memref (with clipping).
5964ead2cf7SAlex Zinenko ///   4. local memory deallocation.
5974ead2cf7SAlex Zinenko ///
5984ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no
5994ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by
6004ead2cf7SAlex Zinenko /// clipping. This means that a given value in memory can be written to multiple
6014ead2cf7SAlex Zinenko /// times and concurrently.
6024ead2cf7SAlex Zinenko ///
6034ead2cf7SAlex Zinenko /// See `Important notes about clipping and full-tiles only abstraction` in the
6044ead2cf7SAlex Zinenko /// description of `readClipped` above.
6054ead2cf7SAlex Zinenko ///
6069db53a18SRiver Riddle /// TODO: implement alternatives to clipping.
6079db53a18SRiver Riddle /// TODO: support non-data-parallel operations.
6084ead2cf7SAlex Zinenko template <>
6093393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite(
6104ead2cf7SAlex Zinenko     Operation *op, PatternRewriter &rewriter) const {
6114ead2cf7SAlex Zinenko   using namespace edsc::op;
6124ead2cf7SAlex Zinenko 
6134ead2cf7SAlex Zinenko   TransferWriteOp transfer = cast<TransferWriteOp>(op);
614*ec2f2cecSNicolas Vasilache   if (transfer.permutation_map().isMinorIdentity()) {
6154ead2cf7SAlex Zinenko     // If > 1D, emit a bunch of loops around 1-D vector transfers.
6164ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() > 1)
6177c3c5b11SNicolas Vasilache       return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options)
6184ead2cf7SAlex Zinenko           .doReplace();
6194ead2cf7SAlex Zinenko     // If 1-D this is now handled by the target-specific lowering.
6204ead2cf7SAlex Zinenko     if (transfer.getVectorType().getRank() == 1)
6214ead2cf7SAlex Zinenko       return failure();
6224ead2cf7SAlex Zinenko   }
6234ead2cf7SAlex Zinenko 
6244ead2cf7SAlex Zinenko   // 1. Setup all the captures.
6254ead2cf7SAlex Zinenko   ScopedContext scope(rewriter, transfer.getLoc());
6264ead2cf7SAlex Zinenko   StdIndexedValue remote(transfer.memref());
6274ead2cf7SAlex Zinenko   MemRefBoundsCapture memRefBoundsCapture(transfer.memref());
6284ead2cf7SAlex Zinenko   Value vectorValue(transfer.vector());
6294ead2cf7SAlex Zinenko   VectorBoundsCapture vectorBoundsCapture(transfer.vector());
6304ead2cf7SAlex Zinenko   int coalescedIdx = computeCoalescedIndex(transfer);
6314ead2cf7SAlex Zinenko   // Swap the vectorBoundsCapture which will reorder loop bounds.
6324ead2cf7SAlex Zinenko   if (coalescedIdx >= 0)
6334ead2cf7SAlex Zinenko     vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1,
6344ead2cf7SAlex Zinenko                                    coalescedIdx);
6354ead2cf7SAlex Zinenko 
6364ead2cf7SAlex Zinenko   auto lbs = vectorBoundsCapture.getLbs();
6374ead2cf7SAlex Zinenko   auto ubs = vectorBoundsCapture.getUbs();
6384ead2cf7SAlex Zinenko   SmallVector<Value, 8> steps;
6394ead2cf7SAlex Zinenko   steps.reserve(vectorBoundsCapture.getSteps().size());
6404ead2cf7SAlex Zinenko   for (auto step : vectorBoundsCapture.getSteps())
6414ead2cf7SAlex Zinenko     steps.push_back(std_constant_index(step));
6424ead2cf7SAlex Zinenko 
6434ead2cf7SAlex Zinenko   // 2. Emit alloc-store-copy-dealloc.
6444ead2cf7SAlex Zinenko   Value tmp = std_alloc(tmpMemRefType(transfer));
6454ead2cf7SAlex Zinenko   StdIndexedValue local(tmp);
6464ead2cf7SAlex Zinenko   Value vec = vector_type_cast(tmp);
6474ead2cf7SAlex Zinenko   std_store(vectorValue, vec);
648d1560f39SAlex Zinenko   loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) {
649d1560f39SAlex Zinenko     auto ivs = llvm::to_vector<8>(loopIvs);
6504ead2cf7SAlex Zinenko     // Swap the ivs which will reorder memory accesses.
6514ead2cf7SAlex Zinenko     if (coalescedIdx >= 0)
6524ead2cf7SAlex Zinenko       std::swap(ivs.back(), ivs[coalescedIdx]);
6534ead2cf7SAlex Zinenko     // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist).
6544ead2cf7SAlex Zinenko     remote(clip(transfer, memRefBoundsCapture, ivs)) = local(ivs);
6554ead2cf7SAlex Zinenko   });
6564ead2cf7SAlex Zinenko   (std_dealloc(tmp)); // vexing parse...
6574ead2cf7SAlex Zinenko 
6584ead2cf7SAlex Zinenko   rewriter.eraseOp(op);
6594ead2cf7SAlex Zinenko   return success();
6604ead2cf7SAlex Zinenko }
6614ead2cf7SAlex Zinenko 
6623393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns(
6637c3c5b11SNicolas Vasilache     OwningRewritePatternList &patterns, MLIRContext *context,
6647c3c5b11SNicolas Vasilache     const VectorTransferToSCFOptions &options) {
6654ead2cf7SAlex Zinenko   patterns.insert<VectorTransferRewriter<vector::TransferReadOp>,
6667c3c5b11SNicolas Vasilache                   VectorTransferRewriter<vector::TransferWriteOp>>(options,
6677c3c5b11SNicolas Vasilache                                                                    context);
6684ead2cf7SAlex Zinenko }
6693393cc4cSNicolas Vasilache 
6703393cc4cSNicolas Vasilache } // namespace mlir
6713393cc4cSNicolas Vasilache 
6725f9e0466SNicolas Vasilache namespace {
6735f9e0466SNicolas Vasilache 
6745f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass
6755f9e0466SNicolas Vasilache     : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
6765f9e0466SNicolas Vasilache   ConvertVectorToSCFPass() = default;
6775f9e0466SNicolas Vasilache   ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
6785f9e0466SNicolas Vasilache     this->fullUnroll = options.unroll;
6795f9e0466SNicolas Vasilache   }
6805f9e0466SNicolas Vasilache 
6815f9e0466SNicolas Vasilache   void runOnFunction() override {
6825f9e0466SNicolas Vasilache     OwningRewritePatternList patterns;
6835f9e0466SNicolas Vasilache     auto *context = getFunction().getContext();
6845f9e0466SNicolas Vasilache     populateVectorToSCFConversionPatterns(
6855f9e0466SNicolas Vasilache         patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll));
6865f9e0466SNicolas Vasilache     applyPatternsAndFoldGreedily(getFunction(), patterns);
6875f9e0466SNicolas Vasilache   }
6885f9e0466SNicolas Vasilache };
6895f9e0466SNicolas Vasilache 
6905f9e0466SNicolas Vasilache } // namespace
6915f9e0466SNicolas Vasilache 
6925f9e0466SNicolas Vasilache std::unique_ptr<Pass>
6935f9e0466SNicolas Vasilache mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
6945f9e0466SNicolas Vasilache   return std::make_unique<ConvertVectorToSCFPass>(options);
6955f9e0466SNicolas Vasilache }
696