MLIR 24.0.0git
VectorToNVGPU.cpp
Go to the documentation of this file.
1//===- VectorToNVGPU.cpp - Convert vector to NVGPU dialect ----------*- C++
2//-*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements lowering of vector operations to NVGPU dialect ops.
11//
12//===----------------------------------------------------------------------===//
13
15
29#include "mlir/IR/Builders.h"
30#include "mlir/IR/Region.h"
31#include "mlir/Pass/Pass.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/TypeSwitch.h"
35#include "llvm/Support/DebugLog.h"
36
37#define DEBUG_TYPE "vector-to-nvgpu"
38
39namespace mlir {
40#define GEN_PASS_DEF_CONVERTVECTORTONVGPUPASS
41#include "mlir/Conversion/Passes.h.inc"
42} // namespace mlir
43
44using namespace mlir;
45
46/// For a vector TransferOpType `xferOp`, an empty `indices` vector, and an
47/// AffineMap representing offsets to apply to indices, the function fills
48/// `indices` with the original indices plus the offsets. The offsets are
49/// applied by taking into account the permutation map of the transfer op. If
50/// the `offsetMap` has dimension placeholders, those should be provided in
51/// `dimValues`.
52template <typename TransferOpType>
53static void getXferIndices(RewriterBase &rewriter, TransferOpType xferOp,
54 AffineMap offsetMap, ArrayRef<Value> dimValues,
56 indices.append(xferOp.getIndices().begin(), xferOp.getIndices().end());
57 Location loc = xferOp.getLoc();
58 unsigned offsetsIdx = 0;
59 for (auto expr : xferOp.getPermutationMap().getResults()) {
60 if (auto dim = dyn_cast<AffineDimExpr>(expr)) {
61 Value prevIdx = indices[dim.getPosition()];
62 SmallVector<OpFoldResult, 3> dims(dimValues);
63 dims.push_back(prevIdx);
64 AffineExpr d0 = rewriter.getAffineDimExpr(offsetMap.getNumDims());
65 indices[dim.getPosition()] = affine::makeComposedAffineApply(
66 rewriter, loc, d0 + offsetMap.getResult(offsetsIdx++), dims);
67 continue;
68 }
69 }
70}
71
72// Return true if the contract op can be convert to MMA matmul.
73static bool contractSupportsMMAMatrixType(vector::ContractionOp contract) {
74 // nvgpu.mma.sync computes C += A * B, so only the `add` kind matches.
75 if (!contract.isAddKind())
76 return false;
77
78 using MapList = ArrayRef<ArrayRef<AffineExpr>>;
79 auto infer = [&](MapList m) {
80 return AffineMap::inferFromExprList(m, contract.getContext());
81 };
82 AffineExpr m, n, k;
83 bindDims(contract.getContext(), m, n, k);
84 auto iteratorTypes = contract.getIteratorTypes().getValue();
85 if (!(vector::isParallelIterator(iteratorTypes[0]) &&
86 vector::isParallelIterator(iteratorTypes[1]) &&
87 vector::isReductionIterator(iteratorTypes[2])))
88 return false;
89
90 // The contract needs to represent a matmul to be able to convert to
91 // MMAMatrix matmul.
92 if (contract.getIndexingMapsArray() != infer({{m, k}, {n, k}, {m, n}}))
93 return false;
94
95 return true;
96}
97
98/// Returns true if the extract strided slice op is supported with `mma.sync`
99/// path.
100static bool
101extractStridedSliceSupportsMMAMatrixType(vector::ExtractStridedSliceOp op) {
102
103 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
105 if (failed(warpMatrixInfo))
106 return false;
107
108 FailureOr<vector::ContractionOp> contractOp = nvgpu::getUserContract(op);
109 if (failed(contractOp))
110 return false;
111
112 // Handle vector.extract_strided_slice on registers containing
113 // matrixB and matrixC operands. vector.extract_strided_slice op
114 // is not supported on registers containing matrixA operands.
115 if (warpMatrixInfo->operandRole == nvgpu::MatMulOperandRole::B)
116 return (cast<VectorType>(op->getResult(0).getType()) ==
117 cast<VectorType>((*contractOp).getRhs().getType()));
118 if (warpMatrixInfo->operandRole == nvgpu::MatMulOperandRole::C)
119 return (cast<VectorType>(op->getResult(0).getType()) ==
120 cast<VectorType>((*contractOp).getAcc().getType()));
121
122 return false;
123}
124
126 if (isa<scf::ForOp, scf::YieldOp>(op))
127 return true;
128 // MMA ops cannot honor a mask. An op masked by an enclosing vector.mask has
129 // no mask operand, so the checks below would miss it; rewriting it in place
130 // would leave non-maskable ops inside the vector.mask region.
131 auto maskableOp = dyn_cast<vector::MaskableOpInterface>(op);
132 if (maskableOp && maskableOp.isMasked())
133 return false;
134 if (auto transferRead = dyn_cast<vector::TransferReadOp>(op))
135 return nvgpu::canLowerToWarpMatrixOperation(transferRead);
136 if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(op))
137 return nvgpu::canLowerToWarpMatrixOperation(transferWrite);
138 if (auto extractStridedSlice = dyn_cast<vector::ExtractStridedSliceOp>(op))
139 return extractStridedSliceSupportsMMAMatrixType(extractStridedSlice);
140 if (auto contract = dyn_cast<vector::ContractionOp>(op))
142 if (auto constant = dyn_cast<arith::ConstantOp>(op))
143 return constantSupportsMMAMatrixType(constant);
144 if (auto broadcast = dyn_cast<vector::BroadcastOp>(op))
146 if (auto signedExtend = dyn_cast<arith::ExtSIOp>(op))
148 if (auto unsignedExtend = dyn_cast<arith::ExtUIOp>(op))
151}
152
153// Analyze slice of operations based on convert op to figure out if the whole
154// slice can be converted to MMA operations.
156 auto hasVectorDest = [](Operation *op) {
157 return llvm::any_of(op->getResultTypes(), llvm::IsaPred<VectorType>);
158 };
159 BackwardSliceOptions backwardSliceOptions;
160 backwardSliceOptions.filter = hasVectorDest;
161
162 auto hasVectorSrc = [](Operation *op) {
163 return llvm::any_of(op->getOperandTypes(), llvm::IsaPred<VectorType>);
164 };
165 ForwardSliceOptions forwardSliceOptions;
166 forwardSliceOptions.filter = hasVectorSrc;
167
170 DenseMap<Operation *, bool> supportsMMAMatrixTypeCache;
171
172 auto getCachedBackwardSlice =
173 [&](Operation *currentOp) -> ArrayRef<Operation *> {
174 auto [it, inserted] = backwardSliceCache.try_emplace(currentOp);
175 if (!inserted)
176 return it->second;
177
178 SetVector<Operation *> backwardSlice;
179 LogicalResult result =
180 getBackwardSlice(currentOp, &backwardSlice, backwardSliceOptions);
181 assert(result.succeeded() && "expected a backward slice");
182 (void)result;
183 it->second = backwardSlice.takeVector();
184 return it->second;
185 };
186
187 auto getCachedForwardSlice =
188 [&](Operation *currentOp) -> ArrayRef<Operation *> {
189 auto [it, inserted] = forwardSliceCache.try_emplace(currentOp);
190 if (!inserted)
191 return it->second;
192
193 SetVector<Operation *> forwardSlice;
194 // Special case for ForOp, we don't want to include the whole region but
195 // only the value using the region arguments.
196 // TODO: We should refine this to only care about the region arguments being
197 // converted to matrix type.
198 if (auto forOp = dyn_cast<scf::ForOp>(currentOp)) {
199 for (Value forOpResult : forOp.getResults())
200 getForwardSlice(forOpResult, &forwardSlice, forwardSliceOptions);
201 for (BlockArgument &arg : forOp.getRegionIterArgs())
202 getForwardSlice(arg, &forwardSlice, forwardSliceOptions);
203 } else {
204 getForwardSlice(currentOp, &forwardSlice, forwardSliceOptions);
205 }
206 it->second = forwardSlice.takeVector();
207 return it->second;
208 };
209
210 auto cachedSupportsMMAMatrixType = [&](Operation *currentOp) {
211 auto [it, inserted] =
212 supportsMMAMatrixTypeCache.try_emplace(currentOp, false);
213 if (inserted)
214 it->second = supportsMMaMatrixType(currentOp);
215 return it->second;
216 };
217
218 SetVector<Operation *> opToConvert;
219 op->walk([&](Operation *nestedOp) {
220 if (!isa<vector::ContractionOp>(nestedOp) &&
222 return;
223 if (opToConvert.contains(nestedOp))
224 return;
225
226 SetVector<Operation *> dependentOps;
227 dependentOps.insert(nestedOp);
228 unsigned currentIndex = 0;
229 while (currentIndex != dependentOps.size()) {
230 Operation *currentOp = dependentOps[currentIndex++];
231 dependentOps.insert_range(getCachedBackwardSlice(currentOp));
232 dependentOps.insert_range(getCachedForwardSlice(currentOp));
233 }
234 // If any instruction cannot use MMA matrix type drop the whole
235 // chain. MMA matrix are stored in an opaque type so they cannot be used
236 // by all operations.
237 if (llvm::any_of(dependentOps, [&](Operation *op) {
238 if (!cachedSupportsMMAMatrixType(op)) {
239 LDBG() << "cannot convert op: " << *op;
240 return true;
241 }
242 return false;
243 }))
244 return;
245
246 opToConvert.insert_range(dependentOps);
247 });
248 // Sort the operations so that we can convert them in topological order.
249 return topologicalSort(opToConvert);
250}
251
252/// Returns the vector type which represents a matrix fragment.
253static VectorType
254getMmaSyncVectorOperandType(const nvgpu::FragmentElementInfo &regInfo) {
255 SmallVector<int64_t> shape{regInfo.numRegistersPerFragment,
256 regInfo.elementsPerRegister};
257 Type elType = regInfo.registerLLVMType;
258 if (auto vecType = dyn_cast<VectorType>(elType))
259 elType = vecType.getElementType();
260 return VectorType::get(shape, elType);
261}
262
263/// Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op.
264static LogicalResult
265convertConstantOpMmaSync(RewriterBase &rewriter, arith::ConstantOp op,
266 llvm::DenseMap<Value, Value> &valueMapping) {
267 OpBuilder::InsertionGuard g(rewriter);
268 rewriter.setInsertionPoint(op);
269
270 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
272 if (failed(warpMatrixInfo)) {
273 LDBG() << "no warpMatrixInfo";
274 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
275 }
276
277 FailureOr<nvgpu::FragmentElementInfo> regInfo =
278 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
279 if (failed(regInfo)) {
280 LDBG() << "not mma sync reg info";
281 return rewriter.notifyMatchFailure(op, "not mma sync reg info");
282 }
283
284 VectorType vectorType = getMmaSyncVectorOperandType(*regInfo);
285 auto dense = dyn_cast<SplatElementsAttr>(op.getValue());
286 if (!dense) {
287 LDBG() << "not a splat";
288 return rewriter.notifyMatchFailure(op, "not a splat");
289 }
290
291 Value result = arith::ConstantOp::create(
292 rewriter, op.getLoc(), vectorType,
293 DenseElementsAttr::get(vectorType, dense.getSplatValue<Attribute>()));
294 valueMapping[op.getResult()] = result;
295 return success();
296}
297
298/// Check if the loaded matrix operand requires transposed.
299/// Transposed Map Example:
300/// Example 1 : (..., d0, d1) -> (d1 * 1, d0 * 2)
301/// Example 2 : (d0, d1, d2, d3) -> (d3, d2)
302/// The code below checks if the output 2D is transposed using a generalized
303/// version : (d0, d1, dn, ..., dm, ...) -> (dm, dn)
304/// Returns : true; if m > n, false o.w.
305static FailureOr<bool> isTransposed(vector::TransferReadOp op) {
307
308 if (map.getNumResults() != 2) {
309 LDBG() << "Failed because the result of `vector.transfer_read` "
310 "is not a 2d operand";
311 return failure();
312 }
313
314 // Output 2D matrix dimensions in the order of d0, d1.
315 mlir::AffineExpr dM = map.getResult(0);
316 mlir::AffineExpr dN = map.getResult(1);
317
318 // Find the position of these expressions in the input.
319 auto exprM = dyn_cast<AffineDimExpr>(dM);
320 auto exprN = dyn_cast<AffineDimExpr>(dN);
321
322 if (!exprM || !exprN) {
323 LDBG() << "Failed because expressions are not affine dim "
324 "expressions, then transpose cannot be determined.";
325 return failure();
326 }
327
328 return exprM.getPosition() > exprN.getPosition();
329}
330
331static LogicalResult
332creatLdMatrixCompatibleLoads(RewriterBase &rewriter, vector::TransferReadOp op,
333 llvm::DenseMap<Value, Value> &valueMapping) {
334 OpBuilder::InsertionGuard g(rewriter);
335 rewriter.setInsertionPoint(op);
336 Location loc = op->getLoc();
337
338 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
340 if (failed(warpMatrixInfo)) {
341 LDBG() << "no warpMatrixInfo";
342 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
343 }
344
345 FailureOr<nvgpu::FragmentElementInfo> regInfo =
346 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
347 if (failed(regInfo)) {
348 LDBG() << "not mma sync reg info";
349 return rewriter.notifyMatchFailure(op, "not mma sync reg info");
350 }
351
352 FailureOr<bool> transpose = isTransposed(op);
353 if (failed(transpose)) {
354 LDBG() << "failed to determine the transpose";
355 return rewriter.notifyMatchFailure(
356 op, "Op should likely not be converted to a nvgpu.ldmatrix call.");
357 }
358
359 FailureOr<nvgpu::LdMatrixParams> params =
360 nvgpu::getLdMatrixParams(*warpMatrixInfo, *transpose);
361
362 if (failed(params)) {
363 LDBG() << "failed to convert vector.transfer_read to ldmatrix. "
364 << "Op should likely not be converted to a nvgpu.ldmatrix call.";
365 return rewriter.notifyMatchFailure(
366 op, "failed to convert vector.transfer_read to ldmatrix; this op "
367 "likely should not be converted to a nvgpu.ldmatrix call.");
368 }
369
370 // Adjust the load offset.
371 auto laneId = gpu::LaneIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
372 FailureOr<AffineMap> offsets =
373 nvgpu::getLaneIdToLdMatrixMatrixCoord(rewriter, loc, *params);
374 if (failed(offsets)) {
375 LDBG() << "no offsets";
376 return rewriter.notifyMatchFailure(op, "no offsets");
377 }
378
379 VectorType vectorType = getMmaSyncVectorOperandType(*regInfo);
380
382 getXferIndices<vector::TransferReadOp>(rewriter, op, *offsets, {laneId},
383 indices);
384
385 nvgpu::LdMatrixOp newOp =
386 nvgpu::LdMatrixOp::create(rewriter, loc, vectorType, op.getBase(),
387 indices, *transpose, params->numTiles);
388 valueMapping[op] = newOp->getResult(0);
389 return success();
390}
391
392static LogicalResult
393createNonLdMatrixLoads(RewriterBase &rewriter, vector::TransferReadOp op,
394 llvm::DenseMap<Value, Value> &valueMapping) {
395 OpBuilder::InsertionGuard g(rewriter);
396 rewriter.setInsertionPoint(op);
397
398 Location loc = op.getLoc();
399 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
401 if (failed(warpMatrixInfo))
402 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
403 FailureOr<nvgpu::FragmentElementInfo> regInfo =
404 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
405 if (failed(regInfo)) {
406 return rewriter.notifyMatchFailure(
407 op, "Failed to deduce register fragment type during "
408 "conversion to distributed non-ldmatrix compatible load");
409 }
410
411 Value laneId = gpu::LaneIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
412
413 // This is the individual element type.
414 Type loadedElType = regInfo->registerLLVMType;
415 VectorType vectorType = getMmaSyncVectorOperandType(*regInfo);
416
417 Value fill = arith::ConstantOp::create(
418 rewriter, op.getLoc(), vectorType.getElementType(),
419 rewriter.getZeroAttr(vectorType.getElementType()));
420 Value result =
421 vector::BroadcastOp::create(rewriter, op.getLoc(), vectorType, fill);
422
423 bool isTransposeLoad = !op.getPermutationMap().isMinorIdentity();
424
425 // If we are not transposing, then we can use vectorized loads. Otherwise, we
426 // must load each element individually.
427 if (!isTransposeLoad) {
428 if (!isa<VectorType>(loadedElType)) {
429 loadedElType = VectorType::get({1}, loadedElType);
430 }
431
432 for (int i = 0; i < vectorType.getShape()[0]; i++) {
433 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
434 rewriter, op.getLoc(), *warpMatrixInfo);
435 if (failed(coords))
436 return rewriter.notifyMatchFailure(op, "no coords");
437
438 Value logicalValueId = arith::ConstantOp::create(
439 rewriter, loc, rewriter.getIndexType(),
440 rewriter.getIndexAttr(i * regInfo->elementsPerRegister));
441 SmallVector<Value, 4> newIndices;
443 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
444
445 Value el = vector::LoadOp::create(rewriter, loc, loadedElType,
446 op.getBase(), newIndices);
447 result = vector::InsertOp::create(rewriter, loc, el, result, i);
448 }
449 } else {
450 if (auto vecType = dyn_cast<VectorType>(loadedElType)) {
451 loadedElType = vecType.getElementType();
452 }
453 for (int i = 0; i < vectorType.getShape()[0]; i++) {
454 for (unsigned innerIdx = 0; innerIdx < vectorType.getShape()[1];
455 innerIdx++) {
456
457 Value logicalValueId = arith::ConstantOp::create(
458 rewriter, loc, rewriter.getIndexType(),
459 rewriter.getIndexAttr(i * regInfo->elementsPerRegister + innerIdx));
460 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
461 rewriter, op.getLoc(), *warpMatrixInfo);
462 if (failed(coords))
463 return rewriter.notifyMatchFailure(op, "no coords");
464
465 SmallVector<Value, 4> newIndices;
467 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
468 Value el = memref::LoadOp::create(rewriter, op.getLoc(), loadedElType,
469 op.getBase(), newIndices);
470 result = vector::InsertOp::create(rewriter, op.getLoc(), el, result,
471 ArrayRef<int64_t>{i, innerIdx});
472 }
473 }
474 }
475
476 valueMapping[op.getResult()] = result;
477 return success();
478}
479
480/// Return true if this is a shared memory memref type.
481static bool isSharedMemory(MemRefType type) {
482 auto addressSpace =
483 dyn_cast_or_null<gpu::AddressSpaceAttr>(type.getMemorySpace());
484 return addressSpace &&
485 addressSpace.getValue() == gpu::GPUDialect::getWorkgroupAddressSpace();
486}
487
488/// Converts a `vector.transfer_read` operation directly to either a
489/// `vector.load` or a `nvgpu.ldmatrix` operation. This function should only be
490/// used when converting to `nvgpu.mma.sync` operations.
491static LogicalResult
492convertTransferReadToLoads(RewriterBase &rewriter, vector::TransferReadOp op,
493 llvm::DenseMap<Value, Value> &valueMapping) {
494 OpBuilder::InsertionGuard g(rewriter);
495 rewriter.setInsertionPoint(op);
496
497 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
499 if (failed(warpMatrixInfo))
500 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
501
502 bool isLdMatrixCompatible =
503 isSharedMemory(cast<MemRefType>(op.getBase().getType())) &&
504 nvgpu::inferTileWidthInBits(*warpMatrixInfo) == 128;
505
506 VectorType vecTy = op.getVectorType();
507 int64_t bitWidth = vecTy.getElementType().getIntOrFloatBitWidth();
508
509 // When we are transposing the B operand, ldmatrix will only work if we have
510 // at least 8 rows to read and the width to read for the transpose is 128
511 // bits.
512 if (!op.getPermutationMap().isMinorIdentity() &&
513 (bitWidth != 16 || vecTy.getDimSize(1) < 8 ||
514 vecTy.getDimSize(0) * bitWidth < 128))
515 isLdMatrixCompatible = false;
516
517 if (!isLdMatrixCompatible)
518 return createNonLdMatrixLoads(rewriter, op, valueMapping);
519
520 return creatLdMatrixCompatibleLoads(rewriter, op, valueMapping);
521}
522
523static LogicalResult
524convertTransferWriteToStores(RewriterBase &rewriter, vector::TransferWriteOp op,
525 llvm::DenseMap<Value, Value> &valueMapping) {
526 OpBuilder::InsertionGuard g(rewriter);
527 rewriter.setInsertionPoint(op);
528
529 Location loc = op->getLoc();
530 auto it = valueMapping.find(op.getVector());
531 if (it == valueMapping.end())
532 return rewriter.notifyMatchFailure(op, "no mapping");
533 Value matrix = it->second;
534
535 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
537 if (failed(warpMatrixInfo))
538 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
539 FailureOr<nvgpu::FragmentElementInfo> regInfo =
540 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
541 if (failed(regInfo))
542 return rewriter.notifyMatchFailure(op, "not mma sync reg info");
543
544 VectorType vectorType = getMmaSyncVectorOperandType(*regInfo);
545 Value laneId = gpu::LaneIdOp::create(rewriter, loc, /*upper_bound=*/nullptr);
546
547 for (unsigned i = 0; i < vectorType.getShape()[0]; i++) {
548 Value logicalValueId = arith::ConstantOp::create(
549 rewriter, loc, rewriter.getIndexType(),
550 rewriter.getIndexAttr(i * regInfo->elementsPerRegister));
551 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
552 rewriter, op.getLoc(), *warpMatrixInfo);
553 if (failed(coords))
554 return rewriter.notifyMatchFailure(op, "no coords");
555
556 Value el =
557 vector::ExtractOp::create(rewriter, loc, matrix, ArrayRef<int64_t>{i});
558 SmallVector<Value, 4> newIndices;
560 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
561 vector::StoreOp::create(rewriter, loc, el, op.getBase(), newIndices);
562 }
563
564 LDBG() << "erase: " << op;
565 rewriter.eraseOp(op);
566 return success();
567}
568
570 SmallVectorImpl<int64_t> &results) {
571 for (auto attr : arrayAttr)
572 results.push_back(cast<IntegerAttr>(attr).getInt());
573}
574
575static LogicalResult
577 vector::ExtractStridedSliceOp op,
578 llvm::DenseMap<Value, Value> &valueMapping) {
579 OpBuilder::InsertionGuard g(rewriter);
580 rewriter.setInsertionPoint(op);
581
582 Location loc = op->getLoc();
583
584 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
586 if (failed(warpMatrixInfo))
587 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
588
589 FailureOr<nvgpu::FragmentElementInfo> mmaSyncFragmentInfo =
590 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
591 if (failed(mmaSyncFragmentInfo))
592 return rewriter.notifyMatchFailure(op, "no mmaSyncFragmentInfo");
593
594 // Find the vector.transer_read whose result vector is being sliced.
595 auto transferReadOp = op.getSource().getDefiningOp<vector::TransferReadOp>();
596 if (!transferReadOp)
597 return rewriter.notifyMatchFailure(op, "no transfer read");
598
599 warpMatrixInfo = nvgpu::getWarpMatrixInfo(transferReadOp);
600 if (failed(warpMatrixInfo))
601 return rewriter.notifyMatchFailure(op, "no warpMatrixInfo");
602
603 FailureOr<nvgpu::FragmentElementInfo> ldFragmentInfo =
604 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
605 if (failed(ldFragmentInfo))
606 return rewriter.notifyMatchFailure(op, "no ldFragmentInfo");
607
608 assert(
609 (mmaSyncFragmentInfo->elementsPerRegister ==
610 ldFragmentInfo->elementsPerRegister) &&
611 "Number of elements per register should be same for load and mma.sync");
612
613 // Create vector.extract_strided_slice op for thread-owned fragments.
614 std::array<int64_t, 2> strides = {1,
615 1}; // stride for extract slice is always 1.
616 std::array<int64_t, 2> sliceShape = {
617 mmaSyncFragmentInfo->numRegistersPerFragment,
618 mmaSyncFragmentInfo->elementsPerRegister};
619 auto it = valueMapping.find(transferReadOp);
620 if (it == valueMapping.end())
621 return rewriter.notifyMatchFailure(op, "no mapping");
622 auto sourceVector = it->second;
623
624 // offset and sizes at warp-level of onwership.
625 SmallVector<int64_t> offsets;
626 populateFromInt64AttrArray(op.getOffsets(), offsets);
627
629 populateFromInt64AttrArray(op.getSizes(), sizes);
630 ArrayRef<int64_t> warpVectorShape = op.getSourceVectorType().getShape();
631
632 // Compute offset in vector registers. Note that the mma.sync vector registers
633 // are shaped as numberOfFragments x numberOfRegistersPerfFragment. The vector
634 // registers can only be sliced along numberOfFragments, i.e., sliceOffset[0].
635 std::array<int64_t, 2> sliceOffset = {0, 0};
636
637 if (offsets[0] && offsets[1])
638 return op->emitError() << "Slicing fragments in 2D is not supported. ";
639 if (offsets[0])
640 sliceOffset[0] = (warpVectorShape[0] / offsets[0]);
641 else if (offsets[1])
642 sliceOffset[0] = (warpVectorShape[1] / offsets[1]);
643
644 Value newOp = vector::ExtractStridedSliceOp::create(
645 rewriter, loc, sourceVector, sliceOffset, sliceShape, strides);
646
647 valueMapping[op] = newOp;
648 return success();
649}
650
651static LogicalResult
652convertContractOpToMmaSync(RewriterBase &rewriter, vector::ContractionOp op,
653 llvm::DenseMap<Value, Value> &valueMapping) {
654 OpBuilder::InsertionGuard g(rewriter);
655 rewriter.setInsertionPoint(op);
656
657 auto itA = valueMapping.find(op.getLhs());
658 auto itB = valueMapping.find(op.getRhs());
659 auto itC = valueMapping.find(op.getAcc());
660 if (itA == valueMapping.end() || itB == valueMapping.end() ||
661 itC == valueMapping.end())
662 return rewriter.notifyMatchFailure(op, "no mapping");
663 Value opA = itA->second, opB = itB->second, opC = itC->second;
664 int64_t m = cast<VectorType>(op.getLhs().getType()).getShape()[0];
665 int64_t n = cast<VectorType>(op.getRhs().getType()).getShape()[0];
666 int64_t k = cast<VectorType>(op.getLhs().getType()).getShape()[1];
667 Value matmul = nvgpu::MmaSyncOp::create(rewriter, op.getLoc(), opA, opB, opC,
668 rewriter.getI64ArrayAttr({m, n, k}));
669 valueMapping[op.getResult()] = matmul;
670 return success();
671}
672
677
679 Operation *rootOp) {
681 llvm::DenseMap<Value, Value> valueMapping;
682 for (Operation *op : ops) {
684 .Case([&](vector::TransferReadOp transferReadOp) {
685 return convertTransferReadToLoads(rewriter, transferReadOp,
686 valueMapping);
687 })
688 .Case([&](vector::TransferWriteOp transferWriteOp) {
689 return convertTransferWriteToStores(rewriter, transferWriteOp,
690 valueMapping);
691 })
692 .Case([&](vector::ExtractStridedSliceOp extractStridedSliceOp) {
693 return convertExtractStridedSlice(rewriter, extractStridedSliceOp,
694 valueMapping);
695 })
696 .Case([&](vector::ContractionOp contractionOp) {
697 return convertContractOpToMmaSync(rewriter, contractionOp,
698 valueMapping);
699 })
700 .Case([&](scf::ForOp forOp) {
701 return convertForOpForMMA(rewriter, forOp, valueMapping);
702 })
703 .Case([&](scf::YieldOp yieldOp) {
704 return convertYieldOpForMMA(rewriter, yieldOp, valueMapping);
705 })
706 .Case([&](arith::ConstantOp constOp) {
707 return convertConstantOpMmaSync(rewriter, constOp, valueMapping);
708 })
709 .Default([&](Operation *op) {
710 return op->emitError() << "unhandled vector to mma type: " << *op;
711 })
712 .failed()) {
713 return op->emitOpError()
714 << "failed to convert op during vector-to-nvgpu conversion";
715 }
716 }
717 return success();
718}
719
720namespace {
721struct ConvertVectorToNVGPUPass
722 : public impl::ConvertVectorToNVGPUPassBase<ConvertVectorToNVGPUPass> {
723
724 void runOnOperation() override {
725 RewritePatternSet patterns(&getContext());
727 if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
728 return signalPassFailure();
729
730 IRRewriter rewriter(&getContext());
731 if (failed(convertVectorToNVVMCompatibleMMASync(rewriter, getOperation())))
732 return signalPassFailure();
733 }
734};
735} // namespace
return success()
ArrayAttr()
b getContext())
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static void contract(RootOrderingGraph &graph, ArrayRef< Value > cycle, const DenseMap< Value, unsigned > &parentDepths, DenseMap< Value, Value > &actualSource, DenseMap< Value, Value > &actualTarget)
Contracts the specified cycle in the given graph in-place.
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static bool supportsMMaMatrixType(Operation *op)
static LogicalResult convertContractOpToMmaSync(RewriterBase &rewriter, vector::ContractionOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool isSharedMemory(MemRefType type)
Return true if this is a shared memory memref type.
static VectorType getMmaSyncVectorOperandType(const nvgpu::FragmentElementInfo &regInfo)
Returns the vector type which represents a matrix fragment.
static void populateFromInt64AttrArray(ArrayAttr arrayAttr, SmallVectorImpl< int64_t > &results)
static FailureOr< bool > isTransposed(vector::TransferReadOp op)
Check if the loaded matrix operand requires transposed.
static LogicalResult convertTransferReadToLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
Converts a vector.transfer_read operation directly to either a vector.load or a nvgpu....
static LogicalResult creatLdMatrixCompatibleLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool contractSupportsMMAMatrixType(vector::ContractionOp contract)
static bool extractStridedSliceSupportsMMAMatrixType(vector::ExtractStridedSliceOp op)
Returns true if the extract strided slice op is supported with mma.sync path.
static LogicalResult convertConstantOpMmaSync(RewriterBase &rewriter, arith::ConstantOp op, llvm::DenseMap< Value, Value > &valueMapping)
Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op.
static SetVector< Operation * > getOpToConvert(mlir::Operation *op)
static LogicalResult convertTransferWriteToStores(RewriterBase &rewriter, vector::TransferWriteOp op, llvm::DenseMap< Value, Value > &valueMapping)
static void getXferIndices(RewriterBase &rewriter, TransferOpType xferOp, AffineMap offsetMap, ArrayRef< Value > dimValues, SmallVector< Value, 4 > &indices)
For a vector TransferOpType xferOp, an empty indices vector, and an AffineMap representing offsets to...
static LogicalResult convertExtractStridedSlice(RewriterBase &rewriter, vector::ExtractStridedSliceOp op, llvm::DenseMap< Value, Value > &valueMapping)
static LogicalResult createNonLdMatrixLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
unsigned getNumDims() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:290
IndexType getIndexType()
Definition Builders.cpp:59
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
FailureOr< vector::ContractionOp > getUserContract(Operation *op)
Returns the first user of the op that is vector.contract.
Definition MMAUtils.cpp:47
FailureOr< WarpMatrixInfo > getWarpMatrixInfo(Operation *op)
If op is a vector.transfer_write, return the WarpMatrixInfo for the vector operand.
Definition MMAUtils.cpp:55
bool canLowerToWarpMatrixOperation(vector::TransferWriteOp op)
Returns the number of bits in a single tile row.
Definition MMAUtils.cpp:295
bool isReductionIterator(Attribute attr)
Returns true if attr has "reduction" iterator type semantics.
Definition VectorOps.h:151
bool isParallelIterator(Attribute attr)
Returns true if attr has "parallel" iterator type semantics.
Definition VectorOps.h:146
void populateVectorContractCanonicalizeMatmulToMMT(RewritePatternSet &patterns, std::function< LogicalResult(vector::ContractionOp)> constraint=[](vector::ContractionOp) { return success();}, PatternBenefit=1)
Canonicalization of a vector.contract a, b, c with row-major matmul semantics to a contraction with M...
Include the generated interface declarations.
LogicalResult convertYieldOpForMMA(RewriterBase &rewriter, scf::YieldOp op, llvm::DenseMap< Value, Value > &valueMapping)
Update a yield operation to yield the converted values.
LogicalResult getBackwardSlice(Operation *op, SetVector< Operation * > *backwardSlice, const BackwardSliceOptions &options={})
Fills backwardSlice with the computed backward slice (i.e.
bool broadcastSupportsMMAMatrixType(vector::BroadcastOp broadcastOp)
Return true if this is a broadcast from scalar to a 2D vector.
bool elementwiseSupportsMMAMatrixType(Operation *op)
Return true if the operation is supported as elementwise on an MMA matrix.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
LogicalResult convertForOpForMMA(RewriterBase &rewriter, scf::ForOp op, llvm::DenseMap< Value, Value > &valueMapping)
Extend loop-carried values with their converted counterparts.
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
bool constantSupportsMMAMatrixType(arith::ConstantOp constantOp)
Return true if the constant is a splat to a 2D vector so that it can be converted to an MMA constant ...
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
SliceOptions ForwardSliceOptions
LogicalResult convertVectorToNVVMCompatibleMMASync(RewriterBase &rewriter, Operation *rootOp)
Convert vector ops nested under rootOp to vector and GPU operations compatible with the nvvm....
void populateVectorTransferReadTransposePatterns(RewritePatternSet &patterns)
Populate patterns that fold vector.transpose into vector.transfer_read, including through arithmetic ...
template bool integerExtendSupportsMMAMatrixType< arith::ExtSIOp >(arith::ExtSIOp)
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
template bool integerExtendSupportsMMAMatrixType< arith::ExtUIOp >(arith::ExtUIOp)
void populatePrepareVectorToNVMMAPatterns(RewritePatternSet &patterns)
Populate patterns that prepare vector operations for lowering to nvgpu.mma.sync operations.
SetVector< Operation * > topologicalSort(const SetVector< Operation * > &toSort)
Sorts all operations in toSort topologically while also considering region semantics.
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.
TransitiveFilter filter