1 //===- GPUDialect.cpp - MLIR Dialect for GPU Kernels implementation -------===//
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 implements the GPU kernel-related dialect and its operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/GPU/GPUDialect.h"
14 
15 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
16 #include "mlir/Dialect/MemRef/IR/MemRef.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/DialectImplementation.h"
22 #include "mlir/IR/FunctionImplementation.h"
23 #include "mlir/IR/Matchers.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/IR/PatternMatch.h"
26 #include "mlir/IR/TypeUtilities.h"
27 #include "mlir/Transforms/InliningUtils.h"
28 #include "llvm/ADT/TypeSwitch.h"
29 
30 using namespace mlir;
31 using namespace mlir::gpu;
32 
33 #include "mlir/Dialect/GPU/GPUOpsDialect.cpp.inc"
34 
35 //===----------------------------------------------------------------------===//
36 // MMAMatrixType
37 //===----------------------------------------------------------------------===//
38 
39 MMAMatrixType MMAMatrixType::get(ArrayRef<int64_t> shape, Type elementType,
40                                  StringRef operand) {
41   return Base::get(elementType.getContext(), shape, elementType, operand);
42 }
43 
44 MMAMatrixType
45 MMAMatrixType::getChecked(function_ref<InFlightDiagnostic()> emitError,
46                           ArrayRef<int64_t> shape, Type elementType,
47                           StringRef operand) {
48   return Base::getChecked(emitError, elementType.getContext(), shape,
49                           elementType, operand);
50 }
51 
52 unsigned MMAMatrixType::getNumDims() const { return getImpl()->numDims; }
53 
54 ArrayRef<int64_t> MMAMatrixType::getShape() const {
55   return getImpl()->getShape();
56 }
57 
58 Type MMAMatrixType::getElementType() const { return getImpl()->elementType; }
59 
60 StringRef MMAMatrixType::getOperand() const { return getImpl()->getOperand(); }
61 
62 bool MMAMatrixType::isValidElementType(Type elementType) {
63   return elementType.isF16() || elementType.isF32();
64 }
65 
66 LogicalResult
67 MMAMatrixType::verify(function_ref<InFlightDiagnostic()> emitError,
68                       ArrayRef<int64_t> shape, Type elementType,
69                       StringRef operand) {
70   if (!operand.equals("AOp") && !operand.equals("BOp") &&
71       !operand.equals("COp"))
72     return emitError() << "operand expected to be one of AOp, BOp or COp";
73 
74   if (shape.size() != 2)
75     return emitError() << "MMAMatrixType must have exactly two dimensions";
76 
77   if (!MMAMatrixType::isValidElementType(elementType))
78     return emitError() << "MMAMatrixType elements must be F16 or F32";
79 
80   return success();
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // GPUDialect
85 //===----------------------------------------------------------------------===//
86 
87 /// GPU memory space identifiers.
88 enum GPUMemorySpace {
89   /// Generic memory space identifier.
90   kGenericMemorySpace = 0,
91 
92   /// Global memory space identifier.
93   kGlobalMemorySpace = 1,
94 
95   /// Shared memory space identifier.
96   kSharedMemorySpace = 3
97 };
98 
99 bool GPUDialect::isKernel(Operation *op) {
100   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
101   return static_cast<bool>(isKernelAttr);
102 }
103 
104 namespace {
105 /// This class defines the interface for handling inlining with gpu
106 /// operations.
107 struct GPUInlinerInterface : public DialectInlinerInterface {
108   using DialectInlinerInterface::DialectInlinerInterface;
109 
110   /// All gpu dialect ops can be inlined.
111   bool isLegalToInline(Operation *, Region *, bool,
112                        BlockAndValueMapping &) const final {
113     return true;
114   }
115 };
116 } // namespace
117 
118 void GPUDialect::initialize() {
119   addTypes<AsyncTokenType>();
120   addTypes<DeviceAsyncTokenType>();
121   addTypes<MMAMatrixType>();
122   addOperations<
123 #define GET_OP_LIST
124 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
125       >();
126   addAttributes<
127 #define GET_ATTRDEF_LIST
128 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
129       >();
130   addInterfaces<GPUInlinerInterface>();
131 }
132 
133 Type GPUDialect::parseType(DialectAsmParser &parser) const {
134   // Parse the main keyword for the type.
135   StringRef keyword;
136   if (parser.parseKeyword(&keyword))
137     return Type();
138   MLIRContext *context = getContext();
139 
140   // Handle 'async token' types.
141   if (keyword == "async.token")
142     return AsyncTokenType::get(context);
143   // Handle 'device async token' types.
144   if (keyword == "device.async.token")
145     return DeviceAsyncTokenType::get(context);
146 
147   if (keyword == "mma_matrix") {
148     SMLoc beginLoc = parser.getNameLoc();
149 
150     // Parse '<'.
151     if (parser.parseLess())
152       return nullptr;
153 
154     // Parse the size and elementType.
155     SmallVector<int64_t> shape;
156     Type elementType;
157     if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
158         parser.parseType(elementType))
159       return nullptr;
160 
161     // Parse ','
162     if (parser.parseComma())
163       return nullptr;
164 
165     // Parse operand.
166     std::string operand;
167     if (failed(parser.parseOptionalString(&operand)))
168       return nullptr;
169 
170     // Parse '>'.
171     if (parser.parseGreater())
172       return nullptr;
173 
174     return MMAMatrixType::getChecked(mlir::detail::getDefaultDiagnosticEmitFn(
175                                          parser.getEncodedSourceLoc(beginLoc)),
176                                      shape, elementType, operand);
177   }
178 
179   parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
180   return Type();
181 }
182 
183 void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
184   TypeSwitch<Type>(type)
185       .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
186       .Case<DeviceAsyncTokenType>([&](Type) { os << "device.async.token"; })
187       .Case<MMAMatrixType>([&](MMAMatrixType fragTy) {
188         os << "mma_matrix<";
189         auto shape = fragTy.getShape();
190         for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
191           os << *dim << 'x';
192         os << shape.back() << 'x' << fragTy.getElementType();
193         os << ", \"" << fragTy.getOperand() << "\"" << '>';
194       })
195       .Default([](Type) { llvm_unreachable("unexpected 'gpu' type kind"); });
196 }
197 
198 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
199                                                    NamedAttribute attr) {
200   if (!attr.getValue().isa<UnitAttr>() ||
201       attr.getName() != getContainerModuleAttrName())
202     return success();
203 
204   auto module = dyn_cast<ModuleOp>(op);
205   if (!module)
206     return op->emitError("expected '")
207            << getContainerModuleAttrName() << "' attribute to be attached to '"
208            << ModuleOp::getOperationName() << '\'';
209 
210   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
211     // Ignore launches that are nested more or less deep than functions in the
212     // module we are currently checking.
213     if (!launchOp->getParentOp() ||
214         launchOp->getParentOp()->getParentOp() != module)
215       return success();
216 
217     // Ignore launch ops with missing attributes here. The errors will be
218     // reported by the verifiers of those ops.
219     if (!launchOp->getAttrOfType<SymbolRefAttr>(
220             LaunchFuncOp::getKernelAttrName()))
221       return success();
222 
223     // Check that `launch_func` refers to a well-formed GPU kernel module.
224     StringAttr kernelModuleName = launchOp.getKernelModuleName();
225     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
226     if (!kernelModule)
227       return launchOp.emitOpError()
228              << "kernel module '" << kernelModuleName.getValue()
229              << "' is undefined";
230 
231     // Check that `launch_func` refers to a well-formed kernel function.
232     Operation *kernelFunc = module.lookupSymbol(launchOp.kernelAttr());
233     if (!kernelFunc)
234       return launchOp.emitOpError("kernel function '")
235              << launchOp.kernel() << "' is undefined";
236     auto kernelConvertedFunction = dyn_cast<FunctionOpInterface>(kernelFunc);
237     if (!kernelConvertedFunction) {
238       InFlightDiagnostic diag = launchOp.emitOpError()
239                                 << "referenced kernel '" << launchOp.kernel()
240                                 << "' is not a function";
241       diag.attachNote(kernelFunc->getLoc()) << "see the kernel definition here";
242       return diag;
243     }
244 
245     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
246             GPUDialect::getKernelFuncAttrName()))
247       return launchOp.emitOpError("kernel function is missing the '")
248              << GPUDialect::getKernelFuncAttrName() << "' attribute";
249 
250     // TODO: If the kernel isn't a GPU function (which happens during separate
251     // compilation), do not check type correspondence as it would require the
252     // verifier to be aware of the type conversion.
253     auto kernelGPUFunction = dyn_cast<gpu::GPUFuncOp>(kernelFunc);
254     if (!kernelGPUFunction)
255       return success();
256 
257     unsigned actualNumArguments = launchOp.getNumKernelOperands();
258     unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
259     if (expectedNumArguments != actualNumArguments)
260       return launchOp.emitOpError("got ")
261              << actualNumArguments << " kernel operands but expected "
262              << expectedNumArguments;
263 
264     auto functionType = kernelGPUFunction.getFunctionType();
265     for (unsigned i = 0; i < expectedNumArguments; ++i) {
266       if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
267         return launchOp.emitOpError("type of function argument ")
268                << i << " does not match";
269       }
270     }
271 
272     return success();
273   });
274 
275   return walkResult.wasInterrupted() ? failure() : success();
276 }
277 
278 /// Parses an optional list of async operands with an optional leading keyword.
279 /// (`async`)? (`[` ssa-id-list `]`)?
280 ///
281 /// This method is used by the tablegen assembly format for async ops as well.
282 static ParseResult parseAsyncDependencies(
283     OpAsmParser &parser, Type &asyncTokenType,
284     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &asyncDependencies) {
285   auto loc = parser.getCurrentLocation();
286   if (succeeded(parser.parseOptionalKeyword("async"))) {
287     if (parser.getNumResults() == 0)
288       return parser.emitError(loc, "needs to be named when marked 'async'");
289     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
290   }
291   return parser.parseOperandList(asyncDependencies,
292                                  OpAsmParser::Delimiter::OptionalSquare);
293 }
294 
295 /// Prints optional async dependencies with its leading keyword.
296 ///   (`async`)? (`[` ssa-id-list `]`)?
297 // Used by the tablegen assembly format for several async ops.
298 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
299                                    Type asyncTokenType,
300                                    OperandRange asyncDependencies) {
301   if (asyncTokenType)
302     printer << "async";
303   if (asyncDependencies.empty())
304     return;
305   if (asyncTokenType)
306     printer << ' ';
307   printer << '[';
308   llvm::interleaveComma(asyncDependencies, printer);
309   printer << ']';
310 }
311 
312 //===----------------------------------------------------------------------===//
313 // AllReduceOp
314 //===----------------------------------------------------------------------===//
315 
316 LogicalResult gpu::AllReduceOp::verifyRegions() {
317   if (body().empty() != op().hasValue())
318     return emitError("expected either an op attribute or a non-empty body");
319   if (!body().empty()) {
320     if (body().getNumArguments() != 2)
321       return emitError("expected two region arguments");
322     for (auto argument : body().getArguments()) {
323       if (argument.getType() != getType())
324         return emitError("incorrect region argument type");
325     }
326     unsigned yieldCount = 0;
327     for (Block &block : body()) {
328       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
329         if (yield.getNumOperands() != 1)
330           return emitError("expected one gpu.yield operand");
331         if (yield.getOperand(0).getType() != getType())
332           return emitError("incorrect gpu.yield type");
333         ++yieldCount;
334       }
335     }
336     if (yieldCount == 0)
337       return emitError("expected gpu.yield op in region");
338   } else {
339     gpu::AllReduceOperation opName = *op();
340     if ((opName == gpu::AllReduceOperation::AND ||
341          opName == gpu::AllReduceOperation::OR ||
342          opName == gpu::AllReduceOperation::XOR) &&
343         !getType().isa<IntegerType>()) {
344       return emitError()
345              << '`' << gpu::stringifyAllReduceOperation(opName)
346              << "` accumulator is only compatible with Integer type";
347     }
348   }
349   return success();
350 }
351 
352 // TODO: Support optional custom attributes (without dialect prefix).
353 static ParseResult parseAllReduceOperation(AsmParser &parser,
354                                            AllReduceOperationAttr &attr) {
355   StringRef enumStr;
356   if (!parser.parseOptionalKeyword(&enumStr)) {
357     Optional<AllReduceOperation> op = gpu::symbolizeAllReduceOperation(enumStr);
358     if (!op)
359       return parser.emitError(parser.getCurrentLocation(), "invalid op kind");
360     attr = AllReduceOperationAttr::get(parser.getContext(), *op);
361   }
362   return success();
363 }
364 
365 static void printAllReduceOperation(AsmPrinter &printer, Operation *op,
366                                     AllReduceOperationAttr attr) {
367   if (attr)
368     attr.print(printer);
369 }
370 
371 //===----------------------------------------------------------------------===//
372 // AsyncOpInterface
373 //===----------------------------------------------------------------------===//
374 
375 void gpu::addAsyncDependency(Operation *op, Value token) {
376   op->insertOperands(0, {token});
377   if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
378     return;
379   auto attrName =
380       OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr();
381   auto sizeAttr = op->template getAttrOfType<DenseIntElementsAttr>(attrName);
382 
383   // Async dependencies is the only variadic operand.
384   if (!sizeAttr)
385     return;
386 
387   SmallVector<int32_t, 8> sizes(sizeAttr.getValues<int32_t>());
388   ++sizes.front();
389   op->setAttr(attrName, Builder(op->getContext()).getI32VectorAttr(sizes));
390 }
391 
392 //===----------------------------------------------------------------------===//
393 // LaunchOp
394 //===----------------------------------------------------------------------===//
395 
396 void LaunchOp::build(OpBuilder &builder, OperationState &result,
397                      Value gridSizeX, Value gridSizeY, Value gridSizeZ,
398                      Value blockSizeX, Value blockSizeY, Value blockSizeZ,
399                      Value dynamicSharedMemorySize, Type asyncTokenType,
400                      ValueRange asyncDependencies) {
401   result.addOperands(asyncDependencies);
402   if (asyncTokenType)
403     result.types.push_back(builder.getType<AsyncTokenType>());
404 
405   // Add grid and block sizes as op operands, followed by the data operands.
406   result.addOperands(
407       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
408   if (dynamicSharedMemorySize)
409     result.addOperands(dynamicSharedMemorySize);
410 
411   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
412   // where the first kNumConfigRegionAttributes arguments have `index` type and
413   // the rest have the same types as the data operands.
414   Region *kernelRegion = result.addRegion();
415   Block *body = new Block();
416   for (unsigned i = 0; i < kNumConfigRegionAttributes; ++i)
417     body->addArgument(builder.getIndexType(), result.location);
418   kernelRegion->push_back(body);
419   SmallVector<int32_t, 8> segmentSizes(8, 1);
420   segmentSizes.front() = asyncDependencies.size();
421   segmentSizes.back() = dynamicSharedMemorySize ? 1 : 0;
422   result.addAttribute(getOperandSegmentSizeAttr(),
423                       builder.getI32VectorAttr(segmentSizes));
424 }
425 
426 KernelDim3 LaunchOp::getBlockIds() {
427   assert(!body().empty() && "LaunchOp body must not be empty.");
428   auto args = body().getArguments();
429   return KernelDim3{args[0], args[1], args[2]};
430 }
431 
432 KernelDim3 LaunchOp::getThreadIds() {
433   assert(!body().empty() && "LaunchOp body must not be empty.");
434   auto args = body().getArguments();
435   return KernelDim3{args[3], args[4], args[5]};
436 }
437 
438 KernelDim3 LaunchOp::getGridSize() {
439   assert(!body().empty() && "LaunchOp body must not be empty.");
440   auto args = body().getArguments();
441   return KernelDim3{args[6], args[7], args[8]};
442 }
443 
444 KernelDim3 LaunchOp::getBlockSize() {
445   assert(!body().empty() && "LaunchOp body must not be empty.");
446   auto args = body().getArguments();
447   return KernelDim3{args[9], args[10], args[11]};
448 }
449 
450 KernelDim3 LaunchOp::getGridSizeOperandValues() {
451   auto operands = getOperands().drop_front(asyncDependencies().size());
452   return KernelDim3{operands[0], operands[1], operands[2]};
453 }
454 
455 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
456   auto operands = getOperands().drop_front(asyncDependencies().size());
457   return KernelDim3{operands[3], operands[4], operands[5]};
458 }
459 
460 LogicalResult LaunchOp::verifyRegions() {
461   // Kernel launch takes kNumConfigOperands leading operands for grid/block
462   // sizes and transforms them into kNumConfigRegionAttributes region arguments
463   // for block/thread identifiers and grid/block sizes.
464   if (!body().empty()) {
465     if (body().getNumArguments() !=
466         LaunchOp::kNumConfigOperands + getNumOperands() -
467             (dynamicSharedMemorySize() ? 1 : 0) - asyncDependencies().size())
468       return emitOpError("unexpected number of region arguments");
469   }
470 
471   // Block terminators without successors are expected to exit the kernel region
472   // and must be `gpu.terminator`.
473   for (Block &block : body()) {
474     if (block.empty())
475       continue;
476     if (block.back().getNumSuccessors() != 0)
477       continue;
478     if (!isa<gpu::TerminatorOp>(&block.back())) {
479       return block.back()
480           .emitError()
481           .append("expected '", gpu::TerminatorOp::getOperationName(),
482                   "' or a terminator with successors")
483           .attachNote(getLoc())
484           .append("in '", LaunchOp::getOperationName(), "' body region");
485     }
486   }
487 
488   if (getNumResults() == 0 && asyncToken())
489     return emitOpError("needs to be named when async keyword is specified");
490 
491   return success();
492 }
493 
494 // Pretty-print the kernel grid/block size assignment as
495 //   (%iter-x, %iter-y, %iter-z) in
496 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
497 // where %size-* and %iter-* will correspond to the body region arguments.
498 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
499                                 KernelDim3 operands, KernelDim3 ids) {
500   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
501   p << size.x << " = " << operands.x << ", ";
502   p << size.y << " = " << operands.y << ", ";
503   p << size.z << " = " << operands.z << ')';
504 }
505 
506 void LaunchOp::print(OpAsmPrinter &p) {
507   if (asyncToken()) {
508     p << " async";
509     if (!asyncDependencies().empty())
510       p << " [" << asyncDependencies() << ']';
511   }
512   // Print the launch configuration.
513   p << ' ' << getBlocksKeyword();
514   printSizeAssignment(p, getGridSize(), getGridSizeOperandValues(),
515                       getBlockIds());
516   p << ' ' << getThreadsKeyword();
517   printSizeAssignment(p, getBlockSize(), getBlockSizeOperandValues(),
518                       getThreadIds());
519   if (dynamicSharedMemorySize())
520     p << ' ' << getDynamicSharedMemorySizeKeyword() << ' '
521       << dynamicSharedMemorySize();
522 
523   p << ' ';
524   p.printRegion(body(), /*printEntryBlockArgs=*/false);
525   p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{
526                               LaunchOp::getOperandSegmentSizeAttr()});
527 }
528 
529 // Parse the size assignment blocks for blocks and threads.  These have the form
530 //   (%region_arg, %region_arg, %region_arg) in
531 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
532 // where %region_arg are percent-identifiers for the region arguments to be
533 // introduced further (SSA defs), and %operand are percent-identifiers for the
534 // SSA value uses.
535 static ParseResult
536 parseSizeAssignment(OpAsmParser &parser,
537                     MutableArrayRef<OpAsmParser::UnresolvedOperand> sizes,
538                     MutableArrayRef<OpAsmParser::UnresolvedOperand> regionSizes,
539                     MutableArrayRef<OpAsmParser::UnresolvedOperand> indices) {
540   assert(indices.size() == 3 && "space for three indices expected");
541   SmallVector<OpAsmParser::UnresolvedOperand, 3> args;
542   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
543                                      OpAsmParser::Delimiter::Paren) ||
544       parser.parseKeyword("in") || parser.parseLParen())
545     return failure();
546   std::move(args.begin(), args.end(), indices.begin());
547 
548   for (int i = 0; i < 3; ++i) {
549     if (i != 0 && parser.parseComma())
550       return failure();
551     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
552         parser.parseOperand(sizes[i]))
553       return failure();
554   }
555 
556   return parser.parseRParen();
557 }
558 
559 /// Parses a Launch operation.
560 /// operation ::= `gpu.launch` (`async` `[` ssa-id-list `]`)?
561 //        `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
562 ///       `threads` `(` ssa-id-list `)` `in` ssa-reassignment
563 ///       region attr-dict?
564 /// ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
565 ParseResult LaunchOp::parse(OpAsmParser &parser, OperationState &result) {
566   // Sizes of the grid and block.
567   SmallVector<OpAsmParser::UnresolvedOperand, LaunchOp::kNumConfigOperands>
568       sizes(LaunchOp::kNumConfigOperands);
569   MutableArrayRef<OpAsmParser::UnresolvedOperand> sizesRef(sizes);
570 
571   // Actual (data) operands passed to the kernel.
572   SmallVector<OpAsmParser::UnresolvedOperand, 4> dataOperands;
573 
574   // Region arguments to be created.
575   SmallVector<OpAsmParser::UnresolvedOperand, 16> regionArgs(
576       LaunchOp::kNumConfigRegionAttributes);
577   MutableArrayRef<OpAsmParser::UnresolvedOperand> regionArgsRef(regionArgs);
578 
579   // Parse optional async dependencies.
580   SmallVector<OpAsmParser::UnresolvedOperand, 4> asyncDependencies;
581   Type asyncTokenType;
582   if (failed(
583           parseAsyncDependencies(parser, asyncTokenType, asyncDependencies)) ||
584       parser.resolveOperands(asyncDependencies, asyncTokenType,
585                              result.operands))
586     return failure();
587   if (parser.getNumResults() > 0)
588     result.types.push_back(asyncTokenType);
589 
590   // Parse the size assignment segments: the first segment assigns grid sizes
591   // and defines values for block identifiers; the second segment assigns block
592   // sizes and defines values for thread identifiers.  In the region argument
593   // list, identifiers precede sizes, and block-related values precede
594   // thread-related values.
595   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
596       parseSizeAssignment(parser, sizesRef.take_front(3),
597                           regionArgsRef.slice(6, 3),
598                           regionArgsRef.slice(0, 3)) ||
599       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
600       parseSizeAssignment(parser, sizesRef.drop_front(3),
601                           regionArgsRef.slice(9, 3),
602                           regionArgsRef.slice(3, 3)) ||
603       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
604                              result.operands))
605     return failure();
606 
607   OpAsmParser::UnresolvedOperand dynamicSharedMemorySize;
608   bool hasDynamicSharedMemorySize = false;
609   if (!parser.parseOptionalKeyword(
610           LaunchOp::getDynamicSharedMemorySizeKeyword())) {
611     hasDynamicSharedMemorySize = true;
612     if (parser.parseOperand(dynamicSharedMemorySize) ||
613         parser.resolveOperand(dynamicSharedMemorySize,
614                               parser.getBuilder().getI32Type(),
615                               result.operands))
616       return failure();
617   }
618 
619   // Introduce the body region and parse it. The region has
620   // kNumConfigRegionAttributes arguments that correspond to
621   // block/thread identifiers and grid/block sizes, all of the `index` type.
622   Type index = parser.getBuilder().getIndexType();
623   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
624       LaunchOp::kNumConfigRegionAttributes, index);
625   Region *body = result.addRegion();
626   if (parser.parseRegion(*body, regionArgs, dataTypes) ||
627       parser.parseOptionalAttrDict(result.attributes))
628     return failure();
629 
630   SmallVector<int32_t, 8> segmentSizes(8, 1);
631   segmentSizes.front() = asyncDependencies.size();
632   segmentSizes.back() = hasDynamicSharedMemorySize ? 1 : 0;
633   result.addAttribute(LaunchOp::getOperandSegmentSizeAttr(),
634                       parser.getBuilder().getI32VectorAttr(segmentSizes));
635   return success();
636 }
637 
638 /// Simplify the gpu.launch when the range of a thread or block ID is
639 /// trivially known to be one.
640 struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> {
641   using OpRewritePattern<LaunchOp>::OpRewritePattern;
642   LogicalResult matchAndRewrite(LaunchOp op,
643                                 PatternRewriter &rewriter) const override {
644     // If the range implies a single value for `id`, replace `id`'s uses by
645     // zero.
646     Value zero;
647     bool simplified = false;
648     auto constPropIdUses = [&](Value id, Value size) {
649       // Check if size is trivially one.
650       if (!matchPattern(size, m_One()))
651         return;
652       if (!simplified) {
653         // Create a zero value the first time.
654         OpBuilder::InsertionGuard guard(rewriter);
655         rewriter.setInsertionPointToStart(&op.body().front());
656         zero =
657             rewriter.create<arith::ConstantIndexOp>(op.getLoc(), /*value=*/0);
658       }
659       id.replaceAllUsesWith(zero);
660       simplified = true;
661     };
662     constPropIdUses(op.getBlockIds().x, op.gridSizeX());
663     constPropIdUses(op.getBlockIds().y, op.gridSizeY());
664     constPropIdUses(op.getBlockIds().z, op.gridSizeZ());
665     constPropIdUses(op.getThreadIds().x, op.blockSizeX());
666     constPropIdUses(op.getThreadIds().y, op.blockSizeY());
667     constPropIdUses(op.getThreadIds().z, op.blockSizeZ());
668 
669     return success(simplified);
670   }
671 };
672 
673 void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites,
674                                            MLIRContext *context) {
675   rewrites.add<FoldLaunchArguments>(context);
676 }
677 
678 //===----------------------------------------------------------------------===//
679 // LaunchFuncOp
680 //===----------------------------------------------------------------------===//
681 
682 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
683                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
684                          KernelDim3 blockSize, Value dynamicSharedMemorySize,
685                          ValueRange kernelOperands, Type asyncTokenType,
686                          ValueRange asyncDependencies) {
687   result.addOperands(asyncDependencies);
688   if (asyncTokenType)
689     result.types.push_back(builder.getType<AsyncTokenType>());
690 
691   // Add grid and block sizes as op operands, followed by the data operands.
692   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
693                       blockSize.y, blockSize.z});
694   if (dynamicSharedMemorySize)
695     result.addOperands(dynamicSharedMemorySize);
696   result.addOperands(kernelOperands);
697   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
698   auto kernelSymbol =
699       SymbolRefAttr::get(kernelModule.getNameAttr(),
700                          {SymbolRefAttr::get(kernelFunc.getNameAttr())});
701   result.addAttribute(getKernelAttrName(), kernelSymbol);
702   SmallVector<int32_t, 9> segmentSizes(9, 1);
703   segmentSizes.front() = asyncDependencies.size();
704   segmentSizes[segmentSizes.size() - 2] = dynamicSharedMemorySize ? 1 : 0;
705   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
706   result.addAttribute(getOperandSegmentSizeAttr(),
707                       builder.getI32VectorAttr(segmentSizes));
708 }
709 
710 unsigned LaunchFuncOp::getNumKernelOperands() {
711   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands -
712          (dynamicSharedMemorySize() ? 1 : 0);
713 }
714 
715 StringAttr LaunchFuncOp::getKernelModuleName() {
716   return kernel().getRootReference();
717 }
718 
719 StringAttr LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
720 
721 Value LaunchFuncOp::getKernelOperand(unsigned i) {
722   return getOperand(asyncDependencies().size() + kNumConfigOperands +
723                     (dynamicSharedMemorySize() ? 1 : 0) + i);
724 }
725 
726 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
727   auto operands = getOperands().drop_front(asyncDependencies().size());
728   return KernelDim3{operands[0], operands[1], operands[2]};
729 }
730 
731 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
732   auto operands = getOperands().drop_front(asyncDependencies().size());
733   return KernelDim3{operands[3], operands[4], operands[5]};
734 }
735 
736 LogicalResult LaunchFuncOp::verify() {
737   auto module = (*this)->getParentOfType<ModuleOp>();
738   if (!module)
739     return emitOpError("expected to belong to a module");
740 
741   if (!module->getAttrOfType<UnitAttr>(
742           GPUDialect::getContainerModuleAttrName()))
743     return emitOpError("expected the closest surrounding module to have the '" +
744                        GPUDialect::getContainerModuleAttrName() +
745                        "' attribute");
746 
747   auto kernelAttr = (*this)->getAttrOfType<SymbolRefAttr>(getKernelAttrName());
748   if (!kernelAttr)
749     return emitOpError("symbol reference attribute '" + getKernelAttrName() +
750                        "' must be specified");
751 
752   return success();
753 }
754 
755 static ParseResult parseLaunchFuncOperands(
756     OpAsmParser &parser,
757     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &argNames,
758     SmallVectorImpl<Type> &argTypes) {
759   if (parser.parseOptionalKeyword("args"))
760     return success();
761   SmallVector<NamedAttrList> argAttrs;
762   bool isVariadic = false;
763   return function_interface_impl::parseFunctionArgumentList(
764       parser, /*allowAttributes=*/false,
765       /*allowVariadic=*/false, argNames, argTypes, argAttrs, isVariadic);
766 }
767 
768 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
769                                     OperandRange operands, TypeRange types) {
770   if (operands.empty())
771     return;
772   printer << "args(";
773   llvm::interleaveComma(llvm::zip(operands, types), printer,
774                         [&](const auto &pair) {
775                           printer.printOperand(std::get<0>(pair));
776                           printer << " : ";
777                           printer.printType(std::get<1>(pair));
778                         });
779   printer << ")";
780 }
781 
782 //
783 
784 //===----------------------------------------------------------------------===//
785 // ShuffleOp
786 //===----------------------------------------------------------------------===//
787 
788 void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value value,
789                       int32_t offset, int32_t width, ShuffleMode mode) {
790   build(builder, result, value,
791         builder.create<arith::ConstantOp>(result.location,
792                                           builder.getI32IntegerAttr(offset)),
793         builder.create<arith::ConstantOp>(result.location,
794                                           builder.getI32IntegerAttr(width)),
795         mode);
796 }
797 
798 //===----------------------------------------------------------------------===//
799 // GPUFuncOp
800 //===----------------------------------------------------------------------===//
801 
802 /// Adds a new block argument that corresponds to buffers located in
803 /// workgroup memory.
804 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type, Location loc) {
805   auto attrName = getNumWorkgroupAttributionsAttrName();
806   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
807   (*this)->setAttr(attrName,
808                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
809   return getBody().insertArgument(
810       getFunctionType().getNumInputs() + attr.getInt(), type, loc);
811 }
812 
813 /// Adds a new block argument that corresponds to buffers located in
814 /// private memory.
815 BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) {
816   // Buffers on the private memory always come after buffers on the workgroup
817   // memory.
818   return getBody().addArgument(type, loc);
819 }
820 
821 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
822                       StringRef name, FunctionType type,
823                       TypeRange workgroupAttributions,
824                       TypeRange privateAttributions,
825                       ArrayRef<NamedAttribute> attrs) {
826   result.addAttribute(SymbolTable::getSymbolAttrName(),
827                       builder.getStringAttr(name));
828   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
829   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
830                       builder.getI64IntegerAttr(workgroupAttributions.size()));
831   result.addAttributes(attrs);
832   Region *body = result.addRegion();
833   Block *entryBlock = new Block;
834 
835   // TODO: Allow passing in proper locations here.
836   for (Type argTy : type.getInputs())
837     entryBlock->addArgument(argTy, result.location);
838   for (Type argTy : workgroupAttributions)
839     entryBlock->addArgument(argTy, result.location);
840   for (Type argTy : privateAttributions)
841     entryBlock->addArgument(argTy, result.location);
842 
843   body->getBlocks().push_back(entryBlock);
844 }
845 
846 /// Parses a GPU function memory attribution.
847 ///
848 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
849 ///                        (`private` `(` ssa-id-and-type-list `)`)?
850 ///
851 /// Note that this function parses only one of the two similar parts, with the
852 /// keyword provided as argument.
853 static ParseResult
854 parseAttributions(OpAsmParser &parser, StringRef keyword,
855                   SmallVectorImpl<OpAsmParser::UnresolvedOperand> &args,
856                   SmallVectorImpl<Type> &argTypes) {
857   // If we could not parse the keyword, just assume empty list and succeed.
858   if (failed(parser.parseOptionalKeyword(keyword)))
859     return success();
860 
861   if (failed(parser.parseLParen()))
862     return failure();
863 
864   // Early exit for an empty list.
865   if (succeeded(parser.parseOptionalRParen()))
866     return success();
867 
868   do {
869     OpAsmParser::UnresolvedOperand arg;
870     Type type;
871 
872     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
873       return failure();
874 
875     args.push_back(arg);
876     argTypes.push_back(type);
877   } while (succeeded(parser.parseOptionalComma()));
878 
879   return parser.parseRParen();
880 }
881 
882 /// Parses a GPU function.
883 ///
884 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
885 ///                 (`->` function-result-list)? memory-attribution `kernel`?
886 ///                 function-attributes? region
887 ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) {
888   SmallVector<OpAsmParser::UnresolvedOperand> entryArgs;
889   SmallVector<NamedAttrList> argAttrs;
890   SmallVector<NamedAttrList> resultAttrs;
891   SmallVector<Type> argTypes;
892   SmallVector<Type> resultTypes;
893   bool isVariadic;
894 
895   // Parse the function name.
896   StringAttr nameAttr;
897   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
898                              result.attributes))
899     return failure();
900 
901   auto signatureLocation = parser.getCurrentLocation();
902   if (failed(function_interface_impl::parseFunctionSignature(
903           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
904           isVariadic, resultTypes, resultAttrs)))
905     return failure();
906 
907   if (entryArgs.empty() && !argTypes.empty())
908     return parser.emitError(signatureLocation)
909            << "gpu.func requires named arguments";
910 
911   // Construct the function type. More types will be added to the region, but
912   // not to the function type.
913   Builder &builder = parser.getBuilder();
914   auto type = builder.getFunctionType(argTypes, resultTypes);
915   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
916 
917   // Parse workgroup memory attributions.
918   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
919                                entryArgs, argTypes)))
920     return failure();
921 
922   // Store the number of operands we just parsed as the number of workgroup
923   // memory attributions.
924   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
925   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
926                       builder.getI64IntegerAttr(numWorkgroupAttrs));
927 
928   // Parse private memory attributions.
929   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
930                                entryArgs, argTypes)))
931     return failure();
932 
933   // Parse the kernel attribute if present.
934   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
935     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
936                         builder.getUnitAttr());
937 
938   // Parse attributes.
939   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
940     return failure();
941   function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs,
942                                                 resultAttrs);
943 
944   // Parse the region. If no argument names were provided, take all names
945   // (including those of attributions) from the entry block.
946   auto *body = result.addRegion();
947   return parser.parseRegion(*body, entryArgs, argTypes);
948 }
949 
950 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
951                               ArrayRef<BlockArgument> values) {
952   if (values.empty())
953     return;
954 
955   p << ' ' << keyword << '(';
956   llvm::interleaveComma(
957       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
958   p << ')';
959 }
960 
961 void GPUFuncOp::print(OpAsmPrinter &p) {
962   p << ' ';
963   p.printSymbolName(getName());
964 
965   FunctionType type = getFunctionType();
966   function_interface_impl::printFunctionSignature(p, *this, type.getInputs(),
967                                                   /*isVariadic=*/false,
968                                                   type.getResults());
969 
970   printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributions());
971   printAttributions(p, getPrivateKeyword(), getPrivateAttributions());
972   if (isKernel())
973     p << ' ' << getKernelKeyword();
974 
975   function_interface_impl::printFunctionAttributes(
976       p, *this, type.getNumInputs(), type.getNumResults(),
977       {getNumWorkgroupAttributionsAttrName(),
978        GPUDialect::getKernelFuncAttrName()});
979   p << ' ';
980   p.printRegion(getBody(), /*printEntryBlockArgs=*/false);
981 }
982 
983 LogicalResult GPUFuncOp::verifyType() {
984   Type type = getFunctionTypeAttr().getValue();
985   if (!type.isa<FunctionType>())
986     return emitOpError("requires '" + getTypeAttrName() +
987                        "' attribute of function type");
988 
989   if (isKernel() && getFunctionType().getNumResults() != 0)
990     return emitOpError() << "expected void return type for kernel function";
991 
992   return success();
993 }
994 
995 static LogicalResult verifyAttributions(Operation *op,
996                                         ArrayRef<BlockArgument> attributions,
997                                         unsigned memorySpace) {
998   for (Value v : attributions) {
999     auto type = v.getType().dyn_cast<MemRefType>();
1000     if (!type)
1001       return op->emitOpError() << "expected memref type in attribution";
1002 
1003     if (type.getMemorySpaceAsInt() != memorySpace) {
1004       return op->emitOpError()
1005              << "expected memory space " << memorySpace << " in attribution";
1006     }
1007   }
1008   return success();
1009 }
1010 
1011 /// Verifies the body of the function.
1012 LogicalResult GPUFuncOp::verifyBody() {
1013   unsigned numFuncArguments = getNumArguments();
1014   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
1015   unsigned numBlockArguments = front().getNumArguments();
1016   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
1017     return emitOpError() << "expected at least "
1018                          << numFuncArguments + numWorkgroupAttributions
1019                          << " arguments to body region";
1020 
1021   ArrayRef<Type> funcArgTypes = getFunctionType().getInputs();
1022   for (unsigned i = 0; i < numFuncArguments; ++i) {
1023     Type blockArgType = front().getArgument(i).getType();
1024     if (funcArgTypes[i] != blockArgType)
1025       return emitOpError() << "expected body region argument #" << i
1026                            << " to be of type " << funcArgTypes[i] << ", got "
1027                            << blockArgType;
1028   }
1029 
1030   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
1031                                 GPUDialect::getWorkgroupAddressSpace())) ||
1032       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
1033                                 GPUDialect::getPrivateAddressSpace())))
1034     return failure();
1035 
1036   return success();
1037 }
1038 
1039 //===----------------------------------------------------------------------===//
1040 // ReturnOp
1041 //===----------------------------------------------------------------------===//
1042 
1043 LogicalResult gpu::ReturnOp::verify() {
1044   GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>();
1045 
1046   FunctionType funType = function.getFunctionType();
1047 
1048   if (funType.getNumResults() != operands().size())
1049     return emitOpError()
1050         .append("expected ", funType.getNumResults(), " result operands")
1051         .attachNote(function.getLoc())
1052         .append("return type declared here");
1053 
1054   for (const auto &pair : llvm::enumerate(
1055            llvm::zip(function.getFunctionType().getResults(), operands()))) {
1056     Type type;
1057     Value operand;
1058     std::tie(type, operand) = pair.value();
1059     if (type != operand.getType())
1060       return emitOpError() << "unexpected type `" << operand.getType()
1061                            << "' for operand #" << pair.index();
1062   }
1063   return success();
1064 }
1065 
1066 //===----------------------------------------------------------------------===//
1067 // GPUModuleOp
1068 //===----------------------------------------------------------------------===//
1069 
1070 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
1071                         StringRef name) {
1072   ensureTerminator(*result.addRegion(), builder, result.location);
1073   result.attributes.push_back(builder.getNamedAttr(
1074       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
1075 }
1076 
1077 ParseResult GPUModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1078   StringAttr nameAttr;
1079   if (parser.parseSymbolName(nameAttr, mlir::SymbolTable::getSymbolAttrName(),
1080                              result.attributes))
1081     return failure();
1082 
1083   // If module attributes are present, parse them.
1084   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1085     return failure();
1086 
1087   // Parse the module body.
1088   auto *body = result.addRegion();
1089   if (parser.parseRegion(*body, None, None))
1090     return failure();
1091 
1092   // Ensure that this module has a valid terminator.
1093   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1094   return success();
1095 }
1096 
1097 void GPUModuleOp::print(OpAsmPrinter &p) {
1098   p << ' ';
1099   p.printSymbolName(getName());
1100   p.printOptionalAttrDictWithKeyword((*this)->getAttrs(),
1101                                      {mlir::SymbolTable::getSymbolAttrName()});
1102   p << ' ';
1103   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
1104                 /*printBlockTerminators=*/false);
1105 }
1106 
1107 //===----------------------------------------------------------------------===//
1108 // GPUMemcpyOp
1109 //===----------------------------------------------------------------------===//
1110 
1111 LogicalResult MemcpyOp::verify() {
1112   auto srcType = src().getType();
1113   auto dstType = dst().getType();
1114 
1115   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
1116     return emitOpError("arguments have incompatible element type");
1117 
1118   if (failed(verifyCompatibleShape(srcType, dstType)))
1119     return emitOpError("arguments have incompatible shape");
1120 
1121   return success();
1122 }
1123 
1124 //===----------------------------------------------------------------------===//
1125 // GPU_SubgroupMmaLoadMatrixOp
1126 //===----------------------------------------------------------------------===//
1127 
1128 /// Return true if the last dimension of the MemRefType has unit stride. Also
1129 /// return true for memrefs with no strides.
1130 static bool isLastMemrefDimUnitStride(MemRefType type) {
1131   int64_t offset;
1132   SmallVector<int64_t> strides;
1133   if (failed(getStridesAndOffset(type, strides, offset))) {
1134     return false;
1135   }
1136   return strides.back() == 1;
1137 }
1138 
1139 LogicalResult SubgroupMmaLoadMatrixOp::verify() {
1140   auto srcType = srcMemref().getType();
1141   auto resType = res().getType();
1142   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
1143   auto operand = resMatrixType.getOperand();
1144   auto srcMemrefType = srcType.cast<MemRefType>();
1145   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
1146 
1147   if (!isLastMemrefDimUnitStride(srcMemrefType))
1148     return emitError(
1149         "expected source memref most minor dim must have unit stride");
1150 
1151   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1152       srcMemSpace != kGlobalMemorySpace)
1153     return emitError(
1154         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1155         "kGlobalMemorySpace only allowed");
1156 
1157   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1158       !operand.equals("COp"))
1159     return emitError("only AOp, BOp and COp can be loaded");
1160 
1161   return success();
1162 }
1163 
1164 //===----------------------------------------------------------------------===//
1165 // GPU_SubgroupMmaStoreMatrixOp
1166 //===----------------------------------------------------------------------===//
1167 
1168 LogicalResult SubgroupMmaStoreMatrixOp::verify() {
1169   auto srcType = src().getType();
1170   auto dstType = dstMemref().getType();
1171   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1172   auto dstMemrefType = dstType.cast<MemRefType>();
1173   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1174 
1175   if (!isLastMemrefDimUnitStride(dstMemrefType))
1176     return emitError(
1177         "expected destination memref most minor dim must have unit stride");
1178 
1179   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1180       dstMemSpace != kGlobalMemorySpace)
1181     return emitError("destination memorySpace of kGenericMemorySpace, "
1182                      "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1183 
1184   if (!srcMatrixType.getOperand().equals("COp"))
1185     return emitError(
1186         "expected the operand matrix being stored to have 'COp' operand type");
1187 
1188   return success();
1189 }
1190 
1191 //===----------------------------------------------------------------------===//
1192 // GPU_SubgroupMmaComputeOp
1193 //===----------------------------------------------------------------------===//
1194 
1195 LogicalResult SubgroupMmaComputeOp::verify() {
1196   enum OperandMap { A, B, C };
1197   SmallVector<MMAMatrixType, 3> opTypes;
1198   opTypes.push_back(opA().getType().cast<MMAMatrixType>());
1199   opTypes.push_back(opB().getType().cast<MMAMatrixType>());
1200   opTypes.push_back(opC().getType().cast<MMAMatrixType>());
1201 
1202   if (!opTypes[A].getOperand().equals("AOp") ||
1203       !opTypes[B].getOperand().equals("BOp") ||
1204       !opTypes[C].getOperand().equals("COp"))
1205     return emitError("operands must be in the order AOp, BOp, COp");
1206 
1207   ArrayRef<int64_t> aShape, bShape, cShape;
1208   aShape = opTypes[A].getShape();
1209   bShape = opTypes[B].getShape();
1210   cShape = opTypes[C].getShape();
1211 
1212   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1213       bShape[1] != cShape[1])
1214     return emitError("operand shapes do not satisfy matmul constraints");
1215 
1216   return success();
1217 }
1218 
1219 /// This is a common class used for patterns of the form
1220 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1221 /// into the root operation directly.
1222 static LogicalResult foldMemRefCast(Operation *op) {
1223   bool folded = false;
1224   for (OpOperand &operand : op->getOpOperands()) {
1225     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1226     if (cast) {
1227       operand.set(cast.getOperand());
1228       folded = true;
1229     }
1230   }
1231   return success(folded);
1232 }
1233 
1234 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1235                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1236   return foldMemRefCast(*this);
1237 }
1238 
1239 LogicalResult MemsetOp::fold(ArrayRef<Attribute> operands,
1240                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1241   return foldMemRefCast(*this);
1242 }
1243 
1244 //===----------------------------------------------------------------------===//
1245 // GPU_WaitOp
1246 //===----------------------------------------------------------------------===//
1247 
1248 namespace {
1249 
1250 /// Remove gpu.wait op use of gpu.wait op def without async dependencies.
1251 /// %t = gpu.wait async []       // No async dependencies.
1252 /// ...  gpu.wait ... [%t, ...]  // %t can be removed.
1253 struct EraseRedundantGpuWaitOpPairs : public OpRewritePattern<WaitOp> {
1254 public:
1255   using OpRewritePattern::OpRewritePattern;
1256 
1257   LogicalResult matchAndRewrite(WaitOp op,
1258                                 PatternRewriter &rewriter) const final {
1259     auto predicate = [](Value value) {
1260       auto waitOp = value.getDefiningOp<WaitOp>();
1261       return waitOp && waitOp->getNumOperands() == 0;
1262     };
1263     if (llvm::none_of(op.asyncDependencies(), predicate))
1264       return failure();
1265     SmallVector<Value> validOperands;
1266     for (Value operand : op->getOperands()) {
1267       if (predicate(operand))
1268         continue;
1269       validOperands.push_back(operand);
1270     }
1271     op->setOperands(validOperands);
1272     return success();
1273   }
1274 };
1275 
1276 /// Simplify trivial gpu.wait ops for the following patterns.
1277 /// 1. %t = gpu.wait async ... ops, where %t has no uses (regardless of async
1278 /// dependencies).
1279 /// 2. %t1 = gpu.wait async [%t0], in this case, we can replace uses of %t1 with
1280 /// %t0.
1281 /// 3. gpu.wait [] ops, i.e gpu.wait ops that neither have any async
1282 /// dependencies nor return any token.
1283 struct SimplifyGpuWaitOp : public OpRewritePattern<WaitOp> {
1284 public:
1285   using OpRewritePattern::OpRewritePattern;
1286 
1287   LogicalResult matchAndRewrite(WaitOp op,
1288                                 PatternRewriter &rewriter) const final {
1289     // Erase gpu.wait ops that neither have any async dependencies nor return
1290     // any async token.
1291     if (op.asyncDependencies().empty() && !op.asyncToken()) {
1292       rewriter.eraseOp(op);
1293       return success();
1294     }
1295     // Replace uses of %t1 = gpu.wait async [%t0] ops with %t0 and erase the op.
1296     if (llvm::hasSingleElement(op.asyncDependencies()) && op.asyncToken()) {
1297       rewriter.replaceOp(op, op.asyncDependencies());
1298       return success();
1299     }
1300     // Erase %t = gpu.wait async ... ops, where %t has no uses.
1301     if (op.asyncToken() && op.asyncToken().use_empty()) {
1302       rewriter.eraseOp(op);
1303       return success();
1304     }
1305     return failure();
1306   }
1307 };
1308 
1309 } // end anonymous namespace
1310 
1311 void WaitOp::getCanonicalizationPatterns(RewritePatternSet &results,
1312                                          MLIRContext *context) {
1313   results.add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(context);
1314 }
1315 
1316 //===----------------------------------------------------------------------===//
1317 // GPU_AllocOp
1318 //===----------------------------------------------------------------------===//
1319 
1320 LogicalResult AllocOp::verify() {
1321   auto memRefType = memref().getType().cast<MemRefType>();
1322 
1323   if (static_cast<int64_t>(dynamicSizes().size()) !=
1324       memRefType.getNumDynamicDims())
1325     return emitOpError("dimension operand count does not equal memref "
1326                        "dynamic dimension count");
1327 
1328   unsigned numSymbols = 0;
1329   if (!memRefType.getLayout().isIdentity())
1330     numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols();
1331   if (symbolOperands().size() != numSymbols) {
1332     return emitOpError(
1333         "symbol operand count does not equal memref symbol count");
1334   }
1335 
1336   return success();
1337 }
1338 
1339 namespace {
1340 
1341 /// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to
1342 /// `memref::AllocOp`.
1343 struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> {
1344   using OpRewritePattern<memref::DimOp>::OpRewritePattern;
1345 
1346   LogicalResult matchAndRewrite(memref::DimOp dimOp,
1347                                 PatternRewriter &rewriter) const override {
1348     auto index = dimOp.index().getDefiningOp<arith::ConstantIndexOp>();
1349     if (!index)
1350       return failure();
1351 
1352     auto memrefType = dimOp.source().getType().dyn_cast<MemRefType>();
1353     if (!memrefType || !memrefType.isDynamicDim(index.value()))
1354       return failure();
1355 
1356     auto alloc = dimOp.source().getDefiningOp<AllocOp>();
1357     if (!alloc)
1358       return failure();
1359 
1360     Value substituteOp = *(alloc.dynamicSizes().begin() +
1361                            memrefType.getDynamicDimIndex(index.value()));
1362     rewriter.replaceOp(dimOp, substituteOp);
1363     return success();
1364   }
1365 };
1366 
1367 } // namespace
1368 
1369 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results,
1370                                           MLIRContext *context) {
1371   results.add<SimplifyDimOfAllocOp>(context);
1372 }
1373 
1374 //===----------------------------------------------------------------------===//
1375 // GPU_DeviceAsyncCopyOp
1376 //===----------------------------------------------------------------------===//
1377 
1378 LogicalResult DeviceAsyncCopyOp::verify() {
1379   auto srcMemref = src().getType().cast<MemRefType>();
1380   auto dstMemref = dst().getType().cast<MemRefType>();
1381   unsigned workgroupAddressSpace = GPUDialect::getWorkgroupAddressSpace();
1382   if (!isLastMemrefDimUnitStride(srcMemref))
1383     return emitError("source memref most minor dim must have unit stride");
1384   if (!isLastMemrefDimUnitStride(dstMemref))
1385     return emitError("destination memref most minor dim must have unit stride");
1386   if (dstMemref.getMemorySpaceAsInt() != workgroupAddressSpace)
1387     return emitError("destination memref must have memory space ")
1388            << workgroupAddressSpace;
1389   if (dstMemref.getElementType() != srcMemref.getElementType())
1390     return emitError("source and destination must have the same element type");
1391   if (size_t(srcMemref.getRank()) != srcIndices().size())
1392     return emitOpError() << "expected " << srcMemref.getRank()
1393                          << " source indices, got " << srcIndices().size();
1394   if (size_t(dstMemref.getRank()) != dstIndices().size())
1395     return emitOpError() << "expected " << dstMemref.getRank()
1396                          << " destination indices, got " << dstIndices().size();
1397   return success();
1398 }
1399 
1400 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1401 #include "mlir/Dialect/GPU/GPUOpsEnums.cpp.inc"
1402 
1403 #define GET_ATTRDEF_CLASSES
1404 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
1405 
1406 #define GET_OP_CLASSES
1407 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1408