MLIR  20.0.0git
NVVMDialect.cpp
Go to the documentation of this file.
1 //===- NVVMDialect.cpp - NVVM IR Ops and Dialect registration -------------===//
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 types and operation details for the NVVM IR dialect in
10 // MLIR, and the LLVM IR dialect. It also registers the dialect.
11 //
12 // The NVVM dialect only contains GPU specific additions on top of the general
13 // LLVM dialect.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 
22 #include "mlir/IR/Builders.h"
24 #include "mlir/IR/BuiltinTypes.h"
25 #include "mlir/IR/Diagnostics.h"
27 #include "mlir/IR/MLIRContext.h"
28 #include "mlir/IR/Operation.h"
30 #include "mlir/IR/Types.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/TypeSwitch.h"
33 #include "llvm/AsmParser/Parser.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <cassert>
41 #include <optional>
42 #include <string>
43 
44 using namespace mlir;
45 using namespace NVVM;
46 
47 #include "mlir/Dialect/LLVMIR/NVVMOpsDialect.cpp.inc"
48 #include "mlir/Dialect/LLVMIR/NVVMOpsEnums.cpp.inc"
49 
50 //===----------------------------------------------------------------------===//
51 // Printing/parsing for NVVM ops
52 //===----------------------------------------------------------------------===//
53 
55  p << " " << op->getOperands();
56  if (op->getNumResults() > 0)
57  p << " : " << op->getResultTypes();
58 }
59 
60 // <operation> ::= `llvm.nvvm.vote.ballot.sync %mask, %pred` : result_type
61 ParseResult VoteBallotOp::parse(OpAsmParser &parser, OperationState &result) {
62  MLIRContext *context = parser.getContext();
63  auto int32Ty = IntegerType::get(context, 32);
64  auto int1Ty = IntegerType::get(context, 1);
65 
67  Type type;
68  return failure(parser.parseOperandList(ops) ||
69  parser.parseOptionalAttrDict(result.attributes) ||
70  parser.parseColonType(type) ||
71  parser.addTypeToList(type, result.types) ||
72  parser.resolveOperands(ops, {int32Ty, int1Ty},
73  parser.getNameLoc(), result.operands));
74 }
75 
77 
78 // This verifier is shared among the following Ops:
79 // CpAsyncBulkTensorGlobalToSharedClusterOp (TMA Load)
80 // CpAsyncBulkTensorPrefetchOp (TMA Prefetch)
81 // CpAsyncBulkTensorReduceOp (TMA Store-Reduce)
82 static LogicalResult CpAsyncBulkTensorCommonVerifier(size_t tensorDims,
83  bool isIm2Col,
84  size_t numIm2ColOffsets,
85  Location loc) {
86  if (tensorDims < 1 || tensorDims > 5)
87  return emitError(loc, "expects coordinates between 1 to 5 dimension");
88 
89  // For Im2Col mode, there are two constraints:
90  if (isIm2Col) {
91  // 1. Tensor must always be at least 3-d.
92  if (tensorDims < 3)
93  return emitError(
94  loc,
95  "to use im2col mode, the tensor has to be at least 3-dimensional");
96  // 2. When there are Im2ColOffsets, they must be (Dims - 2) in number.
97  if (numIm2ColOffsets && (tensorDims != (numIm2ColOffsets + 2)))
98  return emitError(
99  loc, "im2col offsets must be 2 less than number of coordinates");
100  }
101  return success();
102 }
103 
105  size_t numIm2ColOffsets = getIm2colOffsets().size();
106  bool isIm2Col = numIm2ColOffsets > 0;
107  return CpAsyncBulkTensorCommonVerifier(getCoordinates().size(), isIm2Col,
108  numIm2ColOffsets, getLoc());
109 }
110 
112  if (getCoordinates().size() > 5)
113  return emitError("Maximum 5 coordinates and dimension is supported.");
114  return success();
115 }
116 
117 LogicalResult CpAsyncOp::verify() {
118  if (getModifier() != LoadCacheModifierKind::CG &&
119  getModifier() != LoadCacheModifierKind::CA)
120  return emitError("Only CG and CA cache modifiers are supported.");
121  if (getSize() != 4 && getSize() != 8 && getSize() != 16)
122  return emitError("expected byte size to be either 4, 8 or 16.");
123  if (getModifier() == LoadCacheModifierKind::CG && getSize() != 16)
124  return emitError("CG cache modifier is only support for 16 bytes copy.");
125  return success();
126 }
127 
128 LogicalResult CpAsyncBulkTensorPrefetchOp::verify() {
129  size_t numIm2ColOffsets = getIm2colOffsets().size();
130  bool isIm2Col = numIm2ColOffsets > 0;
131  return CpAsyncBulkTensorCommonVerifier(getCoordinates().size(), isIm2Col,
132  numIm2ColOffsets, getLoc());
133 }
134 
135 LogicalResult CpAsyncBulkTensorReduceOp::verify() {
136  bool isIm2Col = (getMode() == TMAStoreMode::IM2COL);
137  return CpAsyncBulkTensorCommonVerifier(getCoordinates().size(), isIm2Col, 0,
138  getLoc());
139 }
140 
141 // Given the element type of an operand and whether or not it is an accumulator,
142 // this function returns the PTX type (`NVVM::MMATypes`) that corresponds to the
143 // operand's element type.
144 std::optional<mlir::NVVM::MMATypes>
145 MmaOp::inferOperandMMAType(Type operandElType, bool isAccumulator) {
146  auto half2Type =
148  if (operandElType.isF64())
149  return NVVM::MMATypes::f64;
150  if (operandElType.isF16() || operandElType == half2Type)
151  return NVVM::MMATypes::f16;
152  if (operandElType.isF32() && isAccumulator)
153  return NVVM::MMATypes::f32;
154  if (operandElType.isF32() && !isAccumulator)
155  return NVVM::MMATypes::tf32;
156  if (llvm::isa<IntegerType>(operandElType)) {
157  if (isAccumulator)
158  return NVVM::MMATypes::s32;
159  return std::nullopt;
160  }
161 
162  if (auto structType = llvm::dyn_cast<LLVM::LLVMStructType>(operandElType)) {
163  if (structType.getBody().empty())
164  return std::nullopt;
165  return inferOperandMMAType(structType.getBody()[0], isAccumulator);
166  }
167 
168  return std::nullopt;
169 }
170 
171 static bool isInt4PtxType(MMATypes type) {
172  return (type == MMATypes::u4 || type == MMATypes::s4);
173 }
174 
175 static bool isInt8PtxType(MMATypes type) {
176  return (type == MMATypes::u8 || type == MMATypes::s8);
177 }
178 
179 static bool isIntegerPtxType(MMATypes type) {
180  return isInt4PtxType(type) || isInt8PtxType(type) || type == MMATypes::b1 ||
181  type == MMATypes::s32;
182 }
183 
184 MMATypes MmaOp::accumPtxType() {
185  std::optional<mlir::NVVM::MMATypes> val = inferOperandMMAType(
186  getODSOperands(2).getTypes().front(), /*isAccum=*/true);
187  assert(val.has_value() && "accumulator PTX type should always be inferrable");
188  return val.value();
189 }
190 
191 MMATypes MmaOp::resultPtxType() {
192  std::optional<mlir::NVVM::MMATypes> val =
193  inferOperandMMAType(getResult().getType(), /*isAccum=*/true);
194  assert(val.has_value() && "result PTX type should always be inferrable");
195  return val.value();
196 }
197 
198 void MmaOp::print(OpAsmPrinter &p) {
199  SmallVector<Type, 4> regTypes;
200  struct OperandFragment {
201  StringRef operandName;
202  StringRef ptxTypeAttr;
204  explicit OperandFragment(StringRef name, StringRef ptxTypeName)
205  : operandName(name), ptxTypeAttr(ptxTypeName) {}
206  };
207 
208  std::array<OperandFragment, 3> frags{
209  OperandFragment("A", getMultiplicandAPtxTypeAttrName()),
210  OperandFragment("B", getMultiplicandBPtxTypeAttrName()),
211  OperandFragment("C", "")};
212  SmallVector<StringRef, 4> ignoreAttrNames{
213  mlir::NVVM::MmaOp::getOperandSegmentSizeAttr()};
214 
215  for (unsigned fragIdx = 0; fragIdx < frags.size(); fragIdx++) {
216  auto &frag = frags[fragIdx];
217  auto varOperandSpec = getODSOperandIndexAndLength(fragIdx);
218  for (auto operandIdx = varOperandSpec.first;
219  operandIdx < varOperandSpec.first + varOperandSpec.second;
220  operandIdx++) {
221  frag.regs.push_back(this->getOperand(operandIdx));
222  if (operandIdx == 0) {
223  regTypes.push_back(this->getOperand(operandIdx).getType());
224  }
225  }
226  std::optional<MMATypes> inferredType =
227  inferOperandMMAType(regTypes.back(), /*isAccum=*/fragIdx >= 2);
228  if (inferredType)
229  ignoreAttrNames.push_back(frag.ptxTypeAttr);
230  }
231 
232  auto printMmaOperand = [&](const OperandFragment &frag) -> void {
233  p << " " << frag.operandName;
234  p << "[";
235  p.printOperands(frag.regs);
236  p << "] ";
237  };
238 
239  for (const auto &frag : frags) {
240  printMmaOperand(frag);
241  }
242 
243  p.printOptionalAttrDict(this->getOperation()->getAttrs(), ignoreAttrNames);
244 
245  // Print the types of the operands and result.
246  p << " : " << "(";
247  llvm::interleaveComma(SmallVector<Type, 3>{frags[0].regs[0].getType(),
248  frags[1].regs[0].getType(),
249  frags[2].regs[0].getType()},
250  p);
251  p << ")";
252  p.printArrowTypeList(TypeRange{this->getRes().getType()});
253 }
254 
255 void MmaOp::build(OpBuilder &builder, OperationState &result, Type resultType,
256  ValueRange operandA, ValueRange operandB, ValueRange operandC,
257  ArrayRef<int64_t> shape, std::optional<MMAB1Op> b1Op,
258  std::optional<MMAIntOverflow> intOverflow,
259  std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
260  std::optional<std::array<MMALayout, 2>> multiplicandLayouts) {
261 
262  assert(shape.size() == 3 && "expected shape to have size 3 (m, n, k)");
263  MLIRContext *ctx = builder.getContext();
264  result.addAttribute(
265  "shape", builder.getAttr<MMAShapeAttr>(shape[0], shape[1], shape[2]));
266 
267  result.addOperands(operandA);
268  result.addOperands(operandB);
269  result.addOperands(operandC);
270 
271  if (multiplicandPtxTypes) {
272  result.addAttribute("multiplicandAPtxType",
273  MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
274  result.addAttribute("multiplicandBPtxType",
275  MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
276  } else {
277  if (auto res = inferOperandMMAType(operandA[0].getType(), false))
278  result.addAttribute("multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
279  if (auto res = inferOperandMMAType(operandB[0].getType(), false))
280  result.addAttribute("multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
281  }
282 
283  if (multiplicandLayouts) {
284  result.addAttribute("layoutA",
285  MMALayoutAttr::get(ctx, (*multiplicandLayouts)[0]));
286  result.addAttribute("layoutB",
287  MMALayoutAttr::get(ctx, (*multiplicandLayouts)[1]));
288  } else {
289  result.addAttribute("layoutA", MMALayoutAttr::get(ctx, MMALayout::row));
290  result.addAttribute("layoutB", MMALayoutAttr::get(ctx, MMALayout::col));
291  }
292 
293  if (intOverflow.has_value())
294  result.addAttribute("intOverflowBehavior",
295  MMAIntOverflowAttr::get(ctx, *intOverflow));
296  if (b1Op.has_value())
297  result.addAttribute("b1Op", MMAB1OpAttr::get(ctx, *b1Op));
298 
299  result.addTypes(resultType);
300  result.addAttribute(
301  MmaOp::getOperandSegmentSizeAttr(),
302  builder.getDenseI32ArrayAttr({static_cast<int32_t>(operandA.size()),
303  static_cast<int32_t>(operandB.size()),
304  static_cast<int32_t>(operandC.size())}));
305 }
306 
307 // <operation> :=
308 // A `[` $operandA `]` B `[` $operandB `]` C `[` $operandC `]`
309 // attr-dict : (type($operandA[0]), type($operandB[0]), type($operandC[0]))
310 // `->` type($res)
311 ParseResult MmaOp::parse(OpAsmParser &parser, OperationState &result) {
312  struct OperandFragment {
313  std::optional<MMATypes> elemtype;
315  SmallVector<Type> regTypes;
316  };
317 
318  Builder &builder = parser.getBuilder();
319  std::array<OperandFragment, 4> frags;
320 
321  NamedAttrList namedAttributes;
322 
323  // A helper to parse the operand segments.
324  auto parseMmaOperand = [&](StringRef operandName,
325  OperandFragment &frag) -> LogicalResult {
326  if (parser.parseKeyword(operandName).failed())
327  return failure();
328  if (parser
329  .parseOperandList(frag.regs, OpAsmParser::Delimiter::OptionalSquare)
330  .failed())
331  return failure();
332  return success();
333  };
334 
335  // Parse the operand segments.
336  if (parseMmaOperand("A", frags[0]).failed())
337  return failure();
338  if (parseMmaOperand("B", frags[1]).failed())
339  return failure();
340  if (parseMmaOperand("C", frags[2]).failed())
341  return failure();
342 
343  if (parser.parseOptionalAttrDict(namedAttributes).failed())
344  return failure();
345 
346  // Parse the type specification and resolve operands.
347  SmallVector<Type, 3> operandTypes;
348  if (failed(parser.parseColon()))
349  return failure();
350  if (failed(parser.parseLParen()))
351  return failure();
352  if (failed(parser.parseTypeList(operandTypes)))
353  return failure();
354  if (failed(parser.parseRParen()))
355  if (operandTypes.size() != 3)
356  return parser.emitError(
357  parser.getNameLoc(),
358  "expected one type for each operand segment but got " +
359  Twine(operandTypes.size()) + " types");
360  for (const auto &iter : llvm::enumerate(operandTypes)) {
361  auto &frag = frags[iter.index()];
362  frag.regTypes.resize(frag.regs.size(), iter.value());
363  if (failed(parser.resolveOperands(frag.regs, frag.regTypes,
364  parser.getNameLoc(), result.operands)))
365  return failure();
366  frag.elemtype =
367  inferOperandMMAType(frag.regTypes[0], /*isAccum=*/iter.index() < 2);
368  }
369 
370  Type resultType;
371  if (parser.parseArrow() || parser.parseType(resultType))
372  return failure();
373  frags[3].elemtype = inferOperandMMAType(resultType, /*isAccum=*/true);
374 
375  std::array<StringRef, 2> names{"multiplicandAPtxType",
376  "multiplicandBPtxType"};
377  for (unsigned idx = 0; idx < names.size(); idx++) {
378  const auto &frag = frags[idx];
379  std::optional<NamedAttribute> attr = namedAttributes.getNamed(names[idx]);
380  if (!frag.elemtype.has_value() && !attr.has_value()) {
381  return parser.emitError(
382  parser.getNameLoc(),
383  "attribute " + names[idx] +
384  " is not provided explicitly and cannot be inferred");
385  }
386  if (!attr.has_value())
387  result.addAttribute(
388  names[idx], MMATypesAttr::get(parser.getContext(), *frag.elemtype));
389  }
390 
391  result.addTypes(resultType);
392  if (!namedAttributes.empty())
393  result.addAttributes(namedAttributes);
394  result.addAttribute(MmaOp::getOperandSegmentSizeAttr(),
395  builder.getDenseI32ArrayAttr({
396  static_cast<int32_t>(frags[0].regs.size()),
397  static_cast<int32_t>(frags[1].regs.size()),
398  static_cast<int32_t>(frags[2].regs.size()),
399  }));
400  return success();
401 }
402 
403 LogicalResult MmaOp::verify() {
404  MLIRContext *context = getContext();
405  auto f16Ty = Float16Type::get(context);
406  auto i32Ty = IntegerType::get(context, 32);
407  auto f16x2Ty = LLVM::getFixedVectorType(f16Ty, 2);
408  auto f32Ty = Float32Type::get(context);
409  auto f16x2x4StructTy = LLVM::LLVMStructType::getLiteral(
410  context, {f16x2Ty, f16x2Ty, f16x2Ty, f16x2Ty});
411 
412  auto s32x4StructTy =
413  LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty, i32Ty, i32Ty});
414  auto f32x8StructTy =
415  LLVM::LLVMStructType::getLiteral(context, SmallVector<Type>(8, f32Ty));
416  auto f16x2x2StructTy =
417  LLVM::LLVMStructType::getLiteral(context, {f16x2Ty, f16x2Ty});
418  auto f32x4StructTy =
419  LLVM::LLVMStructType::getLiteral(context, {f32Ty, f32Ty, f32Ty, f32Ty});
420  auto s32x2StructTy =
421  LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty});
422 
423  std::array<int64_t, 3> mmaShape{getShapeAttr().getM(), getShapeAttr().getN(),
424  getShapeAttr().getK()};
425 
426  // These variables define the set of allowed data types for matrices A, B, C,
427  // and result.
428  using AllowedShapes = SmallVector<std::array<int64_t, 3>, 2>;
429  using AllowedTypes = SmallVector<SmallVector<Type, 4>, 2>;
430  AllowedShapes allowedShapes;
431  AllowedTypes expectedA;
432  AllowedTypes expectedB;
433  AllowedTypes expectedC;
434  SmallVector<Type> expectedResult;
435 
436  // When M = 16, we just need to calculate the number of 8xk tiles, where
437  // k is a factor that depends on the data type.
438  if (mmaShape[0] == 16) {
439  int64_t kFactor;
440  Type multiplicandFragType;
441  switch (*getMultiplicandAPtxType()) {
442  case MMATypes::tf32:
443  kFactor = 4;
444  multiplicandFragType = i32Ty;
445  expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
446  context, {f32Ty, f32Ty, f32Ty, f32Ty}));
447  break;
448  case MMATypes::f16:
449  case MMATypes::bf16:
450  kFactor = 8;
451  multiplicandFragType = f16x2Ty;
452  expectedResult.push_back(f16x2x2StructTy);
453  expectedResult.push_back(f32x4StructTy);
454  break;
455  case MMATypes::s4:
456  case MMATypes::u4:
457  kFactor = 32;
458  break;
459  case MMATypes::b1:
460  kFactor = 128;
461  break;
462  case MMATypes::s8:
463  case MMATypes::u8:
464  kFactor = 16;
465  break;
466  default:
467  return emitError("invalid shape or multiplicand type: " +
468  stringifyEnum(getMultiplicandAPtxType().value()));
469  }
470 
471  if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
472  expectedResult.push_back(s32x4StructTy);
473  expectedC.emplace_back(4, i32Ty);
474  multiplicandFragType = i32Ty;
475  } else {
476  expectedC.emplace_back(2, f16x2Ty);
477  expectedC.emplace_back(4, f32Ty);
478  }
479 
480  int64_t unitA = (mmaShape[0] / 8) * (mmaShape[2] / kFactor);
481  int64_t unitB = (mmaShape[1] / 8) * (mmaShape[2] / kFactor);
482  expectedA.emplace_back(unitA, multiplicandFragType);
483  expectedB.emplace_back(unitB, multiplicandFragType);
484  allowedShapes.push_back({16, 8, kFactor});
485  allowedShapes.push_back({16, 8, kFactor * 2});
486  }
487 
488  // In the M=8 case, there is only 1 possible case per data type.
489  if (mmaShape[0] == 8) {
490  if (*getMultiplicandAPtxType() == MMATypes::f16) {
491  expectedA.emplace_back(2, f16x2Ty);
492  expectedB.emplace_back(2, f16x2Ty);
493  expectedResult.push_back(f16x2x4StructTy);
494  expectedResult.push_back(f32x8StructTy);
495  expectedC.emplace_back(4, f16x2Ty);
496  expectedC.emplace_back(8, f32Ty);
497  allowedShapes.push_back({8, 8, 4});
498  }
499  if (*getMultiplicandAPtxType() == MMATypes::f64) {
500  Type f64Ty = Float64Type::get(context);
501  expectedA.emplace_back(1, f64Ty);
502  expectedB.emplace_back(1, f64Ty);
503  expectedC.emplace_back(2, f64Ty);
504  // expectedC.emplace_back(1, LLVM::getFixedVectorType(f64Ty, 2));
505  expectedResult.emplace_back(LLVM::LLVMStructType::getLiteral(
506  context, SmallVector<Type>(2, f64Ty)));
507  allowedShapes.push_back({8, 8, 4});
508  }
509  if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
510  expectedA.push_back({i32Ty});
511  expectedB.push_back({i32Ty});
512  expectedC.push_back({i32Ty, i32Ty});
513  expectedResult.push_back(s32x2StructTy);
514  if (isInt4PtxType(getMultiplicandAPtxType().value()))
515  allowedShapes.push_back({8, 8, 32});
516  if (isInt8PtxType(getMultiplicandAPtxType().value()))
517  allowedShapes.push_back({8, 8, 16});
518  if (getMultiplicandAPtxType().value() == MMATypes::b1)
519  allowedShapes.push_back({8, 8, 128});
520  }
521  }
522 
523  std::string errorMessage;
524  llvm::raw_string_ostream errorStream(errorMessage);
525 
526  // Check that we matched an existing shape/dtype combination.
527  if (expectedA.empty() || expectedB.empty() || expectedC.empty() ||
528  !llvm::is_contained(allowedShapes, mmaShape)) {
529  errorStream << "unimplemented variant for MMA shape <";
530  llvm::interleaveComma(mmaShape, errorStream);
531  errorStream << ">";
532  return emitOpError(errorMessage);
533  }
534 
535  // Verify the operand types for segments of A, B, and C operands.
536  std::array<StringRef, 3> operandNames{"A", "B", "C"};
537  for (const auto &iter : llvm::enumerate(
538  SmallVector<AllowedTypes, 3>{expectedA, expectedB, expectedC})) {
539  auto spec = this->getODSOperandIndexAndLength(iter.index());
540  SmallVector<Type, 4> operandTySeg(operand_type_begin() + spec.first,
541  operand_type_begin() + spec.first +
542  spec.second);
543  bool match = llvm::is_contained(iter.value(), operandTySeg);
544 
545  if (!match) {
546  errorStream << "Could not match types for the "
547  << operandNames[iter.index()]
548  << " operands; expected one of ";
549  for (const auto &x : iter.value()) {
550  errorStream << x.size() << "x" << x[0] << " ";
551  }
552  errorStream << "but got ";
553  llvm::interleaveComma(operandTySeg, errorStream);
554  return emitOpError(errorMessage);
555  }
556  }
557 
558  // Check the result type
559  if (!llvm::any_of(expectedResult, [&](Type expectedResultType) {
560  return expectedResultType == getResult().getType();
561  })) {
562  errorStream
563  << "Could not match allowed types for the result; expected one of ";
564  llvm::interleaveComma(expectedResult, errorStream);
565  errorStream << " but got " << getResult().getType();
566  return emitOpError(errorMessage);
567  }
568 
569  // Ensure that binary MMA variants have a b1 MMA operation defined.
570  if (getMultiplicandAPtxType() == MMATypes::b1 && !getB1Op()) {
571  return emitOpError("op requires " + getB1OpAttrName().strref() +
572  " attribute");
573  }
574 
575  // Ensure int4/int8 MMA variants specify the accum overflow behavior
576  // attribute.
577  if (isInt4PtxType(*getMultiplicandAPtxType()) ||
578  isInt8PtxType(*getMultiplicandAPtxType())) {
579  if (!getIntOverflowBehavior())
580  return emitOpError("op requires " +
581  getIntOverflowBehaviorAttrName().strref() +
582  " attribute");
583  }
584 
585  return success();
586 }
587 
588 LogicalResult ShflOp::verify() {
589  if (!(*this)->getAttrOfType<UnitAttr>("return_value_and_is_valid"))
590  return success();
591  auto type = llvm::dyn_cast<LLVM::LLVMStructType>(getType());
592  auto elementType = (type && type.getBody().size() == 2)
593  ? llvm::dyn_cast<IntegerType>(type.getBody()[1])
594  : nullptr;
595  if (!elementType || elementType.getWidth() != 1)
596  return emitError("expected return type to be a two-element struct with "
597  "i1 as the second element");
598  return success();
599 }
600 
601 std::pair<mlir::Type, unsigned> NVVM::inferMMAType(NVVM::MMATypes type,
602  NVVM::MMAFrag frag, int nRow,
603  int nCol,
604  MLIRContext *context) {
605  unsigned numberElements = 0;
606  Type elementType;
607  OpBuilder builder(context);
608  Type f16x2 = VectorType::get(2, builder.getF16Type());
609  if (type == NVVM::MMATypes::f16) {
610  elementType = f16x2;
611  if (frag == NVVM::MMAFrag::a || frag == NVVM::MMAFrag::b)
612  numberElements = 8;
613  else
614  numberElements = 4;
615  } else if (type == NVVM::MMATypes::f32) {
616  elementType = builder.getF32Type();
617  numberElements = 8;
618  } else if (type == NVVM::MMATypes::tf32) {
619  elementType = builder.getI32Type();
620  numberElements = 4;
621  } else if (type == NVVM::MMATypes::s8 || type == NVVM::MMATypes::u8) {
622  elementType = builder.getI32Type();
623  int parallelSize = 0;
624  if (frag == NVVM::MMAFrag::a)
625  parallelSize = nRow;
626  if (frag == NVVM::MMAFrag::b)
627  parallelSize = nCol;
628 
629  // m == 16 && n == 16 && k == 16
630  if (parallelSize == 16)
631  numberElements = 2;
632  // m == 8 && n == 32 && k == 16 or m == 32 && n == 8 && k == 16
633  else if (parallelSize == 8)
634  numberElements = 1;
635  else if (parallelSize == 32)
636  numberElements = 4;
637  } else if (type == NVVM::MMATypes::s32) {
638  elementType = builder.getI32Type();
639  numberElements = 8;
640  }
641  assert(numberElements != 0 && elementType != nullptr);
642  return std::make_pair(elementType, numberElements);
643 }
644 
645 static std::pair<mlir::Type, unsigned>
646 inferMMATypeFromMNK(NVVM::MMATypes type, NVVM::MMAFrag frag, int m, int n,
647  int k, MLIRContext *context) {
648  int nRow, nCol;
649  if (frag == NVVM::MMAFrag::a) {
650  nRow = m;
651  nCol = k;
652  } else if (frag == NVVM::MMAFrag::b) {
653  nRow = k;
654  nCol = n;
655  } else {
656  nRow = m;
657  nCol = n;
658  }
659  assert(nRow && nCol);
660  return inferMMAType(type, frag, nRow, nCol, context);
661 }
662 
663 LogicalResult NVVM::WMMALoadOp::verify() {
664  unsigned addressSpace =
665  llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
666  if (addressSpace != 0 && addressSpace != NVVM::kGlobalMemorySpace &&
667  addressSpace != NVVM::kSharedMemorySpace)
668  return emitOpError("expected source pointer in memory "
669  "space 0, 1, 3");
670 
671  if (NVVM::WMMALoadOp::getIntrinsicID(getM(), getN(), getK(), getLayout(),
672  getEltype(), getFrag()) == 0)
673  return emitOpError() << "invalid attribute combination";
674  std::pair<Type, unsigned> typeInfo = inferMMATypeFromMNK(
675  getEltype(), getFrag(), getM(), getN(), getK(), getContext());
676  Type dstType = LLVM::LLVMStructType::getLiteral(
677  getContext(), SmallVector<Type, 8>(typeInfo.second, typeInfo.first));
678  if (getType() != dstType)
679  return emitOpError("expected destination type is a structure of ")
680  << typeInfo.second << " elements of type " << typeInfo.first;
681  return success();
682 }
683 
684 LogicalResult NVVM::WMMAStoreOp::verify() {
685  unsigned addressSpace =
686  llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
687  if (addressSpace != 0 && addressSpace != NVVM::kGlobalMemorySpace &&
688  addressSpace != NVVM::kSharedMemorySpace)
689  return emitOpError("expected operands to be a source pointer in memory "
690  "space 0, 1, 3");
691 
692  if (NVVM::WMMAStoreOp::getIntrinsicID(getM(), getN(), getK(), getLayout(),
693  getEltype()) == 0)
694  return emitOpError() << "invalid attribute combination";
695  std::pair<Type, unsigned> typeInfo = inferMMATypeFromMNK(
696  getEltype(), NVVM::MMAFrag::c, getM(), getN(), getK(), getContext());
697  if (getArgs().size() != typeInfo.second)
698  return emitOpError() << "expected " << typeInfo.second << " data operands";
699  if (llvm::any_of(getArgs(), [&typeInfo](Value operands) {
700  return operands.getType() != typeInfo.first;
701  }))
702  return emitOpError() << "expected data operands of type " << typeInfo.first;
703  return success();
704 }
705 
706 LogicalResult NVVM::WMMAMmaOp::verify() {
707  if (NVVM::WMMAMmaOp::getIntrinsicID(getM(), getN(), getK(), getLayoutA(),
708  getLayoutB(), getEltypeA(),
709  getEltypeB()) == 0)
710  return emitOpError() << "invalid attribute combination";
711  std::pair<Type, unsigned> typeInfoA = inferMMATypeFromMNK(
712  getEltypeA(), NVVM::MMAFrag::a, getM(), getN(), getK(), getContext());
713  std::pair<Type, unsigned> typeInfoB = inferMMATypeFromMNK(
714  getEltypeA(), NVVM::MMAFrag::b, getM(), getN(), getK(), getContext());
715  std::pair<Type, unsigned> typeInfoC = inferMMATypeFromMNK(
716  getEltypeB(), NVVM::MMAFrag::c, getM(), getN(), getK(), getContext());
717  SmallVector<Type, 32> arguments;
718  arguments.append(typeInfoA.second, typeInfoA.first);
719  arguments.append(typeInfoB.second, typeInfoB.first);
720  arguments.append(typeInfoC.second, typeInfoC.first);
721  unsigned numArgs = arguments.size();
722  if (getArgs().size() != numArgs)
723  return emitOpError() << "expected " << numArgs << " arguments";
724  for (unsigned i = 0; i < numArgs; i++) {
725  if (getArgs()[i].getType() != arguments[i])
726  return emitOpError() << "expected argument " << i << " to be of type "
727  << arguments[i];
728  }
729  Type dstType = LLVM::LLVMStructType::getLiteral(
730  getContext(), SmallVector<Type, 8>(typeInfoC.second, typeInfoC.first));
731  if (getType() != dstType)
732  return emitOpError("expected destination type is a structure of ")
733  << typeInfoC.second << " elements of type " << typeInfoC.first;
734  return success();
735 }
736 
737 LogicalResult NVVM::LdMatrixOp::verify() {
738  unsigned addressSpace =
739  llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
740  if (addressSpace != NVVM::kSharedMemorySpace)
741  return emitOpError("expected source pointer in memory space 3");
742 
743  if (getNum() != 1 && getNum() != 2 && getNum() != 4)
744  return emitOpError("expected num attribute to be 1, 2 or 4");
745 
746  Type i32 = IntegerType::get(getContext(), 32);
747  if (getNum() == 1 && getType() != i32)
748  return emitOpError("expected destination type is i32");
749  if (getNum() == 2 || getNum() == 4) {
750  Type dstType = LLVM::LLVMStructType::getLiteral(
751  getContext(), SmallVector<Type>(getNum(), i32));
752  if (getType() != dstType)
753  return emitOpError("expected destination type is a structure of ")
754  << getNum() << " elements of type i32";
755  }
756  return success();
757 }
758 
759 LogicalResult NVVM::StMatrixOp::verify() {
760  unsigned addressSpace =
761  llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
762  if (addressSpace != NVVM::kSharedMemorySpace)
763  return emitOpError("expected source pointer in memory space 3");
764 
765  int numMatrix = getSources().size();
766  if (numMatrix != 1 && numMatrix != 2 && numMatrix != 4)
767  return emitOpError("expected num attribute to be 1, 2 or 4");
768 
769  return success();
770 }
771 
772 FailureOr<int> getAllowedSizeK(NVVM::WGMMATypes typeA) {
773  if (typeA == NVVM::WGMMATypes::tf32)
774  return 8;
775  if (typeA == NVVM::WGMMATypes::f16 || typeA == NVVM::WGMMATypes::bf16)
776  return 16;
777  if (typeA == NVVM::WGMMATypes::s8 || typeA == NVVM::WGMMATypes::u8)
778  return 32;
779  if (typeA == NVVM::WGMMATypes::e4m3 || typeA == NVVM::WGMMATypes::e5m2)
780  return 32;
781  if (typeA == NVVM::WGMMATypes::b1)
782  return 256;
783  return failure();
784 }
785 
786 LogicalResult isAllowedWGMMADataType(NVVM::WGMMATypes typeD,
787  NVVM::WGMMATypes typeA,
788  NVVM::WGMMATypes typeB) {
789  switch (typeA) {
790  case NVVM::WGMMATypes::f16:
791  if ((typeD == NVVM::WGMMATypes::f32 || typeD == NVVM::WGMMATypes::f16) &&
792  typeB == NVVM::WGMMATypes::f16)
793  return success();
794  break;
795  case NVVM::WGMMATypes::tf32:
796  if (typeD == NVVM::WGMMATypes::f32 && typeB == NVVM::WGMMATypes::tf32)
797  return success();
798  break;
799  case NVVM::WGMMATypes::u8:
800  case NVVM::WGMMATypes::s8:
801  if (typeD == NVVM::WGMMATypes::s32 &&
802  (typeB == NVVM::WGMMATypes::u8 || typeB == NVVM::WGMMATypes::s8))
803  return success();
804  break;
805  case NVVM::WGMMATypes::b1:
806  if (typeD == NVVM::WGMMATypes::s32 && typeB == NVVM::WGMMATypes::b1)
807  return success();
808  break;
809  case NVVM::WGMMATypes::bf16:
810  if ((typeD == NVVM::WGMMATypes::f32 || typeD == NVVM::WGMMATypes::f16) &&
811  typeB == NVVM::WGMMATypes::bf16)
812  return success();
813  break;
814  case NVVM::WGMMATypes::e4m3:
815  case NVVM::WGMMATypes::e5m2:
816  if ((typeD == NVVM::WGMMATypes::f32 || typeD == NVVM::WGMMATypes::f16) &&
817  (typeB == NVVM::WGMMATypes::e5m2 || typeB == NVVM::WGMMATypes::e4m3))
818  return success();
819  break;
820  case WGMMATypes::f32:
821  case WGMMATypes::s32:
822  llvm_unreachable("unsupported input types");
823  break;
824  }
825  return failure();
826 }
827 
828 LogicalResult isAllowedSizeN(int sizeN, NVVM::WGMMATypes typeA) {
829  SmallVector<int> allowedN = {8, 16, 24, 32, 40, 48, 56, 64,
830  72, 80, 88, 96, 104, 112, 120, 128,
831  136, 144, 152, 160, 168, 176, 184, 192,
832  200, 208, 216, 224, 232, 240, 248, 256};
833  SmallVector<int> allowedNshort = {8, 16, 24, 32, 48, 64,
834  80, 96, 112, 128, 144, 160,
835  176, 192, 208, 224, 240, 256};
836  switch (typeA) {
837  case WGMMATypes::f16:
838  case WGMMATypes::tf32:
839  case WGMMATypes::bf16:
840  case WGMMATypes::e4m3:
841  case WGMMATypes::e5m2:
842  if (llvm::is_contained(allowedN, sizeN))
843  return success();
844  break;
845  case WGMMATypes::u8:
846  case WGMMATypes::s8:
847  case WGMMATypes::b1:
848  if (llvm::is_contained(allowedNshort, sizeN))
849  return success();
850  break;
851  case WGMMATypes::f32:
852  case WGMMATypes::s32:
853  llvm_unreachable("unsupported input types");
854  break;
855  }
856  return failure();
857 }
858 
859 LogicalResult NVVM::WgmmaMmaAsyncOp::verify() {
860  Value outValue = getResults();
861  auto stype = dyn_cast<LLVM::LLVMStructType>(outValue.getType());
862  if (!stype)
863  return emitOpError() << "expected results to be struct";
864  int outputSize = stype.getBody().size();
865  WGMMATypes typeD = getTypeD();
866  WGMMATypes typeA = getTypeA();
867  WGMMATypes typeB = getTypeB();
868 
869  for (Type t : stype.getBody()) {
870  if (t != stype.getBody().front())
871  return emitOpError()
872  << "all elements in struct must be same type but there is " << t;
873  }
874 
875  if (typeD != WGMMATypes::f32 && typeD != WGMMATypes::f16 &&
876  typeD != WGMMATypes::s32) {
877  return emitOpError() << "does not support the given output type "
878  << NVVM::stringifyWGMMATypes(typeD);
879  }
880  if (typeD == WGMMATypes::s32 &&
881  (getScaleA() == WGMMAScaleIn::neg || getScaleB() == WGMMAScaleIn::neg)) {
882  return emitOpError() << "has s32 output, scaleA and scaleB cannot be neg";
883  }
884 
885  if (failed(isAllowedWGMMADataType(typeD, typeA, typeB))) {
886  return emitOpError() << NVVM::stringifyWGMMATypes(typeD)
887  << " += " << NVVM::stringifyWGMMATypes(typeA) << " * "
888  << NVVM::stringifyWGMMATypes(typeB)
889  << ", it is not supported.";
890  }
891 
892  // Check M
893  if (getShape().getM() != 64)
894  return emitOpError() << "shape 'm' must be 64";
895 
896  // Check K
897  FailureOr<int> allowedK = getAllowedSizeK(typeA);
898  if (failed(allowedK) || allowedK.value() != getShape().getK())
899  return emitOpError() << "shape 'k' must be " << allowedK.value()
900  << " for input type "
901  << NVVM::stringifyWGMMATypes(typeA);
902 
903  // Check N
904  if (failed(isAllowedSizeN(getShape().getN(), typeA))) {
905  return emitOpError() << "has input type "
906  << NVVM::stringifyWGMMATypes(typeA) << " n is set to "
907  << getShape().getN() << ", it is not supported.";
908  }
909 
910  // Check transpose (only available for f16/bf16)
911  // Matrices A should be stored in row-major and B in column-major.
912  // Only f16/bf16 matrices can be stored in either column-major or row-major
913  // by setting the tranpose value(imm-trans-a,imm-trans-b) in PTX code.
914  if ((typeA != WGMMATypes::f16 && typeA != WGMMATypes::bf16) &&
915  (getLayoutA() == mlir::NVVM::MMALayout::col ||
916  getLayoutB() == mlir::NVVM::MMALayout::row)) {
917  return emitOpError()
918  << "given layouts layout_a = " << stringifyMMALayout(getLayoutA())
919  << " and layout_b = " << stringifyMMALayout(getLayoutB())
920  << " for input types " << stringifyWGMMATypes(typeA) << " and "
921  << stringifyWGMMATypes(typeB)
922  << " requires transpose. However, this is only supported for: "
923  << stringifyMMATypes(MMATypes::f16) << " and "
924  << stringifyMMATypes(MMATypes::bf16);
925  }
926 
927  // Check result registers
928  int expectedOutput = 0;
929  if (typeD == WGMMATypes::f32 || typeD == WGMMATypes::s32)
930  expectedOutput = getShape().getN() / 2;
931  if (typeD == WGMMATypes::f16)
932  expectedOutput = getShape().getN() / 4;
933  if (outputSize != expectedOutput) {
934  return emitOpError() << "results " << expectedOutput
935  << ", however output struct has " << outputSize
936  << " elements";
937  }
938  // Check satfinite (only available for s32 accumulator)
939  if (typeD != WGMMATypes::s32 &&
940  getSatfinite().value_or(NVVM::MMAIntOverflow::wrapped) ==
941  NVVM::MMAIntOverflow::satfinite) {
942  return emitOpError()
943  << " `satfinite` can be only used with s32 accumulator, however "
944  "the current accumulator is "
945  << NVVM::stringifyWGMMATypes(typeD);
946  }
947 
948  return success();
949 }
950 
951 std::string NVVM::WgmmaMmaAsyncOp::getPtx() {
952 
953  int m = getShape().getM(), n = getShape().getN(), k = getShape().getK();
954  bool isF16 = getTypeA() == WGMMATypes::f16 || getTypeA() == WGMMATypes::bf16;
955 
956  StringRef outputTypeName = stringifyWGMMATypes(getTypeD());
957 
958  int expectedOutputRegisters = 0;
959  if (getTypeD() == WGMMATypes::f16)
960  expectedOutputRegisters = getShape().getN() / 4;
961  else
962  expectedOutputRegisters = getShape().getN() / 2;
963 
964  std::string ptx;
965  llvm::raw_string_ostream ss(ptx);
966 
967  ss << "{\n"
968  ".reg .pred p;\n"
969  "setp.ne.b32 p, $"
970  << ((expectedOutputRegisters * 2) + 2)
971  << ", 0;\n"
972  "wgmma.mma_async.sync.aligned.m"
973  << m << "n" << n << "k" << k << "." << outputTypeName << "."
974  << stringifyWGMMATypes(getTypeA()) << "."
975  << stringifyWGMMATypes(getTypeB());
976  if (getSatfinite().value_or(NVVM::MMAIntOverflow::wrapped) ==
977  NVVM::MMAIntOverflow::satfinite)
978  ss << ".satfinite";
979  ss << " {";
980  int regCnt = 0;
981  for (; regCnt < expectedOutputRegisters; ++regCnt) {
982  ss << "$" << regCnt;
983  if (regCnt != expectedOutputRegisters - 1)
984  ss << ", ";
985  }
986 
987  ss << "},";
988  // Need to map read/write registers correctly.
989  regCnt = (regCnt * 2);
990  ss << " $" << (regCnt) << "," << " $" << (regCnt + 1) << "," << " p";
991  if (getTypeD() != WGMMATypes::s32) {
992  ss << ", $" << (regCnt + 3) << ", $" << (regCnt + 4);
993  }
994  // Don't add transpose parameters unless needed.
995  if (isF16) {
996  ss << ", $" << (regCnt + 5) << ", $" << (regCnt + 6);
997  }
998  ss << ";\n"
999  << "}\n";
1000  return ptx;
1001 }
1002 
1003 void NVVM::WgmmaMmaAsyncOp::getAsmValues(
1004  RewriterBase &rewriter,
1005  llvm::SmallVectorImpl<std::pair<mlir::Value, mlir::NVVM::PTXRegisterMod>>
1006  &asmValues) {
1007  bool isF16 = getTypeA() == WGMMATypes::f16 || getTypeA() == WGMMATypes::bf16;
1008  if (getResults())
1009  asmValues.push_back({getResults(), mlir::NVVM::PTXRegisterMod::Write});
1010  if (getInouts())
1011  asmValues.push_back({getInouts(), mlir::NVVM::PTXRegisterMod::ReadWrite});
1012  asmValues.push_back({getDescriptorA(), mlir::NVVM::PTXRegisterMod::Read});
1013  asmValues.push_back({getDescriptorB(), mlir::NVVM::PTXRegisterMod::Read});
1014  asmValues.push_back({makeConstantI32(rewriter, static_cast<int>(getScaleD())),
1016  if (getTypeD() != WGMMATypes::s32) {
1017  asmValues.push_back(
1018  {makeConstantI32(rewriter,
1019  getScaleA() == NVVM::WGMMAScaleIn::neg ? -1 : 1),
1021  asmValues.push_back(
1022  {makeConstantI32(rewriter,
1023  getScaleB() == NVVM::WGMMAScaleIn::neg ? -1 : 1),
1025  }
1026  if (isF16) {
1027  asmValues.push_back(
1028  {makeConstantI32(rewriter, static_cast<int>(getLayoutA())),
1030  asmValues.push_back(
1031  {makeConstantI32(rewriter, 1 - static_cast<int>(getLayoutB())),
1033  }
1034 }
1035 LogicalResult NVVM::FenceProxyOp::verify() {
1036  if (getKind() == NVVM::ProxyKind::TENSORMAP)
1037  return emitOpError() << "tensormap proxy is not a supported proxy kind";
1038  if (getKind() == NVVM::ProxyKind::GENERIC)
1039  return emitOpError() << "generic proxy not a supported proxy kind";
1040  if (getKind() == NVVM::ProxyKind::async_shared && !getSpace().has_value()) {
1041  return emitOpError() << "async_shared fence requires space attribute";
1042  }
1043  if (getKind() != NVVM::ProxyKind::async_shared && getSpace().has_value()) {
1044  return emitOpError() << "only async_shared fence can have space attribute";
1045  }
1046  return success();
1047 }
1048 
1049 LogicalResult NVVM::FenceProxyAcquireOp::verify() {
1050  if (getFromProxy() != NVVM::ProxyKind::GENERIC)
1051  return emitOpError("uni-directional proxies only support generic for "
1052  "from_proxy attribute");
1053 
1054  if (getToProxy() != NVVM::ProxyKind::TENSORMAP)
1055  return emitOpError("uni-directional proxies only support tensormap "
1056  "for to_proxy attribute");
1057 
1058  return success();
1059 }
1060 
1061 LogicalResult NVVM::FenceProxyReleaseOp::verify() {
1062  if (getFromProxy() != NVVM::ProxyKind::GENERIC)
1063  return emitOpError("uni-directional proxies only support generic for "
1064  "from_proxy attribute");
1065 
1066  if (getToProxy() != NVVM::ProxyKind::TENSORMAP)
1067  return emitOpError("uni-directional proxies only support tensormap "
1068  "for to_proxy attribute");
1069 
1070  return success();
1071 }
1072 
1073 LogicalResult NVVM::SetMaxRegisterOp::verify() {
1074  if (getRegCount() % 8)
1075  return emitOpError("new register size must be multiple of 8");
1076  if (getRegCount() < 24 || getRegCount() > 256)
1077  return emitOpError("new register size must be in between 24 to 256");
1078  return success();
1079 }
1080 
1081 LogicalResult NVVM::BarrierOp::verify() {
1082  if (getNumberOfThreads() && !getBarrierId())
1083  return emitOpError(
1084  "barrier id is missing, it should be set between 0 to 15");
1085  return success();
1086 }
1087 
1088 llvm::Intrinsic::ID CpAsyncBulkTensorPrefetchOp::getIntrinsicID(int tensorDims,
1089  bool isIm2Col) {
1090  switch (tensorDims) {
1091  case 1:
1092  return llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_tile_1d;
1093  case 2:
1094  return llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_tile_2d;
1095  case 3:
1096  return isIm2Col
1097  ? llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_im2col_3d
1098  : llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_tile_3d;
1099  case 4:
1100  return isIm2Col
1101  ? llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_im2col_4d
1102  : llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_tile_4d;
1103  case 5:
1104  return isIm2Col
1105  ? llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_im2col_5d
1106  : llvm::Intrinsic::nvvm_cp_async_bulk_tensor_prefetch_tile_5d;
1107  default:
1108  llvm_unreachable("Invalid TensorDim in CpAsyncBulkTensorPrefetchOp.");
1109  }
1110 }
1111 
1112 #define CP_ASYNC_BULK_TENSOR_REDUCE_MODE(op, dim, mode) \
1113  llvm::Intrinsic::nvvm_cp_async_bulk_tensor_##op##_##mode##_##dim##d
1114 
1115 #define CP_ASYNC_BULK_TENSOR_REDUCE(op, dim, is_im2col) \
1116  is_im2col ? CP_ASYNC_BULK_TENSOR_REDUCE_MODE(op, dim, im2col) \
1117  : CP_ASYNC_BULK_TENSOR_REDUCE_MODE(op, dim, tile)
1118 
1119 #define GET_CP_ASYNC_BULK_TENSOR_ID(op, dims, is_im2col) \
1120  [&]() -> auto { \
1121  switch (dims) { \
1122  case 1: \
1123  return CP_ASYNC_BULK_TENSOR_REDUCE_MODE(op, 1, tile); \
1124  case 2: \
1125  return CP_ASYNC_BULK_TENSOR_REDUCE_MODE(op, 2, tile); \
1126  case 3: \
1127  return CP_ASYNC_BULK_TENSOR_REDUCE(op, 3, is_im2col); \
1128  case 4: \
1129  return CP_ASYNC_BULK_TENSOR_REDUCE(op, 4, is_im2col); \
1130  case 5: \
1131  return CP_ASYNC_BULK_TENSOR_REDUCE(op, 5, is_im2col); \
1132  default: \
1133  llvm_unreachable("Invalid TensorDim in CpAsyncBulkTensorReduceOp."); \
1134  } \
1135  }()
1136 
1137 llvm::Intrinsic::ID CpAsyncBulkTensorReduceOp::getIntrinsicID(
1138  int tensorDims, NVVM::TMAReduxKind kind, bool isIm2Col) {
1139  using RedTy = NVVM::TMAReduxKind;
1140  switch (kind) {
1141  case RedTy::ADD:
1142  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_add, tensorDims, isIm2Col);
1143  case RedTy::MIN:
1144  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_min, tensorDims, isIm2Col);
1145  case RedTy::MAX:
1146  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_max, tensorDims, isIm2Col);
1147  case RedTy::INC:
1148  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_inc, tensorDims, isIm2Col);
1149  case RedTy::DEC:
1150  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_dec, tensorDims, isIm2Col);
1151  case RedTy::AND:
1152  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_and, tensorDims, isIm2Col);
1153  case RedTy::OR:
1154  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_or, tensorDims, isIm2Col);
1155  case RedTy::XOR:
1156  return GET_CP_ASYNC_BULK_TENSOR_ID(reduce_xor, tensorDims, isIm2Col);
1157  }
1158  llvm_unreachable("Invalid Reduction Op for CpAsyncBulkTensorReduceOp");
1159 }
1160 
1161 //===----------------------------------------------------------------------===//
1162 // NVVMDialect initialization, type parsing, and registration.
1163 //===----------------------------------------------------------------------===//
1164 
1165 // TODO: This should be the llvm.nvvm dialect once this is supported.
1166 void NVVMDialect::initialize() {
1167  addOperations<
1168 #define GET_OP_LIST
1169 #include "mlir/Dialect/LLVMIR/NVVMOps.cpp.inc"
1170  >();
1171  addAttributes<
1172 #define GET_ATTRDEF_LIST
1173 #include "mlir/Dialect/LLVMIR/NVVMOpsAttributes.cpp.inc"
1174  >();
1175 
1176  // Support unknown operations because not all NVVM operations are
1177  // registered.
1178  allowUnknownOperations();
1179  declarePromisedInterface<ConvertToLLVMPatternInterface, NVVMDialect>();
1180  declarePromisedInterface<gpu::TargetAttrInterface, NVVMTargetAttr>();
1181 }
1182 
1183 LogicalResult NVVMDialect::verifyOperationAttribute(Operation *op,
1184  NamedAttribute attr) {
1185  StringAttr attrName = attr.getName();
1186  // Kernel function attribute should be attached to functions.
1187  if (attrName == NVVMDialect::getKernelFuncAttrName()) {
1188  if (!isa<LLVM::LLVMFuncOp>(op)) {
1189  return op->emitError() << "'" << NVVMDialect::getKernelFuncAttrName()
1190  << "' attribute attached to unexpected op";
1191  }
1192  }
1193  // If maxntid / reqntid / cluster_dim exist, it must be an array with max 3
1194  // dim
1195  if (attrName == NVVMDialect::getMaxntidAttrName() ||
1196  attrName == NVVMDialect::getReqntidAttrName() ||
1197  attrName == NVVMDialect::getClusterDimAttrName()) {
1198  auto values = llvm::dyn_cast<DenseI32ArrayAttr>(attr.getValue());
1199  if (!values || values.empty() || values.size() > 3)
1200  return op->emitError()
1201  << "'" << attrName
1202  << "' attribute must be integer array with maximum 3 index";
1203  }
1204  // If minctasm / maxnreg / cluster_max_blocks exist, it must be an integer
1205  // attribute
1206  if (attrName == NVVMDialect::getMinctasmAttrName() ||
1207  attrName == NVVMDialect::getMaxnregAttrName() ||
1208  attrName == NVVMDialect::getClusterMaxBlocksAttrName()) {
1209  if (!llvm::dyn_cast<IntegerAttr>(attr.getValue()))
1210  return op->emitError()
1211  << "'" << attrName << "' attribute must be integer constant";
1212  }
1213 
1214  return success();
1215 }
1216 
1217 LogicalResult NVVMDialect::verifyRegionArgAttribute(Operation *op,
1218  unsigned regionIndex,
1219  unsigned argIndex,
1220  NamedAttribute argAttr) {
1221  auto funcOp = dyn_cast<FunctionOpInterface>(op);
1222  if (!funcOp)
1223  return success();
1224 
1225  bool isKernel = op->hasAttr(NVVMDialect::getKernelFuncAttrName());
1226  StringAttr attrName = argAttr.getName();
1227  if (attrName == NVVM::NVVMDialect::getGridConstantAttrName()) {
1228  if (!isKernel) {
1229  return op->emitError()
1230  << "'" << attrName
1231  << "' attribute must be present only on kernel arguments";
1232  }
1233  if (!isa<UnitAttr>(argAttr.getValue()))
1234  return op->emitError() << "'" << attrName << "' must be a unit attribute";
1235  if (!funcOp.getArgAttr(argIndex, LLVM::LLVMDialect::getByValAttrName())) {
1236  return op->emitError()
1237  << "'" << attrName
1238  << "' attribute requires the argument to also have attribute '"
1239  << LLVM::LLVMDialect::getByValAttrName() << "'";
1240  }
1241  }
1242 
1243  return success();
1244 }
1245 
1246 //===----------------------------------------------------------------------===//
1247 // NVVM target attribute.
1248 //===----------------------------------------------------------------------===//
1249 LogicalResult
1251  int optLevel, StringRef triple, StringRef chip,
1252  StringRef features, DictionaryAttr flags,
1253  ArrayAttr files) {
1254  if (optLevel < 0 || optLevel > 3) {
1255  emitError() << "The optimization level must be a number between 0 and 3.";
1256  return failure();
1257  }
1258  if (triple.empty()) {
1259  emitError() << "The target triple cannot be empty.";
1260  return failure();
1261  }
1262  if (chip.empty()) {
1263  emitError() << "The target chip cannot be empty.";
1264  return failure();
1265  }
1266  if (files && !llvm::all_of(files, [](::mlir::Attribute attr) {
1267  return attr && mlir::isa<StringAttr>(attr);
1268  })) {
1269  emitError() << "All the elements in the `link` array must be strings.";
1270  return failure();
1271  }
1272  return success();
1273 }
1274 
1275 #define GET_OP_CLASSES
1276 #include "mlir/Dialect/LLVMIR/NVVMOps.cpp.inc"
1277 
1278 #define GET_ATTRDEF_CLASSES
1279 #include "mlir/Dialect/LLVMIR/NVVMOpsAttributes.cpp.inc"
static MLIRContext * getContext(OpFoldResult val)
static std::pair< mlir::Type, unsigned > inferMMATypeFromMNK(NVVM::MMATypes type, NVVM::MMAFrag frag, int m, int n, int k, MLIRContext *context)
LogicalResult isAllowedSizeN(int sizeN, NVVM::WGMMATypes typeA)
static void printNVVMIntrinsicOp(OpAsmPrinter &p, Operation *op)
Definition: NVVMDialect.cpp:54
FailureOr< int > getAllowedSizeK(NVVM::WGMMATypes typeA)
LogicalResult isAllowedWGMMADataType(NVVM::WGMMATypes typeD, NVVM::WGMMATypes typeA, NVVM::WGMMATypes typeB)
static bool isInt8PtxType(MMATypes type)
static bool isInt4PtxType(MMATypes type)
static bool isIntegerPtxType(MMATypes type)
static LogicalResult CpAsyncBulkTensorCommonVerifier(size_t tensorDims, bool isIm2Col, size_t numIm2ColOffsets, Location loc)
Definition: NVVMDialect.cpp:82
#define GET_CP_ASYNC_BULK_TENSOR_ID(op, dims, is_im2col)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition: Traits.cpp:118
@ 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 parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
MLIRContext * getContext() const
Definition: AsmPrinter.cpp:73
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 addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
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.
ParseResult parseTypeList(SmallVectorImpl< Type > &result)
Parse a type list.
Definition: AsmPrinter.cpp:78
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
void printArrowTypeList(TypeRange &&types)
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class is a general helper class for creating context-global objects like types,...
Definition: Builders.h:51
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition: Builders.cpp:203
FloatType getF32Type()
Definition: Builders.cpp:87
IntegerType getI32Type()
Definition: Builders.cpp:107
FloatType getF16Type()
Definition: Builders.cpp:83
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:107
This class represents a diagnostic that is inflight and set to be reported.
Definition: Diagnostics.h:314
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
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.
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:207
StringAttr getName() const
Return the name of the attribute.
Definition: Attributes.cpp:49
Attribute getValue() const
Return the value of the attribute.
Definition: Attributes.h:221
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(const ContainerType &container)
Print a comma separated list of operands.
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:216
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
bool hasAttr(StringAttr name)
Return true if the operation has an attribute with the provided name, false otherwise.
Definition: Operation.h:560
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:268
result_type_range getResultTypes()
Definition: Operation.h:428
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition: Operation.h:378
unsigned getNumResults()
Return the number of results held by this operation.
Definition: Operation.h:404
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:400
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:36
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:60
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition: Types.cpp:35
bool isF32() const
Definition: Types.cpp:59
bool isF16() const
Definition: Types.cpp:57
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:381
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:129
SmallVector< int64_t, 4 > getCoordinates(ArrayRef< int64_t > basis, unsigned linearIndex)
Type getFixedVectorType(Type elementType, unsigned numElements)
Creates an LLVM dialect-compatible type with the given element type and length.
Definition: LLVMTypes.cpp:957
@ Write
Read register with '+' modifier.
@ ReadWrite
Read register with '=' modifier.
@ Read
Read register with no modifier.
@ kGlobalMemorySpace
Global memory space identifier.
Definition: NVVMDialect.h:36
@ kSharedMemorySpace
Shared memory space identifier.
Definition: NVVMDialect.h:38
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.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition: Query.cpp:20
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:305
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
Definition: Verifier.cpp:425
This represents an operation in an abstracted form, suitable for use with the builder APIs.
SmallVector< Value, 4 > operands
void addOperands(ValueRange newOperands)
void addAttributes(ArrayRef< NamedAttribute > newAttributes)
Add an array of named attributes.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
void addTypes(ArrayRef< Type > newTypes)
NamedAttrList attributes
SmallVector< Type, 4 > types
Types of the results of this operation.