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"
19a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
20edd9515bSthomasraoux #include "mlir/Dialect/GPU/GPUDialect.h"
2166f878ceSMatthias Springer #include "mlir/Dialect/MemRef/IR/MemRef.h"
221a865592Sthomasraoux #include "mlir/Dialect/SCF/SCF.h"
23edd9515bSthomasraoux #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
24edd9515bSthomasraoux #include "mlir/Dialect/Vector/VectorOps.h"
25edd9515bSthomasraoux #include "mlir/Dialect/Vector/VectorUtils.h"
26edd9515bSthomasraoux #include "mlir/IR/Builders.h"
27edd9515bSthomasraoux #include "mlir/Pass/Pass.h"
28edd9515bSthomasraoux #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
29edd9515bSthomasraoux #include "mlir/Transforms/Passes.h"
30edd9515bSthomasraoux 
31edd9515bSthomasraoux using namespace mlir;
32edd9515bSthomasraoux 
33edd9515bSthomasraoux // Return true if the contract op can be convert to MMA matmul.
34edd9515bSthomasraoux static bool contractSupportsMMAMatrixType(vector::ContractionOp contract) {
35edd9515bSthomasraoux   if (llvm::size(contract.masks()) != 0)
36edd9515bSthomasraoux     return false;
37edd9515bSthomasraoux 
38edd9515bSthomasraoux   using MapList = ArrayRef<ArrayRef<AffineExpr>>;
39edd9515bSthomasraoux   auto infer = [](MapList m) { return AffineMap::inferFromExprList(m); };
40edd9515bSthomasraoux   AffineExpr m, n, k;
41edd9515bSthomasraoux   bindDims(contract.getContext(), m, n, k);
42edd9515bSthomasraoux   auto iteratorTypes = contract.iterator_types().getValue();
43edd9515bSthomasraoux   if (!(isParallelIterator(iteratorTypes[0]) &&
44edd9515bSthomasraoux         isParallelIterator(iteratorTypes[1]) &&
45edd9515bSthomasraoux         isReductionIterator(iteratorTypes[2])))
46edd9515bSthomasraoux     return false;
47edd9515bSthomasraoux 
48edd9515bSthomasraoux   // The contract needs to represent a matmul to be able to convert to
49edd9515bSthomasraoux   // MMAMatrix matmul.
50edd9515bSthomasraoux   if (contract.getIndexingMaps() != infer({{m, k}, {k, n}, {m, n}}))
51edd9515bSthomasraoux     return false;
52edd9515bSthomasraoux 
53edd9515bSthomasraoux   // Check that the size matches what is natively supported.
54edd9515bSthomasraoux   VectorType lhsType = contract.lhs().getType().cast<VectorType>();
55edd9515bSthomasraoux   VectorType rhsType = contract.rhs().getType().cast<VectorType>();
56edd9515bSthomasraoux   VectorType accType = contract.acc().getType().cast<VectorType>();
57edd9515bSthomasraoux 
58edd9515bSthomasraoux   std::tuple<int, int, int> dim(lhsType.getDimSize(0), rhsType.getDimSize(1),
59edd9515bSthomasraoux                                 lhsType.getDimSize(1));
60edd9515bSthomasraoux   if (lhsType.getElementType().isInteger(8) &&
61edd9515bSthomasraoux       rhsType.getElementType().isInteger(8) &&
62edd9515bSthomasraoux       accType.getElementType().isInteger(32) &&
63edd9515bSthomasraoux       (dim == std::make_tuple(8, 8, 32) || dim == std::make_tuple(16, 16, 32) ||
64edd9515bSthomasraoux        dim == std::make_tuple(16, 8, 32)))
65edd9515bSthomasraoux     return true;
66edd9515bSthomasraoux 
67edd9515bSthomasraoux   if (lhsType.getElementType().isF16() && rhsType.getElementType().isF16() &&
68edd9515bSthomasraoux       (accType.getElementType().isF16() || accType.getElementType().isF32()) &&
69edd9515bSthomasraoux       (dim == std::make_tuple(8, 8, 16) || dim == std::make_tuple(16, 16, 16) ||
70edd9515bSthomasraoux        dim == std::make_tuple(16, 8, 16)))
71edd9515bSthomasraoux     return true;
72edd9515bSthomasraoux   return false;
73edd9515bSthomasraoux }
74edd9515bSthomasraoux 
75edd9515bSthomasraoux // Return the stide for the dimension 0 of |type| if it is a memref and has a
76edd9515bSthomasraoux // constant stride.
77edd9515bSthomasraoux static llvm::Optional<int64_t>
78edd9515bSthomasraoux getMemrefConstantHorizontalStride(ShapedType type) {
79edd9515bSthomasraoux   auto memrefType = type.dyn_cast<MemRefType>();
80edd9515bSthomasraoux   if (!memrefType)
81edd9515bSthomasraoux     return false;
82edd9515bSthomasraoux   int64_t offset = 0;
83edd9515bSthomasraoux   SmallVector<int64_t, 2> strides;
84edd9515bSthomasraoux   if (failed(getStridesAndOffset(memrefType, strides, offset)))
85edd9515bSthomasraoux     return llvm::None;
86edd9515bSthomasraoux   if (strides[0] == ShapedType::kDynamicStrideOrOffset)
87edd9515bSthomasraoux     return llvm::None;
88edd9515bSthomasraoux   return strides[0];
89edd9515bSthomasraoux }
90edd9515bSthomasraoux 
91edd9515bSthomasraoux // Return true if the transfer op can be converted to a MMA matrix load.
92edd9515bSthomasraoux static bool transferReadSupportsMMAMatrixType(vector::TransferReadOp readOp) {
93edd9515bSthomasraoux   if (readOp.mask() || readOp.hasOutOfBoundsDim() ||
94edd9515bSthomasraoux       readOp.getVectorType().getRank() != 2)
95edd9515bSthomasraoux     return false;
96edd9515bSthomasraoux   if (!getMemrefConstantHorizontalStride(readOp.getShapedType()))
97edd9515bSthomasraoux     return false;
98edd9515bSthomasraoux   // TODO: Support transpose once it is added to GPU dialect ops.
99edd9515bSthomasraoux   if (!readOp.permutation_map().isMinorIdentity())
100edd9515bSthomasraoux     return false;
101edd9515bSthomasraoux   return true;
102edd9515bSthomasraoux }
103edd9515bSthomasraoux 
104edd9515bSthomasraoux // Return true if the transfer op can be converted to a MMA matrix store.
105edd9515bSthomasraoux static bool
106edd9515bSthomasraoux transferWriteSupportsMMAMatrixType(vector::TransferWriteOp writeOp) {
107edd9515bSthomasraoux   if (writeOp.mask() || writeOp.hasOutOfBoundsDim() ||
108edd9515bSthomasraoux       writeOp.getVectorType().getRank() != 2)
109edd9515bSthomasraoux     return false;
110edd9515bSthomasraoux   if (!getMemrefConstantHorizontalStride(writeOp.getShapedType()))
111edd9515bSthomasraoux     return false;
112edd9515bSthomasraoux   // TODO: Support transpose once it is added to GPU dialect ops.
113edd9515bSthomasraoux   if (!writeOp.permutation_map().isMinorIdentity())
114edd9515bSthomasraoux     return false;
115edd9515bSthomasraoux   return true;
116edd9515bSthomasraoux }
117edd9515bSthomasraoux 
1186413226dSthomasraoux /// Return true if the constant is a splat to a 2D vector so that it can be
1196413226dSthomasraoux /// converted to a MMA constant matrix op.
120a54f4eaeSMogball static bool constantSupportsMMAMatrixType(arith::ConstantOp constantOp) {
1216413226dSthomasraoux   auto vecType = constantOp.getType().dyn_cast<VectorType>();
1226413226dSthomasraoux   if (!vecType || vecType.getRank() != 2)
1236413226dSthomasraoux     return false;
124cfb72fd3SJacques Pienaar   return constantOp.getValue().isa<SplatElementsAttr>();
1256413226dSthomasraoux }
1266413226dSthomasraoux 
12743928419Sthomasraoux /// Return true if this is a broadcast from scalar to a 2D vector.
12843928419Sthomasraoux static bool broadcastSupportsMMAMatrixType(vector::BroadcastOp broadcastOp) {
12943928419Sthomasraoux   return broadcastOp.getVectorType().getRank() == 2 &&
13043928419Sthomasraoux          broadcastOp.source().getType().isa<FloatType>();
13143928419Sthomasraoux }
13243928419Sthomasraoux 
133*7fbb0678Sthomasraoux /// Return the MMA elementwise enum associated with `op` if it is supported.
134*7fbb0678Sthomasraoux /// Return `llvm::None` otherwise.
135*7fbb0678Sthomasraoux static llvm::Optional<gpu::MMAElementwiseOp>
136*7fbb0678Sthomasraoux convertElementwiseOpToMMA(Operation *op) {
137*7fbb0678Sthomasraoux   if (isa<arith::AddFOp>(op))
138*7fbb0678Sthomasraoux     return gpu::MMAElementwiseOp::ADDF;
139*7fbb0678Sthomasraoux   if (isa<arith::MulFOp>(op))
140*7fbb0678Sthomasraoux     return gpu::MMAElementwiseOp::MULF;
141*7fbb0678Sthomasraoux   if (isa<MaxFOp>(op))
142*7fbb0678Sthomasraoux     return gpu::MMAElementwiseOp::MAXF;
143*7fbb0678Sthomasraoux   if (isa<MinFOp>(op))
144*7fbb0678Sthomasraoux     return gpu::MMAElementwiseOp::MINF;
145*7fbb0678Sthomasraoux   return llvm::None;
146*7fbb0678Sthomasraoux }
147*7fbb0678Sthomasraoux 
148*7fbb0678Sthomasraoux /// Return true if the op is supported as elementwise op on MMAMatrix type.
149*7fbb0678Sthomasraoux static bool elementwiseSupportsMMAMatrixType(Operation *op) {
150*7fbb0678Sthomasraoux   return convertElementwiseOpToMMA(op).hasValue();
151*7fbb0678Sthomasraoux }
152*7fbb0678Sthomasraoux 
153edd9515bSthomasraoux static bool supportsMMaMatrixType(Operation *op) {
1541a865592Sthomasraoux   if (isa<scf::ForOp, scf::YieldOp>(op))
1551a865592Sthomasraoux     return true;
156edd9515bSthomasraoux   if (auto transferRead = dyn_cast<vector::TransferReadOp>(op))
157edd9515bSthomasraoux     return transferReadSupportsMMAMatrixType(transferRead);
158edd9515bSthomasraoux   if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op))
159edd9515bSthomasraoux     return transferWriteSupportsMMAMatrixType(transferWrite);
160edd9515bSthomasraoux   if (auto contract = dyn_cast<vector::ContractionOp>(op))
161edd9515bSthomasraoux     return contractSupportsMMAMatrixType(contract);
162a54f4eaeSMogball   if (auto constant = dyn_cast<arith::ConstantOp>(op))
1636413226dSthomasraoux     return constantSupportsMMAMatrixType(constant);
16443928419Sthomasraoux   if (auto broadcast = dyn_cast<vector::BroadcastOp>(op))
16543928419Sthomasraoux     return broadcastSupportsMMAMatrixType(broadcast);
166*7fbb0678Sthomasraoux   return elementwiseSupportsMMAMatrixType(op);
167edd9515bSthomasraoux }
168edd9515bSthomasraoux 
169edd9515bSthomasraoux // Analyze slice of operations based on convert op to figure out if the whole
170edd9515bSthomasraoux // slice can be converted to MMA operations.
171edd9515bSthomasraoux static SetVector<Operation *> getOpToConvert(mlir::Operation *op) {
172edd9515bSthomasraoux   auto hasVectorDest = [](Operation *op) {
17343928419Sthomasraoux     return llvm::any_of(op->getResultTypes(),
17443928419Sthomasraoux                         [](Type t) { return t.isa<VectorType>(); });
17543928419Sthomasraoux   };
17643928419Sthomasraoux   auto hasVectorSrc = [](Operation *op) {
17743928419Sthomasraoux     return llvm::any_of(op->getOperandTypes(),
178edd9515bSthomasraoux                         [](Type t) { return t.isa<VectorType>(); });
179edd9515bSthomasraoux   };
180edd9515bSthomasraoux   SetVector<Operation *> opToConvert;
181edd9515bSthomasraoux   op->walk([&](vector::ContractionOp contract) {
182edd9515bSthomasraoux     if (opToConvert.contains(contract.getOperation()))
183edd9515bSthomasraoux       return;
184edd9515bSthomasraoux     SetVector<Operation *> dependentOps =
18543928419Sthomasraoux         getSlice(contract, hasVectorDest, hasVectorSrc);
186edd9515bSthomasraoux     // If any instruction cannot use MMA matrix type drop the whole
187edd9515bSthomasraoux     // chaine. MMA matrix are stored in an opaque type so they cannot be used
188edd9515bSthomasraoux     // by all operations.
189edd9515bSthomasraoux     if (llvm::any_of(dependentOps,
190edd9515bSthomasraoux                      [](Operation *op) { return !supportsMMaMatrixType(op); }))
191edd9515bSthomasraoux       return;
192edd9515bSthomasraoux     opToConvert.insert(dependentOps.begin(), dependentOps.end());
193edd9515bSthomasraoux   });
194edd9515bSthomasraoux   return opToConvert;
195edd9515bSthomasraoux }
196edd9515bSthomasraoux 
197edd9515bSthomasraoux namespace {
198edd9515bSthomasraoux // Transform contract into (m, k)x(k, n)x(m, n) form so that it can be converted
199edd9515bSthomasraoux // to MMA matmul.
200edd9515bSthomasraoux struct PrepareContractToGPUMMA
201edd9515bSthomasraoux     : public OpRewritePattern<vector::ContractionOp> {
202edd9515bSthomasraoux   using OpRewritePattern<vector::ContractionOp>::OpRewritePattern;
203edd9515bSthomasraoux 
204edd9515bSthomasraoux   LogicalResult matchAndRewrite(vector::ContractionOp op,
205edd9515bSthomasraoux                                 PatternRewriter &rewriter) const override {
206edd9515bSthomasraoux     Location loc = op.getLoc();
207edd9515bSthomasraoux     Value lhs = op.lhs(), rhs = op.rhs(), res = op.acc();
208edd9515bSthomasraoux 
209edd9515bSthomasraoux     // Set up the parallel/reduction structure in right form.
210edd9515bSthomasraoux     using MapList = ArrayRef<ArrayRef<AffineExpr>>;
211edd9515bSthomasraoux     auto infer = [](MapList m) { return AffineMap::inferFromExprList(m); };
212edd9515bSthomasraoux     AffineExpr m, n, k;
213edd9515bSthomasraoux     bindDims(rewriter.getContext(), m, n, k);
214edd9515bSthomasraoux     static constexpr std::array<int64_t, 2> perm = {1, 0};
215edd9515bSthomasraoux     auto iteratorTypes = op.iterator_types().getValue();
216edd9515bSthomasraoux     SmallVector<AffineMap, 4> maps = op.getIndexingMaps();
217edd9515bSthomasraoux     if (!(isParallelIterator(iteratorTypes[0]) &&
218edd9515bSthomasraoux           isParallelIterator(iteratorTypes[1]) &&
219edd9515bSthomasraoux           isReductionIterator(iteratorTypes[2])))
220edd9515bSthomasraoux       return failure();
221edd9515bSthomasraoux     //
222edd9515bSthomasraoux     // Two outer parallel, one inner reduction (matmat flavor).
223edd9515bSthomasraoux     //
224edd9515bSthomasraoux     if (maps == infer({{m, k}, {k, n}, {m, n}})) {
225edd9515bSthomasraoux       // This is the classical row-major matmul, nothing to do.
226edd9515bSthomasraoux       return failure();
227edd9515bSthomasraoux     }
228edd9515bSthomasraoux     if (maps == infer({{m, k}, {n, k}, {m, n}})) {
229edd9515bSthomasraoux       rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm);
230edd9515bSthomasraoux     } else if (maps == infer({{k, m}, {k, n}, {m, n}})) {
231edd9515bSthomasraoux       lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm);
232edd9515bSthomasraoux     } else if (maps == infer({{k, m}, {n, k}, {m, n}})) {
233edd9515bSthomasraoux       rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm);
234edd9515bSthomasraoux       lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm);
235edd9515bSthomasraoux     } else if (maps == infer({{m, k}, {k, n}, {n, m}})) {
236edd9515bSthomasraoux       std::swap(rhs, lhs);
237edd9515bSthomasraoux       rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm);
238edd9515bSthomasraoux       lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm);
239edd9515bSthomasraoux     } else if (maps == infer({{m, k}, {n, k}, {n, m}})) {
240edd9515bSthomasraoux       std::swap(rhs, lhs);
241edd9515bSthomasraoux       rhs = rewriter.create<vector::TransposeOp>(loc, rhs, perm);
242edd9515bSthomasraoux     } else if (maps == infer({{k, m}, {k, n}, {n, m}})) {
243edd9515bSthomasraoux       std::swap(lhs, rhs);
244edd9515bSthomasraoux       lhs = rewriter.create<vector::TransposeOp>(loc, lhs, perm);
245edd9515bSthomasraoux     } else if (maps == infer({{k, m}, {n, k}, {n, m}})) {
246edd9515bSthomasraoux       std::swap(lhs, rhs);
247edd9515bSthomasraoux     } else {
248edd9515bSthomasraoux       return failure();
249edd9515bSthomasraoux     }
250edd9515bSthomasraoux     rewriter.replaceOpWithNewOp<vector::ContractionOp>(
251edd9515bSthomasraoux         op, lhs, rhs, res,
252edd9515bSthomasraoux         rewriter.getAffineMapArrayAttr(infer({{m, k}, {k, n}, {m, n}})),
253edd9515bSthomasraoux         op.iterator_types());
254edd9515bSthomasraoux     return success();
255edd9515bSthomasraoux   }
256edd9515bSthomasraoux };
257edd9515bSthomasraoux 
258edd9515bSthomasraoux // Merge transpose op into the transfer read op. Transpose are not supported on
259edd9515bSthomasraoux // MMA types but MMA load can transpose the matrix when loading.
260edd9515bSthomasraoux struct CombineTransferReadOpTranspose final
261edd9515bSthomasraoux     : public OpRewritePattern<vector::TransposeOp> {
262edd9515bSthomasraoux   using OpRewritePattern<vector::TransposeOp>::OpRewritePattern;
263edd9515bSthomasraoux 
264edd9515bSthomasraoux   LogicalResult matchAndRewrite(vector::TransposeOp op,
265edd9515bSthomasraoux                                 PatternRewriter &rewriter) const override {
266edd9515bSthomasraoux     auto transferReadOp = op.vector().getDefiningOp<vector::TransferReadOp>();
267edd9515bSthomasraoux     if (!transferReadOp)
268edd9515bSthomasraoux       return failure();
269edd9515bSthomasraoux     if (transferReadOp.mask() || transferReadOp.hasOutOfBoundsDim())
270edd9515bSthomasraoux       return failure();
271edd9515bSthomasraoux     SmallVector<int64_t, 2> perm;
272edd9515bSthomasraoux     op.getTransp(perm);
273edd9515bSthomasraoux     SmallVector<unsigned, 2> permU;
274edd9515bSthomasraoux     for (int64_t o : perm)
275edd9515bSthomasraoux       permU.push_back(unsigned(o));
276edd9515bSthomasraoux     AffineMap permutationMap =
277edd9515bSthomasraoux         AffineMap::getPermutationMap(permU, op.getContext());
278edd9515bSthomasraoux     AffineMap newMap = permutationMap.compose(transferReadOp.permutation_map());
279edd9515bSthomasraoux     rewriter.replaceOpWithNewOp<vector::TransferReadOp>(
280edd9515bSthomasraoux         op, op.getType(), transferReadOp.source(), transferReadOp.indices(),
281edd9515bSthomasraoux         newMap, transferReadOp.padding(), transferReadOp.mask(),
282edd9515bSthomasraoux         transferReadOp.in_boundsAttr());
283edd9515bSthomasraoux     return success();
284edd9515bSthomasraoux   }
285edd9515bSthomasraoux };
286edd9515bSthomasraoux 
287edd9515bSthomasraoux } // namespace
288edd9515bSthomasraoux 
289edd9515bSthomasraoux // MMA types have different layout based on how they are used in matmul ops.
2906413226dSthomasraoux // Figure the right layout to use by looking at op uses.
291edd9515bSthomasraoux // TODO: Change the GPU dialect to abstract the layout at the this level and
292edd9515bSthomasraoux // only care about it during lowering to NVVM.
2936413226dSthomasraoux template <typename OpTy>
2946413226dSthomasraoux static const char *inferFragType(OpTy op) {
295edd9515bSthomasraoux   for (Operation *users : op->getUsers()) {
296edd9515bSthomasraoux     auto contract = dyn_cast<vector::ContractionOp>(users);
297edd9515bSthomasraoux     if (!contract)
298edd9515bSthomasraoux       continue;
299edd9515bSthomasraoux     if (contract.lhs() == op.getResult())
300edd9515bSthomasraoux       return "AOp";
301edd9515bSthomasraoux     if (contract.rhs() == op.getResult())
302edd9515bSthomasraoux       return "BOp";
303edd9515bSthomasraoux   }
304edd9515bSthomasraoux   return "COp";
305edd9515bSthomasraoux }
306edd9515bSthomasraoux 
307edd9515bSthomasraoux static void convertTransferReadOp(vector::TransferReadOp op,
308edd9515bSthomasraoux                                   llvm::DenseMap<Value, Value> &valueMapping) {
309edd9515bSthomasraoux   assert(transferReadSupportsMMAMatrixType(op));
310edd9515bSthomasraoux   Optional<int64_t> stride =
311edd9515bSthomasraoux       getMemrefConstantHorizontalStride(op.getShapedType());
312edd9515bSthomasraoux   assert(stride);
313edd9515bSthomasraoux   const char *fragType = inferFragType(op);
314edd9515bSthomasraoux   gpu::MMAMatrixType type =
315edd9515bSthomasraoux       gpu::MMAMatrixType::get(op.getVectorType().getShape(),
316edd9515bSthomasraoux                               op.getVectorType().getElementType(), fragType);
317edd9515bSthomasraoux   OpBuilder b(op);
318edd9515bSthomasraoux   Value load = b.create<gpu::SubgroupMmaLoadMatrixOp>(
319edd9515bSthomasraoux       op.getLoc(), type, op.source(), op.indices(), b.getIndexAttr(*stride));
320edd9515bSthomasraoux   valueMapping[op.getResult()] = load;
321edd9515bSthomasraoux }
322edd9515bSthomasraoux 
323edd9515bSthomasraoux static void convertTransferWriteOp(vector::TransferWriteOp op,
324edd9515bSthomasraoux                                    llvm::DenseMap<Value, Value> &valueMapping) {
325edd9515bSthomasraoux   assert(transferWriteSupportsMMAMatrixType(op));
326edd9515bSthomasraoux   Optional<int64_t> stride =
327edd9515bSthomasraoux       getMemrefConstantHorizontalStride(op.getShapedType());
328edd9515bSthomasraoux   assert(stride);
329edd9515bSthomasraoux   OpBuilder b(op);
330edd9515bSthomasraoux   Value matrix = valueMapping.find(op.vector())->second;
331edd9515bSthomasraoux   b.create<gpu::SubgroupMmaStoreMatrixOp>(
332edd9515bSthomasraoux       op.getLoc(), matrix, op.source(), op.indices(), b.getIndexAttr(*stride));
333edd9515bSthomasraoux   op.erase();
334edd9515bSthomasraoux }
335edd9515bSthomasraoux 
336edd9515bSthomasraoux static void convertContractOp(vector::ContractionOp op,
337edd9515bSthomasraoux                               llvm::DenseMap<Value, Value> &valueMapping) {
338edd9515bSthomasraoux   OpBuilder b(op);
339edd9515bSthomasraoux   Value opA = valueMapping.find(op.lhs())->second;
340edd9515bSthomasraoux   Value opB = valueMapping.find(op.rhs())->second;
341edd9515bSthomasraoux   Value opC = valueMapping.find(op.acc())->second;
342edd9515bSthomasraoux   Value matmul = b.create<gpu::SubgroupMmaComputeOp>(op.getLoc(), opC.getType(),
343edd9515bSthomasraoux                                                      opA, opB, opC);
344edd9515bSthomasraoux   valueMapping[op.getResult()] = matmul;
345edd9515bSthomasraoux }
346edd9515bSthomasraoux 
3476413226dSthomasraoux /// Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op.
348a54f4eaeSMogball static void convertConstantOp(arith::ConstantOp op,
3496413226dSthomasraoux                               llvm::DenseMap<Value, Value> &valueMapping) {
3506413226dSthomasraoux   assert(constantSupportsMMAMatrixType(op));
3516413226dSthomasraoux   OpBuilder b(op);
352cfb72fd3SJacques Pienaar   Attribute splat = op.getValue().cast<SplatElementsAttr>().getSplatValue();
3536413226dSthomasraoux   auto scalarConstant =
354a54f4eaeSMogball       b.create<arith::ConstantOp>(op.getLoc(), splat.getType(), splat);
3556413226dSthomasraoux   const char *fragType = inferFragType(op);
3566413226dSthomasraoux   auto vecType = op.getType().cast<VectorType>();
3576413226dSthomasraoux   gpu::MMAMatrixType type = gpu::MMAMatrixType::get(
3586413226dSthomasraoux       vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType));
3596413226dSthomasraoux   auto matrix = b.create<gpu::SubgroupMmaConstantMatrixOp>(op.getLoc(), type,
3606413226dSthomasraoux                                                            scalarConstant);
3616413226dSthomasraoux   valueMapping[op.getResult()] = matrix;
3626413226dSthomasraoux }
3636413226dSthomasraoux 
36443928419Sthomasraoux /// Convert a vector.broadcast from scalar to a SubgroupMmaConstantMatrix op.
36543928419Sthomasraoux static void convertBroadcastOp(vector::BroadcastOp op,
36643928419Sthomasraoux                                llvm::DenseMap<Value, Value> &valueMapping) {
36743928419Sthomasraoux   assert(broadcastSupportsMMAMatrixType(op));
36843928419Sthomasraoux   OpBuilder b(op);
36943928419Sthomasraoux   const char *fragType = inferFragType(op);
37043928419Sthomasraoux   auto vecType = op.getVectorType();
37143928419Sthomasraoux   gpu::MMAMatrixType type = gpu::MMAMatrixType::get(
37243928419Sthomasraoux       vecType.getShape(), vecType.getElementType(), llvm::StringRef(fragType));
37343928419Sthomasraoux   auto matrix = b.create<gpu::SubgroupMmaConstantMatrixOp>(op.getLoc(), type,
37443928419Sthomasraoux                                                            op.source());
37543928419Sthomasraoux   valueMapping[op.getResult()] = matrix;
37643928419Sthomasraoux }
37743928419Sthomasraoux 
3781a865592Sthomasraoux // Replace ForOp with a new ForOp with extra operands. The YieldOp is not
3791a865592Sthomasraoux // updated and needs to be updated separatly for the loop to be correct.
3801a865592Sthomasraoux static scf::ForOp replaceForOpWithNewSignature(OpBuilder &b, scf::ForOp loop,
3811a865592Sthomasraoux                                                ValueRange newIterOperands) {
3821a865592Sthomasraoux   // Create a new loop before the existing one, with the extra operands.
3831a865592Sthomasraoux   OpBuilder::InsertionGuard g(b);
3841a865592Sthomasraoux   b.setInsertionPoint(loop);
3851a865592Sthomasraoux   auto operands = llvm::to_vector<4>(loop.getIterOperands());
3861a865592Sthomasraoux   operands.append(newIterOperands.begin(), newIterOperands.end());
3871a865592Sthomasraoux   scf::ForOp newLoop =
3881a865592Sthomasraoux       b.create<scf::ForOp>(loop.getLoc(), loop.lowerBound(), loop.upperBound(),
3891a865592Sthomasraoux                            loop.step(), operands);
3901a865592Sthomasraoux   newLoop.getBody()->erase();
3911a865592Sthomasraoux   newLoop.getLoopBody().getBlocks().splice(
3921a865592Sthomasraoux       newLoop.getLoopBody().getBlocks().begin(),
3931a865592Sthomasraoux       loop.getLoopBody().getBlocks());
3941a865592Sthomasraoux   for (auto operand : newIterOperands)
3951a865592Sthomasraoux     newLoop.getBody()->addArgument(operand.getType());
3961a865592Sthomasraoux 
3971a865592Sthomasraoux   for (auto it : llvm::zip(loop.getResults(), newLoop.getResults().take_front(
3981a865592Sthomasraoux                                                   loop.getNumResults())))
3991a865592Sthomasraoux     std::get<0>(it).replaceAllUsesWith(std::get<1>(it));
4001a865592Sthomasraoux   loop.erase();
4011a865592Sthomasraoux   return newLoop;
4021a865592Sthomasraoux }
4031a865592Sthomasraoux 
4041a865592Sthomasraoux static void convertForOp(scf::ForOp op,
4051a865592Sthomasraoux                          llvm::DenseMap<Value, Value> &valueMapping) {
4061a865592Sthomasraoux   SmallVector<Value> newOperands;
4071a865592Sthomasraoux   SmallVector<std::pair<size_t, size_t>> argMapping;
4081a865592Sthomasraoux   for (auto operand : llvm::enumerate(op.getIterOperands())) {
4091a865592Sthomasraoux     auto it = valueMapping.find(operand.value());
4101a865592Sthomasraoux     if (it == valueMapping.end())
4111a865592Sthomasraoux       continue;
4121a865592Sthomasraoux     argMapping.push_back(std::make_pair(
4131a865592Sthomasraoux         operand.index(), op.getNumIterOperands() + newOperands.size()));
4141a865592Sthomasraoux     newOperands.push_back(it->second);
4151a865592Sthomasraoux   }
4161a865592Sthomasraoux   OpBuilder b(op);
4171a865592Sthomasraoux   scf::ForOp newForOp = replaceForOpWithNewSignature(b, op, newOperands);
4181a865592Sthomasraoux   Block &loopBody = *newForOp.getBody();
4191a865592Sthomasraoux   for (auto mapping : argMapping) {
4201a865592Sthomasraoux     valueMapping[newForOp.getResult(mapping.first)] =
4211a865592Sthomasraoux         newForOp.getResult(mapping.second);
4221a865592Sthomasraoux     valueMapping[loopBody.getArgument(mapping.first +
4231a865592Sthomasraoux                                       newForOp.getNumInductionVars())] =
4241a865592Sthomasraoux         loopBody.getArgument(mapping.second + newForOp.getNumInductionVars());
4251a865592Sthomasraoux   }
4261a865592Sthomasraoux }
4271a865592Sthomasraoux 
4281a865592Sthomasraoux static void convertYieldOp(scf::YieldOp op,
4291a865592Sthomasraoux                            llvm::DenseMap<Value, Value> &valueMapping) {
4301a865592Sthomasraoux   OpBuilder b(op);
4311a865592Sthomasraoux   auto loop = cast<scf::ForOp>(op->getParentOp());
4321a865592Sthomasraoux   auto yieldOperands = llvm::to_vector<4>(op.getOperands());
4331a865592Sthomasraoux   for (auto operand : llvm::enumerate(op.getOperands())) {
4341a865592Sthomasraoux     auto it = valueMapping.find(operand.value());
4351a865592Sthomasraoux     if (it == valueMapping.end())
4361a865592Sthomasraoux       continue;
4371a865592Sthomasraoux     // Replace the yield of old value with the for op argument to make it easier
4381a865592Sthomasraoux     // to remove the dead code.
4391a865592Sthomasraoux     yieldOperands[operand.index()] = loop.getIterOperands()[operand.index()];
4401a865592Sthomasraoux     yieldOperands.push_back(it->second);
4411a865592Sthomasraoux   }
4421a865592Sthomasraoux   b.create<scf::YieldOp>(op.getLoc(), yieldOperands);
4431a865592Sthomasraoux   op.erase();
4441a865592Sthomasraoux }
4451a865592Sthomasraoux 
446*7fbb0678Sthomasraoux /// Convert an elementwise op to the equivalent elementwise op on MMA matrix.
447*7fbb0678Sthomasraoux static void convertElementwiseOp(Operation *op, gpu::MMAElementwiseOp opType,
448*7fbb0678Sthomasraoux                                  llvm::DenseMap<Value, Value> &valueMapping) {
449*7fbb0678Sthomasraoux   OpBuilder b(op);
450*7fbb0678Sthomasraoux   SmallVector<Value> matrixOperands;
451*7fbb0678Sthomasraoux   for (Value operand : op->getOperands())
452*7fbb0678Sthomasraoux     matrixOperands.push_back(valueMapping.find(operand)->second);
453*7fbb0678Sthomasraoux   Value newOp = b.create<gpu::SubgroupMmaElementwiseOp>(
454*7fbb0678Sthomasraoux       op->getLoc(), matrixOperands[0].getType(), matrixOperands, opType);
455*7fbb0678Sthomasraoux   valueMapping[op->getResult(0)] = newOp;
456*7fbb0678Sthomasraoux }
457*7fbb0678Sthomasraoux 
458edd9515bSthomasraoux namespace mlir {
459edd9515bSthomasraoux 
460edd9515bSthomasraoux void populatePrepareVectorToMMAPatterns(RewritePatternSet &patterns) {
461edd9515bSthomasraoux   patterns.add<PrepareContractToGPUMMA, CombineTransferReadOpTranspose>(
462edd9515bSthomasraoux       patterns.getContext());
463edd9515bSthomasraoux }
464edd9515bSthomasraoux 
465edd9515bSthomasraoux void convertVectorToMMAOps(FuncOp funcOp) {
466edd9515bSthomasraoux   SetVector<Operation *> ops = getOpToConvert(funcOp);
467edd9515bSthomasraoux   llvm::DenseMap<Value, Value> valueMapping;
468edd9515bSthomasraoux   for (Operation *op : ops) {
469edd9515bSthomasraoux     if (auto transferRead = dyn_cast<vector::TransferReadOp>(op)) {
470edd9515bSthomasraoux       convertTransferReadOp(transferRead, valueMapping);
471edd9515bSthomasraoux     } else if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op)) {
472edd9515bSthomasraoux       convertTransferWriteOp(transferWrite, valueMapping);
473edd9515bSthomasraoux     } else if (auto contractOp = dyn_cast<vector::ContractionOp>(op)) {
474edd9515bSthomasraoux       convertContractOp(contractOp, valueMapping);
475a54f4eaeSMogball     } else if (auto constantOp = dyn_cast<arith::ConstantOp>(op)) {
4766413226dSthomasraoux       convertConstantOp(constantOp, valueMapping);
47743928419Sthomasraoux     } else if (auto broadcastOp = dyn_cast<vector::BroadcastOp>(op)) {
47843928419Sthomasraoux       convertBroadcastOp(broadcastOp, valueMapping);
4791a865592Sthomasraoux     } else if (auto forOp = dyn_cast<scf::ForOp>(op)) {
4801a865592Sthomasraoux       convertForOp(forOp, valueMapping);
4811a865592Sthomasraoux     } else if (auto yiledOp = dyn_cast<scf::YieldOp>(op)) {
4821a865592Sthomasraoux       convertYieldOp(yiledOp, valueMapping);
483*7fbb0678Sthomasraoux     } else if (auto elementwiseType = convertElementwiseOpToMMA(op)) {
484*7fbb0678Sthomasraoux       convertElementwiseOp(op, *elementwiseType, valueMapping);
485edd9515bSthomasraoux     }
486edd9515bSthomasraoux   }
487edd9515bSthomasraoux }
488edd9515bSthomasraoux 
489edd9515bSthomasraoux } // namespace mlir
490edd9515bSthomasraoux namespace {
491edd9515bSthomasraoux 
492edd9515bSthomasraoux struct ConvertVectorToGPUPass
493edd9515bSthomasraoux     : public ConvertVectorToGPUBase<ConvertVectorToGPUPass> {
494edd9515bSthomasraoux   void runOnFunction() override {
495edd9515bSthomasraoux     RewritePatternSet patterns(getFunction().getContext());
496edd9515bSthomasraoux     populatePrepareVectorToMMAPatterns(patterns);
497edd9515bSthomasraoux     (void)applyPatternsAndFoldGreedily(getFunction(), std::move(patterns));
498edd9515bSthomasraoux 
499edd9515bSthomasraoux     convertVectorToMMAOps(getFunction());
500edd9515bSthomasraoux   }
501edd9515bSthomasraoux };
502edd9515bSthomasraoux 
503edd9515bSthomasraoux } // namespace
504edd9515bSthomasraoux 
505edd9515bSthomasraoux std::unique_ptr<Pass> mlir::createConvertVectorToGPUPass() {
506edd9515bSthomasraoux   return std::make_unique<ConvertVectorToGPUPass>();
507edd9515bSthomasraoux }
508