1edd9515bSthomasraoux //===- VectorToGPU.cpp - Convert vector to GPU dialect ----------*- C++ -*-===// 2edd9515bSthomasraoux // 3edd9515bSthomasraoux // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4edd9515bSthomasraoux // See https://llvm.org/LICENSE.txt for license information. 5edd9515bSthomasraoux // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6edd9515bSthomasraoux // 7edd9515bSthomasraoux //===----------------------------------------------------------------------===// 8edd9515bSthomasraoux // 9edd9515bSthomasraoux // This file implements lowering of vector operations to GPU dialect ops. 10edd9515bSthomasraoux // 11edd9515bSthomasraoux //===----------------------------------------------------------------------===// 12edd9515bSthomasraoux 13edd9515bSthomasraoux #include <type_traits> 14edd9515bSthomasraoux 15edd9515bSthomasraoux #include "mlir/Conversion/VectorToGPU/VectorToGPU.h" 16edd9515bSthomasraoux 17edd9515bSthomasraoux #include "../PassDetail.h" 18edd9515bSthomasraoux #include "mlir/Analysis/SliceAnalysis.h" 19edd9515bSthomasraoux #include "mlir/Dialect/GPU/GPUDialect.h" 2066f878ceSMatthias Springer #include "mlir/Dialect/MemRef/IR/MemRef.h" 21*1a865592Sthomasraoux #include "mlir/Dialect/SCF/SCF.h" 22edd9515bSthomasraoux #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 23edd9515bSthomasraoux #include "mlir/Dialect/Vector/VectorOps.h" 24edd9515bSthomasraoux #include "mlir/Dialect/Vector/VectorUtils.h" 25edd9515bSthomasraoux #include "mlir/IR/Builders.h" 26edd9515bSthomasraoux #include "mlir/Pass/Pass.h" 27edd9515bSthomasraoux #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 28edd9515bSthomasraoux #include "mlir/Transforms/Passes.h" 29edd9515bSthomasraoux 30edd9515bSthomasraoux using namespace mlir; 31edd9515bSthomasraoux 32edd9515bSthomasraoux // Return true if the contract op can be convert to MMA matmul. 33edd9515bSthomasraoux static bool contractSupportsMMAMatrixType(vector::ContractionOp contract) { 34edd9515bSthomasraoux if (llvm::size(contract.masks()) != 0) 35edd9515bSthomasraoux return false; 36edd9515bSthomasraoux 37edd9515bSthomasraoux using MapList = ArrayRef<ArrayRef<AffineExpr>>; 38edd9515bSthomasraoux auto infer = [](MapList m) { return AffineMap::inferFromExprList(m); }; 39edd9515bSthomasraoux AffineExpr m, n, k; 40edd9515bSthomasraoux bindDims(contract.getContext(), m, n, k); 41edd9515bSthomasraoux auto iteratorTypes = contract.iterator_types().getValue(); 42edd9515bSthomasraoux if (!(isParallelIterator(iteratorTypes[0]) && 43edd9515bSthomasraoux isParallelIterator(iteratorTypes[1]) && 44edd9515bSthomasraoux isReductionIterator(iteratorTypes[2]))) 45edd9515bSthomasraoux return false; 46edd9515bSthomasraoux 47edd9515bSthomasraoux // The contract needs to represent a matmul to be able to convert to 48edd9515bSthomasraoux // MMAMatrix matmul. 49edd9515bSthomasraoux if (contract.getIndexingMaps() != infer({{m, k}, {k, n}, {m, n}})) 50edd9515bSthomasraoux return false; 51edd9515bSthomasraoux 52edd9515bSthomasraoux // Check that the size matches what is natively supported. 53edd9515bSthomasraoux VectorType lhsType = contract.lhs().getType().cast<VectorType>(); 54edd9515bSthomasraoux VectorType rhsType = contract.rhs().getType().cast<VectorType>(); 55edd9515bSthomasraoux VectorType accType = contract.acc().getType().cast<VectorType>(); 56edd9515bSthomasraoux 57edd9515bSthomasraoux std::tuple<int, int, int> dim(lhsType.getDimSize(0), rhsType.getDimSize(1), 58edd9515bSthomasraoux lhsType.getDimSize(1)); 59edd9515bSthomasraoux if (lhsType.getElementType().isInteger(8) && 60edd9515bSthomasraoux rhsType.getElementType().isInteger(8) && 61edd9515bSthomasraoux accType.getElementType().isInteger(32) && 62edd9515bSthomasraoux (dim == std::make_tuple(8, 8, 32) || dim == std::make_tuple(16, 16, 32) || 63edd9515bSthomasraoux dim == std::make_tuple(16, 8, 32))) 64edd9515bSthomasraoux return true; 65edd9515bSthomasraoux 66edd9515bSthomasraoux if (lhsType.getElementType().isF16() && rhsType.getElementType().isF16() && 67edd9515bSthomasraoux (accType.getElementType().isF16() || accType.getElementType().isF32()) && 68edd9515bSthomasraoux (dim == std::make_tuple(8, 8, 16) || dim == std::make_tuple(16, 16, 16) || 69edd9515bSthomasraoux dim == std::make_tuple(16, 8, 16))) 70edd9515bSthomasraoux return true; 71edd9515bSthomasraoux return false; 72edd9515bSthomasraoux } 73edd9515bSthomasraoux 74edd9515bSthomasraoux // Return the stide for the dimension 0 of |type| if it is a memref and has a 75edd9515bSthomasraoux // constant stride. 76edd9515bSthomasraoux static llvm::Optional<int64_t> 77edd9515bSthomasraoux getMemrefConstantHorizontalStride(ShapedType type) { 78edd9515bSthomasraoux auto memrefType = type.dyn_cast<MemRefType>(); 79edd9515bSthomasraoux if (!memrefType) 80edd9515bSthomasraoux return false; 81edd9515bSthomasraoux int64_t offset = 0; 82edd9515bSthomasraoux SmallVector<int64_t, 2> strides; 83edd9515bSthomasraoux if (failed(getStridesAndOffset(memrefType, strides, offset))) 84edd9515bSthomasraoux return llvm::None; 85edd9515bSthomasraoux if (strides[0] == ShapedType::kDynamicStrideOrOffset) 86edd9515bSthomasraoux return llvm::None; 87edd9515bSthomasraoux return strides[0]; 88edd9515bSthomasraoux } 89edd9515bSthomasraoux 90edd9515bSthomasraoux // Return true if the transfer op can be converted to a MMA matrix load. 91edd9515bSthomasraoux static bool transferReadSupportsMMAMatrixType(vector::TransferReadOp readOp) { 92edd9515bSthomasraoux if (readOp.mask() || readOp.hasOutOfBoundsDim() || 93edd9515bSthomasraoux readOp.getVectorType().getRank() != 2) 94edd9515bSthomasraoux return false; 95edd9515bSthomasraoux if (!getMemrefConstantHorizontalStride(readOp.getShapedType())) 96edd9515bSthomasraoux return false; 97edd9515bSthomasraoux // TODO: Support transpose once it is added to GPU dialect ops. 98edd9515bSthomasraoux if (!readOp.permutation_map().isMinorIdentity()) 99edd9515bSthomasraoux return false; 100edd9515bSthomasraoux return true; 101edd9515bSthomasraoux } 102edd9515bSthomasraoux 103edd9515bSthomasraoux // Return true if the transfer op can be converted to a MMA matrix store. 104edd9515bSthomasraoux static bool 105edd9515bSthomasraoux transferWriteSupportsMMAMatrixType(vector::TransferWriteOp writeOp) { 106edd9515bSthomasraoux if (writeOp.mask() || writeOp.hasOutOfBoundsDim() || 107edd9515bSthomasraoux writeOp.getVectorType().getRank() != 2) 108edd9515bSthomasraoux return false; 109edd9515bSthomasraoux if (!getMemrefConstantHorizontalStride(writeOp.getShapedType())) 110edd9515bSthomasraoux return false; 111edd9515bSthomasraoux // TODO: Support transpose once it is added to GPU dialect ops. 112edd9515bSthomasraoux if (!writeOp.permutation_map().isMinorIdentity()) 113edd9515bSthomasraoux return false; 114edd9515bSthomasraoux return true; 115edd9515bSthomasraoux } 116edd9515bSthomasraoux 1176413226dSthomasraoux /// Return true if the constant is a splat to a 2D vector so that it can be 1186413226dSthomasraoux /// converted to a MMA constant matrix op. 1196413226dSthomasraoux static bool constantSupportsMMAMatrixType(ConstantOp constantOp) { 1206413226dSthomasraoux auto vecType = constantOp.getType().dyn_cast<VectorType>(); 1216413226dSthomasraoux if (!vecType || vecType.getRank() != 2) 1226413226dSthomasraoux return false; 1236413226dSthomasraoux return constantOp.value().isa<SplatElementsAttr>(); 1246413226dSthomasraoux } 1256413226dSthomasraoux 126edd9515bSthomasraoux static bool supportsMMaMatrixType(Operation *op) { 127*1a865592Sthomasraoux if (isa<scf::ForOp, scf::YieldOp>(op)) 128*1a865592Sthomasraoux return true; 129edd9515bSthomasraoux if (auto transferRead = dyn_cast<vector::TransferReadOp>(op)) 130edd9515bSthomasraoux return transferReadSupportsMMAMatrixType(transferRead); 131edd9515bSthomasraoux if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op)) 132edd9515bSthomasraoux return transferWriteSupportsMMAMatrixType(transferWrite); 133edd9515bSthomasraoux if (auto contract = dyn_cast<vector::ContractionOp>(op)) 134edd9515bSthomasraoux return contractSupportsMMAMatrixType(contract); 1356413226dSthomasraoux if (auto constant = dyn_cast<ConstantOp>(op)) 1366413226dSthomasraoux return constantSupportsMMAMatrixType(constant); 137edd9515bSthomasraoux return false; 138edd9515bSthomasraoux } 139edd9515bSthomasraoux 140edd9515bSthomasraoux // Analyze slice of operations based on convert op to figure out if the whole 141edd9515bSthomasraoux // slice can be converted to MMA operations. 142edd9515bSthomasraoux static SetVector<Operation *> getOpToConvert(mlir::Operation *op) { 143edd9515bSthomasraoux auto hasVectorDest = [](Operation *op) { 144edd9515bSthomasraoux return op->getNumResults() == 0 || 145edd9515bSthomasraoux llvm::any_of(op->getResultTypes(), 146edd9515bSthomasraoux [](Type t) { return t.isa<VectorType>(); }); 147edd9515bSthomasraoux }; 148edd9515bSthomasraoux SetVector<Operation *> opToConvert; 149edd9515bSthomasraoux op->walk([&](vector::ContractionOp contract) { 150edd9515bSthomasraoux if (opToConvert.contains(contract.getOperation())) 151edd9515bSthomasraoux return; 152edd9515bSthomasraoux SetVector<Operation *> dependentOps = 153edd9515bSthomasraoux getSlice(contract, hasVectorDest, hasVectorDest); 154edd9515bSthomasraoux // If any instruction cannot use MMA matrix type drop the whole 155edd9515bSthomasraoux // chaine. MMA matrix are stored in an opaque type so they cannot be used 156edd9515bSthomasraoux // by all operations. 157edd9515bSthomasraoux if (llvm::any_of(dependentOps, 158edd9515bSthomasraoux [](Operation *op) { return !supportsMMaMatrixType(op); })) 159edd9515bSthomasraoux return; 160edd9515bSthomasraoux opToConvert.insert(dependentOps.begin(), dependentOps.end()); 161edd9515bSthomasraoux }); 162edd9515bSthomasraoux return opToConvert; 163edd9515bSthomasraoux } 164edd9515bSthomasraoux 165edd9515bSthomasraoux namespace { 166edd9515bSthomasraoux // Transform contract into (m, k)x(k, n)x(m, n) form so that it can be converted 167edd9515bSthomasraoux // to MMA matmul. 168edd9515bSthomasraoux struct PrepareContractToGPUMMA 169edd9515bSthomasraoux : public OpRewritePattern<vector::ContractionOp> { 170edd9515bSthomasraoux using OpRewritePattern<vector::ContractionOp>::OpRewritePattern; 171edd9515bSthomasraoux 172edd9515bSthomasraoux LogicalResult matchAndRewrite(vector::ContractionOp op, 173edd9515bSthomasraoux PatternRewriter &rewriter) const override { 174edd9515bSthomasraoux Location loc = op.getLoc(); 175edd9515bSthomasraoux Value lhs = op.lhs(), rhs = op.rhs(), res = op.acc(); 176edd9515bSthomasraoux 177edd9515bSthomasraoux // Set up the parallel/reduction structure in right form. 178edd9515bSthomasraoux using MapList = ArrayRef<ArrayRef<AffineExpr>>; 179edd9515bSthomasraoux auto infer = [](MapList m) { return AffineMap::inferFromExprList(m); }; 180edd9515bSthomasraoux AffineExpr m, n, k; 181edd9515bSthomasraoux bindDims(rewriter.getContext(), m, n, k); 182edd9515bSthomasraoux static constexpr std::array<int64_t, 2> perm = {1, 0}; 183edd9515bSthomasraoux auto iteratorTypes = op.iterator_types().getValue(); 184edd9515bSthomasraoux SmallVector<AffineMap, 4> maps = op.getIndexingMaps(); 185edd9515bSthomasraoux if (!(isParallelIterator(iteratorTypes[0]) && 186edd9515bSthomasraoux isParallelIterator(iteratorTypes[1]) && 187edd9515bSthomasraoux isReductionIterator(iteratorTypes[2]))) 188edd9515bSthomasraoux return failure(); 189edd9515bSthomasraoux // 190edd9515bSthomasraoux // Two outer parallel, one inner reduction (matmat flavor). 191edd9515bSthomasraoux // 192edd9515bSthomasraoux if (maps == infer({{m, k}, {k, n}, {m, n}})) { 193edd9515bSthomasraoux // This is the classical row-major matmul, nothing to do. 194edd9515bSthomasraoux return failure(); 195edd9515bSthomasraoux } 196edd9515bSthomasraoux if (maps == infer({{m, k}, {n, k}, {m, n}})) { 197edd9515bSthomasraoux rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); 198edd9515bSthomasraoux } else if (maps == infer({{k, m}, {k, n}, {m, n}})) { 199edd9515bSthomasraoux lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); 200edd9515bSthomasraoux } else if (maps == infer({{k, m}, {n, k}, {m, n}})) { 201edd9515bSthomasraoux rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); 202edd9515bSthomasraoux lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); 203edd9515bSthomasraoux } else if (maps == infer({{m, k}, {k, n}, {n, m}})) { 204edd9515bSthomasraoux std::swap(rhs, lhs); 205edd9515bSthomasraoux rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); 206edd9515bSthomasraoux lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); 207edd9515bSthomasraoux } else if (maps == infer({{m, k}, {n, k}, {n, m}})) { 208edd9515bSthomasraoux std::swap(rhs, lhs); 209edd9515bSthomasraoux rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm); 210edd9515bSthomasraoux } else if (maps == infer({{k, m}, {k, n}, {n, m}})) { 211edd9515bSthomasraoux std::swap(lhs, rhs); 212edd9515bSthomasraoux lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm); 213edd9515bSthomasraoux } else if (maps == infer({{k, m}, {n, k}, {n, m}})) { 214edd9515bSthomasraoux std::swap(lhs, rhs); 215edd9515bSthomasraoux } else { 216edd9515bSthomasraoux return failure(); 217edd9515bSthomasraoux } 218edd9515bSthomasraoux rewriter.replaceOpWithNewOp<vector::ContractionOp>( 219edd9515bSthomasraoux op, lhs, rhs, res, 220edd9515bSthomasraoux rewriter.getAffineMapArrayAttr(infer({{m, k}, {k, n}, {m, n}})), 221edd9515bSthomasraoux op.iterator_types()); 222edd9515bSthomasraoux return success(); 223edd9515bSthomasraoux } 224edd9515bSthomasraoux }; 225edd9515bSthomasraoux 226edd9515bSthomasraoux // Merge transpose op into the transfer read op. Transpose are not supported on 227edd9515bSthomasraoux // MMA types but MMA load can transpose the matrix when loading. 228edd9515bSthomasraoux struct CombineTransferReadOpTranspose final 229edd9515bSthomasraoux : public OpRewritePattern<vector::TransposeOp> { 230edd9515bSthomasraoux using OpRewritePattern<vector::TransposeOp>::OpRewritePattern; 231edd9515bSthomasraoux 232edd9515bSthomasraoux LogicalResult matchAndRewrite(vector::TransposeOp op, 233edd9515bSthomasraoux PatternRewriter &rewriter) const override { 234edd9515bSthomasraoux auto transferReadOp = op.vector().getDefiningOp<vector::TransferReadOp>(); 235edd9515bSthomasraoux if (!transferReadOp) 236edd9515bSthomasraoux return failure(); 237edd9515bSthomasraoux if (transferReadOp.mask() || transferReadOp.hasOutOfBoundsDim()) 238edd9515bSthomasraoux return failure(); 239edd9515bSthomasraoux SmallVector<int64_t, 2> perm; 240edd9515bSthomasraoux op.getTransp(perm); 241edd9515bSthomasraoux SmallVector<unsigned, 2> permU; 242edd9515bSthomasraoux for (int64_t o : perm) 243edd9515bSthomasraoux permU.push_back(unsigned(o)); 244edd9515bSthomasraoux AffineMap permutationMap = 245edd9515bSthomasraoux AffineMap::getPermutationMap(permU, op.getContext()); 246edd9515bSthomasraoux AffineMap newMap = permutationMap.compose(transferReadOp.permutation_map()); 247edd9515bSthomasraoux rewriter.replaceOpWithNewOp<vector::TransferReadOp>( 248edd9515bSthomasraoux op, op.getType(), transferReadOp.source(), transferReadOp.indices(), 249edd9515bSthomasraoux newMap, transferReadOp.padding(), transferReadOp.mask(), 250edd9515bSthomasraoux transferReadOp.in_boundsAttr()); 251edd9515bSthomasraoux return success(); 252edd9515bSthomasraoux } 253edd9515bSthomasraoux }; 254edd9515bSthomasraoux 255edd9515bSthomasraoux } // namespace 256edd9515bSthomasraoux 257edd9515bSthomasraoux // MMA types have different layout based on how they are used in matmul ops. 2586413226dSthomasraoux // Figure the right layout to use by looking at op uses. 259edd9515bSthomasraoux // TODO: Change the GPU dialect to abstract the layout at the this level and 260edd9515bSthomasraoux // only care about it during lowering to NVVM. 2616413226dSthomasraoux template <typename OpTy> 2626413226dSthomasraoux static const char *inferFragType(OpTy op) { 263edd9515bSthomasraoux for (Operation *users : op->getUsers()) { 264edd9515bSthomasraoux auto contract = dyn_cast<vector::ContractionOp>(users); 265edd9515bSthomasraoux if (!contract) 266edd9515bSthomasraoux continue; 267edd9515bSthomasraoux if (contract.lhs() == op.getResult()) 268edd9515bSthomasraoux return "AOp"; 269edd9515bSthomasraoux if (contract.rhs() == op.getResult()) 270edd9515bSthomasraoux return "BOp"; 271edd9515bSthomasraoux } 272edd9515bSthomasraoux return "COp"; 273edd9515bSthomasraoux } 274edd9515bSthomasraoux 275edd9515bSthomasraoux static void convertTransferReadOp(vector::TransferReadOp op, 276edd9515bSthomasraoux llvm::DenseMap<Value, Value> &valueMapping) { 277edd9515bSthomasraoux assert(transferReadSupportsMMAMatrixType(op)); 278edd9515bSthomasraoux Optional<int64_t> stride = 279edd9515bSthomasraoux getMemrefConstantHorizontalStride(op.getShapedType()); 280edd9515bSthomasraoux assert(stride); 281edd9515bSthomasraoux const char *fragType = inferFragType(op); 282edd9515bSthomasraoux gpu::MMAMatrixType type = 283edd9515bSthomasraoux gpu::MMAMatrixType::get(op.getVectorType().getShape(), 284edd9515bSthomasraoux op.getVectorType().getElementType(), fragType); 285edd9515bSthomasraoux OpBuilder b(op); 286edd9515bSthomasraoux Value load = b.create<gpu::SubgroupMmaLoadMatrixOp>( 287edd9515bSthomasraoux op.getLoc(), type, op.source(), op.indices(), b.getIndexAttr(*stride)); 288edd9515bSthomasraoux valueMapping[op.getResult()] = load; 289edd9515bSthomasraoux } 290edd9515bSthomasraoux 291edd9515bSthomasraoux static void convertTransferWriteOp(vector::TransferWriteOp op, 292edd9515bSthomasraoux llvm::DenseMap<Value, Value> &valueMapping) { 293edd9515bSthomasraoux assert(transferWriteSupportsMMAMatrixType(op)); 294edd9515bSthomasraoux Optional<int64_t> stride = 295edd9515bSthomasraoux getMemrefConstantHorizontalStride(op.getShapedType()); 296edd9515bSthomasraoux assert(stride); 297edd9515bSthomasraoux OpBuilder b(op); 298edd9515bSthomasraoux Value matrix = valueMapping.find(op.vector())->second; 299edd9515bSthomasraoux b.create<gpu::SubgroupMmaStoreMatrixOp>( 300edd9515bSthomasraoux op.getLoc(), matrix, op.source(), op.indices(), b.getIndexAttr(*stride)); 301edd9515bSthomasraoux op.erase(); 302edd9515bSthomasraoux } 303edd9515bSthomasraoux 304edd9515bSthomasraoux static void convertContractOp(vector::ContractionOp op, 305edd9515bSthomasraoux llvm::DenseMap<Value, Value> &valueMapping) { 306edd9515bSthomasraoux OpBuilder b(op); 307edd9515bSthomasraoux Value opA = valueMapping.find(op.lhs())->second; 308edd9515bSthomasraoux Value opB = valueMapping.find(op.rhs())->second; 309edd9515bSthomasraoux Value opC = valueMapping.find(op.acc())->second; 310edd9515bSthomasraoux Value matmul = b.create<gpu::SubgroupMmaComputeOp>(op.getLoc(), opC.getType(), 311edd9515bSthomasraoux opA, opB, opC); 312edd9515bSthomasraoux valueMapping[op.getResult()] = matmul; 313edd9515bSthomasraoux } 314edd9515bSthomasraoux 3156413226dSthomasraoux /// Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op. 3166413226dSthomasraoux static void convertConstantOp(ConstantOp op, 3176413226dSthomasraoux llvm::DenseMap<Value, Value> &valueMapping) { 3186413226dSthomasraoux assert(constantSupportsMMAMatrixType(op)); 3196413226dSthomasraoux OpBuilder b(op); 3206413226dSthomasraoux Attribute splat = op.getValue().cast<SplatElementsAttr>().getSplatValue(); 3216413226dSthomasraoux auto scalarConstant = 3226413226dSthomasraoux b.create<ConstantOp>(op.getLoc(), splat.getType(), splat); 3236413226dSthomasraoux const char *fragType = inferFragType(op); 3246413226dSthomasraoux auto vecType = op.getType().cast<VectorType>(); 3256413226dSthomasraoux gpu::MMAMatrixType type = gpu::MMAMatrixType::get( 3266413226dSthomasraoux vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType)); 3276413226dSthomasraoux auto matrix = b.create<gpu::SubgroupMmaConstantMatrixOp>(op.getLoc(), type, 3286413226dSthomasraoux scalarConstant); 3296413226dSthomasraoux valueMapping[op.getResult()] = matrix; 3306413226dSthomasraoux } 3316413226dSthomasraoux 332*1a865592Sthomasraoux // Replace ForOp with a new ForOp with extra operands. The YieldOp is not 333*1a865592Sthomasraoux // updated and needs to be updated separatly for the loop to be correct. 334*1a865592Sthomasraoux static scf::ForOp replaceForOpWithNewSignature(OpBuilder &b, scf::ForOp loop, 335*1a865592Sthomasraoux ValueRange newIterOperands) { 336*1a865592Sthomasraoux // Create a new loop before the existing one, with the extra operands. 337*1a865592Sthomasraoux OpBuilder::InsertionGuard g(b); 338*1a865592Sthomasraoux b.setInsertionPoint(loop); 339*1a865592Sthomasraoux auto operands = llvm::to_vector<4>(loop.getIterOperands()); 340*1a865592Sthomasraoux operands.append(newIterOperands.begin(), newIterOperands.end()); 341*1a865592Sthomasraoux scf::ForOp newLoop = 342*1a865592Sthomasraoux b.create<scf::ForOp>(loop.getLoc(), loop.lowerBound(), loop.upperBound(), 343*1a865592Sthomasraoux loop.step(), operands); 344*1a865592Sthomasraoux newLoop.getBody()->erase(); 345*1a865592Sthomasraoux newLoop.getLoopBody().getBlocks().splice( 346*1a865592Sthomasraoux newLoop.getLoopBody().getBlocks().begin(), 347*1a865592Sthomasraoux loop.getLoopBody().getBlocks()); 348*1a865592Sthomasraoux for (auto operand : newIterOperands) 349*1a865592Sthomasraoux newLoop.getBody()->addArgument(operand.getType()); 350*1a865592Sthomasraoux 351*1a865592Sthomasraoux for (auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front( 352*1a865592Sthomasraoux loop.getNumResults()))) 353*1a865592Sthomasraoux std::get<0>(it).replaceAllUsesWith(std::get<1>(it)); 354*1a865592Sthomasraoux loop.erase(); 355*1a865592Sthomasraoux return newLoop; 356*1a865592Sthomasraoux } 357*1a865592Sthomasraoux 358*1a865592Sthomasraoux static void convertForOp(scf::ForOp op, 359*1a865592Sthomasraoux llvm::DenseMap<Value, Value> &valueMapping) { 360*1a865592Sthomasraoux SmallVector<Value> newOperands; 361*1a865592Sthomasraoux SmallVector<std::pair<size_t, size_t>> argMapping; 362*1a865592Sthomasraoux for (auto operand : llvm::enumerate(op.getIterOperands())) { 363*1a865592Sthomasraoux auto it = valueMapping.find(operand.value()); 364*1a865592Sthomasraoux if (it == valueMapping.end()) 365*1a865592Sthomasraoux continue; 366*1a865592Sthomasraoux argMapping.push_back(std::make_pair( 367*1a865592Sthomasraoux operand.index(), op.getNumIterOperands() + newOperands.size())); 368*1a865592Sthomasraoux newOperands.push_back(it->second); 369*1a865592Sthomasraoux } 370*1a865592Sthomasraoux OpBuilder b(op); 371*1a865592Sthomasraoux scf::ForOp newForOp = replaceForOpWithNewSignature(b, op, newOperands); 372*1a865592Sthomasraoux Block &loopBody = *newForOp.getBody(); 373*1a865592Sthomasraoux for (auto mapping : argMapping) { 374*1a865592Sthomasraoux valueMapping[newForOp.getResult(mapping.first)] = 375*1a865592Sthomasraoux newForOp.getResult(mapping.second); 376*1a865592Sthomasraoux valueMapping[loopBody.getArgument(mapping.first + 377*1a865592Sthomasraoux newForOp.getNumInductionVars())] = 378*1a865592Sthomasraoux loopBody.getArgument(mapping.second + newForOp.getNumInductionVars()); 379*1a865592Sthomasraoux } 380*1a865592Sthomasraoux } 381*1a865592Sthomasraoux 382*1a865592Sthomasraoux static void convertYieldOp(scf::YieldOp op, 383*1a865592Sthomasraoux llvm::DenseMap<Value, Value> &valueMapping) { 384*1a865592Sthomasraoux OpBuilder b(op); 385*1a865592Sthomasraoux auto loop = cast<scf::ForOp>(op->getParentOp()); 386*1a865592Sthomasraoux auto yieldOperands = llvm::to_vector<4>(op.getOperands()); 387*1a865592Sthomasraoux for (auto operand : llvm::enumerate(op.getOperands())) { 388*1a865592Sthomasraoux auto it = valueMapping.find(operand.value()); 389*1a865592Sthomasraoux if (it == valueMapping.end()) 390*1a865592Sthomasraoux continue; 391*1a865592Sthomasraoux // Replace the yield of old value with the for op argument to make it easier 392*1a865592Sthomasraoux // to remove the dead code. 393*1a865592Sthomasraoux yieldOperands[operand.index()] = loop.getIterOperands()[operand.index()]; 394*1a865592Sthomasraoux yieldOperands.push_back(it->second); 395*1a865592Sthomasraoux } 396*1a865592Sthomasraoux b.create<scf::YieldOp>(op.getLoc(), yieldOperands); 397*1a865592Sthomasraoux op.erase(); 398*1a865592Sthomasraoux } 399*1a865592Sthomasraoux 400edd9515bSthomasraoux namespace mlir { 401edd9515bSthomasraoux 402edd9515bSthomasraoux void populatePrepareVectorToMMAPatterns(RewritePatternSet &patterns) { 403edd9515bSthomasraoux patterns.add<PrepareContractToGPUMMA, CombineTransferReadOpTranspose>( 404edd9515bSthomasraoux patterns.getContext()); 405edd9515bSthomasraoux } 406edd9515bSthomasraoux 407edd9515bSthomasraoux void convertVectorToMMAOps(FuncOp funcOp) { 408edd9515bSthomasraoux SetVector<Operation *> ops = getOpToConvert(funcOp); 409edd9515bSthomasraoux llvm::DenseMap<Value, Value> valueMapping; 410edd9515bSthomasraoux for (Operation *op : ops) { 411edd9515bSthomasraoux if (auto transferRead = dyn_cast<vector::TransferReadOp>(op)) { 412edd9515bSthomasraoux convertTransferReadOp(transferRead, valueMapping); 413edd9515bSthomasraoux } else if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op)) { 414edd9515bSthomasraoux convertTransferWriteOp(transferWrite, valueMapping); 415edd9515bSthomasraoux } else if (auto contractOp = dyn_cast<vector::ContractionOp>(op)) { 416edd9515bSthomasraoux convertContractOp(contractOp, valueMapping); 4176413226dSthomasraoux } else if (auto constantOp = dyn_cast<ConstantOp>(op)) { 4186413226dSthomasraoux convertConstantOp(constantOp, valueMapping); 419*1a865592Sthomasraoux } else if (auto forOp = dyn_cast<scf::ForOp>(op)) { 420*1a865592Sthomasraoux convertForOp(forOp, valueMapping); 421*1a865592Sthomasraoux } else if (auto yiledOp = dyn_cast<scf::YieldOp>(op)) { 422*1a865592Sthomasraoux convertYieldOp(yiledOp, valueMapping); 423edd9515bSthomasraoux } 424edd9515bSthomasraoux } 425edd9515bSthomasraoux } 426edd9515bSthomasraoux 427edd9515bSthomasraoux } // namespace mlir 428edd9515bSthomasraoux namespace { 429edd9515bSthomasraoux 430edd9515bSthomasraoux struct ConvertVectorToGPUPass 431edd9515bSthomasraoux : public ConvertVectorToGPUBase<ConvertVectorToGPUPass> { 432edd9515bSthomasraoux void runOnFunction() override { 433edd9515bSthomasraoux RewritePatternSet patterns(getFunction().getContext()); 434edd9515bSthomasraoux populatePrepareVectorToMMAPatterns(patterns); 435edd9515bSthomasraoux (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns)); 436edd9515bSthomasraoux 437edd9515bSthomasraoux convertVectorToMMAOps(getFunction()); 438edd9515bSthomasraoux } 439edd9515bSthomasraoux }; 440edd9515bSthomasraoux 441edd9515bSthomasraoux } // namespace 442edd9515bSthomasraoux 443edd9515bSthomasraoux std::unique_ptr<Pass> mlir::createConvertVectorToGPUPass() { 444edd9515bSthomasraoux return std::make_unique<ConvertVectorToGPUPass>(); 445edd9515bSthomasraoux } 446