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" 198dace28fSJakub Lichman #include "mlir/Dialect/Linalg/Utils/Utils.h" 204ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Builders.h" 214ead2cf7SAlex Zinenko #include "mlir/Dialect/SCF/EDSC/Intrinsics.h" 224ead2cf7SAlex Zinenko #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 234ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 244ead2cf7SAlex Zinenko #include "mlir/Dialect/Vector/VectorOps.h" 257c3c5b11SNicolas Vasilache #include "mlir/Dialect/Vector/VectorUtils.h" 264ead2cf7SAlex Zinenko #include "mlir/IR/AffineExpr.h" 274ead2cf7SAlex Zinenko #include "mlir/IR/AffineMap.h" 284ead2cf7SAlex Zinenko #include "mlir/IR/Attributes.h" 294ead2cf7SAlex Zinenko #include "mlir/IR/Builders.h" 304ead2cf7SAlex Zinenko #include "mlir/IR/Location.h" 314ead2cf7SAlex Zinenko #include "mlir/IR/Matchers.h" 324ead2cf7SAlex Zinenko #include "mlir/IR/OperationSupport.h" 334ead2cf7SAlex Zinenko #include "mlir/IR/PatternMatch.h" 344ead2cf7SAlex Zinenko #include "mlir/IR/Types.h" 355f9e0466SNicolas Vasilache #include "mlir/Pass/Pass.h" 365f9e0466SNicolas Vasilache #include "mlir/Transforms/Passes.h" 374ead2cf7SAlex Zinenko 38f5ed22f0SJakub Lichman #define ALIGNMENT_SIZE 128 39f5ed22f0SJakub Lichman 404ead2cf7SAlex Zinenko using namespace mlir; 414ead2cf7SAlex Zinenko using namespace mlir::edsc; 424ead2cf7SAlex Zinenko using namespace mlir::edsc::intrinsics; 434ead2cf7SAlex Zinenko using vector::TransferReadOp; 444ead2cf7SAlex Zinenko using vector::TransferWriteOp; 454ead2cf7SAlex Zinenko 46350dadaaSBenjamin Kramer namespace { 474ead2cf7SAlex Zinenko /// Helper class captures the common information needed to lower N>1-D vector 484ead2cf7SAlex Zinenko /// transfer operations (read and write). 494ead2cf7SAlex Zinenko /// On construction, this class opens an edsc::ScopedContext for simpler IR 504ead2cf7SAlex Zinenko /// manipulation. 514ead2cf7SAlex Zinenko /// In pseudo-IR, for an n-D vector_transfer_read such as: 524ead2cf7SAlex Zinenko /// 534ead2cf7SAlex Zinenko /// ``` 544ead2cf7SAlex Zinenko /// vector_transfer_read(%m, %offsets, identity_map, %fill) : 554ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 564ead2cf7SAlex Zinenko /// vector<(major_dims) x (minor_dims) x type> 574ead2cf7SAlex Zinenko /// ``` 584ead2cf7SAlex Zinenko /// 594ead2cf7SAlex Zinenko /// where rank(minor_dims) is the lower-level vector rank (e.g. 1 for LLVM or 604ead2cf7SAlex Zinenko /// higher). 614ead2cf7SAlex Zinenko /// 624ead2cf7SAlex Zinenko /// This is the entry point to emitting pseudo-IR resembling: 634ead2cf7SAlex Zinenko /// 644ead2cf7SAlex Zinenko /// ``` 654ead2cf7SAlex Zinenko /// %tmp = alloc(): memref<(major_dims) x vector<minor_dim x type>> 664ead2cf7SAlex Zinenko /// for (%ivs_major, {0}, {vector_shape}, {1}) { // (N-1)-D loop nest 674ead2cf7SAlex Zinenko /// if (any_of(%ivs_major + %offsets, <, major_dims)) { 684ead2cf7SAlex Zinenko /// %v = vector_transfer_read( 694ead2cf7SAlex Zinenko /// {%offsets_leading, %ivs_major + %offsets_major, %offsets_minor}, 704ead2cf7SAlex Zinenko /// %ivs_minor): 714ead2cf7SAlex Zinenko /// memref<(leading_dims) x (major_dims) x (minor_dims) x type>, 724ead2cf7SAlex Zinenko /// vector<(minor_dims) x type>; 734ead2cf7SAlex Zinenko /// store(%v, %tmp); 744ead2cf7SAlex Zinenko /// } else { 754ead2cf7SAlex Zinenko /// %v = splat(vector<(minor_dims) x type>, %fill) 764ead2cf7SAlex Zinenko /// store(%v, %tmp, %ivs_major); 774ead2cf7SAlex Zinenko /// } 784ead2cf7SAlex Zinenko /// } 794ead2cf7SAlex Zinenko /// %res = load(%tmp, %0): memref<(major_dims) x vector<minor_dim x type>>): 804ead2cf7SAlex Zinenko // vector<(major_dims) x (minor_dims) x type> 814ead2cf7SAlex Zinenko /// ``` 824ead2cf7SAlex Zinenko /// 834ead2cf7SAlex Zinenko template <typename ConcreteOp> 844ead2cf7SAlex Zinenko class NDTransferOpHelper { 854ead2cf7SAlex Zinenko public: 867c3c5b11SNicolas Vasilache NDTransferOpHelper(PatternRewriter &rewriter, ConcreteOp xferOp, 877c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) 887c3c5b11SNicolas Vasilache : rewriter(rewriter), options(options), loc(xferOp.getLoc()), 894ead2cf7SAlex Zinenko scope(std::make_unique<ScopedContext>(rewriter, loc)), xferOp(xferOp), 904ead2cf7SAlex Zinenko op(xferOp.getOperation()) { 914ead2cf7SAlex Zinenko vectorType = xferOp.getVectorType(); 929db53a18SRiver Riddle // TODO: when we go to k > 1-D vectors adapt minorRank. 934ead2cf7SAlex Zinenko minorRank = 1; 944ead2cf7SAlex Zinenko majorRank = vectorType.getRank() - minorRank; 95ec2f2cecSNicolas Vasilache leadingRank = xferOp.getLeadingMemRefRank(); 964ead2cf7SAlex Zinenko majorVectorType = 974ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_front(majorRank), 984ead2cf7SAlex Zinenko vectorType.getElementType()); 994ead2cf7SAlex Zinenko minorVectorType = 1004ead2cf7SAlex Zinenko VectorType::get(vectorType.getShape().take_back(minorRank), 1014ead2cf7SAlex Zinenko vectorType.getElementType()); 1024ead2cf7SAlex Zinenko /// Memref of minor vector type is used for individual transfers. 1034ead2cf7SAlex Zinenko memRefMinorVectorType = 1044ead2cf7SAlex Zinenko MemRefType::get(majorVectorType.getShape(), minorVectorType, {}, 1054ead2cf7SAlex Zinenko xferOp.getMemRefType().getMemorySpace()); 1064ead2cf7SAlex Zinenko } 1074ead2cf7SAlex Zinenko 1084ead2cf7SAlex Zinenko LogicalResult doReplace(); 1094ead2cf7SAlex Zinenko 1104ead2cf7SAlex Zinenko private: 1114ead2cf7SAlex Zinenko /// Creates the loop nest on the "major" dimensions and calls the 1124ead2cf7SAlex Zinenko /// `loopBodyBuilder` lambda in the context of the loop nest. 1134ead2cf7SAlex Zinenko template <typename Lambda> 1144ead2cf7SAlex Zinenko void emitLoops(Lambda loopBodyBuilder); 1154ead2cf7SAlex Zinenko 1164ead2cf7SAlex Zinenko /// Operate within the body of `emitLoops` to: 1177c3c5b11SNicolas Vasilache /// 1. Compute the indexings `majorIvs + majorOffsets` and save them in 1187c3c5b11SNicolas Vasilache /// `majorIvsPlusOffsets`. 1197c3c5b11SNicolas Vasilache /// 2. Return a boolean that determines whether the first `majorIvs.rank()` 1204ead2cf7SAlex Zinenko /// dimensions `majorIvs + majorOffsets` are all within `memrefBounds`. 1217c3c5b11SNicolas Vasilache Value emitInBoundsCondition(ValueRange majorIvs, ValueRange majorOffsets, 1224ead2cf7SAlex Zinenko MemRefBoundsCapture &memrefBounds, 1237c3c5b11SNicolas Vasilache SmallVectorImpl<Value> &majorIvsPlusOffsets); 1244ead2cf7SAlex Zinenko 1254ead2cf7SAlex Zinenko /// Common state to lower vector transfer ops. 1264ead2cf7SAlex Zinenko PatternRewriter &rewriter; 1277c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options; 1284ead2cf7SAlex Zinenko Location loc; 1294ead2cf7SAlex Zinenko std::unique_ptr<ScopedContext> scope; 1304ead2cf7SAlex Zinenko ConcreteOp xferOp; 1314ead2cf7SAlex Zinenko Operation *op; 1324ead2cf7SAlex Zinenko // A vector transfer copies data between: 1334ead2cf7SAlex Zinenko // - memref<(leading_dims) x (major_dims) x (minor_dims) x type> 1344ead2cf7SAlex Zinenko // - vector<(major_dims) x (minor_dims) x type> 1354ead2cf7SAlex Zinenko unsigned minorRank; // for now always 1 1364ead2cf7SAlex Zinenko unsigned majorRank; // vector rank - minorRank 1374ead2cf7SAlex Zinenko unsigned leadingRank; // memref rank - vector rank 1384ead2cf7SAlex Zinenko VectorType vectorType; // vector<(major_dims) x (minor_dims) x type> 1394ead2cf7SAlex Zinenko VectorType majorVectorType; // vector<(major_dims) x type> 1404ead2cf7SAlex Zinenko VectorType minorVectorType; // vector<(minor_dims) x type> 1414ead2cf7SAlex Zinenko MemRefType memRefMinorVectorType; // memref<vector<(minor_dims) x type>> 1424ead2cf7SAlex Zinenko }; 1434ead2cf7SAlex Zinenko 1444ead2cf7SAlex Zinenko template <typename ConcreteOp> 1454ead2cf7SAlex Zinenko template <typename Lambda> 1464ead2cf7SAlex Zinenko void NDTransferOpHelper<ConcreteOp>::emitLoops(Lambda loopBodyBuilder) { 1474ead2cf7SAlex Zinenko /// Loop nest operates on the major dimensions 1484ead2cf7SAlex Zinenko MemRefBoundsCapture memrefBoundsCapture(xferOp.memref()); 1497c3c5b11SNicolas Vasilache 1507c3c5b11SNicolas Vasilache if (options.unroll) { 1517c3c5b11SNicolas Vasilache auto shape = majorVectorType.getShape(); 1527c3c5b11SNicolas Vasilache auto strides = computeStrides(shape); 1537c3c5b11SNicolas Vasilache unsigned numUnrolledInstances = computeMaxLinearIndex(shape); 1547c3c5b11SNicolas Vasilache ValueRange indices(xferOp.indices()); 1557c3c5b11SNicolas Vasilache for (unsigned idx = 0; idx < numUnrolledInstances; ++idx) { 1567c3c5b11SNicolas Vasilache SmallVector<int64_t, 4> offsets = delinearize(strides, idx); 1577c3c5b11SNicolas Vasilache SmallVector<Value, 4> offsetValues = 1587c3c5b11SNicolas Vasilache llvm::to_vector<4>(llvm::map_range(offsets, [](int64_t off) -> Value { 1597c3c5b11SNicolas Vasilache return std_constant_index(off); 1607c3c5b11SNicolas Vasilache })); 1617c3c5b11SNicolas Vasilache loopBodyBuilder(offsetValues, indices.take_front(leadingRank), 1627c3c5b11SNicolas Vasilache indices.drop_front(leadingRank).take_front(majorRank), 1637c3c5b11SNicolas Vasilache indices.take_back(minorRank), memrefBoundsCapture); 1647c3c5b11SNicolas Vasilache } 1657c3c5b11SNicolas Vasilache } else { 1664ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(majorVectorType); 1674ead2cf7SAlex Zinenko auto majorLbs = vectorBoundsCapture.getLbs(); 1684ead2cf7SAlex Zinenko auto majorUbs = vectorBoundsCapture.getUbs(); 1694ead2cf7SAlex Zinenko auto majorSteps = vectorBoundsCapture.getSteps(); 1703f5bd53eSAlex Zinenko affineLoopNestBuilder( 1713f5bd53eSAlex Zinenko majorLbs, majorUbs, majorSteps, [&](ValueRange majorIvs) { 1724ead2cf7SAlex Zinenko ValueRange indices(xferOp.indices()); 1734ead2cf7SAlex Zinenko loopBodyBuilder(majorIvs, indices.take_front(leadingRank), 1744ead2cf7SAlex Zinenko indices.drop_front(leadingRank).take_front(majorRank), 1754ead2cf7SAlex Zinenko indices.take_back(minorRank), memrefBoundsCapture); 1764ead2cf7SAlex Zinenko }); 1774ead2cf7SAlex Zinenko } 1787c3c5b11SNicolas Vasilache } 1794ead2cf7SAlex Zinenko 180bd87c6bcSNicolas Vasilache static Optional<int64_t> extractConstantIndex(Value v) { 181bd87c6bcSNicolas Vasilache if (auto cstOp = v.getDefiningOp<ConstantIndexOp>()) 182bd87c6bcSNicolas Vasilache return cstOp.getValue(); 183bd87c6bcSNicolas Vasilache if (auto affineApplyOp = v.getDefiningOp<AffineApplyOp>()) 184bd87c6bcSNicolas Vasilache if (affineApplyOp.getAffineMap().isSingleConstant()) 185bd87c6bcSNicolas Vasilache return affineApplyOp.getAffineMap().getSingleConstantResult(); 186bd87c6bcSNicolas Vasilache return None; 187bd87c6bcSNicolas Vasilache } 188bd87c6bcSNicolas Vasilache 189bd87c6bcSNicolas Vasilache // Missing foldings of scf.if make it necessary to perform poor man's folding 190bd87c6bcSNicolas Vasilache // eagerly, especially in the case of unrolling. In the future, this should go 191bd87c6bcSNicolas Vasilache // away once scf.if folds properly. 192bd87c6bcSNicolas Vasilache static Value onTheFlyFoldSLT(Value v, Value ub) { 193bd87c6bcSNicolas Vasilache using namespace mlir::edsc::op; 194bd87c6bcSNicolas Vasilache auto maybeCstV = extractConstantIndex(v); 195bd87c6bcSNicolas Vasilache auto maybeCstUb = extractConstantIndex(ub); 196bd87c6bcSNicolas Vasilache if (maybeCstV && maybeCstUb && *maybeCstV < *maybeCstUb) 197bd87c6bcSNicolas Vasilache return Value(); 198bd87c6bcSNicolas Vasilache return slt(v, ub); 199bd87c6bcSNicolas Vasilache } 200bd87c6bcSNicolas Vasilache 2014ead2cf7SAlex Zinenko template <typename ConcreteOp> 2027c3c5b11SNicolas Vasilache Value NDTransferOpHelper<ConcreteOp>::emitInBoundsCondition( 2034ead2cf7SAlex Zinenko ValueRange majorIvs, ValueRange majorOffsets, 2047c3c5b11SNicolas Vasilache MemRefBoundsCapture &memrefBounds, 2057c3c5b11SNicolas Vasilache SmallVectorImpl<Value> &majorIvsPlusOffsets) { 2067c3c5b11SNicolas Vasilache Value inBoundsCondition; 2074ead2cf7SAlex Zinenko majorIvsPlusOffsets.reserve(majorIvs.size()); 2081870e787SNicolas Vasilache unsigned idx = 0; 2098dace28fSJakub Lichman SmallVector<Value, 4> bounds = 2108dace28fSJakub Lichman linalg::applyMapToValues(rewriter, xferOp.getLoc(), 2118dace28fSJakub Lichman xferOp.permutation_map(), memrefBounds.getUbs()); 2128dace28fSJakub Lichman for (auto it : llvm::zip(majorIvs, majorOffsets, bounds)) { 2134ead2cf7SAlex Zinenko Value iv = std::get<0>(it), off = std::get<1>(it), ub = std::get<2>(it); 2144ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 2154ead2cf7SAlex Zinenko majorIvsPlusOffsets.push_back(iv + off); 2161870e787SNicolas Vasilache if (xferOp.isMaskedDim(leadingRank + idx)) { 217bd87c6bcSNicolas Vasilache Value inBoundsCond = onTheFlyFoldSLT(majorIvsPlusOffsets.back(), ub); 218bd87c6bcSNicolas Vasilache if (inBoundsCond) 219bd87c6bcSNicolas Vasilache inBoundsCondition = (inBoundsCondition) 220bd87c6bcSNicolas Vasilache ? (inBoundsCondition && inBoundsCond) 221bd87c6bcSNicolas Vasilache : inBoundsCond; 2221870e787SNicolas Vasilache } 2231870e787SNicolas Vasilache ++idx; 2244ead2cf7SAlex Zinenko } 2257c3c5b11SNicolas Vasilache return inBoundsCondition; 2264ead2cf7SAlex Zinenko } 2274ead2cf7SAlex Zinenko 228247e185dSNicolas Vasilache // TODO: Parallelism and threadlocal considerations. 229247e185dSNicolas Vasilache static Value setAllocAtFunctionEntry(MemRefType memRefMinorVectorType, 230247e185dSNicolas Vasilache Operation *op) { 231247e185dSNicolas Vasilache auto &b = ScopedContext::getBuilderRef(); 232247e185dSNicolas Vasilache OpBuilder::InsertionGuard guard(b); 233a4b8c2deSJakub Lichman Operation *scope = 234a4b8c2deSJakub Lichman op->getParentWithTrait<OpTrait::AutomaticAllocationScope>(); 235a4b8c2deSJakub Lichman assert(scope && "Expected op to be inside automatic allocation scope"); 236a4b8c2deSJakub Lichman b.setInsertionPointToStart(&scope->getRegion(0).front()); 237f5ed22f0SJakub Lichman Value res = std_alloca(memRefMinorVectorType, ValueRange{}, 238f5ed22f0SJakub Lichman b.getI64IntegerAttr(ALIGNMENT_SIZE)); 239247e185dSNicolas Vasilache return res; 240247e185dSNicolas Vasilache } 241247e185dSNicolas Vasilache 2424ead2cf7SAlex Zinenko template <> 2434ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferReadOp>::doReplace() { 2447c3c5b11SNicolas Vasilache Value alloc, result; 2457c3c5b11SNicolas Vasilache if (options.unroll) 2467c3c5b11SNicolas Vasilache result = std_splat(vectorType, xferOp.padding()); 2477c3c5b11SNicolas Vasilache else 248247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 2494ead2cf7SAlex Zinenko 2504ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 2514ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 2524ead2cf7SAlex Zinenko MemRefBoundsCapture &memrefBounds) { 2537c3c5b11SNicolas Vasilache /// Lambda to load 1-D vector in the current loop ivs + offset context. 2547c3c5b11SNicolas Vasilache auto load1DVector = [&](ValueRange majorIvsPlusOffsets) -> Value { 2554ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 2564ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 2574ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 2584ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 2594ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 26036cdc17fSNicolas Vasilache Value memref = xferOp.memref(); 26147cbd9f9SNicolas Vasilache auto map = 26247cbd9f9SNicolas Vasilache getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType); 2631870e787SNicolas Vasilache ArrayAttr masked; 264cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 2651870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 266cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 2671870e787SNicolas Vasilache } 2687c3c5b11SNicolas Vasilache return vector_transfer_read(minorVectorType, memref, indexing, 2697c3c5b11SNicolas Vasilache AffineMapAttr::get(map), xferOp.padding(), 2707c3c5b11SNicolas Vasilache masked); 2714ead2cf7SAlex Zinenko }; 2727c3c5b11SNicolas Vasilache 2737c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 2747c3c5b11SNicolas Vasilache // context. 2757c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 2767c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 2777c3c5b11SNicolas Vasilache majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 2787c3c5b11SNicolas Vasilache 2797c3c5b11SNicolas Vasilache if (inBoundsCondition) { 2807c3c5b11SNicolas Vasilache // 2. If the condition is not null, we need an IfOp, which may yield 2817c3c5b11SNicolas Vasilache // if `options.unroll` is true. 2827c3c5b11SNicolas Vasilache SmallVector<Type, 1> resultType; 2837c3c5b11SNicolas Vasilache if (options.unroll) 2847c3c5b11SNicolas Vasilache resultType.push_back(vectorType); 2857c3c5b11SNicolas Vasilache 286cadb7ccfSAlex Zinenko // 3. If in-bounds, progressively lower to a 1-D transfer read, otherwise 287cadb7ccfSAlex Zinenko // splat a 1-D vector. 288cadb7ccfSAlex Zinenko ValueRange ifResults = conditionBuilder( 289cadb7ccfSAlex Zinenko resultType, inBoundsCondition, 290cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 2917c3c5b11SNicolas Vasilache Value vector = load1DVector(majorIvsPlusOffsets); 292cadb7ccfSAlex Zinenko // 3.a. If `options.unroll` is true, insert the 1-D vector in the 2937c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `else` branch. 2947c3c5b11SNicolas Vasilache if (options.unroll) { 2957c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 296cadb7ccfSAlex Zinenko return {vector}; 2977c3c5b11SNicolas Vasilache } 298cadb7ccfSAlex Zinenko // 3.b. Otherwise, just go through the temporary `alloc`. 2994ead2cf7SAlex Zinenko std_store(vector, alloc, majorIvs); 300cadb7ccfSAlex Zinenko return {}; 301cadb7ccfSAlex Zinenko }, 302cadb7ccfSAlex Zinenko [&]() -> scf::ValueVector { 3037c3c5b11SNicolas Vasilache Value vector = std_splat(minorVectorType, xferOp.padding()); 304cadb7ccfSAlex Zinenko // 3.c. If `options.unroll` is true, insert the 1-D vector in the 3057c3c5b11SNicolas Vasilache // aggregate. We must yield and merge with the `then` branch. 3067c3c5b11SNicolas Vasilache if (options.unroll) { 3077c3c5b11SNicolas Vasilache vector = vector_insert(vector, result, majorIvs); 308cadb7ccfSAlex Zinenko return {vector}; 3097c3c5b11SNicolas Vasilache } 310cadb7ccfSAlex Zinenko // 3.d. Otherwise, just go through the temporary `alloc`. 3117c3c5b11SNicolas Vasilache std_store(vector, alloc, majorIvs); 312cadb7ccfSAlex Zinenko return {}; 3137c3c5b11SNicolas Vasilache }); 314cadb7ccfSAlex Zinenko 3157c3c5b11SNicolas Vasilache if (!resultType.empty()) 316cadb7ccfSAlex Zinenko result = *ifResults.begin(); 3177c3c5b11SNicolas Vasilache } else { 3187c3c5b11SNicolas Vasilache // 4. Guaranteed in-bounds, progressively lower to a 1-D transfer read. 3197c3c5b11SNicolas Vasilache Value loaded1D = load1DVector(majorIvsPlusOffsets); 3207c3c5b11SNicolas Vasilache // 5.a. If `options.unroll` is true, insert the 1-D vector in the 3217c3c5b11SNicolas Vasilache // aggregate. 3227c3c5b11SNicolas Vasilache if (options.unroll) 3237c3c5b11SNicolas Vasilache result = vector_insert(loaded1D, result, majorIvs); 3247c3c5b11SNicolas Vasilache // 5.b. Otherwise, just go through the temporary `alloc`. 3257c3c5b11SNicolas Vasilache else 3267c3c5b11SNicolas Vasilache std_store(loaded1D, alloc, majorIvs); 3277c3c5b11SNicolas Vasilache } 3287c3c5b11SNicolas Vasilache }); 3297c3c5b11SNicolas Vasilache 330a9b5edc5SBenjamin Kramer assert((!options.unroll ^ (bool)result) && 331a9b5edc5SBenjamin Kramer "Expected resulting Value iff unroll"); 3327c3c5b11SNicolas Vasilache if (!result) 3337c3c5b11SNicolas Vasilache result = std_load(vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3347c3c5b11SNicolas Vasilache rewriter.replaceOp(op, result); 3354ead2cf7SAlex Zinenko 3364ead2cf7SAlex Zinenko return success(); 3374ead2cf7SAlex Zinenko } 3384ead2cf7SAlex Zinenko 3394ead2cf7SAlex Zinenko template <> 3404ead2cf7SAlex Zinenko LogicalResult NDTransferOpHelper<TransferWriteOp>::doReplace() { 3417c3c5b11SNicolas Vasilache Value alloc; 3427c3c5b11SNicolas Vasilache if (!options.unroll) { 343247e185dSNicolas Vasilache alloc = setAllocAtFunctionEntry(memRefMinorVectorType, op); 3444ead2cf7SAlex Zinenko std_store(xferOp.vector(), 3454ead2cf7SAlex Zinenko vector_type_cast(MemRefType::get({}, vectorType), alloc)); 3467c3c5b11SNicolas Vasilache } 3474ead2cf7SAlex Zinenko 3484ead2cf7SAlex Zinenko emitLoops([&](ValueRange majorIvs, ValueRange leadingOffsets, 3494ead2cf7SAlex Zinenko ValueRange majorOffsets, ValueRange minorOffsets, 3504ead2cf7SAlex Zinenko MemRefBoundsCapture &memrefBounds) { 3517c3c5b11SNicolas Vasilache // Lower to 1-D vector_transfer_write and let recursion handle it. 3527c3c5b11SNicolas Vasilache auto emitTransferWrite = [&](ValueRange majorIvsPlusOffsets) { 3534ead2cf7SAlex Zinenko SmallVector<Value, 8> indexing; 3544ead2cf7SAlex Zinenko indexing.reserve(leadingRank + majorRank + minorRank); 3554ead2cf7SAlex Zinenko indexing.append(leadingOffsets.begin(), leadingOffsets.end()); 3564ead2cf7SAlex Zinenko indexing.append(majorIvsPlusOffsets.begin(), majorIvsPlusOffsets.end()); 3574ead2cf7SAlex Zinenko indexing.append(minorOffsets.begin(), minorOffsets.end()); 3587c3c5b11SNicolas Vasilache Value result; 3597c3c5b11SNicolas Vasilache // If `options.unroll` is true, extract the 1-D vector from the 3607c3c5b11SNicolas Vasilache // aggregate. 3617c3c5b11SNicolas Vasilache if (options.unroll) 3627c3c5b11SNicolas Vasilache result = vector_extract(xferOp.vector(), majorIvs); 3637c3c5b11SNicolas Vasilache else 3647c3c5b11SNicolas Vasilache result = std_load(alloc, majorIvs); 36547cbd9f9SNicolas Vasilache auto map = 36647cbd9f9SNicolas Vasilache getTransferMinorIdentityMap(xferOp.getMemRefType(), minorVectorType); 3671870e787SNicolas Vasilache ArrayAttr masked; 368cc0a58d7SNicolas Vasilache if (!xferOp.isMaskedDim(xferOp.getVectorType().getRank() - 1)) { 3691870e787SNicolas Vasilache OpBuilder &b = ScopedContext::getBuilderRef(); 370cc0a58d7SNicolas Vasilache masked = b.getBoolArrayAttr({false}); 3711870e787SNicolas Vasilache } 3727c3c5b11SNicolas Vasilache vector_transfer_write(result, xferOp.memref(), indexing, 3731870e787SNicolas Vasilache AffineMapAttr::get(map), masked); 3744ead2cf7SAlex Zinenko }; 3757c3c5b11SNicolas Vasilache 3767c3c5b11SNicolas Vasilache // 1. Compute the inBoundsCondition in the current loops ivs + offset 3777c3c5b11SNicolas Vasilache // context. 3787c3c5b11SNicolas Vasilache SmallVector<Value, 4> majorIvsPlusOffsets; 3797c3c5b11SNicolas Vasilache Value inBoundsCondition = emitInBoundsCondition( 3807c3c5b11SNicolas Vasilache majorIvs, majorOffsets, memrefBounds, majorIvsPlusOffsets); 3817c3c5b11SNicolas Vasilache 3827c3c5b11SNicolas Vasilache if (inBoundsCondition) { 3837c3c5b11SNicolas Vasilache // 2.a. If the condition is not null, we need an IfOp, to write 3847c3c5b11SNicolas Vasilache // conditionally. Progressively lower to a 1-D transfer write. 385cadb7ccfSAlex Zinenko conditionBuilder(inBoundsCondition, 386cadb7ccfSAlex Zinenko [&] { emitTransferWrite(majorIvsPlusOffsets); }); 3877c3c5b11SNicolas Vasilache } else { 3887c3c5b11SNicolas Vasilache // 2.b. Guaranteed in-bounds. Progressively lower to a 1-D transfer write. 3897c3c5b11SNicolas Vasilache emitTransferWrite(majorIvsPlusOffsets); 3907c3c5b11SNicolas Vasilache } 3914ead2cf7SAlex Zinenko }); 3924ead2cf7SAlex Zinenko 3934ead2cf7SAlex Zinenko rewriter.eraseOp(op); 3944ead2cf7SAlex Zinenko 3954ead2cf7SAlex Zinenko return success(); 3964ead2cf7SAlex Zinenko } 3974ead2cf7SAlex Zinenko 398da95a0d8SNicolas Vasilache } // namespace 399da95a0d8SNicolas Vasilache 4004ead2cf7SAlex Zinenko /// Analyzes the `transfer` to find an access dimension along the fastest remote 4014ead2cf7SAlex Zinenko /// MemRef dimension. If such a dimension with coalescing properties is found, 4024ead2cf7SAlex Zinenko /// `pivs` and `vectorBoundsCapture` are swapped so that the invocation of 4034ead2cf7SAlex Zinenko /// LoopNestBuilder captures it in the innermost loop. 4044ead2cf7SAlex Zinenko template <typename TransferOpTy> 4054ead2cf7SAlex Zinenko static int computeCoalescedIndex(TransferOpTy transfer) { 4064ead2cf7SAlex Zinenko // rank of the remote memory access, coalescing behavior occurs on the 4074ead2cf7SAlex Zinenko // innermost memory dimension. 4084ead2cf7SAlex Zinenko auto remoteRank = transfer.getMemRefType().getRank(); 4094ead2cf7SAlex Zinenko // Iterate over the results expressions of the permutation map to determine 4104ead2cf7SAlex Zinenko // the loop order for creating pointwise copies between remote and local 4114ead2cf7SAlex Zinenko // memories. 4124ead2cf7SAlex Zinenko int coalescedIdx = -1; 4134ead2cf7SAlex Zinenko auto exprs = transfer.permutation_map().getResults(); 4144ead2cf7SAlex Zinenko for (auto en : llvm::enumerate(exprs)) { 4154ead2cf7SAlex Zinenko auto dim = en.value().template dyn_cast<AffineDimExpr>(); 4164ead2cf7SAlex Zinenko if (!dim) { 4174ead2cf7SAlex Zinenko continue; 4184ead2cf7SAlex Zinenko } 4194ead2cf7SAlex Zinenko auto memRefDim = dim.getPosition(); 4204ead2cf7SAlex Zinenko if (memRefDim == remoteRank - 1) { 4214ead2cf7SAlex Zinenko // memRefDim has coalescing properties, it should be swapped in the last 4224ead2cf7SAlex Zinenko // position. 4234ead2cf7SAlex Zinenko assert(coalescedIdx == -1 && "Unexpected > 1 coalesced indices"); 4244ead2cf7SAlex Zinenko coalescedIdx = en.index(); 4254ead2cf7SAlex Zinenko } 4264ead2cf7SAlex Zinenko } 4274ead2cf7SAlex Zinenko return coalescedIdx; 4284ead2cf7SAlex Zinenko } 4294ead2cf7SAlex Zinenko 4304ead2cf7SAlex Zinenko /// Emits remote memory accesses that are clipped to the boundaries of the 4314ead2cf7SAlex Zinenko /// MemRef. 4324ead2cf7SAlex Zinenko template <typename TransferOpTy> 4334ead2cf7SAlex Zinenko static SmallVector<Value, 8> 4344ead2cf7SAlex Zinenko clip(TransferOpTy transfer, MemRefBoundsCapture &bounds, ArrayRef<Value> ivs) { 4354ead2cf7SAlex Zinenko using namespace mlir::edsc; 4364ead2cf7SAlex Zinenko 4374ead2cf7SAlex Zinenko Value zero(std_constant_index(0)), one(std_constant_index(1)); 4384ead2cf7SAlex Zinenko SmallVector<Value, 8> memRefAccess(transfer.indices()); 4394ead2cf7SAlex Zinenko SmallVector<Value, 8> clippedScalarAccessExprs(memRefAccess.size()); 4404ead2cf7SAlex Zinenko // Indices accessing to remote memory are clipped and their expressions are 4414ead2cf7SAlex Zinenko // returned in clippedScalarAccessExprs. 4424ead2cf7SAlex Zinenko for (unsigned memRefDim = 0; memRefDim < clippedScalarAccessExprs.size(); 4434ead2cf7SAlex Zinenko ++memRefDim) { 4444ead2cf7SAlex Zinenko // Linear search on a small number of entries. 4454ead2cf7SAlex Zinenko int loopIndex = -1; 4464ead2cf7SAlex Zinenko auto exprs = transfer.permutation_map().getResults(); 4474ead2cf7SAlex Zinenko for (auto en : llvm::enumerate(exprs)) { 4484ead2cf7SAlex Zinenko auto expr = en.value(); 4494ead2cf7SAlex Zinenko auto dim = expr.template dyn_cast<AffineDimExpr>(); 4504ead2cf7SAlex Zinenko // Sanity check. 4514ead2cf7SAlex Zinenko assert( 4524ead2cf7SAlex Zinenko (dim || expr.template cast<AffineConstantExpr>().getValue() == 0) && 4534ead2cf7SAlex Zinenko "Expected dim or 0 in permutationMap"); 4544ead2cf7SAlex Zinenko if (dim && memRefDim == dim.getPosition()) { 4554ead2cf7SAlex Zinenko loopIndex = en.index(); 4564ead2cf7SAlex Zinenko break; 4574ead2cf7SAlex Zinenko } 4584ead2cf7SAlex Zinenko } 4594ead2cf7SAlex Zinenko 4604ead2cf7SAlex Zinenko // We cannot distinguish atm between unrolled dimensions that implement 4614ead2cf7SAlex Zinenko // the "always full" tile abstraction and need clipping from the other 4624ead2cf7SAlex Zinenko // ones. So we conservatively clip everything. 4634ead2cf7SAlex Zinenko using namespace edsc::op; 4644ead2cf7SAlex Zinenko auto N = bounds.ub(memRefDim); 4654ead2cf7SAlex Zinenko auto i = memRefAccess[memRefDim]; 4664ead2cf7SAlex Zinenko if (loopIndex < 0) { 4674ead2cf7SAlex Zinenko auto N_minus_1 = N - one; 46825055a4fSAdam D Straw auto select_1 = std_select(slt(i, N), i, N_minus_1); 4694ead2cf7SAlex Zinenko clippedScalarAccessExprs[memRefDim] = 47025055a4fSAdam D Straw std_select(slt(i, zero), zero, select_1); 4714ead2cf7SAlex Zinenko } else { 4724ead2cf7SAlex Zinenko auto ii = ivs[loopIndex]; 4734ead2cf7SAlex Zinenko auto i_plus_ii = i + ii; 4744ead2cf7SAlex Zinenko auto N_minus_1 = N - one; 47525055a4fSAdam D Straw auto select_1 = std_select(slt(i_plus_ii, N), i_plus_ii, N_minus_1); 4764ead2cf7SAlex Zinenko clippedScalarAccessExprs[memRefDim] = 47725055a4fSAdam D Straw std_select(slt(i_plus_ii, zero), zero, select_1); 4784ead2cf7SAlex Zinenko } 4794ead2cf7SAlex Zinenko } 4804ead2cf7SAlex Zinenko 4814ead2cf7SAlex Zinenko return clippedScalarAccessExprs; 4824ead2cf7SAlex Zinenko } 4834ead2cf7SAlex Zinenko 4843393cc4cSNicolas Vasilache namespace mlir { 4853393cc4cSNicolas Vasilache 4864ead2cf7SAlex Zinenko template <typename TransferOpTy> 4873393cc4cSNicolas Vasilache VectorTransferRewriter<TransferOpTy>::VectorTransferRewriter( 4887c3c5b11SNicolas Vasilache VectorTransferToSCFOptions options, MLIRContext *context) 4897c3c5b11SNicolas Vasilache : RewritePattern(TransferOpTy::getOperationName(), 1, context), 4907c3c5b11SNicolas Vasilache options(options) {} 4914ead2cf7SAlex Zinenko 4927c3c5b11SNicolas Vasilache /// Used for staging the transfer in a local buffer. 4937c3c5b11SNicolas Vasilache template <typename TransferOpTy> 4943393cc4cSNicolas Vasilache MemRefType VectorTransferRewriter<TransferOpTy>::tmpMemRefType( 4957c3c5b11SNicolas Vasilache TransferOpTy transfer) const { 4964ead2cf7SAlex Zinenko auto vectorType = transfer.getVectorType(); 4977c3c5b11SNicolas Vasilache return MemRefType::get(vectorType.getShape(), vectorType.getElementType(), {}, 4987c3c5b11SNicolas Vasilache 0); 4994ead2cf7SAlex Zinenko } 5004ead2cf7SAlex Zinenko 5014ead2cf7SAlex Zinenko /// Lowers TransferReadOp into a combination of: 5024ead2cf7SAlex Zinenko /// 1. local memory allocation; 5034ead2cf7SAlex Zinenko /// 2. perfect loop nest over: 5044ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 5054ead2cf7SAlex Zinenko /// a. scalar store to original memref (with clipping). 5064ead2cf7SAlex Zinenko /// 3. vector_load from local buffer (viewed as a memref<1 x vector>); 5074ead2cf7SAlex Zinenko /// 4. local memory deallocation. 5084ead2cf7SAlex Zinenko /// 5094ead2cf7SAlex Zinenko /// Lowers the data transfer part of a TransferReadOp while ensuring no 5104ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 5114ead2cf7SAlex Zinenko /// clipping. This means that a given value in memory can be read multiple 5124ead2cf7SAlex Zinenko /// times and concurrently. 5134ead2cf7SAlex Zinenko /// 5144ead2cf7SAlex Zinenko /// Important notes about clipping and "full-tiles only" abstraction: 5154ead2cf7SAlex Zinenko /// ================================================================= 5164ead2cf7SAlex Zinenko /// When using clipping for dealing with boundary conditions, the same edge 5174ead2cf7SAlex Zinenko /// value will appear multiple times (a.k.a edge padding). This is fine if the 5184ead2cf7SAlex Zinenko /// subsequent vector operations are all data-parallel but **is generally 5194ead2cf7SAlex Zinenko /// incorrect** in the presence of reductions or extract operations. 5204ead2cf7SAlex Zinenko /// 5214ead2cf7SAlex Zinenko /// More generally, clipping is a scalar abstraction that is expected to work 5224ead2cf7SAlex Zinenko /// fine as a baseline for CPUs and GPUs but not for vector_load and DMAs. 5234ead2cf7SAlex Zinenko /// To deal with real vector_load and DMAs, a "padded allocation + view" 5244ead2cf7SAlex Zinenko /// abstraction with the ability to read out-of-memref-bounds (but still within 5254ead2cf7SAlex Zinenko /// the allocated region) is necessary. 5264ead2cf7SAlex Zinenko /// 5274ead2cf7SAlex Zinenko /// Whether using scalar loops or vector_load/DMAs to perform the transfer, 5284ead2cf7SAlex Zinenko /// junk values will be materialized in the vectors and generally need to be 5294ead2cf7SAlex Zinenko /// filtered out and replaced by the "neutral element". This neutral element is 5304ead2cf7SAlex Zinenko /// op-dependent so, in the future, we expect to create a vector filter and 5314ead2cf7SAlex Zinenko /// apply it to a splatted constant vector with the proper neutral element at 5324ead2cf7SAlex Zinenko /// each ssa-use. This filtering is not necessary for pure data-parallel 5334ead2cf7SAlex Zinenko /// operations. 5344ead2cf7SAlex Zinenko /// 5354ead2cf7SAlex Zinenko /// In the case of vector_store/DMAs, Read-Modify-Write will be required, which 5364ead2cf7SAlex Zinenko /// also have concurrency implications. Note that by using clipped scalar stores 5374ead2cf7SAlex Zinenko /// in the presence of data-parallel only operations, we generate code that 5384ead2cf7SAlex Zinenko /// writes the same value multiple time on the edge locations. 5394ead2cf7SAlex Zinenko /// 5409db53a18SRiver Riddle /// TODO: implement alternatives to clipping. 5419db53a18SRiver Riddle /// TODO: support non-data-parallel operations. 5424ead2cf7SAlex Zinenko 5434ead2cf7SAlex Zinenko /// Performs the rewrite. 5444ead2cf7SAlex Zinenko template <> 5453393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferReadOp>::matchAndRewrite( 5464ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 5474ead2cf7SAlex Zinenko using namespace mlir::edsc::op; 5484ead2cf7SAlex Zinenko 5494ead2cf7SAlex Zinenko TransferReadOp transfer = cast<TransferReadOp>(op); 550*dfb7b3feSBenjamin Kramer 551*dfb7b3feSBenjamin Kramer // Fall back to a loop if the fastest varying stride is not 1 or it is 552*dfb7b3feSBenjamin Kramer // permuted. 553*dfb7b3feSBenjamin Kramer int64_t offset; 554*dfb7b3feSBenjamin Kramer SmallVector<int64_t, 4> strides; 555*dfb7b3feSBenjamin Kramer auto successStrides = 556*dfb7b3feSBenjamin Kramer getStridesAndOffset(transfer.getMemRefType(), strides, offset); 557*dfb7b3feSBenjamin Kramer if (succeeded(successStrides) && strides.back() == 1 && 558*dfb7b3feSBenjamin Kramer transfer.permutation_map().isMinorIdentity()) { 5594ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 5604ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 5617c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferReadOp>(rewriter, transfer, options) 5627c3c5b11SNicolas Vasilache .doReplace(); 5634ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 5644ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 5654ead2cf7SAlex Zinenko return failure(); 5664ead2cf7SAlex Zinenko } 5674ead2cf7SAlex Zinenko 5684ead2cf7SAlex Zinenko // Conservative lowering to scalar load / stores. 5694ead2cf7SAlex Zinenko // 1. Setup all the captures. 5704ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 5714ead2cf7SAlex Zinenko StdIndexedValue remote(transfer.memref()); 5724ead2cf7SAlex Zinenko MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 5734ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 5744ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 5754ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 5764ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 5774ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 5784ead2cf7SAlex Zinenko coalescedIdx); 5794ead2cf7SAlex Zinenko 5804ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 5814ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 5824ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 5834ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 5844ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 5854ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 5864ead2cf7SAlex Zinenko 5874ead2cf7SAlex Zinenko // 2. Emit alloc-copy-load-dealloc. 588f5ed22f0SJakub Lichman Value tmp = std_alloc(tmpMemRefType(transfer), ValueRange{}, 589f5ed22f0SJakub Lichman rewriter.getI64IntegerAttr(ALIGNMENT_SIZE)); 5904ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 5914ead2cf7SAlex Zinenko Value vec = vector_type_cast(tmp); 592d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 593d1560f39SAlex Zinenko auto ivs = llvm::to_vector<8>(loopIvs); 5944ead2cf7SAlex Zinenko // Swap the ivs which will reorder memory accesses. 5954ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 5964ead2cf7SAlex Zinenko std::swap(ivs.back(), ivs[coalescedIdx]); 5974ead2cf7SAlex Zinenko // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 5984ead2cf7SAlex Zinenko local(ivs) = remote(clip(transfer, memRefBoundsCapture, ivs)); 5994ead2cf7SAlex Zinenko }); 6004ead2cf7SAlex Zinenko Value vectorValue = std_load(vec); 6014ead2cf7SAlex Zinenko (std_dealloc(tmp)); // vexing parse 6024ead2cf7SAlex Zinenko 6034ead2cf7SAlex Zinenko // 3. Propagate. 6044ead2cf7SAlex Zinenko rewriter.replaceOp(op, vectorValue); 6054ead2cf7SAlex Zinenko return success(); 6064ead2cf7SAlex Zinenko } 6074ead2cf7SAlex Zinenko 6084ead2cf7SAlex Zinenko /// Lowers TransferWriteOp into a combination of: 6094ead2cf7SAlex Zinenko /// 1. local memory allocation; 6104ead2cf7SAlex Zinenko /// 2. vector_store to local buffer (viewed as a memref<1 x vector>); 6114ead2cf7SAlex Zinenko /// 3. perfect loop nest over: 6124ead2cf7SAlex Zinenko /// a. scalar load from local buffers (viewed as a scalar memref); 6134ead2cf7SAlex Zinenko /// a. scalar store to original memref (with clipping). 6144ead2cf7SAlex Zinenko /// 4. local memory deallocation. 6154ead2cf7SAlex Zinenko /// 6164ead2cf7SAlex Zinenko /// More specifically, lowers the data transfer part while ensuring no 6174ead2cf7SAlex Zinenko /// out-of-bounds accesses are possible. Out-of-bounds behavior is handled by 6184ead2cf7SAlex Zinenko /// clipping. This means that a given value in memory can be written to multiple 6194ead2cf7SAlex Zinenko /// times and concurrently. 6204ead2cf7SAlex Zinenko /// 6214ead2cf7SAlex Zinenko /// See `Important notes about clipping and full-tiles only abstraction` in the 6224ead2cf7SAlex Zinenko /// description of `readClipped` above. 6234ead2cf7SAlex Zinenko /// 6249db53a18SRiver Riddle /// TODO: implement alternatives to clipping. 6259db53a18SRiver Riddle /// TODO: support non-data-parallel operations. 6264ead2cf7SAlex Zinenko template <> 6273393cc4cSNicolas Vasilache LogicalResult VectorTransferRewriter<TransferWriteOp>::matchAndRewrite( 6284ead2cf7SAlex Zinenko Operation *op, PatternRewriter &rewriter) const { 6294ead2cf7SAlex Zinenko using namespace edsc::op; 6304ead2cf7SAlex Zinenko 6314ead2cf7SAlex Zinenko TransferWriteOp transfer = cast<TransferWriteOp>(op); 632*dfb7b3feSBenjamin Kramer 633*dfb7b3feSBenjamin Kramer // Fall back to a loop if the fastest varying stride is not 1 or it is 634*dfb7b3feSBenjamin Kramer // permuted. 635*dfb7b3feSBenjamin Kramer int64_t offset; 636*dfb7b3feSBenjamin Kramer SmallVector<int64_t, 4> strides; 637*dfb7b3feSBenjamin Kramer auto successStrides = 638*dfb7b3feSBenjamin Kramer getStridesAndOffset(transfer.getMemRefType(), strides, offset); 639*dfb7b3feSBenjamin Kramer if (succeeded(successStrides) && strides.back() == 1 && 640*dfb7b3feSBenjamin Kramer transfer.permutation_map().isMinorIdentity()) { 6414ead2cf7SAlex Zinenko // If > 1D, emit a bunch of loops around 1-D vector transfers. 6424ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() > 1) 6437c3c5b11SNicolas Vasilache return NDTransferOpHelper<TransferWriteOp>(rewriter, transfer, options) 6444ead2cf7SAlex Zinenko .doReplace(); 6454ead2cf7SAlex Zinenko // If 1-D this is now handled by the target-specific lowering. 6464ead2cf7SAlex Zinenko if (transfer.getVectorType().getRank() == 1) 6474ead2cf7SAlex Zinenko return failure(); 6484ead2cf7SAlex Zinenko } 6494ead2cf7SAlex Zinenko 6504ead2cf7SAlex Zinenko // 1. Setup all the captures. 6514ead2cf7SAlex Zinenko ScopedContext scope(rewriter, transfer.getLoc()); 6524ead2cf7SAlex Zinenko StdIndexedValue remote(transfer.memref()); 6534ead2cf7SAlex Zinenko MemRefBoundsCapture memRefBoundsCapture(transfer.memref()); 6544ead2cf7SAlex Zinenko Value vectorValue(transfer.vector()); 6554ead2cf7SAlex Zinenko VectorBoundsCapture vectorBoundsCapture(transfer.vector()); 6564ead2cf7SAlex Zinenko int coalescedIdx = computeCoalescedIndex(transfer); 6574ead2cf7SAlex Zinenko // Swap the vectorBoundsCapture which will reorder loop bounds. 6584ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 6594ead2cf7SAlex Zinenko vectorBoundsCapture.swapRanges(vectorBoundsCapture.rank() - 1, 6604ead2cf7SAlex Zinenko coalescedIdx); 6614ead2cf7SAlex Zinenko 6624ead2cf7SAlex Zinenko auto lbs = vectorBoundsCapture.getLbs(); 6634ead2cf7SAlex Zinenko auto ubs = vectorBoundsCapture.getUbs(); 6644ead2cf7SAlex Zinenko SmallVector<Value, 8> steps; 6654ead2cf7SAlex Zinenko steps.reserve(vectorBoundsCapture.getSteps().size()); 6664ead2cf7SAlex Zinenko for (auto step : vectorBoundsCapture.getSteps()) 6674ead2cf7SAlex Zinenko steps.push_back(std_constant_index(step)); 6684ead2cf7SAlex Zinenko 6694ead2cf7SAlex Zinenko // 2. Emit alloc-store-copy-dealloc. 670f5ed22f0SJakub Lichman Value tmp = std_alloc(tmpMemRefType(transfer), ValueRange{}, 671f5ed22f0SJakub Lichman rewriter.getI64IntegerAttr(ALIGNMENT_SIZE)); 6724ead2cf7SAlex Zinenko StdIndexedValue local(tmp); 6734ead2cf7SAlex Zinenko Value vec = vector_type_cast(tmp); 6744ead2cf7SAlex Zinenko std_store(vectorValue, vec); 675d1560f39SAlex Zinenko loopNestBuilder(lbs, ubs, steps, [&](ValueRange loopIvs) { 676d1560f39SAlex Zinenko auto ivs = llvm::to_vector<8>(loopIvs); 6774ead2cf7SAlex Zinenko // Swap the ivs which will reorder memory accesses. 6784ead2cf7SAlex Zinenko if (coalescedIdx >= 0) 6794ead2cf7SAlex Zinenko std::swap(ivs.back(), ivs[coalescedIdx]); 6804ead2cf7SAlex Zinenko // Computes clippedScalarAccessExprs in the loop nest scope (ivs exist). 6814ead2cf7SAlex Zinenko remote(clip(transfer, memRefBoundsCapture, ivs)) = local(ivs); 6824ead2cf7SAlex Zinenko }); 6834ead2cf7SAlex Zinenko (std_dealloc(tmp)); // vexing parse... 6844ead2cf7SAlex Zinenko 6854ead2cf7SAlex Zinenko rewriter.eraseOp(op); 6864ead2cf7SAlex Zinenko return success(); 6874ead2cf7SAlex Zinenko } 6884ead2cf7SAlex Zinenko 6893393cc4cSNicolas Vasilache void populateVectorToSCFConversionPatterns( 6907c3c5b11SNicolas Vasilache OwningRewritePatternList &patterns, MLIRContext *context, 6917c3c5b11SNicolas Vasilache const VectorTransferToSCFOptions &options) { 6924ead2cf7SAlex Zinenko patterns.insert<VectorTransferRewriter<vector::TransferReadOp>, 6937c3c5b11SNicolas Vasilache VectorTransferRewriter<vector::TransferWriteOp>>(options, 6947c3c5b11SNicolas Vasilache context); 6954ead2cf7SAlex Zinenko } 6963393cc4cSNicolas Vasilache 6973393cc4cSNicolas Vasilache } // namespace mlir 6983393cc4cSNicolas Vasilache 6995f9e0466SNicolas Vasilache namespace { 7005f9e0466SNicolas Vasilache 7015f9e0466SNicolas Vasilache struct ConvertVectorToSCFPass 7025f9e0466SNicolas Vasilache : public ConvertVectorToSCFBase<ConvertVectorToSCFPass> { 7035f9e0466SNicolas Vasilache ConvertVectorToSCFPass() = default; 7045f9e0466SNicolas Vasilache ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 7055f9e0466SNicolas Vasilache this->fullUnroll = options.unroll; 7065f9e0466SNicolas Vasilache } 7075f9e0466SNicolas Vasilache 7085f9e0466SNicolas Vasilache void runOnFunction() override { 7095f9e0466SNicolas Vasilache OwningRewritePatternList patterns; 7105f9e0466SNicolas Vasilache auto *context = getFunction().getContext(); 7115f9e0466SNicolas Vasilache populateVectorToSCFConversionPatterns( 7125f9e0466SNicolas Vasilache patterns, context, VectorTransferToSCFOptions().setUnroll(fullUnroll)); 7135f9e0466SNicolas Vasilache applyPatternsAndFoldGreedily(getFunction(), patterns); 7145f9e0466SNicolas Vasilache } 7155f9e0466SNicolas Vasilache }; 7165f9e0466SNicolas Vasilache 7175f9e0466SNicolas Vasilache } // namespace 7185f9e0466SNicolas Vasilache 7195f9e0466SNicolas Vasilache std::unique_ptr<Pass> 7205f9e0466SNicolas Vasilache mlir::createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) { 7215f9e0466SNicolas Vasilache return std::make_unique<ConvertVectorToSCFPass>(options); 7225f9e0466SNicolas Vasilache } 723