MLIR 24.0.0git
NVVMMmaOps.cpp
Go to the documentation of this file.
1//===- NVVMMmaOps.cpp - NVVM dialect MMA ops ------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ops of op partition `Mma` of the NVVM dialect.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "IR/NVVMOps.h"
16#include "mlir/IR/Builders.h"
18#include "mlir/IR/Diagnostics.h"
19#include "mlir/IR/MLIRContext.h"
20#include "mlir/IR/Operation.h"
23#include "mlir/IR/Types.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/IntrinsicsNVPTX.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/raw_ostream.h"
30
31#include <array>
32#include <cassert>
33#include <optional>
34#include <string>
35#include <utility>
36
37using namespace mlir;
38using namespace mlir::NVVM;
39
40//===----------------------------------------------------------------------===//
41// Helper/Utility methods
42//===----------------------------------------------------------------------===//
43
44template <typename AttrTy>
45static ParseResult parseEnumKeyword(OpAsmParser &parser, AttrTy &attr) {
46 SMLoc loc = parser.getCurrentLocation();
47 std::string keyword;
48 if (parser.parseKeywordOrString(&keyword))
49 return failure();
50
51 using EnumTy = decltype(attr.getValue());
52 std::optional<EnumTy> value = NVVM::symbolizeEnum<EnumTy>(keyword);
53 if (!value)
54 return parser.emitError(loc) << "unknown enum value '" << keyword << "'";
55
56 attr = AttrTy::get(parser.getContext(), *value);
57 return success();
58}
59
60//===----------------------------------------------------------------------===//
61// Verifier methods
62//===----------------------------------------------------------------------===//
63
64// Given the element type of an operand and whether or not it is an accumulator,
65// this function returns the PTX type (`NVVM::MMATypes`) that corresponds to the
66// operand's element type.
67std::optional<mlir::NVVM::MMATypes>
68MmaOp::inferOperandMMAType(Type operandElType, bool isAccumulator) {
69 auto half2Type =
70 VectorType::get(2, Float16Type::get(operandElType.getContext()));
71 if (operandElType.isF64())
72 return NVVM::MMATypes::f64;
73 if (operandElType.isF16() || operandElType == half2Type)
74 return NVVM::MMATypes::f16;
75 if (operandElType.isF32() && isAccumulator)
76 return NVVM::MMATypes::f32;
77 if (operandElType.isF32() && !isAccumulator)
78 return NVVM::MMATypes::tf32;
79 if (llvm::isa<IntegerType>(operandElType)) {
80 if (isAccumulator)
81 return NVVM::MMATypes::s32;
82 return std::nullopt;
83 }
84
85 if (auto structType = llvm::dyn_cast<LLVM::LLVMStructType>(operandElType)) {
86 if (structType.getBody().empty())
87 return std::nullopt;
88 return inferOperandMMAType(structType.getBody()[0], isAccumulator);
89 }
90
91 return std::nullopt;
92}
93
94static bool isInt4PtxType(MMATypes type) {
95 return (type == MMATypes::u4 || type == MMATypes::s4);
96}
97
98static bool isInt8PtxType(MMATypes type) {
99 return (type == MMATypes::u8 || type == MMATypes::s8);
100}
101
102static bool isIntegerPtxType(MMATypes type) {
103 return isInt4PtxType(type) || isInt8PtxType(type) || type == MMATypes::b1 ||
104 type == MMATypes::s32;
105}
106
107MMATypes MmaOp::accumPtxType() {
108 std::optional<mlir::NVVM::MMATypes> val = inferOperandMMAType(
109 getODSOperands(2).getTypes().front(), /*isAccumulator=*/true);
110 assert(val.has_value() && "accumulator PTX type should always be inferrable");
111 return val.value();
112}
113
114MMATypes MmaOp::resultPtxType() {
115 std::optional<mlir::NVVM::MMATypes> val =
116 inferOperandMMAType(getResult().getType(), /*isAccumulator=*/true);
117 assert(val.has_value() && "result PTX type should always be inferrable");
118 return val.value();
119}
120
121template <typename AttrTy>
122static void printMmaProperty(OpAsmPrinter &printer, bool &isFirst,
123 StringRef keyword, AttrTy value) {
124 printer << (isFirst ? " " : ", ") << keyword << " = ";
125 printer.printStrippedAttrOrType(value);
126 isFirst = false;
127}
128
129template <typename AttrTy>
130static void printMmaEnumProperty(OpAsmPrinter &printer, bool &isFirst,
131 StringRef keyword, AttrTy value) {
132 printer << (isFirst ? " " : ", ") << keyword << " = "
133 << NVVM::stringifyEnum(value.getValue());
134 isFirst = false;
135}
136
137static void printMmaUnitProperty(OpAsmPrinter &printer, bool &isFirst,
138 StringRef keyword) {
139 printer << (isFirst ? " " : ", ") << keyword;
140 isFirst = false;
141}
142
143template <typename AttrTy>
144static ParseResult parseMmaPropertyValue(OpAsmParser &parser,
145 NamedAttrList &attributes,
146 StringRef name) {
147 if (attributes.get(name))
148 return parser.emitError(parser.getCurrentLocation(),
149 "duplicate property '" + name + "'");
150 AttrTy value;
151 if (parser.parseEqual() || parser.parseCustomAttributeWithFallback(value))
152 return failure();
153 attributes.append(name, value);
154 return success();
155}
156
157template <typename AttrTy>
158static ParseResult parseMmaEnumPropertyValue(OpAsmParser &parser,
159 NamedAttrList &attributes,
160 StringRef name) {
161 if (attributes.get(name))
162 return parser.emitError(parser.getCurrentLocation(),
163 "duplicate property '" + name + "'");
164 AttrTy value;
165 if (parser.parseEqual() || parseEnumKeyword(parser, value))
166 return failure();
167 attributes.append(name, value);
168 return success();
169}
170
171static bool isMmaPropertyName(StringRef name) {
172 return llvm::is_contained(
174 "shape", "b1Op", "intOverflowBehavior", "layoutA", "layoutB",
175 "multiplicandAPtxType", "multiplicandBPtxType", "orderedMetadata",
176 "kind", "scaleVecSize", "blockScaleFormat", "operandSegmentSizes"},
177 name);
178}
179
180static ParseResult parseMmaProperties(OpAsmParser &parser,
181 NamedAttrList &attributes,
182 ArrayRef<StringRef> allowedKeywords,
183 ArrayRef<StringRef> requiredProperties) {
184 while (true) {
185 StringRef keyword;
186 if (parser.parseKeyword(&keyword))
187 return failure();
188 if (!llvm::is_contained(allowedKeywords, keyword))
189 return parser.emitError(parser.getCurrentLocation(),
190 "unknown MMA property '" + keyword + "'");
191
192 ParseResult parseResult = success();
193 if (keyword == "shape")
194 parseResult =
195 parseMmaPropertyValue<MMAShapeAttr>(parser, attributes, "shape");
196 else if (keyword == "b1_op")
197 parseResult =
198 parseMmaEnumPropertyValue<MMAB1OpAttr>(parser, attributes, "b1Op");
199 else if (keyword == "int_overflow")
201 parser, attributes, "intOverflowBehavior");
202 else if (keyword == "layout_a")
203 parseResult = parseMmaEnumPropertyValue<MMALayoutAttr>(parser, attributes,
204 "layoutA");
205 else if (keyword == "layout_b")
206 parseResult = parseMmaEnumPropertyValue<MMALayoutAttr>(parser, attributes,
207 "layoutB");
208 else if (keyword == "multiplicand_a_ptx_type")
210 parser, attributes, "multiplicandAPtxType");
211 else if (keyword == "multiplicand_b_ptx_type")
213 parser, attributes, "multiplicandBPtxType");
214 else if (keyword == "kind") {
215 if (llvm::is_contained(allowedKeywords, "block_scale_format"))
217 parser, attributes, "kind");
218 else
219 parseResult =
220 parseMmaEnumPropertyValue<MMAKindAttr>(parser, attributes, "kind");
221 } else if (keyword == "scale_vec_size")
223 parser, attributes, "scaleVecSize");
224 else if (keyword == "block_scale_format")
226 parser, attributes, "blockScaleFormat");
227 else if (keyword == "ordered_metadata") {
228 if (attributes.get("orderedMetadata"))
229 return parser.emitError(parser.getCurrentLocation(),
230 "duplicate property 'orderedMetadata'");
231 attributes.append("orderedMetadata", parser.getBuilder().getUnitAttr());
232 } else {
233 return parser.emitError(parser.getCurrentLocation(),
234 "unknown MMA property '" + keyword + "'");
235 }
236 if (failed(parseResult))
237 return failure();
238 if (failed(parser.parseOptionalComma()))
239 break;
240 }
241
242 for (StringRef property : requiredProperties) {
243 if (!attributes.get(property))
244 return parser.emitError(parser.getCurrentLocation(),
245 "missing required property '" + property + "'");
246 }
247
248 NamedAttrList discardableAttributes;
249 if (parser.parseOptionalAttrDict(discardableAttributes))
250 return failure();
251 for (NamedAttribute attribute : discardableAttributes) {
252 if (isMmaPropertyName(attribute.getName()))
253 return parser.emitError(
254 parser.getCurrentLocation(),
255 "inherent property '" + attribute.getName().getValue() +
256 "' must be spelled directly in the operation syntax");
257 attributes.append(attribute);
258 }
259 return success();
260}
261
262void MmaOp::print(OpAsmPrinter &p) {
263 SmallVector<Type, 4> regTypes;
264 struct MMAOperandFragment {
265 StringRef operandName;
266 StringRef ptxTypeAttr;
267 SmallVector<Value, 4> regs;
268 explicit MMAOperandFragment(StringRef name, StringRef ptxTypeName)
269 : operandName(name), ptxTypeAttr(ptxTypeName) {}
270 };
271
272 std::array<MMAOperandFragment, 3> frags{
273 MMAOperandFragment("A", getMultiplicandAPtxTypeAttrName()),
274 MMAOperandFragment("B", getMultiplicandBPtxTypeAttrName()),
275 MMAOperandFragment("C", "")};
276 SmallVector<StringRef, 4> ignoreAttrNames{
277 mlir::NVVM::MmaOp::getOperandSegmentSizeAttr()};
278
279 for (unsigned fragIdx = 0; fragIdx < frags.size(); fragIdx++) {
280 auto &frag = frags[fragIdx];
281 auto varOperandSpec = getODSOperandIndexAndLength(fragIdx);
282 for (auto operandIdx = varOperandSpec.first;
283 operandIdx < varOperandSpec.first + varOperandSpec.second;
284 operandIdx++) {
285 frag.regs.push_back(this->getOperand(operandIdx));
286 if (operandIdx == 0) {
287 regTypes.push_back(this->getOperand(operandIdx).getType());
288 }
289 }
290 std::optional<MMATypes> inferredType = MmaOp::inferOperandMMAType(
291 regTypes.back(), /*isAccumulator=*/fragIdx >= 2);
292 if (inferredType)
293 ignoreAttrNames.push_back(frag.ptxTypeAttr);
294 }
295
296 auto printMmaOperand = [&](const MMAOperandFragment &frag) -> void {
297 p << " " << frag.operandName;
298 p << "[";
299 p.printOperands(frag.regs);
300 p << "] ";
301 };
302
303 for (const auto &frag : frags) {
304 printMmaOperand(frag);
305 }
306
307 bool isFirstProperty = true;
308 printMmaProperty(p, isFirstProperty, "shape", getShapeAttr());
309 if (getB1OpAttr())
310 printMmaEnumProperty(p, isFirstProperty, "b1_op", getB1OpAttr());
311 if (getIntOverflowBehaviorAttr())
312 printMmaEnumProperty(p, isFirstProperty, "int_overflow",
313 getIntOverflowBehaviorAttr());
314 printMmaEnumProperty(p, isFirstProperty, "layout_a", getLayoutAAttr());
315 printMmaEnumProperty(p, isFirstProperty, "layout_b", getLayoutBAttr());
316 if (getMultiplicandAPtxTypeAttr() &&
317 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
318 printMmaEnumProperty(p, isFirstProperty, "multiplicand_a_ptx_type",
319 getMultiplicandAPtxTypeAttr());
320 if (getMultiplicandBPtxTypeAttr() &&
321 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
322 printMmaEnumProperty(p, isFirstProperty, "multiplicand_b_ptx_type",
323 getMultiplicandBPtxTypeAttr());
324 llvm::append_range(ignoreAttrNames,
325 ArrayRef<StringRef>{getShapeAttrName(), getB1OpAttrName(),
326 getIntOverflowBehaviorAttrName(),
327 getLayoutAAttrName(),
328 getLayoutBAttrName(),
329 getMultiplicandAPtxTypeAttrName(),
330 getMultiplicandBPtxTypeAttrName()});
331 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue(),
332 ignoreAttrNames);
333
334 // Print the types of the operands and result.
335 p << " : " << "(";
336 llvm::interleaveComma(SmallVector<Type, 3>{frags[0].regs[0].getType(),
337 frags[1].regs[0].getType(),
338 frags[2].regs[0].getType()},
339 p);
340 p << ")";
341 p.printArrowTypeList(TypeRange{this->getRes().getType()});
342}
343
344void MmaOp::build(OpBuilder &builder, OperationState &result, Type resultType,
345 ValueRange operandA, ValueRange operandB, ValueRange operandC,
346 ArrayRef<int64_t> shape, std::optional<MMAB1Op> b1Op,
347 std::optional<MMAIntOverflow> intOverflow,
348 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
349 std::optional<std::array<MMALayout, 2>> multiplicandLayouts) {
350
351 assert(shape.size() == 3 && "expected shape to have size 3 (m, n, k)");
352 MLIRContext *ctx = builder.getContext();
353 result.addAttribute(
354 "shape", builder.getAttr<MMAShapeAttr>(shape[0], shape[1], shape[2]));
355
356 result.addOperands(operandA);
357 result.addOperands(operandB);
358 result.addOperands(operandC);
359
360 if (multiplicandPtxTypes) {
361 result.addAttribute("multiplicandAPtxType",
362 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
363 result.addAttribute("multiplicandBPtxType",
364 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
365 } else {
366 if (auto res = inferOperandMMAType(operandA[0].getType(), false))
367 result.addAttribute("multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
368 if (auto res = inferOperandMMAType(operandB[0].getType(), false))
369 result.addAttribute("multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
370 }
371
372 if (multiplicandLayouts) {
373 result.addAttribute("layoutA",
374 MMALayoutAttr::get(ctx, (*multiplicandLayouts)[0]));
375 result.addAttribute("layoutB",
376 MMALayoutAttr::get(ctx, (*multiplicandLayouts)[1]));
377 } else {
378 result.addAttribute("layoutA", MMALayoutAttr::get(ctx, MMALayout::row));
379 result.addAttribute("layoutB", MMALayoutAttr::get(ctx, MMALayout::col));
380 }
381
382 if (intOverflow.has_value())
383 result.addAttribute("intOverflowBehavior",
384 MMAIntOverflowAttr::get(ctx, *intOverflow));
385 if (b1Op.has_value())
386 result.addAttribute("b1Op", MMAB1OpAttr::get(ctx, *b1Op));
387
388 result.addTypes(resultType);
389 result.addAttribute(
390 MmaOp::getOperandSegmentSizeAttr(),
391 builder.getDenseI32ArrayAttr({static_cast<int32_t>(operandA.size()),
392 static_cast<int32_t>(operandB.size()),
393 static_cast<int32_t>(operandC.size())}));
394}
395
396// <operation> :=
397// A `[` $operandA `]` B `[` $operandB `]` C `[` $operandC `]`
398// properties attr-dict
399// : (type($operandA[0]), type($operandB[0]), type($operandC[0]))
400// `->` type($res)
401ParseResult MmaOp::parse(OpAsmParser &parser, OperationState &result) {
402 struct MMAOperandFragment {
403 std::optional<MMATypes> elemtype;
404 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
405 SmallVector<Type> regTypes;
406 };
407
408 Builder &builder = parser.getBuilder();
409 std::array<MMAOperandFragment, 4> frags;
410
411 NamedAttrList namedAttributes;
412
413 // A helper to parse the operand segments.
414 auto parseMmaOperand = [&](StringRef operandName,
415 MMAOperandFragment &frag) -> LogicalResult {
416 if (parser.parseKeyword(operandName).failed())
417 return failure();
418 if (parser
419 .parseOperandList(frag.regs, OpAsmParser::Delimiter::OptionalSquare)
420 .failed())
421 return failure();
422 return success();
423 };
424
425 // Parse the operand segments.
426 if (parseMmaOperand("A", frags[0]).failed())
427 return failure();
428 if (parseMmaOperand("B", frags[1]).failed())
429 return failure();
430 if (parseMmaOperand("C", frags[2]).failed())
431 return failure();
432
433 if (parseMmaProperties(parser, namedAttributes,
434 {"shape", "b1_op", "int_overflow", "layout_a",
435 "layout_b", "multiplicand_a_ptx_type",
436 "multiplicand_b_ptx_type"},
437 {"shape", "layoutA", "layoutB"}))
438 return failure();
439
440 // Parse the type specification and resolve operands.
441 SmallVector<Type, 3> operandTypes;
442 if (failed(parser.parseColon()))
443 return failure();
444 if (failed(parser.parseLParen()))
445 return failure();
446 if (failed(parser.parseTypeList(operandTypes)))
447 return failure();
448 if (failed(parser.parseRParen()))
449 if (operandTypes.size() != 3)
450 return parser.emitError(
451 parser.getNameLoc(),
452 "expected one type for each operand segment but got " +
453 Twine(operandTypes.size()) + " types");
454 for (const auto &iter : llvm::enumerate(operandTypes)) {
455 auto &frag = frags[iter.index()];
456 frag.regTypes.resize(frag.regs.size(), iter.value());
457 if (failed(parser.resolveOperands(frag.regs, frag.regTypes,
458 parser.getNameLoc(), result.operands)))
459 return failure();
460 frag.elemtype = inferOperandMMAType(frag.regTypes[0],
461 /*isAccumulator*/ iter.index() < 2);
462 }
463
464 Type resultType;
465 if (parser.parseArrow() || parser.parseType(resultType))
466 return failure();
467 frags[3].elemtype = inferOperandMMAType(resultType, /*isAccumulator*/ true);
468
469 std::array<StringRef, 2> names{"multiplicandAPtxType",
470 "multiplicandBPtxType"};
471 for (unsigned idx = 0; idx < names.size(); idx++) {
472 const auto &frag = frags[idx];
473 std::optional<NamedAttribute> attr = namedAttributes.getNamed(names[idx]);
474 if (!frag.elemtype.has_value() && !attr.has_value()) {
475 return parser.emitError(
476 parser.getNameLoc(),
477 "attribute " + names[idx] +
478 " is not provided explicitly and cannot be inferred");
479 }
480 if (!attr.has_value())
481 result.addAttribute(
482 names[idx], MMATypesAttr::get(parser.getContext(), *frag.elemtype));
483 }
484
485 result.addTypes(resultType);
486 if (!namedAttributes.empty())
487 result.addAttributes(namedAttributes);
488 result.addAttribute(MmaOp::getOperandSegmentSizeAttr(),
489 builder.getDenseI32ArrayAttr({
490 static_cast<int32_t>(frags[0].regs.size()),
491 static_cast<int32_t>(frags[1].regs.size()),
492 static_cast<int32_t>(frags[2].regs.size()),
493 }));
494 return success();
495}
496
497LogicalResult MmaOp::verify() {
498 MLIRContext *context = getContext();
499 auto f16Ty = Float16Type::get(context);
500 auto i32Ty = IntegerType::get(context, 32);
501 auto f16x2Ty = VectorType::get(2, f16Ty);
502 auto f32Ty = Float32Type::get(context);
503 auto f16x2x4StructTy = LLVM::LLVMStructType::getLiteral(
504 context, {f16x2Ty, f16x2Ty, f16x2Ty, f16x2Ty});
505
506 auto s32x4StructTy =
507 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty, i32Ty, i32Ty});
508 auto f32x8StructTy =
509 LLVM::LLVMStructType::getLiteral(context, SmallVector<Type>(8, f32Ty));
510 auto f16x2x2StructTy =
511 LLVM::LLVMStructType::getLiteral(context, {f16x2Ty, f16x2Ty});
512 auto f32x4StructTy =
513 LLVM::LLVMStructType::getLiteral(context, {f32Ty, f32Ty, f32Ty, f32Ty});
514 auto s32x2StructTy =
515 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty});
516
517 std::array<int64_t, 3> mmaShape{getShapeAttr().getM(), getShapeAttr().getN(),
518 getShapeAttr().getK()};
519
520 // These variables define the set of allowed data types for matrices A, B, C,
521 // and result.
522 using AllowedShapes = SmallVector<std::array<int64_t, 3>, 2>;
523 using AllowedTypes = SmallVector<SmallVector<Type, 4>, 2>;
524 AllowedShapes allowedShapes;
525 AllowedTypes expectedA;
526 AllowedTypes expectedB;
527 AllowedTypes expectedC;
528 SmallVector<Type> expectedResult;
529
530 // When M = 16, we just need to calculate the number of 8xk tiles, where
531 // k is a factor that depends on the data type.
532 if (mmaShape[0] == 16) {
533 int64_t kFactor;
534 Type multiplicandFragType;
535 switch (*getMultiplicandAPtxType()) {
536 case MMATypes::tf32:
537 kFactor = 4;
538 multiplicandFragType = i32Ty;
539 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
540 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
541 break;
542 case MMATypes::bf16:
543 kFactor = 8;
544 multiplicandFragType = i32Ty;
545 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
546 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
547 break;
548 case MMATypes::f16:
549 kFactor = 8;
550 multiplicandFragType = f16x2Ty;
551 expectedResult.push_back(f16x2x2StructTy);
552 expectedResult.push_back(f32x4StructTy);
553 break;
554 case MMATypes::e4m3:
555 case MMATypes::e5m2:
556 // FP8 (m16n8k16 / m16n8k32) packs 4 values per 32-bit register, same
557 // as s8/u8, but the accumulator is f16 or f32 (not integer).
558 kFactor = 16;
559 multiplicandFragType = i32Ty;
560 expectedResult.push_back(f16x2x2StructTy);
561 expectedResult.push_back(f32x4StructTy);
562 break;
563 case MMATypes::s4:
564 case MMATypes::u4:
565 kFactor = 32;
566 break;
567 case MMATypes::b1:
568 kFactor = 128;
569 break;
570 case MMATypes::s8:
571 case MMATypes::u8:
572 kFactor = 16;
573 break;
574 default:
575 return emitError("invalid shape or multiplicand type: ")
576 << getMultiplicandAPtxType().value();
577 }
578
579 if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
580 expectedResult.push_back(s32x4StructTy);
581 expectedC.emplace_back(4, i32Ty);
582 multiplicandFragType = i32Ty;
583 } else {
584 expectedC.emplace_back(2, f16x2Ty);
585 expectedC.emplace_back(4, f32Ty);
586 }
587
588 int64_t unitA = (mmaShape[0] / 8) * (mmaShape[2] / kFactor);
589 int64_t unitB = (mmaShape[1] / 8) * (mmaShape[2] / kFactor);
590 expectedA.emplace_back(unitA, multiplicandFragType);
591 expectedB.emplace_back(unitB, multiplicandFragType);
592 allowedShapes.push_back({16, 8, kFactor});
593 allowedShapes.push_back({16, 8, kFactor * 2});
594
595 if (resultPtxType() != accumPtxType())
596 return emitOpError("ctype does not match dtype");
597 }
598
599 // In the M=8 case, there is only 1 possible case per data type.
600 if (mmaShape[0] == 8) {
601 if (*getMultiplicandAPtxType() == MMATypes::f16) {
602 expectedA.emplace_back(2, f16x2Ty);
603 expectedB.emplace_back(2, f16x2Ty);
604 expectedResult.push_back(f16x2x4StructTy);
605 expectedResult.push_back(f32x8StructTy);
606 expectedC.emplace_back(4, f16x2Ty);
607 expectedC.emplace_back(8, f32Ty);
608 allowedShapes.push_back({8, 8, 4});
609 }
610 if (*getMultiplicandAPtxType() == MMATypes::f64) {
611 Type f64Ty = Float64Type::get(context);
612 expectedA.emplace_back(1, f64Ty);
613 expectedB.emplace_back(1, f64Ty);
614 expectedC.emplace_back(2, f64Ty);
615 expectedResult.emplace_back(LLVM::LLVMStructType::getLiteral(
616 context, SmallVector<Type>(2, f64Ty)));
617 allowedShapes.push_back({8, 8, 4});
618 }
619 if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
620 expectedA.push_back({i32Ty});
621 expectedB.push_back({i32Ty});
622 expectedC.push_back({i32Ty, i32Ty});
623 expectedResult.push_back(s32x2StructTy);
624 if (isInt4PtxType(getMultiplicandAPtxType().value()))
625 allowedShapes.push_back({8, 8, 32});
626 if (isInt8PtxType(getMultiplicandAPtxType().value()))
627 allowedShapes.push_back({8, 8, 16});
628 if (getMultiplicandAPtxType().value() == MMATypes::b1)
629 allowedShapes.push_back({8, 8, 128});
630 }
631 }
632
633 std::string errorMessage;
634 llvm::raw_string_ostream errorStream(errorMessage);
635
636 // Check that we matched an existing shape/dtype combination.
637 if (expectedA.empty() || expectedB.empty() || expectedC.empty() ||
638 !llvm::is_contained(allowedShapes, mmaShape)) {
639 errorStream << "unimplemented variant for MMA shape <";
640 llvm::interleaveComma(mmaShape, errorStream);
641 errorStream << ">";
642 return emitOpError(errorMessage);
643 }
644
645 // Verify the operand types for segments of A, B, and C operands.
646 std::array<StringRef, 3> operandNames{"A", "B", "C"};
647 for (const auto &iter : llvm::enumerate(std::array<AllowedTypes, 3>{
648 std::move(expectedA), std::move(expectedB), std::move(expectedC)})) {
649 auto spec = this->getODSOperandIndexAndLength(iter.index());
650 SmallVector<Type, 4> operandTySeg(operand_type_begin() + spec.first,
651 operand_type_begin() + spec.first +
652 spec.second);
653 bool match = llvm::is_contained(iter.value(), operandTySeg);
654
655 if (!match) {
656 errorStream << "Could not match types for the "
657 << operandNames[iter.index()]
658 << " operands; expected one of ";
659 for (const auto &x : iter.value()) {
660 errorStream << x.size() << "x" << x[0] << " ";
661 }
662 errorStream << "but got ";
663 llvm::interleaveComma(operandTySeg, errorStream);
664 return emitOpError(errorMessage);
665 }
666 }
667
668 // Check the result type
669 if (!llvm::any_of(expectedResult, [&](Type expectedResultType) {
670 return expectedResultType == getResult().getType();
671 })) {
672 errorStream
673 << "Could not match allowed types for the result; expected one of ";
674 llvm::interleaveComma(expectedResult, errorStream);
675 errorStream << " but got " << getResult().getType();
676 return emitOpError(errorMessage);
677 }
678
679 // Ensure that binary MMA variants have a b1 MMA operation defined.
680 if (getMultiplicandAPtxType() == MMATypes::b1 && !getB1Op()) {
681 return emitOpError("op requires " + getB1OpAttrName().strref() +
682 " attribute");
683 }
684
685 // Ensure int4/int8 MMA variants specify the accum overflow behavior
686 // attribute.
687 if (isInt4PtxType(*getMultiplicandAPtxType()) ||
688 isInt8PtxType(*getMultiplicandAPtxType())) {
689 if (!getIntOverflowBehavior())
690 return emitOpError("op requires " +
691 getIntOverflowBehaviorAttrName().strref() +
692 " attribute");
693 }
694
695 // Validate layout combinations. According to the operation description, most
696 // MMA operations require layoutA=row and layoutB=col. Only m8n8k4 with f16
697 // can use other layout combinations.
698 bool isM8N8K4_F16 =
699 (mmaShape[0] == 8 && mmaShape[1] == 8 && mmaShape[2] == 4 &&
700 getMultiplicandAPtxType() == MMATypes::f16);
701
702 if (!isM8N8K4_F16) {
703 // For all other shapes/types, layoutA must be row and layoutB must be col
704 if (getLayoutA() != MMALayout::row || getLayoutB() != MMALayout::col) {
705 return emitOpError("requires layoutA = #nvvm.mma_layout<row> and "
706 "layoutB = #nvvm.mma_layout<col> for shape <")
707 << mmaShape[0] << ", " << mmaShape[1] << ", " << mmaShape[2]
708 << "> with element types " << *getMultiplicandAPtxType() << " and "
709 << *getMultiplicandBPtxType()
710 << ". Only m8n8k4 with f16 supports other layouts.";
711 }
712 }
713
714 return success();
715}
716
717MMATypes MmaSpOp::accumPtxType() {
718 std::optional<mlir::NVVM::MMATypes> val = MmaOp::inferOperandMMAType(
719 getODSOperands(2).getTypes().front(), /*isAccumulator=*/true);
720 assert(val.has_value() && "accumulator PTX type should always be inferrable");
721 return val.value();
722}
723
724MMATypes MmaSpOp::resultPtxType() {
725 std::optional<mlir::NVVM::MMATypes> val =
726 MmaOp::inferOperandMMAType(getResult().getType(), /*isAccumulator=*/true);
727 assert(val.has_value() && "result PTX type should always be inferrable");
728 return val.value();
729}
730
732MmaSpOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
733 llvm::IRBuilderBase &builder) {
734 auto thisOp = cast<NVVM::MmaSpOp>(op);
735
736 // Get operands
738 for (mlir::Value v : thisOp.getOperands())
739 args.push_back(mt.lookupValue(v));
740
741 // Get intrinsic ID using the existing getIntrinsicID method
742 auto intId = MmaSpOp::getIntrinsicID(
743 thisOp.getShape().getM(), thisOp.getShape().getN(),
744 thisOp.getShape().getK(), thisOp.getIntOverflowBehavior(),
745 thisOp.getOrderedMetadata(), thisOp.getKind(),
746 *thisOp.getMultiplicandAPtxType(), *thisOp.getMultiplicandBPtxType(),
747 thisOp.accumPtxType(), thisOp.resultPtxType());
748
749 return {intId, args};
750}
751
752void MmaSpOp::print(OpAsmPrinter &p) {
753 SmallVector<Type, 4> regTypes;
754 struct MMAOperandFragment {
755 StringRef operandName;
756 StringRef ptxTypeAttr;
757 SmallVector<Value, 4> regs;
758 explicit MMAOperandFragment(StringRef name, StringRef ptxTypeName)
759 : operandName(name), ptxTypeAttr(ptxTypeName) {}
760 };
761
762 std::array<MMAOperandFragment, 5> frags{
763 MMAOperandFragment("A", getMultiplicandAPtxTypeAttrName()),
764 MMAOperandFragment("B", getMultiplicandBPtxTypeAttrName()),
765 MMAOperandFragment("C", ""), MMAOperandFragment("sparseMetadata", ""),
766 MMAOperandFragment("selector", "")};
767 SmallVector<StringRef, 4> ignoreAttrNames{
768 mlir::NVVM::MmaSpOp::getOperandSegmentSizeAttr()};
769
770 // Handle variadic operands A, B, C
771 for (unsigned fragIdx = 0; fragIdx < 3; fragIdx++) {
772 auto &frag = frags[fragIdx];
773 auto varOperandSpec = getODSOperandIndexAndLength(fragIdx);
774 for (auto operandIdx = varOperandSpec.first;
775 operandIdx < varOperandSpec.first + varOperandSpec.second;
776 operandIdx++) {
777 frag.regs.push_back(this->getOperand(operandIdx));
778 if (operandIdx == varOperandSpec.first) {
779 regTypes.push_back(this->getOperand(operandIdx).getType());
780 }
781 }
782 std::optional<MMATypes> inferredType = MmaOp::inferOperandMMAType(
783 regTypes.back(), /*isAccumulator=*/fragIdx >= 2);
784 if (inferredType)
785 ignoreAttrNames.push_back(frag.ptxTypeAttr);
786 }
787
788 // Handle sparse metadata and selector (single operands)
789 frags[3].regs.push_back(getSparseMetadata());
790 frags[4].regs.push_back(getSparsitySelector());
791
792 auto printMmaSpOperand = [&](const MMAOperandFragment &frag) -> void {
793 p << " " << frag.operandName;
794 p << "[";
795 p.printOperands(frag.regs);
796 p << "]";
797 };
798
799 for (const auto &frag : frags)
800 printMmaSpOperand(frag);
801
802 bool isFirstProperty = true;
803 printMmaProperty(p, isFirstProperty, "shape", getShapeAttr());
804 if (getIntOverflowBehaviorAttr())
805 printMmaEnumProperty(p, isFirstProperty, "int_overflow",
806 getIntOverflowBehaviorAttr());
807 if (getMultiplicandAPtxTypeAttr() &&
808 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
809 printMmaEnumProperty(p, isFirstProperty, "multiplicand_a_ptx_type",
810 getMultiplicandAPtxTypeAttr());
811 if (getMultiplicandBPtxTypeAttr() &&
812 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
813 printMmaEnumProperty(p, isFirstProperty, "multiplicand_b_ptx_type",
814 getMultiplicandBPtxTypeAttr());
815 if (getOrderedMetadata())
816 printMmaUnitProperty(p, isFirstProperty, "ordered_metadata");
817 if (getKindAttr())
818 printMmaEnumProperty(p, isFirstProperty, "kind", getKindAttr());
819 llvm::append_range(
820 ignoreAttrNames,
821 ArrayRef<StringRef>{getShapeAttrName(), getIntOverflowBehaviorAttrName(),
822 getMultiplicandAPtxTypeAttrName(),
823 getMultiplicandBPtxTypeAttrName(),
824 getOrderedMetadataAttrName(), getKindAttrName()});
825 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue(),
826 ignoreAttrNames);
827 p << " : ";
828 p << "(";
829 for (int i = 0; i < 3; ++i) {
830 p << regTypes[i];
831 if (i < 2)
832 p << ", ";
833 }
834 p << ") -> " << getResult().getType();
835}
836
837void MmaSpOp::build(
838 OpBuilder &builder, OperationState &result, Type resultType,
839 ValueRange operandA, ValueRange operandB, ValueRange operandC,
840 Value sparseMetadata, Value sparsitySelector, ArrayRef<int64_t> shape,
841 std::optional<MMAIntOverflow> intOverflow,
842 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes) {
843
844 assert(shape.size() == 3 && "expected shape to have size 3 (m, n, k)");
845 MLIRContext *ctx = builder.getContext();
846 result.addAttribute(
847 "shape", builder.getAttr<MMAShapeAttr>(shape[0], shape[1], shape[2]));
848
849 result.addOperands(operandA);
850 result.addOperands(operandB);
851 result.addOperands(operandC);
852 result.addOperands(sparseMetadata);
853 result.addOperands(sparsitySelector);
854
855 if (multiplicandPtxTypes) {
856 result.addAttribute("multiplicandAPtxType",
857 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
858 result.addAttribute("multiplicandBPtxType",
859 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
860 } else {
861 if (auto res = MmaOp::inferOperandMMAType(operandA[0].getType(), false))
862 result.addAttribute("multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
863 if (auto res = MmaOp::inferOperandMMAType(operandB[0].getType(), false))
864 result.addAttribute("multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
865 }
866
867 if (intOverflow.has_value())
868 result.addAttribute("intOverflowBehavior",
869 MMAIntOverflowAttr::get(ctx, *intOverflow));
870
871 result.addTypes(resultType);
872 result.addAttribute(
873 MmaSpOp::getOperandSegmentSizeAttr(),
874 builder.getDenseI32ArrayAttr({static_cast<int32_t>(operandA.size()),
875 static_cast<int32_t>(operandB.size()),
876 static_cast<int32_t>(operandC.size()), 1,
877 1})); // sparseMetadata and sparsitySelector
878}
879
880ParseResult MmaSpOp::parse(OpAsmParser &parser, OperationState &result) {
881 struct MMAOperandFragment {
882 std::optional<MMATypes> elemtype;
883 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
884 SmallVector<Type> regTypes;
885 };
886
887 Builder &builder = parser.getBuilder();
888 std::array<MMAOperandFragment, 6> frags; // A, B, C, sparseMetadata, selector
889
890 NamedAttrList namedAttributes;
891
892 // A helper to parse the operand segments.
893 auto parseMmaSpOperand = [&](StringRef operandName,
894 MMAOperandFragment &frag) -> LogicalResult {
895 if (parser.parseKeyword(operandName).failed())
896 return failure();
897 if (parser
898 .parseOperandList(frag.regs, OpAsmParser::Delimiter::OptionalSquare)
899 .failed())
900 return failure();
901 return success();
902 };
903
904 // Parse the operand segments.
905 if (parseMmaSpOperand("A", frags[0]).failed())
906 return failure();
907 if (parseMmaSpOperand("B", frags[1]).failed())
908 return failure();
909 if (parseMmaSpOperand("C", frags[2]).failed())
910 return failure();
911 if (parseMmaSpOperand("sparseMetadata", frags[3]).failed())
912 return failure();
913 if (parseMmaSpOperand("selector", frags[4]).failed())
914 return failure();
915
916 if (parseMmaProperties(parser, namedAttributes,
917 {"shape", "int_overflow", "multiplicand_a_ptx_type",
918 "multiplicand_b_ptx_type", "ordered_metadata",
919 "kind"},
920 {"shape"}))
921 return failure();
922
923 // Parse the type specification and resolve operands.
924 SmallVector<Type, 3> operandTypes;
925 if (failed(parser.parseColon()))
926 return failure();
927 if (failed(parser.parseLParen()))
928 return failure();
929 if (failed(parser.parseTypeList(operandTypes)))
930 return failure();
931 if (failed(parser.parseRParen()))
932 return failure();
933 if (operandTypes.size() != 3)
934 return parser.emitError(
935 parser.getNameLoc(),
936 "expected one type for each operand segment but got " +
937 Twine(operandTypes.size()) + " types");
938 for (const auto &iter : llvm::enumerate(operandTypes)) {
939 auto &frag = frags[iter.index()];
940 frag.regTypes.resize(frag.regs.size(), iter.value());
941 if (failed(parser.resolveOperands(frag.regs, frag.regTypes,
942 parser.getNameLoc(), result.operands)))
943 return failure();
944 frag.elemtype =
945 MmaOp::inferOperandMMAType(frag.regTypes[0],
946 /*isAccumulator*/ iter.index() >= 2);
947 }
948
949 Type resultType;
950 if (parser.parseArrow() || parser.parseType(resultType))
951 return failure();
952 frags[5].elemtype =
953 MmaOp::inferOperandMMAType(resultType, /*isAccumulator*/ true);
954
955 // Resolve sparse metadata and selector (assume i32 type)
956 Type i32Type = builder.getIntegerType(32);
957 if (parser
958 .resolveOperands(frags[3].regs, i32Type, parser.getCurrentLocation(),
959 result.operands)
960 .failed())
961 return failure();
962 if (parser
963 .resolveOperands(frags[4].regs, i32Type, parser.getCurrentLocation(),
964 result.operands)
965 .failed())
966 return failure();
967
968 std::array<StringRef, 2> names{"multiplicandAPtxType",
969 "multiplicandBPtxType"};
970 for (unsigned idx = 0; idx < names.size(); idx++) {
971 const auto &frag = frags[idx];
972 std::optional<NamedAttribute> attr = namedAttributes.getNamed(names[idx]);
973 if (!frag.elemtype.has_value() && !attr.has_value()) {
974 return parser.emitError(
975 parser.getNameLoc(),
976 "attribute " + names[idx] +
977 " is not provided explicitly and cannot be inferred");
978 }
979 if (!attr.has_value())
980 result.addAttribute(
981 names[idx], MMATypesAttr::get(parser.getContext(), *frag.elemtype));
982 }
983
984 result.addTypes(resultType);
985 if (!namedAttributes.empty())
986 result.addAttributes(namedAttributes);
987 result.addAttribute(MmaSpOp::getOperandSegmentSizeAttr(),
988 builder.getDenseI32ArrayAttr({
989 static_cast<int32_t>(frags[0].regs.size()),
990 static_cast<int32_t>(frags[1].regs.size()),
991 static_cast<int32_t>(frags[2].regs.size()),
992 1, // sparseMetadata
993 1 // sparsitySelector
994 }));
995 return success();
996}
997
998LogicalResult MmaSpOp::verify() {
999 MLIRContext *context = getContext();
1000 auto f16Ty = Float16Type::get(context);
1001 auto i32Ty = IntegerType::get(context, 32);
1002 auto f16x2Ty = VectorType::get(2, f16Ty);
1003 auto f32Ty = Float32Type::get(context);
1004 auto f16x2x4StructTy = LLVM::LLVMStructType::getLiteral(
1005 context, {f16x2Ty, f16x2Ty, f16x2Ty, f16x2Ty});
1006
1007 auto s32x4StructTy =
1008 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty, i32Ty, i32Ty});
1009 auto f32x8StructTy =
1010 LLVM::LLVMStructType::getLiteral(context, SmallVector<Type>(8, f32Ty));
1011 auto f16x2x2StructTy =
1012 LLVM::LLVMStructType::getLiteral(context, {f16x2Ty, f16x2Ty});
1013 auto f32x4StructTy =
1014 LLVM::LLVMStructType::getLiteral(context, {f32Ty, f32Ty, f32Ty, f32Ty});
1015 auto s32x2StructTy =
1016 LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty});
1017
1018 std::array<int64_t, 3> mmaShape{getShapeAttr().getM(), getShapeAttr().getN(),
1019 getShapeAttr().getK()};
1020
1021 // These variables define the set of allowed data types for matrices A, B, C,
1022 // and result.
1023 using AllowedShapes = SmallVector<std::array<int64_t, 3>, 2>;
1024 using AllowedTypes = SmallVector<SmallVector<Type, 4>, 2>;
1025 AllowedShapes allowedShapes;
1026 AllowedTypes expectedA;
1027 AllowedTypes expectedB;
1028 AllowedTypes expectedC;
1029 SmallVector<Type> expectedResult;
1030
1031 // When M = 16, we just need to calculate the number of 8xk tiles, where
1032 // k is a factor that depends on the data type.
1033 if (mmaShape[0] == 16) {
1034 int64_t kFactor;
1035 Type multiplicandFragType;
1036 switch (*getMultiplicandAPtxType()) {
1037 case MMATypes::tf32:
1038 kFactor = 4;
1039 multiplicandFragType = i32Ty;
1040 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
1041 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
1042 // Sparse MMA supports m16n8k8 and m16n8k16 for tf32
1043 allowedShapes.push_back({16, 8, 8});
1044 allowedShapes.push_back({16, 8, 16});
1045 break;
1046 case MMATypes::bf16:
1047 kFactor = 8;
1048 multiplicandFragType = i32Ty;
1049 expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
1050 context, {f32Ty, f32Ty, f32Ty, f32Ty}));
1051 // Sparse MMA supports m16n8k16 and m16n8k32 for bf16
1052 allowedShapes.push_back({16, 8, 16});
1053 allowedShapes.push_back({16, 8, 32});
1054 break;
1055 case MMATypes::f16:
1056 kFactor = 8;
1057 multiplicandFragType = f16x2Ty;
1058 expectedResult.push_back(f16x2x2StructTy);
1059 expectedResult.push_back(f32x4StructTy);
1060 // Sparse MMA supports m16n8k16 and m16n8k32 for f16
1061 allowedShapes.push_back({16, 8, 16});
1062 allowedShapes.push_back({16, 8, 32});
1063 break;
1064 case MMATypes::s4:
1065 case MMATypes::u4:
1066 kFactor = 32;
1067 // Sparse MMA supports m16n8k64 and m16n8k128 for s4/u4
1068 allowedShapes.push_back({16, 8, 64});
1069 allowedShapes.push_back({16, 8, 128});
1070 break;
1071 case MMATypes::s8:
1072 case MMATypes::u8:
1073 kFactor = 16;
1074 // Sparse MMA supports m16n8k32 and m16n8k64 for s8/u8
1075 allowedShapes.push_back({16, 8, 32});
1076 allowedShapes.push_back({16, 8, 64});
1077 break;
1078 case MMATypes::e4m3:
1079 case MMATypes::e5m2:
1080 case MMATypes::e3m2:
1081 case MMATypes::e2m3:
1082 case MMATypes::e2m1:
1083 kFactor = 16;
1084 multiplicandFragType = i32Ty;
1085 expectedResult.push_back(f16x2x2StructTy);
1086 expectedResult.push_back(f32x4StructTy);
1087 // Sparse MMA supports m16n8k64 for FP8 types
1088 allowedShapes.push_back({16, 8, 64});
1089 break;
1090 default:
1091 return emitError("invalid shape or multiplicand type: ")
1092 << getMultiplicandAPtxType().value();
1093 }
1094
1095 if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
1096 expectedResult.push_back(s32x4StructTy);
1097 expectedC.emplace_back(4, i32Ty);
1098 multiplicandFragType = i32Ty;
1099 } else if (*getMultiplicandAPtxType() >= MMATypes::e4m3 &&
1100 *getMultiplicandAPtxType() <= MMATypes::e2m1) {
1101 // FP8 types
1102 expectedC.emplace_back(2, f16x2Ty);
1103 expectedC.emplace_back(4, f32Ty);
1104 } else {
1105 expectedC.emplace_back(2, f16x2Ty);
1106 expectedC.emplace_back(4, f32Ty);
1107 }
1108
1109 // For sparse MMA, A operand is compressed (2:4 sparsity means half the
1110 // elements)
1111 int64_t unitA = (mmaShape[0] / 8) * (mmaShape[2] / kFactor) / 2;
1112 int64_t unitB = (mmaShape[1] / 8) * (mmaShape[2] / kFactor);
1113 expectedA.emplace_back(unitA, multiplicandFragType);
1114 expectedB.emplace_back(unitB, multiplicandFragType);
1115
1116 if (resultPtxType() != accumPtxType())
1117 return emitOpError("ctype does not match dtype");
1118 }
1119
1120 // In the M=8 case, there is only 1 possible case per data type.
1121 if (mmaShape[0] == 8) {
1122 if (*getMultiplicandAPtxType() == MMATypes::f16) {
1123 expectedA.emplace_back(2, f16x2Ty);
1124 expectedB.emplace_back(2, f16x2Ty);
1125 expectedResult.push_back(f16x2x4StructTy);
1126 expectedResult.push_back(f32x8StructTy);
1127 expectedC.emplace_back(4, f16x2Ty);
1128 expectedC.emplace_back(8, f32Ty);
1129 allowedShapes.push_back({8, 8, 4});
1130 }
1131 if (*getMultiplicandAPtxType() == MMATypes::f64) {
1132 Type f64Ty = Float64Type::get(context);
1133 expectedA.emplace_back(1, f64Ty);
1134 expectedB.emplace_back(1, f64Ty);
1135 expectedC.emplace_back(2, f64Ty);
1136 expectedResult.emplace_back(LLVM::LLVMStructType::getLiteral(
1137 context, SmallVector<Type>(2, f64Ty)));
1138 allowedShapes.push_back({8, 8, 4});
1139 }
1140 if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
1141 expectedA.push_back({i32Ty});
1142 expectedB.push_back({i32Ty});
1143 expectedC.push_back({i32Ty, i32Ty});
1144 expectedResult.push_back(s32x2StructTy);
1145 if (isInt4PtxType(getMultiplicandAPtxType().value()))
1146 allowedShapes.push_back({8, 8, 32});
1147 if (isInt8PtxType(getMultiplicandAPtxType().value()))
1148 allowedShapes.push_back({8, 8, 16});
1149 }
1150 }
1151
1152 std::string errorMessage;
1153 llvm::raw_string_ostream errorStream(errorMessage);
1154
1155 // Check that we matched an existing shape/dtype combination.
1156 if (expectedA.empty() || expectedB.empty() || expectedC.empty() ||
1157 !llvm::is_contained(allowedShapes, mmaShape)) {
1158 errorStream << "unimplemented variant for MMA shape <";
1159 llvm::interleaveComma(mmaShape, errorStream);
1160 errorStream << ">";
1161 return emitOpError(errorMessage);
1162 }
1163
1164 // Verify the operand types for segments of A, B, and C operands.
1165 std::array<StringRef, 3> operandNames{"A", "B", "C"};
1166 for (const auto &iter : llvm::enumerate(std::array<AllowedTypes, 3>{
1167 std::move(expectedA), std::move(expectedB), std::move(expectedC)})) {
1168 auto spec = this->getODSOperandIndexAndLength(iter.index());
1169 SmallVector<Type, 4> operandTySeg(operand_type_begin() + spec.first,
1170 operand_type_begin() + spec.first +
1171 spec.second);
1172 bool match = llvm::is_contained(iter.value(), operandTySeg);
1173
1174 if (!match) {
1175 errorStream << "Could not match types for the "
1176 << operandNames[iter.index()]
1177 << " operands; expected one of ";
1178 for (const auto &x : iter.value()) {
1179 errorStream << x.size() << "x" << x[0] << " ";
1180 }
1181 errorStream << "but got ";
1182 llvm::interleaveComma(operandTySeg, errorStream);
1183 return emitOpError(errorMessage);
1184 }
1185 }
1186
1187 // Check the result type
1188 if (!llvm::any_of(expectedResult, [&](Type expectedResultType) {
1189 return expectedResultType == getResult().getType();
1190 })) {
1191 errorStream
1192 << "Could not match allowed types for the result; expected one of ";
1193 llvm::interleaveComma(expectedResult, errorStream);
1194 errorStream << " but got " << getResult().getType();
1195 return emitOpError(errorMessage);
1196 }
1197
1198 // Ensure int4/int8 MMA variants specify the accum overflow behavior
1199 // attribute.
1200 if (isInt4PtxType(*getMultiplicandAPtxType()) ||
1201 isInt8PtxType(*getMultiplicandAPtxType())) {
1202 if (!getIntOverflowBehavior())
1203 return emitOpError("op requires " +
1204 getIntOverflowBehaviorAttrName().strref() +
1205 " attribute");
1206 }
1207
1208 // Validate sparse metadata type (should be i32)
1209 if (!getSparseMetadata().getType().isInteger(32)) {
1210 return emitOpError() << "sparse metadata must be i32 type";
1211 }
1212
1213 // Validate sparsity selector type (should be i32)
1214 if (!getSparsitySelector().getType().isInteger(32)) {
1215 return emitOpError() << "sparsity selector must be i32 type";
1216 }
1217
1218 return success();
1219}
1220
1221//===----------------------------------------------------------------------===//
1222// MMA Block Scale Operations - Shared Helpers
1223//===----------------------------------------------------------------------===//
1224
1225namespace {
1226// Shared structure for MMA operand fragments (A, B, C)
1227struct MMAOperandFragment {
1228 StringRef operandName;
1229 StringRef ptxTypeAttr;
1230 SmallVector<Value, 4> regs;
1231 explicit MMAOperandFragment(StringRef name, StringRef ptxTypeName)
1232 : operandName(name), ptxTypeAttr(ptxTypeName) {}
1233};
1234} // namespace
1235
1236// Helper to print operand list in the format: name[operands]
1237static void printOperandList(OpAsmPrinter &p, StringRef name,
1238 ArrayRef<Value> operands) {
1239 p << " " << name << "[";
1240 p.printOperands(operands);
1241 p << "]";
1242}
1243
1244// Helper to parse operand list in the format: name[operands]
1245static LogicalResult
1246parseMmaOperand(OpAsmParser &parser, StringRef operandName,
1248 if (parser.parseKeyword(operandName).failed())
1249 return failure();
1251 .failed())
1252 return failure();
1253 return success();
1254}
1255
1256// Helper to process operand fragments and determine which attributes can be
1257// inferred
1258template <typename Op>
1259static void
1260processOperandFragments(Op &op, std::array<MMAOperandFragment, 3> &frags,
1261 SmallVectorImpl<Type> &regTypes,
1262 SmallVectorImpl<StringRef> &ignoreAttrNames) {
1263 for (unsigned fragIdx = 0; fragIdx < frags.size(); fragIdx++) {
1264 auto &frag = frags[fragIdx];
1265 auto varOperandSpec = op.getODSOperandIndexAndLength(fragIdx);
1266 for (auto operandIdx = varOperandSpec.first;
1267 operandIdx < varOperandSpec.first + varOperandSpec.second;
1268 operandIdx++) {
1269 frag.regs.push_back(op.getOperand(operandIdx));
1270 if (fragIdx == 0 && operandIdx == varOperandSpec.first) {
1271 regTypes.push_back(op.getOperand(operandIdx).getType());
1272 }
1273 }
1274 if (fragIdx < 2) {
1275 regTypes.push_back(frag.regs[0].getType());
1276 }
1277 std::optional<MMATypes> inferredType =
1278 MmaOp::inferOperandMMAType(regTypes.back(),
1279 /*isAccumulator=*/fragIdx >= 2);
1280 if (inferredType)
1281 ignoreAttrNames.push_back(frag.ptxTypeAttr);
1282 }
1283}
1284
1285// Helper to parse type signature: (A_type, B_type, C_type)
1286static LogicalResult
1288 SmallVectorImpl<Type> &operandTypes) {
1289 if (parser.parseColon().failed() || parser.parseLParen().failed())
1290 return failure();
1291
1292 auto typeParser = [&]() {
1293 Type ty;
1294 if (parser.parseType(ty).failed())
1295 return failure();
1296 operandTypes.push_back(ty);
1297 return success();
1298 };
1299 if (parser.parseCommaSeparatedList(typeParser))
1300 return failure();
1301
1302 if (operandTypes.size() != 3)
1303 return parser.emitError(parser.getCurrentLocation(),
1304 "expected exactly 3 types");
1305
1306 return parser.parseRParen();
1307}
1308
1309// Helper to infer and set multiplicand PTX type attributes
1310static void
1312 const SmallVectorImpl<Type> &operandTypes) {
1313 if (!attrs.get("multiplicandAPtxType")) {
1314 if (auto inferredType =
1315 MmaOp::inferOperandMMAType(operandTypes[0], false)) {
1316 attrs.set("multiplicandAPtxType", MMATypesAttr::get(ctx, *inferredType));
1317 }
1318 }
1319 if (!attrs.get("multiplicandBPtxType")) {
1320 if (auto inferredType =
1321 MmaOp::inferOperandMMAType(operandTypes[1], false)) {
1322 attrs.set("multiplicandBPtxType", MMATypesAttr::get(ctx, *inferredType));
1323 }
1324 }
1325}
1326
1327// Helper to add common block scale properties
1328template <typename OpType>
1331 ScaleVecSize scaleVecSize,
1332 BlockScaleFormat blockScaleFormat,
1333 MMABlockScaleKind kind) {
1334 MLIRContext *ctx = builder.getContext();
1335 auto &properties = result.getOrAddProperties<typename OpType::Properties>();
1336 properties.setShape(
1337 builder.getAttr<MMAShapeAttr>(shape[0], shape[1], shape[2]));
1338 properties.setScaleVecSize(ScaleVecSizeAttr::get(ctx, scaleVecSize));
1339 properties.setBlockScaleFormat(
1340 BlockScaleFormatAttr::get(ctx, blockScaleFormat));
1341 properties.setKind(MMABlockScaleKindAttr::get(ctx, kind));
1342}
1343
1344// Helper to infer and add multiplicand PTX types to builder
1347 ValueRange operandB,
1348 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes) {
1349 if (multiplicandPtxTypes) {
1350 result.addAttribute("multiplicandAPtxType",
1351 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
1352 result.addAttribute("multiplicandBPtxType",
1353 MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
1354 } else {
1355 if (auto res = MmaOp::inferOperandMMAType(operandA[0].getType(), false))
1356 result.addAttribute("multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
1357 if (auto res = MmaOp::inferOperandMMAType(operandB[0].getType(), false))
1358 result.addAttribute("multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
1359 }
1360}
1361
1362// Template helper for common accumPtxType/resultPtxType implementation
1363template <typename OpTy>
1364static MMATypes inferPtxTypeFromResult(OpTy op) {
1365 return *MmaOp::inferOperandMMAType(
1366 cast<LLVM::LLVMStructType>(op.getRes().getType()).getBody()[0],
1367 /*isAccumulator=*/true);
1368}
1369
1370//===----------------------------------------------------------------------===//
1371// MmaBlockScaleOp
1372//===----------------------------------------------------------------------===//
1373
1374void MmaBlockScaleOp::print(OpAsmPrinter &p) {
1375 SmallVector<Type, 4> regTypes;
1376 std::array<MMAOperandFragment, 3> frags{
1377 MMAOperandFragment("A", getMultiplicandAPtxTypeAttrName()),
1378 MMAOperandFragment("B", getMultiplicandBPtxTypeAttrName()),
1379 MMAOperandFragment("C", "")};
1380 SmallVector<StringRef, 4> ignoreAttrNames{
1381 mlir::NVVM::MmaBlockScaleOp::getOperandSegmentSizeAttr()};
1382
1383 processOperandFragments(*this, frags, regTypes, ignoreAttrNames);
1384
1385 // Print A, B, C operands
1386 for (const auto &frag : frags)
1387 printOperandList(p, frag.operandName, frag.regs);
1388
1389 // Print scale operands
1390 printOperandList(p, "scaleA",
1391 {getScaleAData(), getByteIdA(), getThreadIdA()});
1392 printOperandList(p, "scaleB",
1393 {getScaleBData(), getByteIdB(), getThreadIdB()});
1394
1395 bool isFirstProperty = true;
1396 printMmaProperty(p, isFirstProperty, "shape", getShapeAttr());
1397 if (getMultiplicandAPtxTypeAttr() &&
1398 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
1399 printMmaEnumProperty(p, isFirstProperty, "multiplicand_a_ptx_type",
1400 getMultiplicandAPtxTypeAttr());
1401 if (getMultiplicandBPtxTypeAttr() &&
1402 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
1403 printMmaEnumProperty(p, isFirstProperty, "multiplicand_b_ptx_type",
1404 getMultiplicandBPtxTypeAttr());
1405 printMmaEnumProperty(p, isFirstProperty, "scale_vec_size",
1406 getScaleVecSizeAttr());
1407 printMmaEnumProperty(p, isFirstProperty, "block_scale_format",
1408 getBlockScaleFormatAttr());
1409 printMmaEnumProperty(p, isFirstProperty, "kind", getKindAttr());
1410 llvm::append_range(
1411 ignoreAttrNames,
1412 ArrayRef<StringRef>{getShapeAttrName(), getMultiplicandAPtxTypeAttrName(),
1413 getMultiplicandBPtxTypeAttrName(),
1414 getScaleVecSizeAttrName(),
1415 getBlockScaleFormatAttrName(), getKindAttrName()});
1416 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue(),
1417 ignoreAttrNames);
1418
1419 // Print type signature
1420 p << " : (";
1421 llvm::interleaveComma(SmallVector<Type, 3>{frags[0].regs[0].getType(),
1422 frags[1].regs[0].getType(),
1423 frags[2].regs[0].getType()},
1424 p);
1425 p << ")";
1426 p.printArrowTypeList(TypeRange{this->getRes().getType()});
1427}
1428
1429ParseResult MmaBlockScaleOp::parse(OpAsmParser &parser,
1431 struct LocalOperandFragment {
1432 std::optional<MMATypes> elemtype;
1433 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
1434 };
1435
1436 Builder &builder = parser.getBuilder();
1437 std::array<LocalOperandFragment, 3> frags;
1438 NamedAttrList namedAttributes;
1439
1440 // Parse A[...] B[...] C[...]
1441 if (parseMmaOperand(parser, "A", frags[0].regs).failed() ||
1442 parseMmaOperand(parser, "B", frags[1].regs).failed() ||
1443 parseMmaOperand(parser, "C", frags[2].regs).failed())
1444 return failure();
1445
1446 // Parse scale operands: scaleA[...] scaleB[...]
1447 SmallVector<OpAsmParser::UnresolvedOperand, 3> scaleAOperands, scaleBOperands;
1448 if (parseMmaOperand(parser, "scaleA", scaleAOperands).failed() ||
1449 parseMmaOperand(parser, "scaleB", scaleBOperands).failed())
1450 return failure();
1451
1452 if (parseMmaProperties(parser, namedAttributes,
1453 {"shape", "multiplicand_a_ptx_type",
1454 "multiplicand_b_ptx_type", "scale_vec_size",
1455 "block_scale_format", "kind"},
1456 {"shape", "scaleVecSize", "blockScaleFormat", "kind"}))
1457 return failure();
1458
1459 // Parse type signature
1460 SmallVector<Type, 3> operandTypes;
1461 if (parseMmaTypeSignature(parser, operandTypes).failed())
1462 return failure();
1463
1464 // Parse result type
1465 SmallVector<Type, 1> resultTypes;
1466 if (parser.parseArrowTypeList(resultTypes).failed())
1467 return failure();
1468
1469 // Infer element types and resolve operands
1470 for (const auto &[idx, frag] : llvm::enumerate(frags)) {
1471 frag.elemtype = MmaOp::inferOperandMMAType(operandTypes[idx],
1472 /*isAccumulator=*/idx >= 2);
1473 if (parser
1474 .resolveOperands(frag.regs, operandTypes[idx], parser.getNameLoc(),
1475 result.operands)
1476 .failed())
1477 return failure();
1478 }
1479
1480 // Resolve scale operands
1481 SmallVector<Type, 3> scaleTypes = {builder.getI32Type(), builder.getI16Type(),
1482 builder.getI16Type()};
1483 if (parser
1484 .resolveOperands(scaleAOperands, scaleTypes, parser.getNameLoc(),
1485 result.operands)
1486 .failed() ||
1487 parser
1488 .resolveOperands(scaleBOperands, scaleTypes, parser.getNameLoc(),
1489 result.operands)
1490 .failed())
1491 return failure();
1492
1493 // Add attributes
1494 result.addAttributes(namedAttributes);
1495 inferAndSetMultiplicandTypes(parser.getContext(), result.attributes,
1496 operandTypes);
1497
1498 result.addTypes(resultTypes);
1499 result.addAttribute(MmaBlockScaleOp::getOperandSegmentSizeAttr(),
1500 builder.getDenseI32ArrayAttr({
1501 static_cast<int32_t>(frags[0].regs.size()),
1502 static_cast<int32_t>(frags[1].regs.size()),
1503 static_cast<int32_t>(frags[2].regs.size()),
1504 1, // scaleAData
1505 1, // byteIdA
1506 1, // threadIdA
1507 1, // scaleBData
1508 1, // byteIdB
1509 1 // threadIdB
1510 }));
1511 return success();
1512}
1513
1514void MmaBlockScaleOp::build(
1515 OpBuilder &builder, OperationState &result, Type resultType,
1516 ValueRange operandA, ValueRange operandB, ValueRange operandC,
1517 Value scaleAData, Value byteIdA, Value threadIdA, Value scaleBData,
1518 Value byteIdB, Value threadIdB, ArrayRef<int64_t> shape,
1519 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
1520 ScaleVecSize scaleVecSize, BlockScaleFormat blockScaleFormat,
1521 MMABlockScaleKind kind) {
1522 assert(shape.size() == 3 && "expected shape to have size 3 (m, n, k)");
1523
1525 blockScaleFormat, kind);
1526
1527 result.addOperands(operandA);
1528 result.addOperands(operandB);
1529 result.addOperands(operandC);
1530 result.addOperands(
1531 {scaleAData, byteIdA, threadIdA, scaleBData, byteIdB, threadIdB});
1532
1533 addInferredMultiplicandTypes(builder.getContext(), result, operandA, operandB,
1534 multiplicandPtxTypes);
1535
1536 result.addTypes(resultType);
1537 result.addAttribute(MmaBlockScaleOp::getOperandSegmentSizeAttr(),
1538 builder.getDenseI32ArrayAttr({
1539 static_cast<int32_t>(operandA.size()),
1540 static_cast<int32_t>(operandB.size()),
1541 static_cast<int32_t>(operandC.size()),
1542 1, // scaleAData
1543 1, // byteIdA
1544 1, // threadIdA
1545 1, // scaleBData
1546 1, // byteIdB
1547 1 // threadIdB
1548 }));
1549}
1550
1551NVVM::IDArgPair MmaBlockScaleOp::getIntrinsicIDAndArgs(
1552 Operation &op, LLVM::ModuleTranslation &mt, llvm::IRBuilderBase &builder) {
1553 auto curOp = cast<NVVM::MmaBlockScaleOp>(op);
1554
1556 // Add A, B, C operands
1557 for (Value operand : curOp.getOperandA())
1558 args.push_back(mt.lookupValue(operand));
1559 for (Value operand : curOp.getOperandB())
1560 args.push_back(mt.lookupValue(operand));
1561 for (Value operand : curOp.getOperandC())
1562 args.push_back(mt.lookupValue(operand));
1563
1564 // Add scale operands
1565 args.push_back(mt.lookupValue(curOp.getScaleAData()));
1566 args.push_back(mt.lookupValue(curOp.getByteIdA()));
1567 args.push_back(mt.lookupValue(curOp.getThreadIdA()));
1568 args.push_back(mt.lookupValue(curOp.getScaleBData()));
1569 args.push_back(mt.lookupValue(curOp.getByteIdB()));
1570 args.push_back(mt.lookupValue(curOp.getThreadIdB()));
1571
1572 unsigned intId = MmaBlockScaleOp::getIntrinsicID(
1573 curOp.getShape().getM(), curOp.getShape().getN(), curOp.getShape().getK(),
1574 *curOp.getMultiplicandAPtxType(), *curOp.getMultiplicandBPtxType(),
1575 inferPtxTypeFromResult(curOp), curOp.getScaleVecSize(),
1576 curOp.getBlockScaleFormat(), curOp.getKind());
1577
1578 return {intId, args};
1579}
1580
1581LogicalResult MmaBlockScaleOp::verify() {
1582 LogicalResult result = success();
1583 int m = getShape().getM();
1584 int n = getShape().getN();
1585 int k = getShape().getK();
1586
1587 if (m == 16 && n == 8 && k == 64) {
1588 if (getMultiplicandAPtxType() != NVVM::MMATypes::e2m1 ||
1589 getMultiplicandBPtxType() != NVVM::MMATypes::e2m1)
1590 result = emitOpError(
1591 "unsupported MMATypes attribute for mma.m16n8k64.(mxf4nvf4|mxf4)");
1592 if (getKind() == NVVM::MMABlockScaleKind::MXF4) {
1593 if (getScaleVecSize() != NVVM::ScaleVecSize::X2)
1594 result = emitOpError(
1595 "unsupported ScaleVecSize attribute for mma.m16n8k64.mxf4");
1596 if (getBlockScaleFormat() != NVVM::BlockScaleFormat::UE8M0)
1597 result = emitOpError(
1598 "unsupported BlockScaleFormat attribute for mma.m16n8k64.mxf4");
1599 } else if (getKind() == NVVM::MMABlockScaleKind::MXF4NVF4) {
1600 if (!((getScaleVecSize() == NVVM::ScaleVecSize::X2 &&
1601 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0) ||
1602 (getScaleVecSize() == NVVM::ScaleVecSize::X4 &&
1603 (getBlockScaleFormat() == NVVM::BlockScaleFormat::UE4M3 ||
1604 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))))
1605 result = emitOpError("unsupported ScaleVecSize and BlockScaleFormat "
1606 "attributes for mma.m16n8k64.mxf4nvf4");
1607 } else {
1608 result = emitOpError("unsupported Kind attribute for mma.m16n8k64");
1609 }
1610 } else if (m == 16 && n == 8 && k == 32) {
1611 if (!(getKind() == NVVM::MMABlockScaleKind::MXF8F6F4 &&
1612 getScaleVecSize() == NVVM::ScaleVecSize::X1 &&
1613 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))
1614 result =
1615 emitOpError("unsupported Kind, ScaleVecSize and BlockScaleFormat "
1616 "attributes for mma.m16n8k32");
1617 } else {
1618 result = emitOpError("unsupported Geom for mma with block scaling");
1619 }
1620 return result;
1621}
1622
1623//===----------------------------------------------------------------------===//
1624// MmaSpBlockScaleOp
1625//===----------------------------------------------------------------------===//
1626
1627void MmaSpBlockScaleOp::print(OpAsmPrinter &p) {
1628 SmallVector<Type, 4> regTypes;
1629 std::array<MMAOperandFragment, 3> frags{
1630 MMAOperandFragment("A", getMultiplicandAPtxTypeAttrName()),
1631 MMAOperandFragment("B", getMultiplicandBPtxTypeAttrName()),
1632 MMAOperandFragment("C", "")};
1633 SmallVector<StringRef, 4> ignoreAttrNames{
1634 mlir::NVVM::MmaSpBlockScaleOp::getOperandSegmentSizeAttr()};
1635
1636 processOperandFragments(*this, frags, regTypes, ignoreAttrNames);
1637
1638 // Print A, B, C operands
1639 for (const auto &frag : frags)
1640 printOperandList(p, frag.operandName, frag.regs);
1641
1642 // Print sparse-specific operands
1643 printOperandList(p, "sparseMetadata", {getSparseMetadata()});
1644 printOperandList(p, "selector", {getSparsitySelector()});
1645
1646 // Print scale operands
1647 printOperandList(p, "scaleA",
1648 {getScaleAData(), getByteIdA(), getThreadIdA()});
1649 printOperandList(p, "scaleB",
1650 {getScaleBData(), getByteIdB(), getThreadIdB()});
1651
1652 bool isFirstProperty = true;
1653 printMmaProperty(p, isFirstProperty, "shape", getShapeAttr());
1654 if (getMultiplicandAPtxTypeAttr() &&
1655 !llvm::is_contained(ignoreAttrNames, getMultiplicandAPtxTypeAttrName()))
1656 printMmaEnumProperty(p, isFirstProperty, "multiplicand_a_ptx_type",
1657 getMultiplicandAPtxTypeAttr());
1658 if (getMultiplicandBPtxTypeAttr() &&
1659 !llvm::is_contained(ignoreAttrNames, getMultiplicandBPtxTypeAttrName()))
1660 printMmaEnumProperty(p, isFirstProperty, "multiplicand_b_ptx_type",
1661 getMultiplicandBPtxTypeAttr());
1662 printMmaUnitProperty(p, isFirstProperty, "ordered_metadata");
1663 printMmaEnumProperty(p, isFirstProperty, "scale_vec_size",
1664 getScaleVecSizeAttr());
1665 printMmaEnumProperty(p, isFirstProperty, "block_scale_format",
1666 getBlockScaleFormatAttr());
1667 printMmaEnumProperty(p, isFirstProperty, "kind", getKindAttr());
1668 llvm::append_range(
1669 ignoreAttrNames,
1670 ArrayRef<StringRef>{getShapeAttrName(), getMultiplicandAPtxTypeAttrName(),
1671 getMultiplicandBPtxTypeAttrName(),
1672 getOrderedMetadataAttrName(),
1673 getScaleVecSizeAttrName(),
1674 getBlockScaleFormatAttrName(), getKindAttrName()});
1675 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue(),
1676 ignoreAttrNames);
1677
1678 // Print type signature
1679 p << " : (";
1680 llvm::interleaveComma(SmallVector<Type, 3>{frags[0].regs[0].getType(),
1681 frags[1].regs[0].getType(),
1682 frags[2].regs[0].getType()},
1683 p);
1684 p << ")";
1685 p.printArrowTypeList(TypeRange{this->getRes().getType()});
1686}
1687
1688ParseResult MmaSpBlockScaleOp::parse(OpAsmParser &parser,
1690 struct LocalOperandFragment {
1691 std::optional<MMATypes> elemtype;
1692 SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
1693 };
1694
1695 Builder &builder = parser.getBuilder();
1696 std::array<LocalOperandFragment, 3> frags;
1697 NamedAttrList namedAttributes;
1698
1699 // Parse A[...] B[...] C[...]
1700 if (parseMmaOperand(parser, "A", frags[0].regs).failed() ||
1701 parseMmaOperand(parser, "B", frags[1].regs).failed() ||
1702 parseMmaOperand(parser, "C", frags[2].regs).failed())
1703 return failure();
1704
1705 // Parse sparse-specific operands
1707 selectorOperands;
1708 if (parseMmaOperand(parser, "sparseMetadata", metadataOperands).failed() ||
1709 parseMmaOperand(parser, "selector", selectorOperands).failed())
1710 return failure();
1711
1712 // Parse scale operands
1713 SmallVector<OpAsmParser::UnresolvedOperand, 3> scaleAOperands, scaleBOperands;
1714 if (parseMmaOperand(parser, "scaleA", scaleAOperands).failed() ||
1715 parseMmaOperand(parser, "scaleB", scaleBOperands).failed())
1716 return failure();
1717
1718 if (parseMmaProperties(parser, namedAttributes,
1719 {"shape", "multiplicand_a_ptx_type",
1720 "multiplicand_b_ptx_type", "ordered_metadata",
1721 "scale_vec_size", "block_scale_format", "kind"},
1722 {"shape", "scaleVecSize", "blockScaleFormat", "kind"}))
1723 return failure();
1724
1725 // Parse type signature
1726 SmallVector<Type, 3> operandTypes;
1727 if (parseMmaTypeSignature(parser, operandTypes).failed())
1728 return failure();
1729
1730 // Parse result type
1731 SmallVector<Type, 1> resultTypes;
1732 if (parser.parseArrowTypeList(resultTypes).failed())
1733 return failure();
1734
1735 // Infer element types and resolve operands
1736 for (const auto &[idx, frag] : llvm::enumerate(frags)) {
1737 frag.elemtype = MmaOp::inferOperandMMAType(operandTypes[idx],
1738 /*isAccumulator=*/idx >= 2);
1739 if (parser
1740 .resolveOperands(frag.regs, operandTypes[idx], parser.getNameLoc(),
1741 result.operands)
1742 .failed())
1743 return failure();
1744 }
1745
1746 // Resolve sparse metadata and selector
1747 Type i32Type = builder.getI32Type();
1748 if (parser
1749 .resolveOperands(metadataOperands, i32Type, parser.getNameLoc(),
1750 result.operands)
1751 .failed() ||
1752 parser
1753 .resolveOperands(selectorOperands, i32Type, parser.getNameLoc(),
1754 result.operands)
1755 .failed())
1756 return failure();
1757
1758 // Resolve scale operands
1759 SmallVector<Type, 3> scaleTypes = {i32Type, builder.getI16Type(),
1760 builder.getI16Type()};
1761 if (parser
1762 .resolveOperands(scaleAOperands, scaleTypes, parser.getNameLoc(),
1763 result.operands)
1764 .failed() ||
1765 parser
1766 .resolveOperands(scaleBOperands, scaleTypes, parser.getNameLoc(),
1767 result.operands)
1768 .failed())
1769 return failure();
1770
1771 // Add attributes
1772 result.addAttributes(namedAttributes);
1773 inferAndSetMultiplicandTypes(parser.getContext(), result.attributes,
1774 operandTypes);
1775
1776 // orderedMetadata is mandatory
1777 if (!result.attributes.get("orderedMetadata"))
1778 result.addAttribute("orderedMetadata", builder.getUnitAttr());
1779
1780 result.addTypes(resultTypes);
1781 result.addAttribute(MmaSpBlockScaleOp::getOperandSegmentSizeAttr(),
1782 builder.getDenseI32ArrayAttr({
1783 static_cast<int32_t>(frags[0].regs.size()),
1784 static_cast<int32_t>(frags[1].regs.size()),
1785 static_cast<int32_t>(frags[2].regs.size()),
1786 1, // sparseMetadata
1787 1, // sparsitySelector
1788 1, // scaleAData
1789 1, // byteIdA
1790 1, // threadIdA
1791 1, // scaleBData
1792 1, // byteIdB
1793 1 // threadIdB
1794 }));
1795 return success();
1796}
1797
1798void MmaSpBlockScaleOp::build(
1799 OpBuilder &builder, OperationState &result, Type resultType,
1800 ValueRange operandA, ValueRange operandB, ValueRange operandC,
1801 Value sparseMetadata, Value sparsitySelector, Value scaleAData,
1802 Value byteIdA, Value threadIdA, Value scaleBData, Value byteIdB,
1803 Value threadIdB, ArrayRef<int64_t> shape,
1804 std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
1805 ScaleVecSize scaleVecSize, BlockScaleFormat blockScaleFormat,
1806 MMABlockScaleKind kind) {
1807 assert(shape.size() == 3 && "expected shape to have size 3 (m, n, k)");
1808
1810 builder, result, shape, scaleVecSize, blockScaleFormat, kind);
1811 result.addAttribute("orderedMetadata", builder.getUnitAttr());
1812
1813 result.addOperands(operandA);
1814 result.addOperands(operandB);
1815 result.addOperands(operandC);
1816 result.addOperands({sparseMetadata, sparsitySelector, scaleAData, byteIdA,
1817 threadIdA, scaleBData, byteIdB, threadIdB});
1818
1819 addInferredMultiplicandTypes(builder.getContext(), result, operandA, operandB,
1820 multiplicandPtxTypes);
1821
1822 result.addTypes(resultType);
1823 result.addAttribute(MmaSpBlockScaleOp::getOperandSegmentSizeAttr(),
1824 builder.getDenseI32ArrayAttr({
1825 static_cast<int32_t>(operandA.size()),
1826 static_cast<int32_t>(operandB.size()),
1827 static_cast<int32_t>(operandC.size()),
1828 1, // sparseMetadata
1829 1, // sparsitySelector
1830 1, // scaleAData
1831 1, // byteIdA
1832 1, // threadIdA
1833 1, // scaleBData
1834 1, // byteIdB
1835 1 // threadIdB
1836 }));
1837}
1838
1839NVVM::IDArgPair MmaSpBlockScaleOp::getIntrinsicIDAndArgs(
1840 Operation &op, LLVM::ModuleTranslation &mt, llvm::IRBuilderBase &builder) {
1841 auto curOp = cast<NVVM::MmaSpBlockScaleOp>(op);
1842
1844 // Add A, B, C operands
1845 for (Value operand : curOp.getOperandA())
1846 args.push_back(mt.lookupValue(operand));
1847 for (Value operand : curOp.getOperandB())
1848 args.push_back(mt.lookupValue(operand));
1849 for (Value operand : curOp.getOperandC())
1850 args.push_back(mt.lookupValue(operand));
1851
1852 // Add sparse metadata and selector
1853 args.push_back(mt.lookupValue(curOp.getSparseMetadata()));
1854 args.push_back(mt.lookupValue(curOp.getSparsitySelector()));
1855
1856 // Add scale operands
1857 args.push_back(mt.lookupValue(curOp.getScaleAData()));
1858 args.push_back(mt.lookupValue(curOp.getByteIdA()));
1859 args.push_back(mt.lookupValue(curOp.getThreadIdA()));
1860 args.push_back(mt.lookupValue(curOp.getScaleBData()));
1861 args.push_back(mt.lookupValue(curOp.getByteIdB()));
1862 args.push_back(mt.lookupValue(curOp.getThreadIdB()));
1863
1864 unsigned intId = MmaSpBlockScaleOp::getIntrinsicID(
1865 curOp.getShape().getM(), curOp.getShape().getN(), curOp.getShape().getK(),
1866 *curOp.getMultiplicandAPtxType(), *curOp.getMultiplicandBPtxType(),
1867 inferPtxTypeFromResult(curOp), curOp.getScaleVecSize(),
1868 curOp.getBlockScaleFormat(), curOp.getKind());
1869
1870 return {intId, args};
1871}
1872
1873LogicalResult MmaSpBlockScaleOp::verify() {
1874 // Check that orderedMetadata is present
1875 if (!getOrderedMetadata()) {
1876 return emitOpError("'orderedMetadata' attribute is mandatory");
1877 }
1878
1879 LogicalResult result = success();
1880 int m = getShape().getM();
1881 int n = getShape().getN();
1882 int k = getShape().getK();
1883
1884 if (m == 16 && n == 8 && k == 128) {
1885 if (getMultiplicandAPtxType() != NVVM::MMATypes::e2m1 ||
1886 getMultiplicandBPtxType() != NVVM::MMATypes::e2m1)
1887 result = emitOpError(
1888 "unsupported MMATypes attribute for mma.m16n8k128.(mxf4nvf4|mxf4)");
1889 if (getKind() == NVVM::MMABlockScaleKind::MXF4) {
1890 if (getScaleVecSize() != NVVM::ScaleVecSize::X2)
1891 result = emitOpError(
1892 "unsupported ScaleVecSize attribute for mma.m16n8k128.mxf4");
1893 if (getBlockScaleFormat() != NVVM::BlockScaleFormat::UE8M0)
1894 result = emitOpError(
1895 "unsupported BlockScaleFormat attribute for mma.m16n8k128.mxf4");
1896 } else if (getKind() == NVVM::MMABlockScaleKind::MXF4NVF4) {
1897 if (!((getScaleVecSize() == NVVM::ScaleVecSize::X2 &&
1898 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0) ||
1899 (getScaleVecSize() == NVVM::ScaleVecSize::X4 &&
1900 (getBlockScaleFormat() == NVVM::BlockScaleFormat::UE4M3 ||
1901 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))))
1902 result = emitOpError("unsupported ScaleVecSize and BlockScaleFormat "
1903 "attributes for mma.m16n8k128.mxf4nvf4");
1904 } else {
1905 result = emitOpError("unsupported Kind attribute for mma.m16n8k128");
1906 }
1907 } else if (m == 16 && n == 8 && k == 64) {
1908 if (!(getKind() == NVVM::MMABlockScaleKind::MXF8F6F4 &&
1909 getScaleVecSize() == NVVM::ScaleVecSize::X1 &&
1910 getBlockScaleFormat() == NVVM::BlockScaleFormat::UE8M0))
1911 result =
1912 emitOpError("unsupported Kind, ScaleVecSize and BlockScaleFormat "
1913 "attributes for mma.m16n8k64");
1914 } else {
1915 result = emitOpError("unsupported Geom for sparse mma with block scaling");
1916 }
1917 return result;
1918}
1919
1920std::pair<mlir::Type, unsigned> NVVM::inferMMAType(NVVM::MMATypes type,
1921 NVVM::MMAFrag frag, int nRow,
1922 int nCol,
1923 MLIRContext *context) {
1924 unsigned numberElements = 0;
1925 Type elementType;
1926 OpBuilder builder(context);
1927 Type f16x2 = VectorType::get(2, builder.getF16Type());
1928 if (type == NVVM::MMATypes::f16) {
1929 elementType = f16x2;
1930 if (frag == NVVM::MMAFrag::a || frag == NVVM::MMAFrag::b)
1931 numberElements = 8;
1932 else
1933 numberElements = 4;
1934 } else if (type == NVVM::MMATypes::f32) {
1935 elementType = builder.getF32Type();
1936 numberElements = 8;
1937 } else if (type == NVVM::MMATypes::f64) {
1938 elementType = builder.getF64Type();
1939 if (frag == NVVM::MMAFrag::a || frag == NVVM::MMAFrag::b)
1940 numberElements = 1;
1941 else
1942 numberElements = 2;
1943 } else if (type == NVVM::MMATypes::tf32) {
1944 elementType = builder.getI32Type();
1945 numberElements = 4;
1946 } else if (type == NVVM::MMATypes::s8 || type == NVVM::MMATypes::u8) {
1947 elementType = builder.getI32Type();
1948 int parallelSize = 0;
1949 if (frag == NVVM::MMAFrag::a)
1950 parallelSize = nRow;
1951 if (frag == NVVM::MMAFrag::b)
1952 parallelSize = nCol;
1953
1954 // m == 16 && n == 16 && k == 16
1955 if (parallelSize == 16)
1956 numberElements = 2;
1957 // m == 8 && n == 32 && k == 16 or m == 32 && n == 8 && k == 16
1958 else if (parallelSize == 8)
1959 numberElements = 1;
1960 else if (parallelSize == 32)
1961 numberElements = 4;
1962 } else if (type == NVVM::MMATypes::s32) {
1963 elementType = builder.getI32Type();
1964 numberElements = 8;
1965 }
1966 assert(numberElements != 0 && elementType != nullptr);
1967 return std::make_pair(elementType, numberElements);
1968}
1969
1970static std::pair<mlir::Type, unsigned>
1971inferMMATypeFromMNK(NVVM::MMATypes type, NVVM::MMAFrag frag, int m, int n,
1972 int k, MLIRContext *context) {
1973 int nRow, nCol;
1974 if (frag == NVVM::MMAFrag::a) {
1975 nRow = m;
1976 nCol = k;
1977 } else if (frag == NVVM::MMAFrag::b) {
1978 nRow = k;
1979 nCol = n;
1980 } else {
1981 nRow = m;
1982 nCol = n;
1983 }
1984 assert(nRow && nCol);
1985 return inferMMAType(type, frag, nRow, nCol, context);
1986}
1987
1988LogicalResult NVVM::WMMALoadOp::verify() {
1989 unsigned addressSpace =
1990 llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
1991 if (addressSpace != 0 && addressSpace != NVVMMemorySpace::Global &&
1992 addressSpace != NVVMMemorySpace::Shared)
1993 return emitOpError("expected source pointer in memory "
1994 "space 0, 1, 3");
1995
1996 if (NVVM::WMMALoadOp::getIntrinsicID(getM(), getN(), getK(), getLayout(),
1997 getEltype(), getFrag()) == 0)
1998 return emitOpError() << "invalid attribute combination";
1999 std::pair<Type, unsigned> typeInfo = inferMMATypeFromMNK(
2000 getEltype(), getFrag(), getM(), getN(), getK(), getContext());
2001 // Special case for f64 fragments
2002 Type f64Ty = Float64Type::get(getContext());
2003 if (typeInfo.first == f64Ty && typeInfo.second == 1) {
2004 if (getType() != f64Ty)
2005 return emitOpError("expected destination type to be f64");
2006 return success();
2007 }
2008 // Everything else is a struct
2009 Type dstType = LLVM::LLVMStructType::getLiteral(
2010 getContext(), SmallVector<Type, 8>(typeInfo.second, typeInfo.first));
2011 if (getType() != dstType)
2012 return emitOpError("expected destination type is a structure of ")
2013 << typeInfo.second << " elements of type " << typeInfo.first;
2014 return success();
2015}
2016
2017LogicalResult NVVM::WMMAStoreOp::verify() {
2018 unsigned addressSpace =
2019 llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
2020 if (addressSpace != 0 && addressSpace != NVVMMemorySpace::Global &&
2021 addressSpace != NVVMMemorySpace::Shared)
2022 return emitOpError("expected operands to be a source pointer in memory "
2023 "space 0, 1, 3");
2024
2025 if (NVVM::WMMAStoreOp::getIntrinsicID(getM(), getN(), getK(), getLayout(),
2026 getEltype()) == 0)
2027 return emitOpError() << "invalid attribute combination";
2028 std::pair<Type, unsigned> typeInfo = inferMMATypeFromMNK(
2029 getEltype(), NVVM::MMAFrag::c, getM(), getN(), getK(), getContext());
2030 if (getArgs().size() != typeInfo.second)
2031 return emitOpError() << "expected " << typeInfo.second << " data operands";
2032 if (llvm::any_of(getArgs(), [&typeInfo](Value operands) {
2033 return operands.getType() != typeInfo.first;
2034 }))
2035 return emitOpError() << "expected data operands of type " << typeInfo.first;
2036 return success();
2037}
2038
2039LogicalResult NVVM::WMMAMmaOp::verify() {
2040 if (NVVM::WMMAMmaOp::getIntrinsicID(getM(), getN(), getK(), getLayoutA(),
2041 getLayoutB(), getEltypeA(),
2042 getEltypeB()) == 0)
2043 return emitOpError() << "invalid attribute combination";
2044 std::pair<Type, unsigned> typeInfoA = inferMMATypeFromMNK(
2045 getEltypeA(), NVVM::MMAFrag::a, getM(), getN(), getK(), getContext());
2046 std::pair<Type, unsigned> typeInfoB = inferMMATypeFromMNK(
2047 getEltypeA(), NVVM::MMAFrag::b, getM(), getN(), getK(), getContext());
2048 std::pair<Type, unsigned> typeInfoC = inferMMATypeFromMNK(
2049 getEltypeB(), NVVM::MMAFrag::c, getM(), getN(), getK(), getContext());
2050 SmallVector<Type, 32> arguments;
2051 arguments.append(typeInfoA.second, typeInfoA.first);
2052 arguments.append(typeInfoB.second, typeInfoB.first);
2053 arguments.append(typeInfoC.second, typeInfoC.first);
2054 unsigned numArgs = arguments.size();
2055 if (getArgs().size() != numArgs)
2056 return emitOpError() << "expected " << numArgs << " arguments";
2057 for (unsigned i = 0; i < numArgs; i++) {
2058 if (getArgs()[i].getType() != arguments[i])
2059 return emitOpError() << "expected argument " << i << " to be of type "
2060 << arguments[i];
2061 }
2062 Type dstType = LLVM::LLVMStructType::getLiteral(
2063 getContext(), SmallVector<Type, 8>(typeInfoC.second, typeInfoC.first));
2064 if (getType() != dstType)
2065 return emitOpError("expected destination type is a structure of ")
2066 << typeInfoC.second << " elements of type " << typeInfoC.first;
2067 return success();
2068}
2069
2070LogicalResult NVVM::LdMatrixOp::verify() {
2071 uint32_t num = getNum(), m = getShape().getM(), n = getShape().getN();
2072 if (m == 8 && n == 8) {
2073 if (num != 1 && num != 2 && num != 4) {
2074 return emitOpError("expected num attribute to be 1, 2 or 4 for 8x8 "
2075 "matrix");
2076 }
2077 if (getEltType() != LdStMatrixEltType::B16) {
2078 return emitOpError("expected element type to be b16 for 8x8 matrix");
2079 }
2080 } else if (m == 8 && n == 16) {
2081 if (num != 1 && num != 2 && num != 4) {
2082 return emitOpError("expected num attribute to be 1, 2 or 4 for 8x16 "
2083 "matrix");
2084 }
2085 if (getLayout() != MMALayout::row) {
2086 return emitOpError("expected layout to be row for 8x16 matrix");
2087 }
2088 if (getEltType() != LdStMatrixEltType::B8X16_B4X16_P64 &&
2089 getEltType() != LdStMatrixEltType::B8X16_B6X16_P32 &&
2090 getEltType() != LdStMatrixEltType::S8_S4) {
2091 return emitOpError("expected element type to be b8x16.b4x16_p64, "
2092 "b8x16.b6x16_p32 or s8.s4 for 8x16 matrix");
2093 }
2094 } else if (m == 16 && n == 16) {
2095 if (num != 1 && num != 2) {
2096 return emitOpError("expected num attribute to be 1 or 2 for 16x16 "
2097 "matrix");
2098 }
2099 if (getLayout() != MMALayout::col) {
2100 return emitOpError("expected layout to be col for 16x16 matrix");
2101 }
2102 if (getEltType() != LdStMatrixEltType::B8 &&
2103 getEltType() != LdStMatrixEltType::B8X16_B4X16_P64 &&
2104 getEltType() != LdStMatrixEltType::B8X16_B6X16_P32) {
2105 return emitOpError("expected element type to be b8, b8x16.b4x16_p64 or "
2106 "b8x16.b6x16_p32 for 16x16 matrix");
2107 }
2108 } else {
2109 return emitOpError("expected shape to be 8x8, 8x16 or 16x16");
2110 }
2111
2112 Type i32 = IntegerType::get(getContext(), 32);
2113 uint32_t numElements = (m == 16 && n == 16 ? num * 2 : num);
2114 if (numElements == 1 && getType() != i32)
2115 return emitOpError("expected destination type is i32");
2116 if (numElements == 2 || numElements == 4) {
2117 Type dstType = LLVM::LLVMStructType::getLiteral(
2118 getContext(), SmallVector<Type>(numElements, i32));
2119 if (getType() != dstType)
2120 return emitOpError("expected destination type is a structure of ")
2121 << numElements << " elements of type i32";
2122 }
2123
2124 return success();
2125}
2126
2127LogicalResult LdMatrixOp::inferReturnTypes(
2128 MLIRContext *context, std::optional<Location> location,
2129 LdMatrixOp::Adaptor adaptor, SmallVectorImpl<Type> &inferredReturnTypes) {
2130 uint32_t num = adaptor.getNum();
2131 uint32_t m = adaptor.getShape().getM();
2132 uint32_t n = adaptor.getShape().getN();
2133 uint32_t numElements = (m == 16 && n == 16) ? num * 2 : num;
2134
2135 Type i32 = IntegerType::get(context, 32);
2136 if (numElements == 1)
2137 inferredReturnTypes.push_back(i32);
2138 else
2139 inferredReturnTypes.push_back(LLVM::LLVMStructType::getLiteral(
2140 context, SmallVector<Type>(numElements, i32)));
2141 return success();
2142}
2143
2144LogicalResult NVVM::StMatrixOp::verify() {
2145 int numMatrix = getSources().size();
2146 if (numMatrix != 1 && numMatrix != 2 && numMatrix != 4)
2147 return emitOpError("expected num attribute to be 1, 2 or 4");
2148
2149 int m = getShape().getM(), n = getShape().getN();
2150 if (m == 8 && n == 8) {
2151 if (getEltType() != NVVM::LdStMatrixEltType::B16) {
2152 return emitOpError("expected element type to be B16 for 8x8 matrix");
2153 }
2154 } else if (m == 16 && n == 8) {
2155 if (getEltType() != NVVM::LdStMatrixEltType::B8) {
2156 return emitOpError("expected element type to be B8 for 16x8 matrix");
2157 }
2158 if (getLayout() != NVVM::MMALayout::col) {
2159 return emitOpError("expected layout to be col for 16x8 matrix");
2160 }
2161 } else {
2162 return emitOpError("expected shape to be 8x8 or 16x8");
2163 }
2164
2165 return success();
2166}
2167
2168LogicalResult NVVM::MovMatrixOp::verify() {
2169 int m = getShape().getM(), n = getShape().getN();
2170 if (m != 8 || n != 8)
2171 return emitOpError("expected shape to be 8x8");
2172 if (getLayout() != NVVM::MMALayout::col)
2173 return emitOpError("expected layout to be col");
2174 if (getEltType() != NVVM::LdStMatrixEltType::B16)
2175 return emitOpError("expected element type to be b16");
2176 return success();
2177}
2178
2179//===----------------------------------------------------------------------===//
2180// getIntrinsicID/getIntrinsicIDAndArgs methods
2181//===----------------------------------------------------------------------===//
2182
2184MovMatrixOp::getIntrinsicIDAndArgs(Operation &op, LLVM::ModuleTranslation &mt,
2185 llvm::IRBuilderBase &builder) {
2186 auto thisOp = cast<NVVM::MovMatrixOp>(op);
2187 return {llvm::Intrinsic::nvvm_movmatrix_sync_aligned_m8n8_trans_b16,
2188 {mt.lookupValue(thisOp.getSrc())}};
2189}
2190
2191#define GET_OP_CLASSES
2192#include "mlir/Dialect/LLVMIR/NVVMMmaOps.cpp.inc"
return success()
b getContext())
static void addInferredMultiplicandTypes(MLIRContext *ctx, OperationState &result, ValueRange operandA, ValueRange operandB, std::optional< std::array< MMATypes, 2 > > multiplicandPtxTypes)
static void addBlockScaleProperties(OpBuilder &builder, OperationState &result, ArrayRef< int64_t > shape, ScaleVecSize scaleVecSize, BlockScaleFormat blockScaleFormat, MMABlockScaleKind kind)
static ParseResult parseEnumKeyword(OpAsmParser &parser, AttrTy &attr)
static void printMmaUnitProperty(OpAsmPrinter &printer, bool &isFirst, StringRef keyword)
static void printOperandList(OpAsmPrinter &p, StringRef name, ArrayRef< Value > operands)
static void printMmaProperty(OpAsmPrinter &printer, bool &isFirst, StringRef keyword, AttrTy value)
static bool isMmaPropertyName(StringRef name)
static void printMmaEnumProperty(OpAsmPrinter &printer, bool &isFirst, StringRef keyword, AttrTy value)
static ParseResult parseMmaProperties(OpAsmParser &parser, NamedAttrList &attributes, ArrayRef< StringRef > allowedKeywords, ArrayRef< StringRef > requiredProperties)
static void inferAndSetMultiplicandTypes(MLIRContext *ctx, NamedAttrList &attrs, const SmallVectorImpl< Type > &operandTypes)
static LogicalResult parseMmaOperand(OpAsmParser &parser, StringRef operandName, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &regs)
static std::pair< mlir::Type, unsigned > inferMMATypeFromMNK(NVVM::MMATypes type, NVVM::MMAFrag frag, int m, int n, int k, MLIRContext *context)
static bool isInt8PtxType(MMATypes type)
static bool isInt4PtxType(MMATypes type)
static bool isIntegerPtxType(MMATypes type)
static MMATypes inferPtxTypeFromResult(OpTy op)
static LogicalResult parseMmaTypeSignature(OpAsmParser &parser, SmallVectorImpl< Type > &operandTypes)
static ParseResult parseMmaEnumPropertyValue(OpAsmParser &parser, NamedAttrList &attributes, StringRef name)
static ParseResult parseMmaPropertyValue(OpAsmParser &parser, NamedAttrList &attributes, StringRef name)
static void processOperandFragments(Op &op, std::array< MMAOperandFragment, 3 > &frags, SmallVectorImpl< Type > &regTypes, SmallVectorImpl< StringRef > &ignoreAttrNames)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseKeywordOrString(std::string *result)
Parse a keyword or a quoted string.
virtual ParseResult parseCustomAttributeWithFallback(Attribute &result, Type type, function_ref< ParseResult(Attribute &result, Type type)> parseAttribute)=0
Parse a custom attribute with the provided callback, unless the next token is #, in which case the ge...
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
ParseResult parseTypeList(SmallVectorImpl< Type > &result)
Parse a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
void printArrowTypeList(TypeRange &&types)
void printStrippedAttrOrType(AttrOrType attrOrType)
Print the provided attribute in the context of an operation custom printer/parser: this will invoke d...
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerType getI16Type()
Definition Builders.cpp:69
UnitAttr getUnitAttr()
Definition Builders.cpp:106
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
MLIRContext * getContext() const
Definition Builders.h:56
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
Implementation class for module translation.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
std::optional< NamedAttribute > getNamed(StringRef name) const
Return the specified named attribute if present, std::nullopt otherwise.
Attribute get(StringAttr name) const
Return the specified attribute if present, null otherwise.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
Attribute set(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
This class helps build Operations.
Definition Builders.h:210
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isF64() const
Definition Types.cpp:41
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isF32() const
Definition Types.cpp:40
bool isF16() const
Definition Types.cpp:38
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
std::pair< mlir::Type, unsigned > inferMMAType(mlir::NVVM::MMATypes type, mlir::NVVM::MMAFrag frag, int nRow, int nCol, mlir::MLIRContext *context)
Return the element type and number of elements associated with a wmma matrix of given chracteristics.
std::pair< llvm::Intrinsic::ID, llvm::SmallVector< llvm::Value * > > IDArgPair
A pair type of LLVM's Intrinsic ID and args (which are llvm values).
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
uint64_t getN(LevelType lt)
Definition Enums.h:442
uint64_t getM(LevelType lt)
Definition Enums.h:443
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
This represents an operation in an abstracted form, suitable for use with the builder APIs.