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/Builders.h" 284ead2cf7SAlex Zinenko #include "mlir/IR/Matchers.h" 295f9e0466SNicolas Vasilache #include "mlir/Pass/Pass.h" 30b6eb26fdSRiver Riddle #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 315f9e0466SNicolas Vasilache #include "mlir/Transforms/Passes.h" 324ead2cf7SAlex Zinenko 334ead2cf7SAlex Zinenko using namespace mlir; 344ead2cf7SAlex Zinenko using namespace mlir::edsc; 354ead2cf7SAlex Zinenko using namespace mlir::edsc::intrinsics; 364ead2cf7SAlex Zinenko using vector::TransferReadOp; 374ead2cf7SAlex Zinenko using vector::TransferWriteOp; 384ead2cf7SAlex Zinenko 39af5be38aSNicolas Vasilache // Return a list of Values that correspond to multiple AffineApplyOp, one for 40af5be38aSNicolas Vasilache // each result of `map`. Each `expr` in `map` is canonicalized and folded 41af5be38aSNicolas Vasilache // greedily according to its operands. 42af5be38aSNicolas Vasilache // TODO: factor out in a common location that both linalg and vector can use. 43af5be38aSNicolas Vasilache static SmallVector<Value, 4> 44af5be38aSNicolas Vasilache applyMapToValues(OpBuilder &b, Location loc, AffineMap map, ValueRange values) { 45af5be38aSNicolas Vasilache SmallVector<Value, 4> res; 46af5be38aSNicolas Vasilache res.reserve(map.getNumResults()); 47af5be38aSNicolas Vasilache unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols(); 48af5be38aSNicolas Vasilache // For each `expr` in `map`, applies the `expr` to the values extracted from 49af5be38aSNicolas Vasilache // ranges. If the resulting application can be folded into a Value, the 50af5be38aSNicolas Vasilache // folding occurs eagerly. Otherwise, an affine.apply operation is emitted. 51af5be38aSNicolas Vasilache for (auto expr : map.getResults()) { 52af5be38aSNicolas Vasilache AffineMap map = AffineMap::get(numDims, numSym, expr); 53af5be38aSNicolas Vasilache SmallVector<Value, 4> operands(values.begin(), values.end()); 54af5be38aSNicolas Vasilache fullyComposeAffineMapAndOperands(&map, &operands); 55af5be38aSNicolas Vasilache canonicalizeMapAndOperands(&map, &operands); 56af5be38aSNicolas Vasilache res.push_back(b.createOrFold<AffineApplyOp>(loc, map, operands)); 57af5be38aSNicolas Vasilache } 58af5be38aSNicolas Vasilache return res; 59af5be38aSNicolas Vasilache } 60af5be38aSNicolas Vasilache 61350dadaaSBenjamin Kramer namespace { 624ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector 634ead2cf7SAlex Zinenko /// transfer operations (read and write). 644ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR 654ead2cf7SAlex Zinenko /// manipulation. 664ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as: 674ead2cf7SAlex Zinenko /// 684ead2cf7SAlex Zinenko /// ``` 694ead2cf7SAlex Zinenko /// vector_transfer_read(%m, %offsets, identity_map, %fill) : 704ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 714ead2cf7SAlex Zinenko /// vector<(major_dims) x (minor_dims) x type> 724ead2cf7SAlex Zinenko /// ``` 734ead2cf7SAlex Zinenko /// 744ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or 754ead2cf7SAlex Zinenko /// higher). 764ead2cf7SAlex Zinenko /// 774ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling: 784ead2cf7SAlex Zinenko /// 794ead2cf7SAlex Zinenko /// ``` 804ead2cf7SAlex Zinenko /// %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>> 814ead2cf7SAlex Zinenko /// for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest 824ead2cf7SAlex Zinenko /// if (any_of(%ivs_major + %offsets, <, major_dims)) { 834ead2cf7SAlex Zinenko /// %v = vector_transfer_read( 844ead2cf7SAlex Zinenko /// {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor}, 854ead2cf7SAlex Zinenko /// %ivs_minor): 864ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 874ead2cf7SAlex Zinenko /// vector<(minor_dims) x type>; 884ead2cf7SAlex Zinenko /// store(%v, %tmp); 894ead2cf7SAlex Zinenko /// } else { 904ead2cf7SAlex Zinenko /// %v = splat(vector<(minor_dims) x type>, %fill) 914ead2cf7SAlex Zinenko /// store(%v, %tmp, %ivs_major); 924ead2cf7SAlex Zinenko /// } 934ead2cf7SAlex Zinenko /// } 944ead2cf7SAlex Zinenko /// %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>): 954ead2cf7SAlex Zinenko // vector<(major_dims) x (minor_dims) x type> 964ead2cf7SAlex Zinenko /// ``` 974ead2cf7SAlex Zinenko /// 984ead2cf7SAlex Zinenko template <typename ConcreteOp> 994ead2cf7SAlex Zinenko class NDTransferOpHelper { 1004ead2cf7SAlex Zinenko public: 1017c3c5b11SNicolas Vasilache NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp, 1027c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) 1037c3c5b11SNicolas Vasilache : rewriter(rewriter), options(options), loc(xferOp.getLoc()), 1044ead2cf7SAlex Zinenko scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp), 1054ead2cf7SAlex Zinenko op(xferOp.getOperation()) { 1064ead2cf7SAlex Zinenko vectorType = xferOp.getVectorType(); 1079db53a18SRiver Riddle // TODO: when we go to k > 1-D vectors adapt minorRank. 1084ead2cf7SAlex Zinenko minorRank = 1; 1094ead2cf7SAlex Zinenko majorRank = vectorType.getRank() - minorRank; 11026c8f908SThomas Raoux leadingRank = xferOp.getLeadingShapedRank(); 1114ead2cf7SAlex Zinenko majorVectorType = 1124ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_front(majorRank), 1134ead2cf7SAlex Zinenko vectorType.getElementType()); 1144ead2cf7SAlex Zinenko minorVectorType = 1154ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_back(minorRank), 1164ead2cf7SAlex Zinenko vectorType.getElementType()); 1174ead2cf7SAlex Zinenko /// Memref of minor vector type is used for individual transfers. 118*37eca08eSVladislav Vinogradov memRefMinorVectorType = 119*37eca08eSVladislav Vinogradov MemRefType::get(majorVectorType.getShape(), minorVectorType, {}, 120*37eca08eSVladislav Vinogradov xferOp.getShapedType() 121*37eca08eSVladislav Vinogradov .template cast<MemRefType>() 122*37eca08eSVladislav Vinogradov .getMemorySpaceAsInt()); 1234ead2cf7SAlex Zinenko } 1244ead2cf7SAlex Zinenko 1254ead2cf7SAlex Zinenko LogicalResult doReplace(); 1264ead2cf7SAlex Zinenko 1274ead2cf7SAlex Zinenko private: 1284ead2cf7SAlex Zinenko /// Creates the loop nest on the "major" dimensions and calls the 1294ead2cf7SAlex Zinenko /// `loopBodyBuilder` lambda in the context of the loop nest. 130307dc7b2SBenjamin Kramer void 131307dc7b2SBenjamin Kramer emitLoops(llvm::function_ref<void(ValueRange, ValueRange, ValueRange, 132307dc7b2SBenjamin Kramer ValueRange, const MemRefBoundsCapture &)> 133307dc7b2SBenjamin Kramer loopBodyBuilder); 1344ead2cf7SAlex Zinenko 1354ead2cf7SAlex Zinenko /// Common state to lower vector transfer ops. 1364ead2cf7SAlex Zinenko PatternRewriter &rewriter; 1377c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options; 1384ead2cf7SAlex Zinenko Location loc; 1394ead2cf7SAlex Zinenko std::unique_ptr<ScopedContext> scope; 1404ead2cf7SAlex Zinenko ConcreteOp xferOp; 1414ead2cf7SAlex Zinenko Operation *op; 1424ead2cf7SAlex Zinenko // A vector transfer copies data between: 1434ead2cf7SAlex Zinenko // - memref<(leading_dims) x (major_dims) x (minor_dims) x type> 1444ead2cf7SAlex Zinenko // - vector<(major_dims) x (minor_dims) x type> 1454ead2cf7SAlex Zinenko unsigned minorRank; // for now always 1 1464ead2cf7SAlex Zinenko unsigned majorRank; // vector rank - minorRank 1474ead2cf7SAlex Zinenko unsigned leadingRank; // memref rank - vector rank 1484ead2cf7SAlex Zinenko VectorType vectorType; // vector<(major_dims) x (minor_dims) x type> 1494ead2cf7SAlex Zinenko VectorType majorVectorType; // vector<(major_dims) x type> 1504ead2cf7SAlex Zinenko VectorType minorVectorType; // vector<(minor_dims) x type> 1514ead2cf7SAlex Zinenko MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>> 1524ead2cf7SAlex Zinenko }; 1534ead2cf7SAlex Zinenko 1544ead2cf7SAlex Zinenko template <typename ConcreteOp> 155307dc7b2SBenjamin Kramer void NDTransferOpHelper<ConcreteOp>::emitLoops( 156307dc7b2SBenjamin Kramer llvm::function_ref<void(ValueRange, ValueRange, ValueRange, ValueRange, 157307dc7b2SBenjamin Kramer const MemRefBoundsCapture &)> 158307dc7b2SBenjamin Kramer loopBodyBuilder) { 1594ead2cf7SAlex Zinenko /// Loop nest operates on the major dimensions 16026c8f908SThomas Raoux MemRefBoundsCapture memrefBoundsCapture(xferOp.source()); 1617c3c5b11SNicolas Vasilache 1627c3c5b11SNicolas Vasilache if (options.unroll) { 1637c3c5b11SNicolas Vasilache auto shape = majorVectorType.getShape(); 1647c3c5b11SNicolas Vasilache auto strides = computeStrides(shape); 1657c3c5b11SNicolas Vasilache unsigned numUnrolledInstances = computeMaxLinearIndex(shape); 1667c3c5b11SNicolas Vasilache ValueRange indices(xferOp.indices()); 1677c3c5b11SNicolas Vasilache for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) { 1687c3c5b11SNicolas Vasilache SmallVector<int64_t, 4> offsets = delinearize(strides, idx); 1697c3c5b11SNicolas Vasilache SmallVector<Value, 4> offsetValues = 1707c3c5b11SNicolas Vasilache llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value { 1717c3c5b11SNicolas Vasilache return std_constant_index(off); 1727c3c5b11SNicolas Vasilache })); 1737c3c5b11SNicolas Vasilache loopBodyBuilder(offsetValues, indices.take_front(leadingRank), 1747c3c5b11SNicolas Vasilache indices.drop_front(leadingRank).take_front(majorRank), 1757c3c5b11SNicolas Vasilache indices.take_back(minorRank), memrefBoundsCapture); 1767c3c5b11SNicolas Vasilache } 1777c3c5b11SNicolas Vasilache } else { 1784ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(majorVectorType); 1794ead2cf7SAlex Zinenko auto majorLbs = vectorBoundsCapture.getLbs(); 1804ead2cf7SAlex Zinenko auto majorUbs = vectorBoundsCapture.getUbs(); 1814ead2cf7SAlex Zinenko auto majorSteps = vectorBoundsCapture.getSteps(); 1823f5bd53eSAlex Zinenko affineLoopNestBuilder( 1833f5bd53eSAlex Zinenko majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) { 1844ead2cf7SAlex Zinenko ValueRange indices(xferOp.indices()); 1854ead2cf7SAlex Zinenko loopBodyBuilder(majorIvs, indices.take_front(leadingRank), 1864ead2cf7SAlex Zinenko indices.drop_front(leadingRank).take_front(majorRank), 1874ead2cf7SAlex Zinenko indices.take_back(minorRank), memrefBoundsCapture); 1884ead2cf7SAlex Zinenko }); 1894ead2cf7SAlex Zinenko } 1907c3c5b11SNicolas Vasilache } 1914ead2cf7SAlex Zinenko 192bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) { 193bd87c6bcSNicolas Vasilache if (auto cstOp = v.getDefiningOp<ConstantIndexOp>()) 194bd87c6bcSNicolas Vasilache return cstOp.getValue(); 195bd87c6bcSNicolas Vasilache if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>()) 196bd87c6bcSNicolas Vasilache if (affineApplyOp.getAffineMap().isSingleConstant()) 197bd87c6bcSNicolas Vasilache return affineApplyOp.getAffineMap().getSingleConstantResult(); 198bd87c6bcSNicolas Vasilache return None; 199bd87c6bcSNicolas Vasilache } 200bd87c6bcSNicolas Vasilache 201bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding 202bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go 203bd87c6bcSNicolas Vasilache // away once scf.if folds properly. 204bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) { 205bd87c6bcSNicolas Vasilache using namespace mlir::edsc::op; 206bd87c6bcSNicolas Vasilache auto maybeCstV = extractConstantIndex(v); 207bd87c6bcSNicolas Vasilache auto maybeCstUb = extractConstantIndex(ub); 208bd87c6bcSNicolas Vasilache if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb) 209bd87c6bcSNicolas Vasilache return Value(); 210bd87c6bcSNicolas Vasilache return slt(v, ub); 211bd87c6bcSNicolas Vasilache } 212bd87c6bcSNicolas Vasilache 213239eff50SBenjamin Kramer /// 1. Compute the indexings `majorIvs + majorOffsets` and save them in 214239eff50SBenjamin Kramer /// `majorIvsPlusOffsets`. 215af5be38aSNicolas Vasilache /// 2. Return a value of i1 that determines whether the first 216af5be38aSNicolas Vasilache /// `majorIvs.rank()` 217239eff50SBenjamin Kramer /// dimensions `majorIvs + majorOffsets` are all within `memrefBounds`. 218239eff50SBenjamin Kramer static Value 219239eff50SBenjamin Kramer emitInBoundsCondition(PatternRewriter &rewriter, 220239eff50SBenjamin Kramer VectorTransferOpInterface xferOp, unsigned leadingRank, 2214ead2cf7SAlex Zinenko ValueRange majorIvs, ValueRange majorOffsets, 222307dc7b2SBenjamin Kramer const MemRefBoundsCapture &memrefBounds, 2237c3c5b11SNicolas Vasilache SmallVectorImpl<Value> &majorIvsPlusOffsets) { 2247c3c5b11SNicolas Vasilache Value inBoundsCondition; 2254ead2cf7SAlex Zinenko majorIvsPlusOffsets.reserve(majorIvs.size()); 2261870e787SNicolas Vasilache unsigned idx = 0; 2278dace28fSJakub Lichman SmallVector<Value, 4> bounds = 228af5be38aSNicolas Vasilache applyMapToValues(rewriter, xferOp.getLoc(), xferOp.permutation_map(), 229af5be38aSNicolas Vasilache memrefBounds.getUbs()); 2308dace28fSJakub Lichman for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) { 2314ead2cf7SAlex Zinenko Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it); 2324ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 2334ead2cf7SAlex Zinenko majorIvsPlusOffsets.push_back(iv + off); 2341870e787SNicolas Vasilache if (xferOp.isMaskedDim(leadingRank + idx)) { 235bd87c6bcSNicolas Vasilache Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub); 236bd87c6bcSNicolas Vasilache if (inBoundsCond) 237bd87c6bcSNicolas Vasilache inBoundsCondition = (inBoundsCondition) 238bd87c6bcSNicolas Vasilache ? (inBoundsCondition && inBoundsCond) 239bd87c6bcSNicolas Vasilache : inBoundsCond; 2401870e787SNicolas Vasilache } 2411870e787SNicolas Vasilache ++idx; 2424ead2cf7SAlex Zinenko } 2437c3c5b11SNicolas Vasilache return inBoundsCondition; 2444ead2cf7SAlex Zinenko } 2454ead2cf7SAlex Zinenko 246247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations. 247247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType, 248247e185dSNicolas Vasilache Operation *op) { 249247e185dSNicolas Vasilache auto &b = ScopedContext::getBuilderRef(); 250247e185dSNicolas Vasilache OpBuilder::InsertionGuard guard(b); 251a4b8c2deSJakub Lichman Operation *scope = 252a4b8c2deSJakub Lichman op->getParentWithTrait<OpTrait::AutomaticAllocationScope>(); 253a4b8c2deSJakub Lichman assert(scope && "Expected op to be inside automatic allocation scope"); 254a4b8c2deSJakub Lichman b.setInsertionPointToStart(&scope->getRegion(0).front()); 255a89035d7SAlexander Belyaev Value res = std_alloca(memRefMinorVectorType); 256247e185dSNicolas Vasilache return res; 257247e185dSNicolas Vasilache } 258247e185dSNicolas Vasilache 2594ead2cf7SAlex Zinenko template <> 2604ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() { 2617c3c5b11SNicolas Vasilache Value alloc, result; 2627c3c5b11SNicolas Vasilache if (options.unroll) 2637c3c5b11SNicolas Vasilache result = std_splat(vectorType, xferOp.padding()); 2647c3c5b11SNicolas Vasilache else 265247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 2664ead2cf7SAlex Zinenko 2674ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 2684ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 269307dc7b2SBenjamin Kramer const MemRefBoundsCapture &memrefBounds) { 2707c3c5b11SNicolas Vasilache /// Lambda to load 1-D vector in the current loop ivs + offset context. 2717c3c5b11SNicolas Vasilache auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value { 2724ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 2734ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 2744ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 2754ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 2764ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 27726c8f908SThomas Raoux Value memref = xferOp.source(); 27847cbd9f9SNicolas Vasilache auto map = 27926c8f908SThomas Raoux getTransferMinorIdentityMap(xferOp.getShapedType(), minorVectorType); 2801870e787SNicolas Vasilache ArrayAttr masked; 281cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 2821870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 283cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 2841870e787SNicolas Vasilache } 2857c3c5b11SNicolas Vasilache return vector_transfer_read(minorVectorType, memref, indexing, 2867c3c5b11SNicolas Vasilache AffineMapAttr::get(map), xferOp.padding(), 2877c3c5b11SNicolas Vasilache masked); 2884ead2cf7SAlex Zinenko }; 2897c3c5b11SNicolas Vasilache 2907c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 2917c3c5b11SNicolas Vasilache // context. 2927c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 2937c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 294239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()), 295239eff50SBenjamin Kramer leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 2967c3c5b11SNicolas Vasilache 2977c3c5b11SNicolas Vasilache if (inBoundsCondition) { 2987c3c5b11SNicolas Vasilache // 2. If the condition is not null, we need an IfOp, which may yield 2997c3c5b11SNicolas Vasilache // if `options.unroll` is true. 3007c3c5b11SNicolas Vasilache SmallVector<Type, 1> resultType; 3017c3c5b11SNicolas Vasilache if (options.unroll) 3027c3c5b11SNicolas Vasilache resultType.push_back(vectorType); 3037c3c5b11SNicolas Vasilache 304cadb7ccfSAlex Zinenko // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise 305cadb7ccfSAlex Zinenko // splat a 1-D vector. 306cadb7ccfSAlex Zinenko ValueRange ifResults = conditionBuilder( 307cadb7ccfSAlex Zinenko resultType, inBoundsCondition, 308cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 3097c3c5b11SNicolas Vasilache Value vector = load1DVector(majorIvsPlusOffsets); 310cadb7ccfSAlex Zinenko // 3.a. If `options.unroll` is true, insert the 1-D vector in the 3117c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `else` branch. 3127c3c5b11SNicolas Vasilache if (options.unroll) { 3137c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 314cadb7ccfSAlex Zinenko return {vector}; 3157c3c5b11SNicolas Vasilache } 316cadb7ccfSAlex Zinenko // 3.b. Otherwise, just go through the temporary `alloc`. 317a89035d7SAlexander Belyaev std_store(vector, alloc, majorIvs); 318cadb7ccfSAlex Zinenko return {}; 319cadb7ccfSAlex Zinenko }, 320cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 3217c3c5b11SNicolas Vasilache Value vector = std_splat(minorVectorType, xferOp.padding()); 322cadb7ccfSAlex Zinenko // 3.c. If `options.unroll` is true, insert the 1-D vector in the 3237c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `then` branch. 3247c3c5b11SNicolas Vasilache if (options.unroll) { 3257c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 326cadb7ccfSAlex Zinenko return {vector}; 3277c3c5b11SNicolas Vasilache } 328cadb7ccfSAlex Zinenko // 3.d. Otherwise, just go through the temporary `alloc`. 329a89035d7SAlexander Belyaev std_store(vector, alloc, majorIvs); 330cadb7ccfSAlex Zinenko return {}; 3317c3c5b11SNicolas Vasilache }); 332cadb7ccfSAlex Zinenko 3337c3c5b11SNicolas Vasilache if (!resultType.empty()) 334cadb7ccfSAlex Zinenko result = *ifResults.begin(); 3357c3c5b11SNicolas Vasilache } else { 3367c3c5b11SNicolas Vasilache // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read. 3377c3c5b11SNicolas Vasilache Value loaded1D = load1DVector(majorIvsPlusOffsets); 3387c3c5b11SNicolas Vasilache // 5.a. If `options.unroll` is true, insert the 1-D vector in the 3397c3c5b11SNicolas Vasilache // aggregate. 3407c3c5b11SNicolas Vasilache if (options.unroll) 3417c3c5b11SNicolas Vasilache result = vector_insert(loaded1D, result, majorIvs); 3427c3c5b11SNicolas Vasilache // 5.b. Otherwise, just go through the temporary `alloc`. 3437c3c5b11SNicolas Vasilache else 344a89035d7SAlexander Belyaev std_store(loaded1D, alloc, majorIvs); 3457c3c5b11SNicolas Vasilache } 3467c3c5b11SNicolas Vasilache }); 3477c3c5b11SNicolas Vasilache 348a9b5edc5SBenjamin Kramer assert((!options.unroll ^ (bool)result) && 349a9b5edc5SBenjamin Kramer "Expected resulting Value iff unroll"); 3507c3c5b11SNicolas Vasilache if (!result) 3517c3c5b11SNicolas Vasilache result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3527c3c5b11SNicolas Vasilache rewriter.replaceOp(op, result); 3534ead2cf7SAlex Zinenko 3544ead2cf7SAlex Zinenko return success(); 3554ead2cf7SAlex Zinenko } 3564ead2cf7SAlex Zinenko 3574ead2cf7SAlex Zinenko template <> 3584ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() { 3597c3c5b11SNicolas Vasilache Value alloc; 3607c3c5b11SNicolas Vasilache if (!options.unroll) { 361247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 362a89035d7SAlexander Belyaev std_store(xferOp.vector(), 3634ead2cf7SAlex Zinenko vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3647c3c5b11SNicolas Vasilache } 3654ead2cf7SAlex Zinenko 3664ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 3674ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 368307dc7b2SBenjamin Kramer const MemRefBoundsCapture &memrefBounds) { 3697c3c5b11SNicolas Vasilache // Lower to 1-D vector_transfer_write and let recursion handle it. 3707c3c5b11SNicolas Vasilache auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) { 3714ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 3724ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 3734ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 3744ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 3754ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 3767c3c5b11SNicolas Vasilache Value result; 3777c3c5b11SNicolas Vasilache // If `options.unroll` is true, extract the 1-D vector from the 3787c3c5b11SNicolas Vasilache // aggregate. 3797c3c5b11SNicolas Vasilache if (options.unroll) 3807c3c5b11SNicolas Vasilache result = vector_extract(xferOp.vector(), majorIvs); 3817c3c5b11SNicolas Vasilache else 3827c3c5b11SNicolas Vasilache result = std_load(alloc, majorIvs); 38347cbd9f9SNicolas Vasilache auto map = 38426c8f908SThomas Raoux getTransferMinorIdentityMap(xferOp.getShapedType(), minorVectorType); 3851870e787SNicolas Vasilache ArrayAttr masked; 386cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 3871870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 388cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 3891870e787SNicolas Vasilache } 39026c8f908SThomas Raoux vector_transfer_write(result, xferOp.source(), indexing, 3911870e787SNicolas Vasilache AffineMapAttr::get(map), masked); 3924ead2cf7SAlex Zinenko }; 3937c3c5b11SNicolas Vasilache 3947c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 3957c3c5b11SNicolas Vasilache // context. 3967c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 3977c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 398239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()), 399239eff50SBenjamin Kramer leadingRank, majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 4007c3c5b11SNicolas Vasilache 4017c3c5b11SNicolas Vasilache if (inBoundsCondition) { 4027c3c5b11SNicolas Vasilache // 2.a. If the condition is not null, we need an IfOp, to write 4037c3c5b11SNicolas Vasilache // conditionally. Progressively lower to a 1-D transfer write. 404cadb7ccfSAlex Zinenko conditionBuilder(inBoundsCondition, 405cadb7ccfSAlex Zinenko [&] { emitTransferWrite(majorIvsPlusOffsets); }); 4067c3c5b11SNicolas Vasilache } else { 4077c3c5b11SNicolas Vasilache // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write. 4087c3c5b11SNicolas Vasilache emitTransferWrite(majorIvsPlusOffsets); 4097c3c5b11SNicolas Vasilache } 4104ead2cf7SAlex Zinenko }); 4114ead2cf7SAlex Zinenko 4124ead2cf7SAlex Zinenko rewriter.eraseOp(op); 4134ead2cf7SAlex Zinenko 4144ead2cf7SAlex Zinenko return success(); 4154ead2cf7SAlex Zinenko } 4164ead2cf7SAlex Zinenko 417df63eedeSBenjamin Kramer } // namespace 418df63eedeSBenjamin Kramer 4194ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote 4204ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found, 4214ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of 4224ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop. 4234ead2cf7SAlex Zinenko template <typename TransferOpTy> 4244ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) { 4254ead2cf7SAlex Zinenko // rank of the remote memory access, coalescing behavior occurs on the 4264ead2cf7SAlex Zinenko // innermost memory dimension. 42726c8f908SThomas Raoux auto remoteRank = transfer.getShapedType().getRank(); 4284ead2cf7SAlex Zinenko // Iterate over the results expressions of the permutation map to determine 4294ead2cf7SAlex Zinenko // the loop order for creating pointwise copies between remote and local 4304ead2cf7SAlex Zinenko // memories. 4314ead2cf7SAlex Zinenko int coalescedIdx = -1; 4324ead2cf7SAlex Zinenko auto exprs = transfer.permutation_map().getResults(); 4334ead2cf7SAlex Zinenko for (auto en : llvm::enumerate(exprs)) { 4344ead2cf7SAlex Zinenko auto dim = en.value().template dyn_cast<AffineDimExpr>(); 4354ead2cf7SAlex Zinenko if (!dim) { 4364ead2cf7SAlex Zinenko continue; 4374ead2cf7SAlex Zinenko } 4384ead2cf7SAlex Zinenko auto memRefDim = dim.getPosition(); 4394ead2cf7SAlex Zinenko if (memRefDim == remoteRank - 1) { 4404ead2cf7SAlex Zinenko // memRefDim has coalescing properties, it should be swapped in the last 4414ead2cf7SAlex Zinenko // position. 4424ead2cf7SAlex Zinenko assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices"); 4434ead2cf7SAlex Zinenko coalescedIdx = en.index(); 4444ead2cf7SAlex Zinenko } 4454ead2cf7SAlex Zinenko } 4464ead2cf7SAlex Zinenko return coalescedIdx; 4474ead2cf7SAlex Zinenko } 4484ead2cf7SAlex Zinenko 4494ead2cf7SAlex Zinenko template <typename TransferOpTy> 4503393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter( 4517c3c5b11SNicolas Vasilache VectorTransferToSCFOptions options, MLIRContext *context) 4527c3c5b11SNicolas Vasilache : RewritePattern(TransferOpTy::getOperationName(), 1, context), 4537c3c5b11SNicolas Vasilache options(options) {} 4544ead2cf7SAlex Zinenko 4557c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer. 4567c3c5b11SNicolas Vasilache template <typename TransferOpTy> 4573393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType( 4587c3c5b11SNicolas Vasilache TransferOpTy transfer) const { 4594ead2cf7SAlex Zinenko auto vectorType = transfer.getVectorType(); 4608d64df9fSNicolas Vasilache return MemRefType::get(vectorType.getShape().drop_back(), 4618d64df9fSNicolas Vasilache VectorType::get(vectorType.getShape().take_back(), 4628d64df9fSNicolas Vasilache vectorType.getElementType()), 4638d64df9fSNicolas Vasilache {}, 0); 4644ead2cf7SAlex Zinenko } 4654ead2cf7SAlex Zinenko 466239eff50SBenjamin Kramer static void emitWithBoundsChecks( 467239eff50SBenjamin Kramer PatternRewriter &rewriter, VectorTransferOpInterface transfer, 468307dc7b2SBenjamin Kramer ValueRange ivs, const MemRefBoundsCapture &memRefBoundsCapture, 469239eff50SBenjamin Kramer function_ref<void(ArrayRef<Value>)> inBoundsFun, 470239eff50SBenjamin Kramer function_ref<void(ArrayRef<Value>)> outOfBoundsFun = nullptr) { 471239eff50SBenjamin Kramer // Permute the incoming indices according to the permutation map. 472239eff50SBenjamin Kramer SmallVector<Value, 4> indices = 473af5be38aSNicolas Vasilache applyMapToValues(rewriter, transfer.getLoc(), transfer.permutation_map(), 474af5be38aSNicolas Vasilache transfer.indices()); 475239eff50SBenjamin Kramer 476239eff50SBenjamin Kramer // Generate a bounds check if necessary. 477239eff50SBenjamin Kramer SmallVector<Value, 4> majorIvsPlusOffsets; 478239eff50SBenjamin Kramer Value inBoundsCondition = 479239eff50SBenjamin Kramer emitInBoundsCondition(rewriter, transfer, 0, ivs, indices, 480239eff50SBenjamin Kramer memRefBoundsCapture, majorIvsPlusOffsets); 481239eff50SBenjamin Kramer 482239eff50SBenjamin Kramer // Apply the permutation map to the ivs. The permutation map may not use all 483239eff50SBenjamin Kramer // the inputs. 484239eff50SBenjamin Kramer SmallVector<Value, 4> scalarAccessExprs(transfer.indices().size()); 485239eff50SBenjamin Kramer for (unsigned memRefDim = 0; memRefDim < transfer.indices().size(); 486239eff50SBenjamin Kramer ++memRefDim) { 487239eff50SBenjamin Kramer // Linear search on a small number of entries. 488239eff50SBenjamin Kramer int loopIndex = -1; 489239eff50SBenjamin Kramer auto exprs = transfer.permutation_map().getResults(); 490239eff50SBenjamin Kramer for (auto en : llvm::enumerate(exprs)) { 491239eff50SBenjamin Kramer auto expr = en.value(); 492239eff50SBenjamin Kramer auto dim = expr.dyn_cast<AffineDimExpr>(); 493239eff50SBenjamin Kramer // Sanity check. 494239eff50SBenjamin Kramer assert((dim || expr.cast<AffineConstantExpr>().getValue() == 0) && 495239eff50SBenjamin Kramer "Expected dim or 0 in permutationMap"); 496239eff50SBenjamin Kramer if (dim && memRefDim == dim.getPosition()) { 497239eff50SBenjamin Kramer loopIndex = en.index(); 498239eff50SBenjamin Kramer break; 499239eff50SBenjamin Kramer } 500239eff50SBenjamin Kramer } 501239eff50SBenjamin Kramer 502239eff50SBenjamin Kramer using namespace edsc::op; 503239eff50SBenjamin Kramer auto i = transfer.indices()[memRefDim]; 504239eff50SBenjamin Kramer scalarAccessExprs[memRefDim] = loopIndex < 0 ? i : i + ivs[loopIndex]; 505239eff50SBenjamin Kramer } 506239eff50SBenjamin Kramer 507239eff50SBenjamin Kramer if (inBoundsCondition) 508239eff50SBenjamin Kramer conditionBuilder( 509239eff50SBenjamin Kramer /* scf.if */ inBoundsCondition, // { 510239eff50SBenjamin Kramer [&] { inBoundsFun(scalarAccessExprs); }, 511239eff50SBenjamin Kramer // } else { 512239eff50SBenjamin Kramer outOfBoundsFun ? [&] { outOfBoundsFun(scalarAccessExprs); } 513239eff50SBenjamin Kramer : function_ref<void()>() 514239eff50SBenjamin Kramer // } 515239eff50SBenjamin Kramer ); 516239eff50SBenjamin Kramer else 517239eff50SBenjamin Kramer inBoundsFun(scalarAccessExprs); 518239eff50SBenjamin Kramer } 519239eff50SBenjamin Kramer 52051d30c34SBenjamin Kramer namespace mlir { 52151d30c34SBenjamin Kramer 5224ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of: 5234ead2cf7SAlex Zinenko /// 1. local memory allocation; 5244ead2cf7SAlex Zinenko /// 2. perfect loop nest over: 5254ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 526307dc7b2SBenjamin Kramer /// a. scalar store to original memref (with padding). 5274ead2cf7SAlex Zinenko /// 3. vector_load from local buffer (viewed as a memref<1 x vector>); 5284ead2cf7SAlex Zinenko /// 4. local memory deallocation. 5294ead2cf7SAlex Zinenko /// 5304ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no 5314ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 532307dc7b2SBenjamin Kramer /// padding. 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); 54126c8f908SThomas Raoux auto memRefType = transfer.getShapedType().dyn_cast<MemRefType>(); 54226c8f908SThomas Raoux if (!memRefType) 54326c8f908SThomas Raoux return failure(); 544dfb7b3feSBenjamin Kramer // Fall back to a loop if the fastest varying stride is not 1 or it is 545dfb7b3feSBenjamin Kramer // permuted. 546dfb7b3feSBenjamin Kramer int64_t offset; 547dfb7b3feSBenjamin Kramer SmallVector<int64_t, 4> strides; 54826c8f908SThomas Raoux auto successStrides = getStridesAndOffset(memRefType, strides, offset); 549dfb7b3feSBenjamin Kramer if (succeeded(successStrides) && strides.back() == 1 && 550dfb7b3feSBenjamin Kramer transfer.permutation_map().isMinorIdentity()) { 5514ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 5524ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 5537c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options) 5547c3c5b11SNicolas Vasilache .doReplace(); 5554ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 5564ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 5574ead2cf7SAlex Zinenko return failure(); 5584ead2cf7SAlex Zinenko } 5594ead2cf7SAlex Zinenko 5604ead2cf7SAlex Zinenko // Conservative lowering to scalar load / stores. 5614ead2cf7SAlex Zinenko // 1. Setup all the captures. 5624ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 56326c8f908SThomas Raoux StdIndexedValue remote(transfer.source()); 56426c8f908SThomas Raoux MemRefBoundsCapture memRefBoundsCapture(transfer.source()); 5654ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 5664ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 5674ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 5684ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 5694ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 5704ead2cf7SAlex Zinenko coalescedIdx); 5714ead2cf7SAlex Zinenko 5724ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 5734ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 5744ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 5754ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 5764ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 5774ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 5784ead2cf7SAlex Zinenko 5794ead2cf7SAlex Zinenko // 2. Emit alloc-copy-load-dealloc. 5809be61784SNicolas Vasilache MLIRContext *ctx = op->getContext(); 5818d64df9fSNicolas Vasilache Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer); 5824ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 583d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 584239eff50SBenjamin Kramer auto ivsStorage = llvm::to_vector<8>(loopIvs); 5854ead2cf7SAlex Zinenko // Swap the ivs which will reorder memory accesses. 5864ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 587239eff50SBenjamin Kramer std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]); 588239eff50SBenjamin Kramer 589239eff50SBenjamin Kramer ArrayRef<Value> ivs(ivsStorage); 5901b97cdf8SRiver Riddle Value pos = std_index_cast(IntegerType::get(ctx, 32), ivs.back()); 591239eff50SBenjamin Kramer Value inVector = local(ivs.drop_back()); 592239eff50SBenjamin Kramer auto loadValue = [&](ArrayRef<Value> indices) { 593239eff50SBenjamin Kramer Value vector = vector_insert_element(remote(indices), inVector, pos); 594239eff50SBenjamin Kramer local(ivs.drop_back()) = vector; 595239eff50SBenjamin Kramer }; 596239eff50SBenjamin Kramer auto loadPadding = [&](ArrayRef<Value>) { 597239eff50SBenjamin Kramer Value vector = vector_insert_element(transfer.padding(), inVector, pos); 598239eff50SBenjamin Kramer local(ivs.drop_back()) = vector; 599239eff50SBenjamin Kramer }; 600239eff50SBenjamin Kramer emitWithBoundsChecks( 601239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs, 602239eff50SBenjamin Kramer memRefBoundsCapture, loadValue, loadPadding); 6034ead2cf7SAlex Zinenko }); 6049be61784SNicolas Vasilache Value vectorValue = std_load(vector_type_cast(tmp)); 6054ead2cf7SAlex Zinenko 6064ead2cf7SAlex Zinenko // 3. Propagate. 6074ead2cf7SAlex Zinenko rewriter.replaceOp(op, vectorValue); 6084ead2cf7SAlex Zinenko return success(); 6094ead2cf7SAlex Zinenko } 6104ead2cf7SAlex Zinenko 6114ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of: 6124ead2cf7SAlex Zinenko /// 1. local memory allocation; 6134ead2cf7SAlex Zinenko /// 2. vector_store to local buffer (viewed as a memref<1 x vector>); 6144ead2cf7SAlex Zinenko /// 3. perfect loop nest over: 6154ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 616307dc7b2SBenjamin Kramer /// a. scalar store to original memref (if in bounds). 6174ead2cf7SAlex Zinenko /// 4. local memory deallocation. 6184ead2cf7SAlex Zinenko /// 6194ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no 620307dc7b2SBenjamin Kramer /// out-of-bounds accesses are possible. 6214ead2cf7SAlex Zinenko template <> 6223393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite( 6234ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 6244ead2cf7SAlex Zinenko using namespace edsc::op; 6254ead2cf7SAlex Zinenko 6264ead2cf7SAlex Zinenko TransferWriteOp transfer = cast<TransferWriteOp>(op); 62726c8f908SThomas Raoux auto memRefType = transfer.getShapedType().template dyn_cast<MemRefType>(); 62826c8f908SThomas Raoux if (!memRefType) 62926c8f908SThomas Raoux return failure(); 630dfb7b3feSBenjamin Kramer 631dfb7b3feSBenjamin Kramer // Fall back to a loop if the fastest varying stride is not 1 or it is 632dfb7b3feSBenjamin Kramer // permuted. 633dfb7b3feSBenjamin Kramer int64_t offset; 634dfb7b3feSBenjamin Kramer SmallVector<int64_t, 4> strides; 63526c8f908SThomas Raoux auto successStrides = getStridesAndOffset(memRefType, strides, offset); 636dfb7b3feSBenjamin Kramer if (succeeded(successStrides) && strides.back() == 1 && 637dfb7b3feSBenjamin Kramer transfer.permutation_map().isMinorIdentity()) { 6384ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 6394ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 6407c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options) 6414ead2cf7SAlex Zinenko .doReplace(); 6424ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 6434ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 6444ead2cf7SAlex Zinenko return failure(); 6454ead2cf7SAlex Zinenko } 6464ead2cf7SAlex Zinenko 6474ead2cf7SAlex Zinenko // 1. Setup all the captures. 6484ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 64926c8f908SThomas Raoux StdIndexedValue remote(transfer.source()); 65026c8f908SThomas Raoux MemRefBoundsCapture memRefBoundsCapture(transfer.source()); 6514ead2cf7SAlex Zinenko Value vectorValue(transfer.vector()); 6524ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 6534ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 6544ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 6554ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 6564ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 6574ead2cf7SAlex Zinenko coalescedIdx); 6584ead2cf7SAlex Zinenko 6594ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 6604ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 6614ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 6624ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 6634ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 6644ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 6654ead2cf7SAlex Zinenko 6664ead2cf7SAlex Zinenko // 2. Emit alloc-store-copy-dealloc. 6678d64df9fSNicolas Vasilache Value tmp = setAllocAtFunctionEntry(tmpMemRefType(transfer), transfer); 6684ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 6694ead2cf7SAlex Zinenko Value vec = vector_type_cast(tmp); 670a89035d7SAlexander Belyaev std_store(vectorValue, vec); 671d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 672239eff50SBenjamin Kramer auto ivsStorage = llvm::to_vector<8>(loopIvs); 673239eff50SBenjamin Kramer // Swap the ivsStorage which will reorder memory accesses. 6744ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 675239eff50SBenjamin Kramer std::swap(ivsStorage.back(), ivsStorage[coalescedIdx]); 676239eff50SBenjamin Kramer 677239eff50SBenjamin Kramer ArrayRef<Value> ivs(ivsStorage); 6788d64df9fSNicolas Vasilache Value pos = 6791b97cdf8SRiver Riddle std_index_cast(IntegerType::get(op->getContext(), 32), ivs.back()); 680239eff50SBenjamin Kramer auto storeValue = [&](ArrayRef<Value> indices) { 681239eff50SBenjamin Kramer Value scalar = vector_extract_element(local(ivs.drop_back()), pos); 6828d64df9fSNicolas Vasilache remote(indices) = scalar; 683239eff50SBenjamin Kramer }; 684239eff50SBenjamin Kramer emitWithBoundsChecks( 685239eff50SBenjamin Kramer rewriter, cast<VectorTransferOpInterface>(transfer.getOperation()), ivs, 686239eff50SBenjamin Kramer memRefBoundsCapture, storeValue); 6874ead2cf7SAlex Zinenko }); 6884ead2cf7SAlex Zinenko 6898d64df9fSNicolas Vasilache // 3. Erase. 6904ead2cf7SAlex Zinenko rewriter.eraseOp(op); 6914ead2cf7SAlex Zinenko return success(); 6924ead2cf7SAlex Zinenko } 6934ead2cf7SAlex Zinenko 6943393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns( 6957c3c5b11SNicolas Vasilache OwningRewritePatternList &patterns, MLIRContext *context, 6967c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) { 6974ead2cf7SAlex Zinenko patterns.insert<VectorTransferRewriter<vector::TransferReadOp>, 6987c3c5b11SNicolas Vasilache VectorTransferRewriter<vector::TransferWriteOp>>(options, 6997c3c5b11SNicolas Vasilache context); 7004ead2cf7SAlex Zinenko } 7013393cc4cSNicolas Vasilache 7023393cc4cSNicolas Vasilache } // namespace mlir 7033393cc4cSNicolas Vasilache 7045f9e0466SNicolas Vasilache namespace { 7055f9e0466SNicolas Vasilache 7065f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass 7075f9e0466SNicolas Vasilache : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> { 7085f9e0466SNicolas Vasilache ConvertVectorToSCFPass() = default; 7095f9e0466SNicolas Vasilache ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 7105f9e0466SNicolas Vasilache this->fullUnroll = options.unroll; 7115f9e0466SNicolas Vasilache } 7125f9e0466SNicolas Vasilache 7135f9e0466SNicolas Vasilache void runOnFunction() override { 7145f9e0466SNicolas Vasilache OwningRewritePatternList patterns; 7155f9e0466SNicolas Vasilache auto *context = getFunction().getContext(); 7165f9e0466SNicolas Vasilache populateVectorToSCFConversionPatterns( 7175f9e0466SNicolas Vasilache patterns, context, 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