xref: /llvm-project/mlir/lib/Dialect/LLVMIR/IR/NVVMDialect.cpp (revision 68433f6b27a2d95d8132d4a636a7e18ed85ca9e6)
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 
17 #include "mlir/Dialect/LLVMIR/NVVMDialect.h"
18 
19 #include "mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h"
20 #include "mlir/Dialect/GPU/IR/CompilationInterfaces.h"
21 #include "mlir/Dialect/Utils/StaticValueUtils.h"
22 #include "mlir/IR/Builders.h"
23 #include "mlir/IR/BuiltinAttributes.h"
24 #include "mlir/IR/BuiltinTypes.h"
25 #include "mlir/IR/DialectImplementation.h"
26 #include "mlir/IR/MLIRContext.h"
27 #include "mlir/IR/Operation.h"
28 #include "mlir/IR/OperationSupport.h"
29 #include "mlir/IR/Types.h"
30 #include "mlir/Support/LogicalResult.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 
54 static void printNVVMIntrinsicOp(OpAsmPrinter &p, Operation *op) {
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 
66   SmallVector<OpAsmParser::UnresolvedOperand, 8> ops;
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 
76 void VoteBallotOp::print(OpAsmPrinter &p) { printNVVMIntrinsicOp(p, *this); }
77 
78 LogicalResult CpAsyncBulkTensorGlobalToSharedClusterOp::verify() {
79   if (getCoordinates().empty() || getCoordinates().size() > 5)
80     return emitError("expects coordinates between 1 to 5 dimension");
81 
82   // Check for im2col mode
83   if (!getIm2colOffsets().empty()) {
84     if (getCoordinates().size() < 3)
85       return emitError(
86           "to use im2col mode, the tensor has to be at least 3-dimensional");
87     if (getCoordinates().size() != (getIm2colOffsets().size() + 2))
88       return emitError(
89           "im2col offsets must be 2 less than number of coordinates");
90   }
91   return success();
92 }
93 
94 LogicalResult CpAsyncBulkTensorSharedCTAToGlobalOp::verify() {
95   if (getCoordinates().size() > 5)
96     return emitError("Maximum 5 coordinates and dimension is supported.");
97   return success();
98 }
99 
100 LogicalResult CpAsyncOp::verify() {
101   if (getModifier() != LoadCacheModifierKind::CG &&
102       getModifier() != LoadCacheModifierKind::CA)
103     return emitError("Only CG and CA cache modifiers are supported.");
104   if (getSize() != 4 && getSize() != 8 && getSize() != 16)
105     return emitError("expected byte size to be either 4, 8 or 16.");
106   if (getModifier() == LoadCacheModifierKind::CG && getSize() != 16)
107     return emitError("CG cache modifier is only support for 16 bytes copy.");
108   return success();
109 }
110 
111 // Given the element type of an operand and whether or not it is an accumulator,
112 // this function returns the PTX type (`NVVM::MMATypes`) that corresponds to the
113 // operand's element type.
114 std::optional<mlir::NVVM::MMATypes>
115 MmaOp::inferOperandMMAType(Type operandElType, bool isAccumulator) {
116   auto half2Type =
117       LLVM::getFixedVectorType(Float16Type::get(operandElType.getContext()), 2);
118   if (operandElType.isF64())
119     return NVVM::MMATypes::f64;
120   if (operandElType.isF16() || operandElType == half2Type)
121     return NVVM::MMATypes::f16;
122   if (operandElType.isF32() && isAccumulator)
123     return NVVM::MMATypes::f32;
124   if (operandElType.isF32() && !isAccumulator)
125     return NVVM::MMATypes::tf32;
126   if (llvm::isa<IntegerType>(operandElType)) {
127     if (isAccumulator)
128       return NVVM::MMATypes::s32;
129     return std::nullopt;
130   }
131 
132   if (auto structType = llvm::dyn_cast<LLVM::LLVMStructType>(operandElType)) {
133     if (structType.getBody().empty())
134       return std::nullopt;
135     return inferOperandMMAType(structType.getBody()[0], isAccumulator);
136   }
137 
138   return std::nullopt;
139 }
140 
141 static bool isInt4PtxType(MMATypes type) {
142   return (type == MMATypes::u4 || type == MMATypes::s4);
143 }
144 
145 static bool isInt8PtxType(MMATypes type) {
146   return (type == MMATypes::u8 || type == MMATypes::s8);
147 }
148 
149 static bool isIntegerPtxType(MMATypes type) {
150   return isInt4PtxType(type) || isInt8PtxType(type) || type == MMATypes::b1 ||
151          type == MMATypes::s32;
152 }
153 
154 MMATypes MmaOp::accumPtxType() {
155   std::optional<mlir::NVVM::MMATypes> val = inferOperandMMAType(
156       getODSOperands(2).getTypes().front(), /*isAccum=*/true);
157   assert(val.has_value() && "accumulator PTX type should always be inferrable");
158   return val.value();
159 }
160 
161 MMATypes MmaOp::resultPtxType() {
162   std::optional<mlir::NVVM::MMATypes> val =
163       inferOperandMMAType(getResult().getType(), /*isAccum=*/true);
164   assert(val.has_value() && "result PTX type should always be inferrable");
165   return val.value();
166 }
167 
168 void MmaOp::print(OpAsmPrinter &p) {
169   SmallVector<Type, 4> regTypes;
170   struct OperandFragment {
171     StringRef operandName;
172     StringRef ptxTypeAttr;
173     SmallVector<Value, 4> regs;
174     explicit OperandFragment(StringRef name, StringRef ptxTypeName)
175         : operandName(name), ptxTypeAttr(ptxTypeName) {}
176   };
177 
178   std::array<OperandFragment, 3> frags{
179       OperandFragment("A", getMultiplicandAPtxTypeAttrName()),
180       OperandFragment("B", getMultiplicandBPtxTypeAttrName()),
181       OperandFragment("C", "")};
182   SmallVector<StringRef, 4> ignoreAttrNames{
183       mlir::NVVM::MmaOp::getOperandSegmentSizeAttr()};
184 
185   for (unsigned fragIdx = 0; fragIdx < frags.size(); fragIdx++) {
186     auto &frag = frags[fragIdx];
187     auto varOperandSpec = getODSOperandIndexAndLength(fragIdx);
188     for (auto operandIdx = varOperandSpec.first;
189          operandIdx < varOperandSpec.first + varOperandSpec.second;
190          operandIdx++) {
191       frag.regs.push_back(this->getOperand(operandIdx));
192       if (operandIdx == 0) {
193         regTypes.push_back(this->getOperand(operandIdx).getType());
194       }
195     }
196     std::optional<MMATypes> inferredType =
197         inferOperandMMAType(regTypes.back(), /*isAccum=*/fragIdx >= 2);
198     if (inferredType)
199       ignoreAttrNames.push_back(frag.ptxTypeAttr);
200   }
201 
202   auto printMmaOperand = [&](const OperandFragment &frag) -> void {
203     p << " " << frag.operandName;
204     p << "[";
205     p.printOperands(frag.regs);
206     p << "] ";
207   };
208 
209   for (const auto &frag : frags) {
210     printMmaOperand(frag);
211   }
212 
213   p.printOptionalAttrDict(this->getOperation()->getAttrs(), ignoreAttrNames);
214 
215   // Print the types of the operands and result.
216   p << " : "
217     << "(";
218   llvm::interleaveComma(SmallVector<Type, 3>{frags[0].regs[0].getType(),
219                                              frags[1].regs[0].getType(),
220                                              frags[2].regs[0].getType()},
221                         p);
222   p << ")";
223   p.printArrowTypeList(TypeRange{this->getRes().getType()});
224 }
225 
226 void MmaOp::build(OpBuilder &builder, OperationState &result, Type resultType,
227                   ValueRange operandA, ValueRange operandB, ValueRange operandC,
228                   ArrayRef<int64_t> shape, std::optional<MMAB1Op> b1Op,
229                   std::optional<MMAIntOverflow> intOverflow,
230                   std::optional<std::array<MMATypes, 2>> multiplicandPtxTypes,
231                   std::optional<std::array<MMALayout, 2>> multiplicandLayouts) {
232 
233   assert(shape.size() == 3 && "expected shape to have size 3 (m, n, k)");
234   MLIRContext *ctx = builder.getContext();
235   result.addAttribute(
236       "shape", builder.getAttr<MMAShapeAttr>(shape[0], shape[1], shape[2]));
237 
238   result.addOperands(operandA);
239   result.addOperands(operandB);
240   result.addOperands(operandC);
241 
242   if (multiplicandPtxTypes) {
243     result.addAttribute("multiplicandAPtxType",
244                         MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[0]));
245     result.addAttribute("multiplicandBPtxType",
246                         MMATypesAttr::get(ctx, (*multiplicandPtxTypes)[1]));
247   } else {
248     if (auto res = inferOperandMMAType(operandA[0].getType(), false))
249       result.addAttribute("multiplicandAPtxType", MMATypesAttr::get(ctx, *res));
250     if (auto res = inferOperandMMAType(operandB[0].getType(), false))
251       result.addAttribute("multiplicandBPtxType", MMATypesAttr::get(ctx, *res));
252   }
253 
254   if (multiplicandLayouts) {
255     result.addAttribute("layoutA",
256                         MMALayoutAttr::get(ctx, (*multiplicandLayouts)[0]));
257     result.addAttribute("layoutB",
258                         MMALayoutAttr::get(ctx, (*multiplicandLayouts)[1]));
259   } else {
260     result.addAttribute("layoutA", MMALayoutAttr::get(ctx, MMALayout::row));
261     result.addAttribute("layoutB", MMALayoutAttr::get(ctx, MMALayout::col));
262   }
263 
264   if (intOverflow.has_value())
265     result.addAttribute("intOverflowBehavior",
266                         MMAIntOverflowAttr::get(ctx, *intOverflow));
267   if (b1Op.has_value())
268     result.addAttribute("b1Op", MMAB1OpAttr::get(ctx, *b1Op));
269 
270   result.addTypes(resultType);
271   result.addAttribute(
272       MmaOp::getOperandSegmentSizeAttr(),
273       builder.getDenseI32ArrayAttr({static_cast<int32_t>(operandA.size()),
274                                     static_cast<int32_t>(operandB.size()),
275                                     static_cast<int32_t>(operandC.size())}));
276 }
277 
278 // <operation> :=
279 //   A `[` $operandA `]` B `[` $operandB `]` C `[` $operandC `]`
280 //   attr-dict : (type($operandA[0]), type($operandB[0]), type($operandC[0]))
281 //     `->` type($res)
282 ParseResult MmaOp::parse(OpAsmParser &parser, OperationState &result) {
283   struct OperandFragment {
284     std::optional<MMATypes> elemtype;
285     SmallVector<OpAsmParser::UnresolvedOperand, 4> regs;
286     SmallVector<Type> regTypes;
287   };
288 
289   Builder &builder = parser.getBuilder();
290   std::array<OperandFragment, 4> frags;
291 
292   NamedAttrList namedAttributes;
293 
294   // A helper to parse the operand segments.
295   auto parseMmaOperand = [&](StringRef operandName,
296                              OperandFragment &frag) -> LogicalResult {
297     if (parser.parseKeyword(operandName).failed())
298       return failure();
299     if (parser
300             .parseOperandList(frag.regs, OpAsmParser::Delimiter::OptionalSquare)
301             .failed())
302       return failure();
303     return success();
304   };
305 
306   // Parse the operand segments.
307   if (parseMmaOperand("A", frags[0]).failed())
308     return failure();
309   if (parseMmaOperand("B", frags[1]).failed())
310     return failure();
311   if (parseMmaOperand("C", frags[2]).failed())
312     return failure();
313 
314   if (parser.parseOptionalAttrDict(namedAttributes).failed())
315     return failure();
316 
317   // Parse the type specification and resolve operands.
318   SmallVector<Type, 3> operandTypes;
319   if (failed(parser.parseColon()))
320     return failure();
321   if (failed(parser.parseLParen()))
322     return failure();
323   if (failed(parser.parseTypeList(operandTypes)))
324     return failure();
325   if (failed(parser.parseRParen()))
326     if (operandTypes.size() != 3)
327       return parser.emitError(
328           parser.getNameLoc(),
329           "expected one type for each operand segment but got " +
330               Twine(operandTypes.size()) + " types");
331   for (const auto &iter : llvm::enumerate(operandTypes)) {
332     auto &frag = frags[iter.index()];
333     frag.regTypes.resize(frag.regs.size(), iter.value());
334     if (failed(parser.resolveOperands(frag.regs, frag.regTypes,
335                                       parser.getNameLoc(), result.operands)))
336       return failure();
337     frag.elemtype =
338         inferOperandMMAType(frag.regTypes[0], /*isAccum=*/iter.index() < 2);
339   }
340 
341   Type resultType;
342   if (parser.parseArrow() || parser.parseType(resultType))
343     return failure();
344   frags[3].elemtype = inferOperandMMAType(resultType, /*isAccum=*/true);
345 
346   std::array<StringRef, 2> names{"multiplicandAPtxType",
347                                  "multiplicandBPtxType"};
348   for (unsigned idx = 0; idx < names.size(); idx++) {
349     const auto &frag = frags[idx];
350     std::optional<NamedAttribute> attr = namedAttributes.getNamed(names[idx]);
351     if (!frag.elemtype.has_value() && !attr.has_value()) {
352       return parser.emitError(
353           parser.getNameLoc(),
354           "attribute " + names[idx] +
355               " is not provided explicitly and cannot be inferred");
356     }
357     if (!attr.has_value())
358       result.addAttribute(
359           names[idx], MMATypesAttr::get(parser.getContext(), *frag.elemtype));
360   }
361 
362   result.addTypes(resultType);
363   if (!namedAttributes.empty())
364     result.addAttributes(namedAttributes);
365   result.addAttribute(MmaOp::getOperandSegmentSizeAttr(),
366                       builder.getDenseI32ArrayAttr({
367                           static_cast<int32_t>(frags[0].regs.size()),
368                           static_cast<int32_t>(frags[1].regs.size()),
369                           static_cast<int32_t>(frags[2].regs.size()),
370                       }));
371   return success();
372 }
373 
374 LogicalResult MmaOp::verify() {
375   MLIRContext *context = getContext();
376   auto f16Ty = Float16Type::get(context);
377   auto i32Ty = IntegerType::get(context, 32);
378   auto f16x2Ty = LLVM::getFixedVectorType(f16Ty, 2);
379   auto f32Ty = Float32Type::get(context);
380   auto f16x2x4StructTy = LLVM::LLVMStructType::getLiteral(
381       context, {f16x2Ty, f16x2Ty, f16x2Ty, f16x2Ty});
382 
383   auto s32x4StructTy =
384       LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty, i32Ty, i32Ty});
385   auto f32x8StructTy =
386       LLVM::LLVMStructType::getLiteral(context, SmallVector<Type>(8, f32Ty));
387   auto f16x2x2StructTy =
388       LLVM::LLVMStructType::getLiteral(context, {f16x2Ty, f16x2Ty});
389   auto f32x4StructTy =
390       LLVM::LLVMStructType::getLiteral(context, {f32Ty, f32Ty, f32Ty, f32Ty});
391   auto s32x2StructTy =
392       LLVM::LLVMStructType::getLiteral(context, {i32Ty, i32Ty});
393 
394   std::array<int64_t, 3> mmaShape{getShapeAttr().getM(), getShapeAttr().getN(),
395                                   getShapeAttr().getK()};
396 
397   // These variables define the set of allowed data types for matrices A, B, C,
398   // and result.
399   using AllowedShapes = SmallVector<std::array<int64_t, 3>, 2>;
400   using AllowedTypes = SmallVector<SmallVector<Type, 4>, 2>;
401   AllowedShapes allowedShapes;
402   AllowedTypes expectedA;
403   AllowedTypes expectedB;
404   AllowedTypes expectedC;
405   SmallVector<Type> expectedResult;
406 
407   // When M = 16, we just need to calculate the number of 8xk tiles, where
408   // k is a factor that depends on the data type.
409   if (mmaShape[0] == 16) {
410     int64_t kFactor;
411     Type multiplicandFragType;
412     switch (*getMultiplicandAPtxType()) {
413     case MMATypes::tf32:
414       kFactor = 4;
415       multiplicandFragType = i32Ty;
416       expectedResult.push_back(LLVM::LLVMStructType::getLiteral(
417           context, {f32Ty, f32Ty, f32Ty, f32Ty}));
418       break;
419     case MMATypes::f16:
420     case MMATypes::bf16:
421       kFactor = 8;
422       multiplicandFragType = f16x2Ty;
423       expectedResult.push_back(f16x2x2StructTy);
424       expectedResult.push_back(f32x4StructTy);
425       break;
426     case MMATypes::s4:
427     case MMATypes::u4:
428       kFactor = 32;
429       break;
430     case MMATypes::b1:
431       kFactor = 128;
432       break;
433     case MMATypes::s8:
434     case MMATypes::u8:
435       kFactor = 16;
436       break;
437     default:
438       return emitError("invalid shape or multiplicand type: " +
439                        stringifyEnum(getMultiplicandAPtxType().value()));
440     }
441 
442     if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
443       expectedResult.push_back(s32x4StructTy);
444       expectedC.emplace_back(4, i32Ty);
445       multiplicandFragType = i32Ty;
446     } else {
447       expectedC.emplace_back(2, f16x2Ty);
448       expectedC.emplace_back(4, f32Ty);
449     }
450 
451     int64_t unitA = (mmaShape[0] / 8) * (mmaShape[2] / kFactor);
452     int64_t unitB = (mmaShape[1] / 8) * (mmaShape[2] / kFactor);
453     expectedA.emplace_back(unitA, multiplicandFragType);
454     expectedB.emplace_back(unitB, multiplicandFragType);
455     allowedShapes.push_back({16, 8, kFactor});
456     allowedShapes.push_back({16, 8, kFactor * 2});
457   }
458 
459   // In the M=8 case, there is only 1 possible case per data type.
460   if (mmaShape[0] == 8) {
461     if (*getMultiplicandAPtxType() == MMATypes::f16) {
462       expectedA.emplace_back(2, f16x2Ty);
463       expectedB.emplace_back(2, f16x2Ty);
464       expectedResult.push_back(f16x2x4StructTy);
465       expectedResult.push_back(f32x8StructTy);
466       expectedC.emplace_back(4, f16x2Ty);
467       expectedC.emplace_back(8, f32Ty);
468       allowedShapes.push_back({8, 8, 4});
469     }
470     if (*getMultiplicandAPtxType() == MMATypes::f64) {
471       Type f64Ty = Float64Type::get(context);
472       expectedA.emplace_back(1, f64Ty);
473       expectedB.emplace_back(1, f64Ty);
474       expectedC.emplace_back(2, f64Ty);
475       // expectedC.emplace_back(1, LLVM::getFixedVectorType(f64Ty, 2));
476       expectedResult.emplace_back(LLVM::LLVMStructType::getLiteral(
477           context, SmallVector<Type>(2, f64Ty)));
478       allowedShapes.push_back({8, 8, 4});
479     }
480     if (isIntegerPtxType(getMultiplicandAPtxType().value())) {
481       expectedA.push_back({i32Ty});
482       expectedB.push_back({i32Ty});
483       expectedC.push_back({i32Ty, i32Ty});
484       expectedResult.push_back(s32x2StructTy);
485       if (isInt4PtxType(getMultiplicandAPtxType().value()))
486         allowedShapes.push_back({8, 8, 32});
487       if (isInt8PtxType(getMultiplicandAPtxType().value()))
488         allowedShapes.push_back({8, 8, 16});
489       if (getMultiplicandAPtxType().value() == MMATypes::b1)
490         allowedShapes.push_back({8, 8, 128});
491     }
492   }
493 
494   std::string errorMessage;
495   llvm::raw_string_ostream errorStream(errorMessage);
496 
497   // Check that we matched an existing shape/dtype combination.
498   if (expectedA.empty() || expectedB.empty() || expectedC.empty() ||
499       !llvm::is_contained(allowedShapes, mmaShape)) {
500     errorStream << "unimplemented variant for MMA shape <";
501     llvm::interleaveComma(mmaShape, errorStream);
502     errorStream << ">";
503     return emitOpError(errorMessage);
504   }
505 
506   // Verify the operand types for segments of A, B, and C operands.
507   std::array<StringRef, 3> operandNames{"A", "B", "C"};
508   for (const auto &iter : llvm::enumerate(
509            SmallVector<AllowedTypes, 3>{expectedA, expectedB, expectedC})) {
510     auto spec = this->getODSOperandIndexAndLength(iter.index());
511     SmallVector<Type, 4> operandTySeg(operand_type_begin() + spec.first,
512                                       operand_type_begin() + spec.first +
513                                           spec.second);
514     bool match = llvm::is_contained(iter.value(), operandTySeg);
515 
516     if (!match) {
517       errorStream << "Could not match types for the "
518                   << operandNames[iter.index()]
519                   << " operands; expected one of ";
520       for (const auto &x : iter.value()) {
521         errorStream << x.size() << "x" << x[0] << " ";
522       }
523       errorStream << "but got ";
524       llvm::interleaveComma(operandTySeg, errorStream);
525       return emitOpError(errorStream.str());
526     }
527   }
528 
529   // Check the result type
530   if (!llvm::any_of(expectedResult, [&](Type expectedResultType) {
531         return expectedResultType == getResult().getType();
532       })) {
533     errorStream
534         << "Could not match allowed types for the result; expected one of ";
535     llvm::interleaveComma(expectedResult, errorStream);
536     errorStream << " but got " << getResult().getType();
537     return emitOpError(errorStream.str());
538   }
539 
540   // Ensure that binary MMA variants have a b1 MMA operation defined.
541   if (getMultiplicandAPtxType() == MMATypes::b1 && !getB1Op()) {
542     return emitOpError("op requires " + getB1OpAttrName().strref() +
543                        " attribute");
544   }
545 
546   // Ensure int4/int8 MMA variants specify the accum overflow behavior
547   // attribute.
548   if (isInt4PtxType(*getMultiplicandAPtxType()) ||
549       isInt8PtxType(*getMultiplicandAPtxType())) {
550     if (!getIntOverflowBehavior())
551       return emitOpError("op requires " +
552                          getIntOverflowBehaviorAttrName().strref() +
553                          " attribute");
554   }
555 
556   return success();
557 }
558 
559 LogicalResult ShflOp::verify() {
560   if (!(*this)->getAttrOfType<UnitAttr>("return_value_and_is_valid"))
561     return success();
562   auto type = llvm::dyn_cast<LLVM::LLVMStructType>(getType());
563   auto elementType = (type && type.getBody().size() == 2)
564                          ? llvm::dyn_cast<IntegerType>(type.getBody()[1])
565                          : nullptr;
566   if (!elementType || elementType.getWidth() != 1)
567     return emitError("expected return type to be a two-element struct with "
568                      "i1 as the second element");
569   return success();
570 }
571 
572 std::pair<mlir::Type, unsigned> NVVM::inferMMAType(NVVM::MMATypes type,
573                                                    NVVM::MMAFrag frag, int nRow,
574                                                    int nCol,
575                                                    MLIRContext *context) {
576   unsigned numberElements = 0;
577   Type elementType;
578   OpBuilder builder(context);
579   Type f16x2 = VectorType::get(2, builder.getF16Type());
580   if (type == NVVM::MMATypes::f16) {
581     elementType = f16x2;
582     if (frag == NVVM::MMAFrag::a || frag == NVVM::MMAFrag::b)
583       numberElements = 8;
584     else
585       numberElements = 4;
586   } else if (type == NVVM::MMATypes::f32) {
587     elementType = builder.getF32Type();
588     numberElements = 8;
589   } else if (type == NVVM::MMATypes::tf32) {
590     elementType = builder.getI32Type();
591     numberElements = 4;
592   } else if (type == NVVM::MMATypes::s8 || type == NVVM::MMATypes::u8) {
593     elementType = builder.getI32Type();
594     int parallelSize = 0;
595     if (frag == NVVM::MMAFrag::a)
596       parallelSize = nRow;
597     if (frag == NVVM::MMAFrag::b)
598       parallelSize = nCol;
599 
600     // m == 16 && n == 16 && k == 16
601     if (parallelSize == 16)
602       numberElements = 2;
603     // m == 8 && n == 32 && k == 16 or m == 32 && n == 8 && k == 16
604     else if (parallelSize == 8)
605       numberElements = 1;
606     else if (parallelSize == 32)
607       numberElements = 4;
608   } else if (type == NVVM::MMATypes::s32) {
609     elementType = builder.getI32Type();
610     numberElements = 8;
611   }
612   assert(numberElements != 0 && elementType != nullptr);
613   return std::make_pair(elementType, numberElements);
614 }
615 
616 static std::pair<mlir::Type, unsigned>
617 inferMMATypeFromMNK(NVVM::MMATypes type, NVVM::MMAFrag frag, int m, int n,
618                     int k, MLIRContext *context) {
619   int nRow, nCol;
620   if (frag == NVVM::MMAFrag::a) {
621     nRow = m;
622     nCol = k;
623   } else if (frag == NVVM::MMAFrag::b) {
624     nRow = k;
625     nCol = n;
626   } else {
627     nRow = m;
628     nCol = n;
629   }
630   assert(nRow && nCol);
631   return inferMMAType(type, frag, nRow, nCol, context);
632 }
633 
634 LogicalResult NVVM::WMMALoadOp::verify() {
635   unsigned addressSpace =
636       llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
637   if (addressSpace != 0 && addressSpace != NVVM::kGlobalMemorySpace &&
638       addressSpace != NVVM::kSharedMemorySpace)
639     return emitOpError("expected source pointer in memory "
640                        "space 0, 1, 3");
641 
642   if (NVVM::WMMALoadOp::getIntrinsicID(getM(), getN(), getK(), getLayout(),
643                                        getEltype(), getFrag()) == 0)
644     return emitOpError() << "invalid attribute combination";
645   std::pair<Type, unsigned> typeInfo = inferMMATypeFromMNK(
646       getEltype(), getFrag(), getM(), getN(), getK(), getContext());
647   Type dstType = LLVM::LLVMStructType::getLiteral(
648       getContext(), SmallVector<Type, 8>(typeInfo.second, typeInfo.first));
649   if (getType() != dstType)
650     return emitOpError("expected destination type is a structure of ")
651            << typeInfo.second << " elements of type " << typeInfo.first;
652   return success();
653 }
654 
655 LogicalResult NVVM::WMMAStoreOp::verify() {
656   unsigned addressSpace =
657       llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
658   if (addressSpace != 0 && addressSpace != NVVM::kGlobalMemorySpace &&
659       addressSpace != NVVM::kSharedMemorySpace)
660     return emitOpError("expected operands to be a source pointer in memory "
661                        "space 0, 1, 3");
662 
663   if (NVVM::WMMAStoreOp::getIntrinsicID(getM(), getN(), getK(), getLayout(),
664                                         getEltype()) == 0)
665     return emitOpError() << "invalid attribute combination";
666   std::pair<Type, unsigned> typeInfo = inferMMATypeFromMNK(
667       getEltype(), NVVM::MMAFrag::c, getM(), getN(), getK(), getContext());
668   if (getArgs().size() != typeInfo.second)
669     return emitOpError() << "expected " << typeInfo.second << " data operands";
670   if (llvm::any_of(getArgs(), [&typeInfo](Value operands) {
671         return operands.getType() != typeInfo.first;
672       }))
673     return emitOpError() << "expected data operands of type " << typeInfo.first;
674   return success();
675 }
676 
677 LogicalResult NVVM::WMMAMmaOp::verify() {
678   if (NVVM::WMMAMmaOp::getIntrinsicID(getM(), getN(), getK(), getLayoutA(),
679                                       getLayoutB(), getEltypeA(),
680                                       getEltypeB()) == 0)
681     return emitOpError() << "invalid attribute combination";
682   std::pair<Type, unsigned> typeInfoA = inferMMATypeFromMNK(
683       getEltypeA(), NVVM::MMAFrag::a, getM(), getN(), getK(), getContext());
684   std::pair<Type, unsigned> typeInfoB = inferMMATypeFromMNK(
685       getEltypeA(), NVVM::MMAFrag::b, getM(), getN(), getK(), getContext());
686   std::pair<Type, unsigned> typeInfoC = inferMMATypeFromMNK(
687       getEltypeB(), NVVM::MMAFrag::c, getM(), getN(), getK(), getContext());
688   SmallVector<Type, 32> arguments;
689   arguments.append(typeInfoA.second, typeInfoA.first);
690   arguments.append(typeInfoB.second, typeInfoB.first);
691   arguments.append(typeInfoC.second, typeInfoC.first);
692   unsigned numArgs = arguments.size();
693   if (getArgs().size() != numArgs)
694     return emitOpError() << "expected " << numArgs << " arguments";
695   for (unsigned i = 0; i < numArgs; i++) {
696     if (getArgs()[i].getType() != arguments[i])
697       return emitOpError() << "expected argument " << i << " to be of type "
698                            << arguments[i];
699   }
700   Type dstType = LLVM::LLVMStructType::getLiteral(
701       getContext(), SmallVector<Type, 8>(typeInfoC.second, typeInfoC.first));
702   if (getType() != dstType)
703     return emitOpError("expected destination type is a structure of ")
704            << typeInfoC.second << " elements of type " << typeInfoC.first;
705   return success();
706 }
707 
708 LogicalResult NVVM::LdMatrixOp::verify() {
709   unsigned addressSpace =
710       llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
711   if (addressSpace != NVVM::kSharedMemorySpace)
712     return emitOpError("expected source pointer in memory space 3");
713 
714   if (getNum() != 1 && getNum() != 2 && getNum() != 4)
715     return emitOpError("expected num attribute to be 1, 2 or 4");
716 
717   Type i32 = IntegerType::get(getContext(), 32);
718   if (getNum() == 1 && getType() != i32)
719     return emitOpError("expected destination type is i32");
720   if (getNum() == 2 || getNum() == 4) {
721     Type dstType = LLVM::LLVMStructType::getLiteral(
722         getContext(), SmallVector<Type>(getNum(), i32));
723     if (getType() != dstType)
724       return emitOpError("expected destination type is a structure of ")
725              << getNum() << " elements of type i32";
726   }
727   return success();
728 }
729 
730 LogicalResult NVVM::StMatrixOp::verify() {
731   unsigned addressSpace =
732       llvm::cast<LLVM::LLVMPointerType>(getPtr().getType()).getAddressSpace();
733   if (addressSpace != NVVM::kSharedMemorySpace)
734     return emitOpError("expected source pointer in memory space 3");
735 
736   int numMatrix = getSources().size();
737   if (numMatrix != 1 && numMatrix != 2 && numMatrix != 4)
738     return emitOpError("expected num attribute to be 1, 2 or 4");
739 
740   return success();
741 }
742 
743 FailureOr<int> getAllowedSizeK(NVVM::WGMMATypes typeA) {
744   if (typeA == NVVM::WGMMATypes::tf32)
745     return 8;
746   if (typeA == NVVM::WGMMATypes::f16 || typeA == NVVM::WGMMATypes::bf16)
747     return 16;
748   if (typeA == NVVM::WGMMATypes::s8 || typeA == NVVM::WGMMATypes::u8)
749     return 32;
750   if (typeA == NVVM::WGMMATypes::e4m3 || typeA == NVVM::WGMMATypes::e5m2)
751     return 32;
752   if (typeA == NVVM::WGMMATypes::b1)
753     return 256;
754   return failure();
755 }
756 
757 LogicalResult isAllowedWGMMADataType(Type typeD, NVVM::WGMMATypes typeA,
758                                      NVVM::WGMMATypes typeB) {
759   switch (typeA) {
760   case NVVM::WGMMATypes::f16:
761     if ((typeD.isF32() || typeD.isF16()) && typeB == NVVM::WGMMATypes::f16)
762       return success();
763     break;
764   case NVVM::WGMMATypes::tf32:
765     if (typeD.isF32() && typeB == NVVM::WGMMATypes::tf32)
766       return success();
767     break;
768   case NVVM::WGMMATypes::u8:
769   case NVVM::WGMMATypes::s8:
770     if (typeD.isInteger(32) &&
771         (typeB == NVVM::WGMMATypes::u8 || typeB == NVVM::WGMMATypes::s8))
772       return success();
773     break;
774   case NVVM::WGMMATypes::b1:
775     if (typeD.isInteger(32) && typeB == NVVM::WGMMATypes::b1)
776       return success();
777     break;
778   case NVVM::WGMMATypes::bf16:
779     if ((typeD.isF32() || typeD.isF16()) && typeB == NVVM::WGMMATypes::bf16)
780       return success();
781     break;
782   case NVVM::WGMMATypes::e4m3:
783   case NVVM::WGMMATypes::e5m2:
784     if ((typeD.isF32() || typeD.isF16()) &&
785         (typeB == NVVM::WGMMATypes::e5m2 || typeB == NVVM::WGMMATypes::e4m3))
786       return success();
787     break;
788   }
789   return failure();
790 }
791 
792 LogicalResult isAllowedSizeN(int sizeN, NVVM::WGMMATypes typeA) {
793   SmallVector<int> allowedN = {8,   16,  24,  32,  40,  48,  56,  64,
794                                72,  80,  88,  96,  104, 112, 120, 128,
795                                136, 144, 152, 160, 168, 176, 184, 192,
796                                200, 208, 216, 224, 232, 240, 248, 256};
797   SmallVector<int> allowedNshort = {8,   16,  24,  32,  48,  64,
798                                     80,  96,  112, 128, 144, 160,
799                                     176, 192, 208, 224, 240, 256};
800   switch (typeA) {
801   case mlir::NVVM::WGMMATypes::f16:
802   case mlir::NVVM::WGMMATypes::tf32:
803   case mlir::NVVM::WGMMATypes::bf16:
804   case mlir::NVVM::WGMMATypes::e4m3:
805   case mlir::NVVM::WGMMATypes::e5m2:
806     if (llvm::is_contained(allowedN, sizeN))
807       return success();
808     break;
809   case mlir::NVVM::WGMMATypes::u8:
810   case mlir::NVVM::WGMMATypes::s8:
811   case mlir::NVVM::WGMMATypes::b1:
812     if (llvm::is_contained(allowedNshort, sizeN))
813       return success();
814   }
815   return failure();
816 }
817 
818 LogicalResult NVVM::WgmmaMmaAsyncOp::verify() {
819   Value outValue = getResults();
820   auto stype = dyn_cast<LLVM::LLVMStructType>(outValue.getType());
821   if (!stype)
822     return emitOpError() << "expected results to be struct";
823   Type outputType = stype.getBody().front();
824   int outputSize = stype.getBody().size();
825   for (Type t : stype.getBody()) {
826     if (t != outputType)
827       return emitOpError()
828              << "all elements in struct must be same type but there is " << t;
829   }
830 
831   if (!outputType.isF32() && !outputType.isInteger(32) && !outputType.isF16()) {
832     return emitOpError() << "does not support the given output type "
833                          << outputType;
834   }
835   if (outputType.isInteger(32) && (getScaleA() == NVVM::WGMMAScaleIn::neg ||
836                                    getScaleB() == NVVM::WGMMAScaleIn::neg)) {
837     return emitOpError() << "has s32 output, scaleA and scaleB cannot be neg";
838   }
839 
840   mlir::NVVM::WGMMATypes typeA = getTypeA();
841   mlir::NVVM::WGMMATypes typeB = getTypeB();
842   if (failed(isAllowedWGMMADataType(outputType, typeA, typeB))) {
843     return emitOpError() << outputType
844                          << " += " << NVVM::stringifyWGMMATypes(typeA) << " * "
845                          << NVVM::stringifyWGMMATypes(typeB)
846                          << ", it is not supported.";
847   }
848 
849   // Check M
850   if (getShape().getM() != 64)
851     return emitOpError() << "shape 'm' must be 64";
852 
853   // Check K
854   FailureOr<int> allowedK = getAllowedSizeK(typeA);
855   if (failed(allowedK) || allowedK.value() != getShape().getK())
856     return emitOpError() << "shape 'k' must be " << allowedK.value()
857                          << " for input type "
858                          << NVVM::stringifyWGMMATypes(typeA);
859 
860   // Check N
861   if (failed(isAllowedSizeN(getShape().getN(), typeA))) {
862     return emitOpError() << "has input type "
863                          << NVVM::stringifyWGMMATypes(typeA) << " n is set to "
864                          << getShape().getN() << ", it is not supported.";
865   }
866 
867   // Check transpose (only available for f16/bf16)
868   if ((typeA != mlir::NVVM::WGMMATypes::f16 &&
869        typeA != mlir::NVVM::WGMMATypes::bf16) &&
870       (getLayoutA() == mlir::NVVM::MMALayout::col ||
871        getLayoutB() == mlir::NVVM::MMALayout::col)) {
872     return emitOpError()
873            << "given layouts layout_a = " << stringifyMMALayout(getLayoutA())
874            << " and layout_b = " << stringifyMMALayout(getLayoutB())
875            << " for input types " << stringifyWGMMATypes(typeA) << " and "
876            << stringifyWGMMATypes(typeB)
877            << " requires transpose. However, this is only supported for: "
878            << stringifyMMATypes(mlir::NVVM::MMATypes::f16) << " and "
879            << stringifyMMATypes(mlir::NVVM::MMATypes::bf16);
880   }
881 
882   // Check result registers
883   int expectedOutput;
884   if (outputType.isF32() || outputType.isInteger(32))
885     expectedOutput = getShape().getN() / 2;
886   if (outputType.isF16())
887     expectedOutput = getShape().getN() / 4;
888   if (outputSize != expectedOutput) {
889     return emitOpError() << "results " << expectedOutput
890                          << ", however output struct has " << outputSize
891                          << " elements";
892   }
893   // Check satfinite (only availalbe for s32 accumulator)
894   if (!outputType.isInteger(32) &&
895       getSatfinite().value_or(NVVM::MMAIntOverflow::wrapped) ==
896           NVVM::MMAIntOverflow::satfinite) {
897     return emitOpError()
898            << " `satfinite` can be only used with s32 accumulator, however "
899               "the current accumulator is "
900            << outputType;
901   }
902 
903   return success();
904 }
905 
906 std::string NVVM::WgmmaMmaAsyncOp::getPtx() {
907 
908   int m = getShape().getM(), n = getShape().getN(), k = getShape().getK();
909   bool isF16 = getTypeA() == mlir::NVVM::WGMMATypes::f16 ||
910                getTypeA() == mlir::NVVM::WGMMATypes::bf16;
911 
912   Value outValue = getResults() ? getResults() : getInouts();
913   auto stype = dyn_cast<LLVM::LLVMStructType>(outValue.getType());
914   Type outputType = stype.getBody().front();
915   std::string outputTypeName;
916   if (outputType.isF16())
917     outputTypeName = "f16";
918   else if (outputType.isF32())
919     outputTypeName = "f32";
920   else if (outputType.isInteger(32))
921     outputTypeName = "s32";
922   else
923     assert(false && "unsupported output type");
924 
925   int expectedOutputRegisters;
926   if (outputType.isF32() || outputType.isInteger(32))
927     expectedOutputRegisters = getShape().getN() / 2;
928   if (outputType.isF16())
929     expectedOutputRegisters = getShape().getN() / 4;
930 
931   std::string ptx;
932   llvm::raw_string_ostream ss(ptx);
933 
934   ss << "{\n"
935         ".reg .pred p;\n"
936         "setp.ne.b32 p, $"
937      << ((expectedOutputRegisters * 2) + 2)
938      << ", 0;\n"
939         "wgmma.mma_async.sync.aligned.m"
940      << m << "n" << n << "k" << k << "." << outputTypeName << "."
941      << stringifyWGMMATypes(getTypeA()) << "."
942      << stringifyWGMMATypes(getTypeB());
943   if (getSatfinite().value_or(NVVM::MMAIntOverflow::wrapped) ==
944       NVVM::MMAIntOverflow::satfinite)
945     ss << ".satfinite";
946   ss << " {";
947   int regCnt = 0;
948   for (; regCnt < expectedOutputRegisters; ++regCnt) {
949     ss << "$" << regCnt;
950     if (regCnt != expectedOutputRegisters - 1)
951       ss << ", ";
952   }
953 
954   ss << "},";
955   // Need to map read/write registers correctly.
956   regCnt = (regCnt * 2);
957   ss << " $" << (regCnt) << ","
958      << " $" << (regCnt + 1) << ","
959      << " p";
960   if (!outputType.isInteger(32)) {
961     ss << ", $" << (regCnt + 3) << ",  $" << (regCnt + 4);
962   }
963   // Don't add transpose parameters unless needed.
964   if (isF16) {
965     ss << ", $" << (regCnt + 5) << ",  $" << (regCnt + 6);
966   }
967   ss << ";\n"
968      << "}\n";
969   ss.flush();
970   return ptx;
971 }
972 
973 void NVVM::WgmmaMmaAsyncOp::getAsmValues(
974     RewriterBase &rewriter,
975     llvm::SmallVectorImpl<std::pair<mlir::Value, mlir::NVVM::PTXRegisterMod>>
976         &asmValues) {
977   Value outValue = getResults() ? getResults() : getInouts();
978   auto stype = dyn_cast<LLVM::LLVMStructType>(outValue.getType());
979   Type outputType = stype.getBody().front();
980   bool isF16 = getTypeA() == mlir::NVVM::WGMMATypes::f16 ||
981                getTypeA() == mlir::NVVM::WGMMATypes::bf16;
982   if (getResults())
983     asmValues.push_back({getResults(), mlir::NVVM::PTXRegisterMod::Write});
984   if (getInouts())
985     asmValues.push_back({getInouts(), mlir::NVVM::PTXRegisterMod::ReadWrite});
986   asmValues.push_back({getDescriptorA(), mlir::NVVM::PTXRegisterMod::Read});
987   asmValues.push_back({getDescriptorB(), mlir::NVVM::PTXRegisterMod::Read});
988   asmValues.push_back({makeConstantI32(rewriter, static_cast<int>(getScaleD())),
989                        mlir::NVVM::PTXRegisterMod::Read});
990   if (!outputType.isInteger(32)) {
991     asmValues.push_back(
992         {makeConstantI32(rewriter,
993                          getScaleA() == NVVM::WGMMAScaleIn::neg ? -1 : 1),
994          mlir::NVVM::PTXRegisterMod::Read});
995     asmValues.push_back(
996         {makeConstantI32(rewriter,
997                          getScaleB() == NVVM::WGMMAScaleIn::neg ? -1 : 1),
998          mlir::NVVM::PTXRegisterMod::Read});
999   }
1000   if (isF16) {
1001     asmValues.push_back(
1002         {makeConstantI32(rewriter, static_cast<int>(getLayoutA())),
1003          mlir::NVVM::PTXRegisterMod::Read});
1004     asmValues.push_back(
1005         {makeConstantI32(rewriter, static_cast<int>(getLayoutB())),
1006          mlir::NVVM::PTXRegisterMod::Read});
1007   }
1008 }
1009 
1010 LogicalResult NVVM::SetMaxRegisterOp::verify() {
1011   if (getRegCount() % 8)
1012     return emitOpError("new register size must be multiple of 8");
1013   if (getRegCount() < 24 || getRegCount() > 256)
1014     return emitOpError("new register size must be in between 24 to 256");
1015   return success();
1016 }
1017 
1018 //===----------------------------------------------------------------------===//
1019 // NVVMDialect initialization, type parsing, and registration.
1020 //===----------------------------------------------------------------------===//
1021 
1022 // TODO: This should be the llvm.nvvm dialect once this is supported.
1023 void NVVMDialect::initialize() {
1024   addOperations<
1025 #define GET_OP_LIST
1026 #include "mlir/Dialect/LLVMIR/NVVMOps.cpp.inc"
1027       >();
1028   addAttributes<
1029 #define GET_ATTRDEF_LIST
1030 #include "mlir/Dialect/LLVMIR/NVVMOpsAttributes.cpp.inc"
1031       >();
1032 
1033   // Support unknown operations because not all NVVM operations are
1034   // registered.
1035   allowUnknownOperations();
1036   declarePromisedInterface<NVVMDialect, ConvertToLLVMPatternInterface>();
1037   declarePromisedInterface<NVVMTargetAttr, gpu::TargetAttrInterface>();
1038 }
1039 
1040 LogicalResult NVVMDialect::verifyOperationAttribute(Operation *op,
1041                                                     NamedAttribute attr) {
1042   StringAttr attrName = attr.getName();
1043   // Kernel function attribute should be attached to functions.
1044   if (attrName == NVVMDialect::getKernelFuncAttrName()) {
1045     if (!isa<LLVM::LLVMFuncOp>(op)) {
1046       return op->emitError() << "'" << NVVMDialect::getKernelFuncAttrName()
1047                              << "' attribute attached to unexpected op";
1048     }
1049   }
1050   // If maxntid and reqntid exist, it must be an array with max 3 dim
1051   if (attrName == NVVMDialect::getMaxntidAttrName() ||
1052       attrName == NVVMDialect::getReqntidAttrName()) {
1053     auto values = llvm::dyn_cast<ArrayAttr>(attr.getValue());
1054     if (!values || values.empty() || values.size() > 3)
1055       return op->emitError()
1056              << "'" << attrName
1057              << "' attribute must be integer array with maximum 3 index";
1058     for (auto val : llvm::cast<ArrayAttr>(attr.getValue())) {
1059       if (!llvm::dyn_cast<IntegerAttr>(val))
1060         return op->emitError()
1061                << "'" << attrName
1062                << "' attribute must be integer array with maximum 3 index";
1063     }
1064   }
1065   // If minctasm and maxnreg exist, it must be an array with max 3 dim
1066   if (attrName == NVVMDialect::getMinctasmAttrName() ||
1067       attrName == NVVMDialect::getMaxnregAttrName()) {
1068     if (!llvm::dyn_cast<IntegerAttr>(attr.getValue()))
1069       return op->emitError()
1070              << "'" << attrName << "' attribute must be integer constant";
1071   }
1072 
1073   return success();
1074 }
1075 
1076 //===----------------------------------------------------------------------===//
1077 // NVVM target attribute.
1078 //===----------------------------------------------------------------------===//
1079 LogicalResult
1080 NVVMTargetAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1081                        int optLevel, StringRef triple, StringRef chip,
1082                        StringRef features, DictionaryAttr flags,
1083                        ArrayAttr files) {
1084   if (optLevel < 0 || optLevel > 3) {
1085     emitError() << "The optimization level must be a number between 0 and 3.";
1086     return failure();
1087   }
1088   if (triple.empty()) {
1089     emitError() << "The target triple cannot be empty.";
1090     return failure();
1091   }
1092   if (chip.empty()) {
1093     emitError() << "The target chip cannot be empty.";
1094     return failure();
1095   }
1096   if (files && !llvm::all_of(files, [](::mlir::Attribute attr) {
1097         return attr && mlir::isa<StringAttr>(attr);
1098       })) {
1099     emitError() << "All the elements in the `link` array must be strings.";
1100     return failure();
1101   }
1102   return success();
1103 }
1104 
1105 #define GET_OP_CLASSES
1106 #include "mlir/Dialect/LLVMIR/NVVMOps.cpp.inc"
1107 
1108 #define GET_ATTRDEF_CLASSES
1109 #include "mlir/Dialect/LLVMIR/NVVMOpsAttributes.cpp.inc"
1110