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