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.parseOperandList(args, OpAsmParser::Delimiter::Paren,
543                               /*allowResultNumber=*/false) ||
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.parseOperand(regionSizes[i], /*allowResultNumber=*/false) ||
552         parser.parseEqual() || 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 
626   SmallVector<OpAsmParser::Argument> regionArguments;
627   for (auto ssaValueAndType : llvm::zip(regionArgs, dataTypes)) {
628     OpAsmParser::Argument arg;
629     arg.ssaName = std::get<0>(ssaValueAndType);
630     arg.type = std::get<1>(ssaValueAndType);
631     regionArguments.push_back(arg);
632   }
633 
634   Region *body = result.addRegion();
635   if (parser.parseRegion(*body, regionArguments) ||
636       parser.parseOptionalAttrDict(result.attributes))
637     return failure();
638 
639   SmallVector<int32_t, 8> segmentSizes(8, 1);
640   segmentSizes.front() = asyncDependencies.size();
641   segmentSizes.back() = hasDynamicSharedMemorySize ? 1 : 0;
642   result.addAttribute(LaunchOp::getOperandSegmentSizeAttr(),
643                       parser.getBuilder().getI32VectorAttr(segmentSizes));
644   return success();
645 }
646 
647 /// Simplify the gpu.launch when the range of a thread or block ID is
648 /// trivially known to be one.
649 struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> {
650   using OpRewritePattern<LaunchOp>::OpRewritePattern;
651   LogicalResult matchAndRewrite(LaunchOp op,
652                                 PatternRewriter &rewriter) const override {
653     // If the range implies a single value for `id`, replace `id`'s uses by
654     // zero.
655     Value zero;
656     bool simplified = false;
657     auto constPropIdUses = [&](Value id, Value size) {
658       // Check if size is trivially one.
659       if (!matchPattern(size, m_One()))
660         return;
661       if (!simplified) {
662         // Create a zero value the first time.
663         OpBuilder::InsertionGuard guard(rewriter);
664         rewriter.setInsertionPointToStart(&op.body().front());
665         zero =
666             rewriter.create<arith::ConstantIndexOp>(op.getLoc(), /*value=*/0);
667       }
668       id.replaceAllUsesWith(zero);
669       simplified = true;
670     };
671     constPropIdUses(op.getBlockIds().x, op.gridSizeX());
672     constPropIdUses(op.getBlockIds().y, op.gridSizeY());
673     constPropIdUses(op.getBlockIds().z, op.gridSizeZ());
674     constPropIdUses(op.getThreadIds().x, op.blockSizeX());
675     constPropIdUses(op.getThreadIds().y, op.blockSizeY());
676     constPropIdUses(op.getThreadIds().z, op.blockSizeZ());
677 
678     return success(simplified);
679   }
680 };
681 
682 void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites,
683                                            MLIRContext *context) {
684   rewrites.add<FoldLaunchArguments>(context);
685 }
686 
687 //===----------------------------------------------------------------------===//
688 // LaunchFuncOp
689 //===----------------------------------------------------------------------===//
690 
691 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
692                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
693                          KernelDim3 blockSize, Value dynamicSharedMemorySize,
694                          ValueRange kernelOperands, Type asyncTokenType,
695                          ValueRange asyncDependencies) {
696   result.addOperands(asyncDependencies);
697   if (asyncTokenType)
698     result.types.push_back(builder.getType<AsyncTokenType>());
699 
700   // Add grid and block sizes as op operands, followed by the data operands.
701   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
702                       blockSize.y, blockSize.z});
703   if (dynamicSharedMemorySize)
704     result.addOperands(dynamicSharedMemorySize);
705   result.addOperands(kernelOperands);
706   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
707   auto kernelSymbol =
708       SymbolRefAttr::get(kernelModule.getNameAttr(),
709                          {SymbolRefAttr::get(kernelFunc.getNameAttr())});
710   result.addAttribute(getKernelAttrName(), kernelSymbol);
711   SmallVector<int32_t, 9> segmentSizes(9, 1);
712   segmentSizes.front() = asyncDependencies.size();
713   segmentSizes[segmentSizes.size() - 2] = dynamicSharedMemorySize ? 1 : 0;
714   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
715   result.addAttribute(getOperandSegmentSizeAttr(),
716                       builder.getI32VectorAttr(segmentSizes));
717 }
718 
719 unsigned LaunchFuncOp::getNumKernelOperands() {
720   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands -
721          (dynamicSharedMemorySize() ? 1 : 0);
722 }
723 
724 StringAttr LaunchFuncOp::getKernelModuleName() {
725   return kernel().getRootReference();
726 }
727 
728 StringAttr LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
729 
730 Value LaunchFuncOp::getKernelOperand(unsigned i) {
731   return getOperand(asyncDependencies().size() + kNumConfigOperands +
732                     (dynamicSharedMemorySize() ? 1 : 0) + i);
733 }
734 
735 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
736   auto operands = getOperands().drop_front(asyncDependencies().size());
737   return KernelDim3{operands[0], operands[1], operands[2]};
738 }
739 
740 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
741   auto operands = getOperands().drop_front(asyncDependencies().size());
742   return KernelDim3{operands[3], operands[4], operands[5]};
743 }
744 
745 LogicalResult LaunchFuncOp::verify() {
746   auto module = (*this)->getParentOfType<ModuleOp>();
747   if (!module)
748     return emitOpError("expected to belong to a module");
749 
750   if (!module->getAttrOfType<UnitAttr>(
751           GPUDialect::getContainerModuleAttrName()))
752     return emitOpError("expected the closest surrounding module to have the '" +
753                        GPUDialect::getContainerModuleAttrName() +
754                        "' attribute");
755 
756   auto kernelAttr = (*this)->getAttrOfType<SymbolRefAttr>(getKernelAttrName());
757   if (!kernelAttr)
758     return emitOpError("symbol reference attribute '" + getKernelAttrName() +
759                        "' must be specified");
760 
761   return success();
762 }
763 
764 static ParseResult parseLaunchFuncOperands(
765     OpAsmParser &parser,
766     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &argNames,
767     SmallVectorImpl<Type> &argTypes) {
768   if (parser.parseOptionalKeyword("args"))
769     return success();
770 
771   SmallVector<OpAsmParser::Argument> args;
772   if (parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
773                                /*allowType=*/true))
774     return failure();
775   for (auto &arg : args) {
776     argNames.push_back(arg.ssaName);
777     argTypes.push_back(arg.type);
778   }
779   return success();
780 }
781 
782 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
783                                     OperandRange operands, TypeRange types) {
784   if (operands.empty())
785     return;
786   printer << "args(";
787   llvm::interleaveComma(llvm::zip(operands, types), printer,
788                         [&](const auto &pair) {
789                           printer.printOperand(std::get<0>(pair));
790                           printer << " : ";
791                           printer.printType(std::get<1>(pair));
792                         });
793   printer << ")";
794 }
795 
796 //===----------------------------------------------------------------------===//
797 // ShuffleOp
798 //===----------------------------------------------------------------------===//
799 
800 void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value value,
801                       int32_t offset, int32_t width, ShuffleMode mode) {
802   build(builder, result, value,
803         builder.create<arith::ConstantOp>(result.location,
804                                           builder.getI32IntegerAttr(offset)),
805         builder.create<arith::ConstantOp>(result.location,
806                                           builder.getI32IntegerAttr(width)),
807         mode);
808 }
809 
810 //===----------------------------------------------------------------------===//
811 // GPUFuncOp
812 //===----------------------------------------------------------------------===//
813 
814 /// Adds a new block argument that corresponds to buffers located in
815 /// workgroup memory.
816 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type, Location loc) {
817   auto attrName = getNumWorkgroupAttributionsAttrName();
818   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
819   (*this)->setAttr(attrName,
820                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
821   return getBody().insertArgument(
822       getFunctionType().getNumInputs() + attr.getInt(), type, loc);
823 }
824 
825 /// Adds a new block argument that corresponds to buffers located in
826 /// private memory.
827 BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) {
828   // Buffers on the private memory always come after buffers on the workgroup
829   // memory.
830   return getBody().addArgument(type, loc);
831 }
832 
833 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
834                       StringRef name, FunctionType type,
835                       TypeRange workgroupAttributions,
836                       TypeRange privateAttributions,
837                       ArrayRef<NamedAttribute> attrs) {
838   result.addAttribute(SymbolTable::getSymbolAttrName(),
839                       builder.getStringAttr(name));
840   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
841   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
842                       builder.getI64IntegerAttr(workgroupAttributions.size()));
843   result.addAttributes(attrs);
844   Region *body = result.addRegion();
845   Block *entryBlock = new Block;
846 
847   // TODO: Allow passing in proper locations here.
848   for (Type argTy : type.getInputs())
849     entryBlock->addArgument(argTy, result.location);
850   for (Type argTy : workgroupAttributions)
851     entryBlock->addArgument(argTy, result.location);
852   for (Type argTy : privateAttributions)
853     entryBlock->addArgument(argTy, result.location);
854 
855   body->getBlocks().push_back(entryBlock);
856 }
857 
858 /// Parses a GPU function memory attribution.
859 ///
860 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
861 ///                        (`private` `(` ssa-id-and-type-list `)`)?
862 ///
863 /// Note that this function parses only one of the two similar parts, with the
864 /// keyword provided as argument.
865 static ParseResult
866 parseAttributions(OpAsmParser &parser, StringRef keyword,
867                   SmallVectorImpl<OpAsmParser::Argument> &args) {
868   // If we could not parse the keyword, just assume empty list and succeed.
869   if (failed(parser.parseOptionalKeyword(keyword)))
870     return success();
871 
872   return parser.parseArgumentList(args, OpAsmParser::Delimiter::Paren,
873                                   /*allowType=*/true);
874 }
875 
876 /// Parses a GPU function.
877 ///
878 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
879 ///                 (`->` function-result-list)? memory-attribution `kernel`?
880 ///                 function-attributes? region
881 ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) {
882   SmallVector<OpAsmParser::Argument> entryArgs;
883   SmallVector<DictionaryAttr> resultAttrs;
884   SmallVector<Type> resultTypes;
885   bool isVariadic;
886 
887   // Parse the function name.
888   StringAttr nameAttr;
889   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
890                              result.attributes))
891     return failure();
892 
893   auto signatureLocation = parser.getCurrentLocation();
894   if (failed(function_interface_impl::parseFunctionSignature(
895           parser, /*allowVariadic=*/false, entryArgs, isVariadic, resultTypes,
896           resultAttrs)))
897     return failure();
898 
899   if (!entryArgs.empty() && entryArgs[0].ssaName.name.empty())
900     return parser.emitError(signatureLocation)
901            << "gpu.func requires named arguments";
902 
903   // Construct the function type. More types will be added to the region, but
904   // not to the function type.
905   Builder &builder = parser.getBuilder();
906 
907   SmallVector<Type> argTypes;
908   for (auto &arg : entryArgs)
909     argTypes.push_back(arg.type);
910   auto type = builder.getFunctionType(argTypes, resultTypes);
911   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
912 
913   function_interface_impl::addArgAndResultAttrs(builder, result, entryArgs,
914                                                 resultAttrs);
915 
916   // Parse workgroup memory attributions.
917   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
918                                entryArgs)))
919     return failure();
920 
921   // Store the number of operands we just parsed as the number of workgroup
922   // memory attributions.
923   unsigned numWorkgroupAttrs = entryArgs.size() - type.getNumInputs();
924   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
925                       builder.getI64IntegerAttr(numWorkgroupAttrs));
926 
927   // Parse private memory attributions.
928   if (failed(
929           parseAttributions(parser, GPUFuncOp::getPrivateKeyword(), entryArgs)))
930     return failure();
931 
932   // Parse the kernel attribute if present.
933   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
934     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
935                         builder.getUnitAttr());
936 
937   // Parse attributes.
938   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
939     return failure();
940 
941   // Parse the region. If no argument names were provided, take all names
942   // (including those of attributions) from the entry block.
943   auto *body = result.addRegion();
944   return parser.parseRegion(*body, entryArgs);
945 }
946 
947 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
948                               ArrayRef<BlockArgument> values) {
949   if (values.empty())
950     return;
951 
952   p << ' ' << keyword << '(';
953   llvm::interleaveComma(
954       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
955   p << ')';
956 }
957 
958 void GPUFuncOp::print(OpAsmPrinter &p) {
959   p << ' ';
960   p.printSymbolName(getName());
961 
962   FunctionType type = getFunctionType();
963   function_interface_impl::printFunctionSignature(p, *this, type.getInputs(),
964                                                   /*isVariadic=*/false,
965                                                   type.getResults());
966 
967   printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributions());
968   printAttributions(p, getPrivateKeyword(), getPrivateAttributions());
969   if (isKernel())
970     p << ' ' << getKernelKeyword();
971 
972   function_interface_impl::printFunctionAttributes(
973       p, *this, type.getNumInputs(), type.getNumResults(),
974       {getNumWorkgroupAttributionsAttrName(),
975        GPUDialect::getKernelFuncAttrName()});
976   p << ' ';
977   p.printRegion(getBody(), /*printEntryBlockArgs=*/false);
978 }
979 
980 LogicalResult GPUFuncOp::verifyType() {
981   Type type = getFunctionTypeAttr().getValue();
982   if (!type.isa<FunctionType>())
983     return emitOpError("requires '" + getTypeAttrName() +
984                        "' attribute of function type");
985 
986   if (isKernel() && getFunctionType().getNumResults() != 0)
987     return emitOpError() << "expected void return type for kernel function";
988 
989   return success();
990 }
991 
992 static LogicalResult verifyAttributions(Operation *op,
993                                         ArrayRef<BlockArgument> attributions,
994                                         unsigned memorySpace) {
995   for (Value v : attributions) {
996     auto type = v.getType().dyn_cast<MemRefType>();
997     if (!type)
998       return op->emitOpError() << "expected memref type in attribution";
999 
1000     if (type.getMemorySpaceAsInt() != memorySpace) {
1001       return op->emitOpError()
1002              << "expected memory space " << memorySpace << " in attribution";
1003     }
1004   }
1005   return success();
1006 }
1007 
1008 /// Verifies the body of the function.
1009 LogicalResult GPUFuncOp::verifyBody() {
1010   unsigned numFuncArguments = getNumArguments();
1011   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
1012   unsigned numBlockArguments = front().getNumArguments();
1013   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
1014     return emitOpError() << "expected at least "
1015                          << numFuncArguments + numWorkgroupAttributions
1016                          << " arguments to body region";
1017 
1018   ArrayRef<Type> funcArgTypes = getFunctionType().getInputs();
1019   for (unsigned i = 0; i < numFuncArguments; ++i) {
1020     Type blockArgType = front().getArgument(i).getType();
1021     if (funcArgTypes[i] != blockArgType)
1022       return emitOpError() << "expected body region argument #" << i
1023                            << " to be of type " << funcArgTypes[i] << ", got "
1024                            << blockArgType;
1025   }
1026 
1027   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
1028                                 GPUDialect::getWorkgroupAddressSpace())) ||
1029       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
1030                                 GPUDialect::getPrivateAddressSpace())))
1031     return failure();
1032 
1033   return success();
1034 }
1035 
1036 //===----------------------------------------------------------------------===//
1037 // ReturnOp
1038 //===----------------------------------------------------------------------===//
1039 
1040 LogicalResult gpu::ReturnOp::verify() {
1041   GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>();
1042 
1043   FunctionType funType = function.getFunctionType();
1044 
1045   if (funType.getNumResults() != operands().size())
1046     return emitOpError()
1047         .append("expected ", funType.getNumResults(), " result operands")
1048         .attachNote(function.getLoc())
1049         .append("return type declared here");
1050 
1051   for (const auto &pair : llvm::enumerate(
1052            llvm::zip(function.getFunctionType().getResults(), operands()))) {
1053     Type type;
1054     Value operand;
1055     std::tie(type, operand) = pair.value();
1056     if (type != operand.getType())
1057       return emitOpError() << "unexpected type `" << operand.getType()
1058                            << "' for operand #" << pair.index();
1059   }
1060   return success();
1061 }
1062 
1063 //===----------------------------------------------------------------------===//
1064 // GPUModuleOp
1065 //===----------------------------------------------------------------------===//
1066 
1067 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
1068                         StringRef name) {
1069   ensureTerminator(*result.addRegion(), builder, result.location);
1070   result.attributes.push_back(builder.getNamedAttr(
1071       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
1072 }
1073 
1074 ParseResult GPUModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1075   StringAttr nameAttr;
1076   if (parser.parseSymbolName(nameAttr, mlir::SymbolTable::getSymbolAttrName(),
1077                              result.attributes) ||
1078       // If module attributes are present, parse them.
1079       parser.parseOptionalAttrDictWithKeyword(result.attributes))
1080     return failure();
1081 
1082   // Parse the module body.
1083   auto *body = result.addRegion();
1084   if (parser.parseRegion(*body, {}))
1085     return failure();
1086 
1087   // Ensure that this module has a valid terminator.
1088   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1089   return success();
1090 }
1091 
1092 void GPUModuleOp::print(OpAsmPrinter &p) {
1093   p << ' ';
1094   p.printSymbolName(getName());
1095   p.printOptionalAttrDictWithKeyword((*this)->getAttrs(),
1096                                      {mlir::SymbolTable::getSymbolAttrName()});
1097   p << ' ';
1098   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
1099                 /*printBlockTerminators=*/false);
1100 }
1101 
1102 //===----------------------------------------------------------------------===//
1103 // GPUMemcpyOp
1104 //===----------------------------------------------------------------------===//
1105 
1106 LogicalResult MemcpyOp::verify() {
1107   auto srcType = src().getType();
1108   auto dstType = dst().getType();
1109 
1110   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
1111     return emitOpError("arguments have incompatible element type");
1112 
1113   if (failed(verifyCompatibleShape(srcType, dstType)))
1114     return emitOpError("arguments have incompatible shape");
1115 
1116   return success();
1117 }
1118 
1119 //===----------------------------------------------------------------------===//
1120 // GPU_SubgroupMmaLoadMatrixOp
1121 //===----------------------------------------------------------------------===//
1122 
1123 /// Return true if the last dimension of the MemRefType has unit stride. Also
1124 /// return true for memrefs with no strides.
1125 static bool isLastMemrefDimUnitStride(MemRefType type) {
1126   int64_t offset;
1127   SmallVector<int64_t> strides;
1128   if (failed(getStridesAndOffset(type, strides, offset))) {
1129     return false;
1130   }
1131   return strides.back() == 1;
1132 }
1133 
1134 LogicalResult SubgroupMmaLoadMatrixOp::verify() {
1135   auto srcType = srcMemref().getType();
1136   auto resType = res().getType();
1137   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
1138   auto operand = resMatrixType.getOperand();
1139   auto srcMemrefType = srcType.cast<MemRefType>();
1140   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
1141 
1142   if (!isLastMemrefDimUnitStride(srcMemrefType))
1143     return emitError(
1144         "expected source memref most minor dim must have unit stride");
1145 
1146   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1147       srcMemSpace != kGlobalMemorySpace)
1148     return emitError(
1149         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1150         "kGlobalMemorySpace only allowed");
1151 
1152   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1153       !operand.equals("COp"))
1154     return emitError("only AOp, BOp and COp can be loaded");
1155 
1156   return success();
1157 }
1158 
1159 //===----------------------------------------------------------------------===//
1160 // GPU_SubgroupMmaStoreMatrixOp
1161 //===----------------------------------------------------------------------===//
1162 
1163 LogicalResult SubgroupMmaStoreMatrixOp::verify() {
1164   auto srcType = src().getType();
1165   auto dstType = dstMemref().getType();
1166   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1167   auto dstMemrefType = dstType.cast<MemRefType>();
1168   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1169 
1170   if (!isLastMemrefDimUnitStride(dstMemrefType))
1171     return emitError(
1172         "expected destination memref most minor dim must have unit stride");
1173 
1174   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1175       dstMemSpace != kGlobalMemorySpace)
1176     return emitError("destination memorySpace of kGenericMemorySpace, "
1177                      "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1178 
1179   if (!srcMatrixType.getOperand().equals("COp"))
1180     return emitError(
1181         "expected the operand matrix being stored to have 'COp' operand type");
1182 
1183   return success();
1184 }
1185 
1186 //===----------------------------------------------------------------------===//
1187 // GPU_SubgroupMmaComputeOp
1188 //===----------------------------------------------------------------------===//
1189 
1190 LogicalResult SubgroupMmaComputeOp::verify() {
1191   enum OperandMap { A, B, C };
1192   SmallVector<MMAMatrixType, 3> opTypes;
1193   opTypes.push_back(opA().getType().cast<MMAMatrixType>());
1194   opTypes.push_back(opB().getType().cast<MMAMatrixType>());
1195   opTypes.push_back(opC().getType().cast<MMAMatrixType>());
1196 
1197   if (!opTypes[A].getOperand().equals("AOp") ||
1198       !opTypes[B].getOperand().equals("BOp") ||
1199       !opTypes[C].getOperand().equals("COp"))
1200     return emitError("operands must be in the order AOp, BOp, COp");
1201 
1202   ArrayRef<int64_t> aShape, bShape, cShape;
1203   aShape = opTypes[A].getShape();
1204   bShape = opTypes[B].getShape();
1205   cShape = opTypes[C].getShape();
1206 
1207   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1208       bShape[1] != cShape[1])
1209     return emitError("operand shapes do not satisfy matmul constraints");
1210 
1211   return success();
1212 }
1213 
1214 /// This is a common class used for patterns of the form
1215 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1216 /// into the root operation directly.
1217 static LogicalResult foldMemRefCast(Operation *op) {
1218   bool folded = false;
1219   for (OpOperand &operand : op->getOpOperands()) {
1220     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1221     if (cast) {
1222       operand.set(cast.getOperand());
1223       folded = true;
1224     }
1225   }
1226   return success(folded);
1227 }
1228 
1229 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1230                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1231   return foldMemRefCast(*this);
1232 }
1233 
1234 LogicalResult MemsetOp::fold(ArrayRef<Attribute> operands,
1235                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1236   return foldMemRefCast(*this);
1237 }
1238 
1239 //===----------------------------------------------------------------------===//
1240 // GPU_WaitOp
1241 //===----------------------------------------------------------------------===//
1242 
1243 namespace {
1244 
1245 /// Remove gpu.wait op use of gpu.wait op def without async dependencies.
1246 /// %t = gpu.wait async []       // No async dependencies.
1247 /// ...  gpu.wait ... [%t, ...]  // %t can be removed.
1248 struct EraseRedundantGpuWaitOpPairs : public OpRewritePattern<WaitOp> {
1249 public:
1250   using OpRewritePattern::OpRewritePattern;
1251 
1252   LogicalResult matchAndRewrite(WaitOp op,
1253                                 PatternRewriter &rewriter) const final {
1254     auto predicate = [](Value value) {
1255       auto waitOp = value.getDefiningOp<WaitOp>();
1256       return waitOp && waitOp->getNumOperands() == 0;
1257     };
1258     if (llvm::none_of(op.asyncDependencies(), predicate))
1259       return failure();
1260     SmallVector<Value> validOperands;
1261     for (Value operand : op->getOperands()) {
1262       if (predicate(operand))
1263         continue;
1264       validOperands.push_back(operand);
1265     }
1266     op->setOperands(validOperands);
1267     return success();
1268   }
1269 };
1270 
1271 /// Simplify trivial gpu.wait ops for the following patterns.
1272 /// 1. %t = gpu.wait async ... ops, where %t has no uses (regardless of async
1273 /// dependencies).
1274 /// 2. %t1 = gpu.wait async [%t0], in this case, we can replace uses of %t1 with
1275 /// %t0.
1276 /// 3. gpu.wait [] ops, i.e gpu.wait ops that neither have any async
1277 /// dependencies nor return any token.
1278 struct SimplifyGpuWaitOp : public OpRewritePattern<WaitOp> {
1279 public:
1280   using OpRewritePattern::OpRewritePattern;
1281 
1282   LogicalResult matchAndRewrite(WaitOp op,
1283                                 PatternRewriter &rewriter) const final {
1284     // Erase gpu.wait ops that neither have any async dependencies nor return
1285     // any async token.
1286     if (op.asyncDependencies().empty() && !op.asyncToken()) {
1287       rewriter.eraseOp(op);
1288       return success();
1289     }
1290     // Replace uses of %t1 = gpu.wait async [%t0] ops with %t0 and erase the op.
1291     if (llvm::hasSingleElement(op.asyncDependencies()) && op.asyncToken()) {
1292       rewriter.replaceOp(op, op.asyncDependencies());
1293       return success();
1294     }
1295     // Erase %t = gpu.wait async ... ops, where %t has no uses.
1296     if (op.asyncToken() && op.asyncToken().use_empty()) {
1297       rewriter.eraseOp(op);
1298       return success();
1299     }
1300     return failure();
1301   }
1302 };
1303 
1304 } // end anonymous namespace
1305 
1306 void WaitOp::getCanonicalizationPatterns(RewritePatternSet &results,
1307                                          MLIRContext *context) {
1308   results.add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(context);
1309 }
1310 
1311 //===----------------------------------------------------------------------===//
1312 // GPU_AllocOp
1313 //===----------------------------------------------------------------------===//
1314 
1315 LogicalResult AllocOp::verify() {
1316   auto memRefType = memref().getType().cast<MemRefType>();
1317 
1318   if (static_cast<int64_t>(dynamicSizes().size()) !=
1319       memRefType.getNumDynamicDims())
1320     return emitOpError("dimension operand count does not equal memref "
1321                        "dynamic dimension count");
1322 
1323   unsigned numSymbols = 0;
1324   if (!memRefType.getLayout().isIdentity())
1325     numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols();
1326   if (symbolOperands().size() != numSymbols) {
1327     return emitOpError(
1328         "symbol operand count does not equal memref symbol count");
1329   }
1330 
1331   return success();
1332 }
1333 
1334 namespace {
1335 
1336 /// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to
1337 /// `memref::AllocOp`.
1338 struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> {
1339   using OpRewritePattern<memref::DimOp>::OpRewritePattern;
1340 
1341   LogicalResult matchAndRewrite(memref::DimOp dimOp,
1342                                 PatternRewriter &rewriter) const override {
1343     auto index = dimOp.index().getDefiningOp<arith::ConstantIndexOp>();
1344     if (!index)
1345       return failure();
1346 
1347     auto memrefType = dimOp.source().getType().dyn_cast<MemRefType>();
1348     if (!memrefType || !memrefType.isDynamicDim(index.value()))
1349       return failure();
1350 
1351     auto alloc = dimOp.source().getDefiningOp<AllocOp>();
1352     if (!alloc)
1353       return failure();
1354 
1355     Value substituteOp = *(alloc.dynamicSizes().begin() +
1356                            memrefType.getDynamicDimIndex(index.value()));
1357     rewriter.replaceOp(dimOp, substituteOp);
1358     return success();
1359   }
1360 };
1361 
1362 } // namespace
1363 
1364 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results,
1365                                           MLIRContext *context) {
1366   results.add<SimplifyDimOfAllocOp>(context);
1367 }
1368 
1369 //===----------------------------------------------------------------------===//
1370 // GPU_DeviceAsyncCopyOp
1371 //===----------------------------------------------------------------------===//
1372 
1373 LogicalResult DeviceAsyncCopyOp::verify() {
1374   auto srcMemref = src().getType().cast<MemRefType>();
1375   auto dstMemref = dst().getType().cast<MemRefType>();
1376   unsigned workgroupAddressSpace = GPUDialect::getWorkgroupAddressSpace();
1377   if (!isLastMemrefDimUnitStride(srcMemref))
1378     return emitError("source memref most minor dim must have unit stride");
1379   if (!isLastMemrefDimUnitStride(dstMemref))
1380     return emitError("destination memref most minor dim must have unit stride");
1381   if (dstMemref.getMemorySpaceAsInt() != workgroupAddressSpace)
1382     return emitError("destination memref must have memory space ")
1383            << workgroupAddressSpace;
1384   if (dstMemref.getElementType() != srcMemref.getElementType())
1385     return emitError("source and destination must have the same element type");
1386   if (size_t(srcMemref.getRank()) != srcIndices().size())
1387     return emitOpError() << "expected " << srcMemref.getRank()
1388                          << " source indices, got " << srcIndices().size();
1389   if (size_t(dstMemref.getRank()) != dstIndices().size())
1390     return emitOpError() << "expected " << dstMemref.getRank()
1391                          << " destination indices, got " << dstIndices().size();
1392   return success();
1393 }
1394 
1395 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1396 #include "mlir/Dialect/GPU/GPUOpsEnums.cpp.inc"
1397 
1398 #define GET_ATTRDEF_CLASSES
1399 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
1400 
1401 #define GET_OP_CLASSES
1402 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1403