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/LLVMIR/LLVMDialect.h"
16 #include "mlir/Dialect/MemRef/IR/MemRef.h"
17 #include "mlir/Dialect/StandardOps/IR/Ops.h"
18 #include "mlir/IR/Attributes.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/BuiltinOps.h"
21 #include "mlir/IR/BuiltinTypes.h"
22 #include "mlir/IR/DialectImplementation.h"
23 #include "mlir/IR/FunctionImplementation.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/IR/PatternMatch.h"
26 #include "mlir/IR/TypeUtilities.h"
27 #include "llvm/ADT/TypeSwitch.h"
28 
29 using namespace mlir;
30 using namespace mlir::gpu;
31 
32 //===----------------------------------------------------------------------===//
33 // MMAMatrixType
34 //===----------------------------------------------------------------------===//
35 
36 MMAMatrixType MMAMatrixType::get(ArrayRef<int64_t> shape, Type elementType,
37                                  StringRef operand) {
38   return Base::get(elementType.getContext(), shape, elementType, operand);
39 }
40 
41 MMAMatrixType
42 MMAMatrixType::getChecked(function_ref<InFlightDiagnostic()> emitError,
43                           ArrayRef<int64_t> shape, Type elementType,
44                           StringRef operand) {
45   return Base::getChecked(emitError, elementType.getContext(), shape,
46                           elementType, operand);
47 }
48 
49 unsigned MMAMatrixType::getNumDims() const { return getImpl()->numDims; }
50 
51 ArrayRef<int64_t> MMAMatrixType::getShape() const {
52   return getImpl()->getShape();
53 }
54 
55 Type MMAMatrixType::getElementType() const { return getImpl()->elementType; }
56 
57 StringRef MMAMatrixType::getOperand() const { return getImpl()->getOperand(); }
58 
59 bool MMAMatrixType::isValidElementType(Type elementType) {
60   return elementType.isF16() || elementType.isF32();
61 }
62 
63 LogicalResult
64 MMAMatrixType::verify(function_ref<InFlightDiagnostic()> emitError,
65                       ArrayRef<int64_t> shape, Type elementType,
66                       StringRef operand) {
67   if (!operand.equals("AOp") && !operand.equals("BOp") &&
68       !operand.equals("COp"))
69     return emitError() << "operand expected to be one of AOp, BOp or COp";
70 
71   if (shape.size() != 2)
72     return emitError() << "MMAMatrixType must have exactly two dimensions";
73 
74   if (!MMAMatrixType::isValidElementType(elementType))
75     return emitError() << "MMAMatrixType elements must be F16 or F32";
76 
77   return success();
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // GPUDialect
82 //===----------------------------------------------------------------------===//
83 
84 /// GPU memory space identifiers.
85 enum GPUMemorySpace {
86   /// Generic memory space identifier.
87   kGenericMemorySpace = 0,
88 
89   /// Global memory space identifier.
90   kGlobalMemorySpace = 1,
91 
92   /// Shared memory space identifier.
93   kSharedMemorySpace = 3
94 };
95 
96 bool GPUDialect::isKernel(Operation *op) {
97   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
98   return static_cast<bool>(isKernelAttr);
99 }
100 
101 void GPUDialect::initialize() {
102   addTypes<AsyncTokenType>();
103   addTypes<MMAMatrixType>();
104   addOperations<
105 #define GET_OP_LIST
106 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
107       >();
108 }
109 
110 Type GPUDialect::parseType(DialectAsmParser &parser) const {
111   // Parse the main keyword for the type.
112   StringRef keyword;
113   if (parser.parseKeyword(&keyword))
114     return Type();
115   MLIRContext *context = getContext();
116 
117   // Handle 'async token' types.
118   if (keyword == "async.token")
119     return AsyncTokenType::get(context);
120 
121   if (keyword == "mma_matrix") {
122     llvm::SMLoc beginLoc = parser.getNameLoc();
123 
124     // Parse '<'.
125     if (parser.parseLess())
126       return nullptr;
127 
128     // Parse the size and elementType.
129     SmallVector<int64_t> shape;
130     Type elementType;
131     if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
132         parser.parseType(elementType))
133       return nullptr;
134 
135     // Parse ','
136     if (parser.parseComma())
137       return nullptr;
138 
139     // Parse operand.
140     StringRef operand;
141     if (failed(parser.parseOptionalString(&operand)))
142       return nullptr;
143 
144     // Parse '>'.
145     if (parser.parseGreater())
146       return nullptr;
147 
148     return MMAMatrixType::getChecked(mlir::detail::getDefaultDiagnosticEmitFn(
149                                          parser.getEncodedSourceLoc(beginLoc)),
150                                      shape, elementType, operand);
151   }
152 
153   parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
154   return Type();
155 }
156 
157 void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
158   TypeSwitch<Type>(type)
159       .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
160       .Case<MMAMatrixType>([&](MMAMatrixType fragTy) {
161         os << "mma_matrix<";
162         auto shape = fragTy.getShape();
163         for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
164           os << *dim << 'x';
165         os << shape.back() << 'x' << fragTy.getElementType();
166         os << ", \"" << fragTy.getOperand() << "\"" << '>';
167       })
168       .Default([](Type) { llvm_unreachable("unexpected 'gpu' type kind"); });
169 }
170 
171 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
172                                                    NamedAttribute attr) {
173   if (!attr.second.isa<UnitAttr>() ||
174       attr.first != getContainerModuleAttrName())
175     return success();
176 
177   auto module = dyn_cast<ModuleOp>(op);
178   if (!module)
179     return op->emitError("expected '")
180            << getContainerModuleAttrName() << "' attribute to be attached to '"
181            << ModuleOp::getOperationName() << '\'';
182 
183   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
184     // Ignore launches that are nested more or less deep than functions in the
185     // module we are currently checking.
186     if (!launchOp->getParentOp() ||
187         launchOp->getParentOp()->getParentOp() != module)
188       return success();
189 
190     // Ignore launch ops with missing attributes here. The errors will be
191     // reported by the verifiers of those ops.
192     if (!launchOp->getAttrOfType<SymbolRefAttr>(
193             LaunchFuncOp::getKernelAttrName()))
194       return success();
195 
196     // Check that `launch_func` refers to a well-formed GPU kernel module.
197     StringRef kernelModuleName = launchOp.getKernelModuleName();
198     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
199     if (!kernelModule)
200       return launchOp.emitOpError()
201              << "kernel module '" << kernelModuleName << "' is undefined";
202 
203     // Check that `launch_func` refers to a well-formed kernel function.
204     Operation *kernelFunc = module.lookupSymbol(launchOp.kernel());
205     auto kernelGPUFunction = dyn_cast_or_null<gpu::GPUFuncOp>(kernelFunc);
206     auto kernelLLVMFunction = dyn_cast_or_null<LLVM::LLVMFuncOp>(kernelFunc);
207     if (!kernelGPUFunction && !kernelLLVMFunction)
208       return launchOp.emitOpError("kernel function '")
209              << launchOp.kernel() << "' is undefined";
210     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
211             GPUDialect::getKernelFuncAttrName()))
212       return launchOp.emitOpError("kernel function is missing the '")
213              << GPUDialect::getKernelFuncAttrName() << "' attribute";
214 
215     // TODO: if the kernel function has been converted to
216     // the LLVM dialect but the caller hasn't (which happens during the
217     // separate compilation), do not check type correspondence as it would
218     // require the verifier to be aware of the LLVM type conversion.
219     if (kernelLLVMFunction)
220       return success();
221 
222     unsigned actualNumArguments = launchOp.getNumKernelOperands();
223     unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
224     if (expectedNumArguments != actualNumArguments)
225       return launchOp.emitOpError("got ")
226              << actualNumArguments << " kernel operands but expected "
227              << expectedNumArguments;
228 
229     auto functionType = kernelGPUFunction.getType();
230     for (unsigned i = 0; i < expectedNumArguments; ++i) {
231       if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
232         return launchOp.emitOpError("type of function argument ")
233                << i << " does not match";
234       }
235     }
236 
237     return success();
238   });
239 
240   return walkResult.wasInterrupted() ? failure() : success();
241 }
242 
243 template <typename T>
244 static LogicalResult verifyIndexOp(T op) {
245   auto dimension = op.dimension();
246   if (dimension != "x" && dimension != "y" && dimension != "z")
247     return op.emitError("dimension \"") << dimension << "\" is invalid";
248   return success();
249 }
250 
251 static LogicalResult verifyAllReduce(gpu::AllReduceOp allReduce) {
252   if (allReduce.body().empty() != allReduce.op().hasValue())
253     return allReduce.emitError(
254         "expected either an op attribute or a non-empty body");
255   if (!allReduce.body().empty()) {
256     if (allReduce.body().getNumArguments() != 2)
257       return allReduce.emitError("expected two region arguments");
258     for (auto argument : allReduce.body().getArguments()) {
259       if (argument.getType() != allReduce.getType())
260         return allReduce.emitError("incorrect region argument type");
261     }
262     unsigned yieldCount = 0;
263     for (Block &block : allReduce.body()) {
264       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
265         if (yield.getNumOperands() != 1)
266           return allReduce.emitError("expected one gpu.yield operand");
267         if (yield.getOperand(0).getType() != allReduce.getType())
268           return allReduce.emitError("incorrect gpu.yield type");
269         ++yieldCount;
270       }
271     }
272     if (yieldCount == 0)
273       return allReduce.emitError("expected gpu.yield op in region");
274   } else {
275     StringRef opName = *allReduce.op();
276     if ((opName == "and" || opName == "or" || opName == "xor") &&
277         !allReduce.getType().isa<IntegerType>()) {
278       return allReduce.emitError()
279              << '`' << opName << '`'
280              << " accumulator is only compatible with Integer type";
281     }
282   }
283   return success();
284 }
285 
286 static LogicalResult verifyShuffleOp(gpu::ShuffleOp shuffleOp) {
287   auto type = shuffleOp.value().getType();
288   if (shuffleOp.result().getType() != type) {
289     return shuffleOp.emitOpError()
290            << "requires the same type for value operand and result";
291   }
292   if (!type.isSignlessIntOrFloat() || type.getIntOrFloatBitWidth() != 32) {
293     return shuffleOp.emitOpError()
294            << "requires value operand type to be f32 or i32";
295   }
296   return success();
297 }
298 
299 static void printShuffleOp(OpAsmPrinter &p, ShuffleOp op) {
300   p << ShuffleOp::getOperationName() << ' ' << op.getOperands() << ' '
301     << op.mode() << " : " << op.value().getType();
302 }
303 
304 static ParseResult parseShuffleOp(OpAsmParser &parser, OperationState &state) {
305   SmallVector<OpAsmParser::OperandType, 3> operandInfo;
306   if (parser.parseOperandList(operandInfo, 3))
307     return failure();
308 
309   StringRef mode;
310   if (parser.parseKeyword(&mode))
311     return failure();
312   state.addAttribute("mode", parser.getBuilder().getStringAttr(mode));
313 
314   Type valueType;
315   Type int32Type = parser.getBuilder().getIntegerType(32);
316   Type int1Type = parser.getBuilder().getI1Type();
317   if (parser.parseColonType(valueType) ||
318       parser.resolveOperands(operandInfo, {valueType, int32Type, int32Type},
319                              parser.getCurrentLocation(), state.operands) ||
320       parser.addTypesToList({valueType, int1Type}, state.types))
321     return failure();
322   return success();
323 }
324 
325 //===----------------------------------------------------------------------===//
326 // AsyncOpInterface
327 //===----------------------------------------------------------------------===//
328 
329 void gpu::addAsyncDependency(Operation *op, Value token) {
330   op->insertOperands(0, {token});
331   if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
332     return;
333   auto attrName =
334       OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr();
335   auto sizeAttr = op->template getAttrOfType<DenseIntElementsAttr>(attrName);
336   if (!sizeAttr)
337     return; // Async dependencies is the only variadic operand.
338   SmallVector<int32_t, 8> sizes;
339   for (auto size : sizeAttr.getIntValues())
340     sizes.push_back(size.getSExtValue());
341   ++sizes.front();
342   op->setAttr(attrName, Builder(op->getContext()).getI32VectorAttr(sizes));
343 }
344 
345 //===----------------------------------------------------------------------===//
346 // LaunchOp
347 //===----------------------------------------------------------------------===//
348 
349 void LaunchOp::build(OpBuilder &builder, OperationState &result,
350                      Value gridSizeX, Value gridSizeY, Value gridSizeZ,
351                      Value blockSizeX, Value blockSizeY, Value blockSizeZ) {
352   // Add grid and block sizes as op operands, followed by the data operands.
353   result.addOperands(
354       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
355 
356   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
357   // where the first kNumConfigRegionAttributes arguments have `index` type and
358   // the rest have the same types as the data operands.
359   Region *kernelRegion = result.addRegion();
360   Block *body = new Block();
361   body->addArguments(
362       std::vector<Type>(kNumConfigRegionAttributes, builder.getIndexType()));
363   kernelRegion->push_back(body);
364 }
365 
366 KernelDim3 LaunchOp::getBlockIds() {
367   assert(!body().empty() && "LaunchOp body must not be empty.");
368   auto args = body().getArguments();
369   return KernelDim3{args[0], args[1], args[2]};
370 }
371 
372 KernelDim3 LaunchOp::getThreadIds() {
373   assert(!body().empty() && "LaunchOp body must not be empty.");
374   auto args = body().getArguments();
375   return KernelDim3{args[3], args[4], args[5]};
376 }
377 
378 KernelDim3 LaunchOp::getGridSize() {
379   assert(!body().empty() && "LaunchOp body must not be empty.");
380   auto args = body().getArguments();
381   return KernelDim3{args[6], args[7], args[8]};
382 }
383 
384 KernelDim3 LaunchOp::getBlockSize() {
385   assert(!body().empty() && "LaunchOp body must not be empty.");
386   auto args = body().getArguments();
387   return KernelDim3{args[9], args[10], args[11]};
388 }
389 
390 KernelDim3 LaunchOp::getGridSizeOperandValues() {
391   return KernelDim3{getOperand(0), getOperand(1), getOperand(2)};
392 }
393 
394 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
395   return KernelDim3{getOperand(3), getOperand(4), getOperand(5)};
396 }
397 
398 static LogicalResult verify(LaunchOp op) {
399   // Kernel launch takes kNumConfigOperands leading operands for grid/block
400   // sizes and transforms them into kNumConfigRegionAttributes region arguments
401   // for block/thread identifiers and grid/block sizes.
402   if (!op.body().empty()) {
403     if (op.body().getNumArguments() !=
404         LaunchOp::kNumConfigOperands + op.getNumOperands())
405       return op.emitOpError("unexpected number of region arguments");
406   }
407 
408   // Block terminators without successors are expected to exit the kernel region
409   // and must be `gpu.terminator`.
410   for (Block &block : op.body()) {
411     if (block.empty())
412       continue;
413     if (block.back().getNumSuccessors() != 0)
414       continue;
415     if (!isa<gpu::TerminatorOp>(&block.back())) {
416       return block.back()
417           .emitError()
418           .append("expected '", gpu::TerminatorOp::getOperationName(),
419                   "' or a terminator with successors")
420           .attachNote(op.getLoc())
421           .append("in '", LaunchOp::getOperationName(), "' body region");
422     }
423   }
424 
425   return success();
426 }
427 
428 // Pretty-print the kernel grid/block size assignment as
429 //   (%iter-x, %iter-y, %iter-z) in
430 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
431 // where %size-* and %iter-* will correspond to the body region arguments.
432 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
433                                 KernelDim3 operands, KernelDim3 ids) {
434   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
435   p << size.x << " = " << operands.x << ", ";
436   p << size.y << " = " << operands.y << ", ";
437   p << size.z << " = " << operands.z << ')';
438 }
439 
440 static void printLaunchOp(OpAsmPrinter &p, LaunchOp op) {
441   // Print the launch configuration.
442   p << LaunchOp::getOperationName() << ' ' << op.getBlocksKeyword();
443   printSizeAssignment(p, op.getGridSize(), op.getGridSizeOperandValues(),
444                       op.getBlockIds());
445   p << ' ' << op.getThreadsKeyword();
446   printSizeAssignment(p, op.getBlockSize(), op.getBlockSizeOperandValues(),
447                       op.getThreadIds());
448 
449   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
450   p.printOptionalAttrDict(op->getAttrs());
451 }
452 
453 // Parse the size assignment blocks for blocks and threads.  These have the form
454 //   (%region_arg, %region_arg, %region_arg) in
455 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
456 // where %region_arg are percent-identifiers for the region arguments to be
457 // introduced further (SSA defs), and %operand are percent-identifiers for the
458 // SSA value uses.
459 static ParseResult
460 parseSizeAssignment(OpAsmParser &parser,
461                     MutableArrayRef<OpAsmParser::OperandType> sizes,
462                     MutableArrayRef<OpAsmParser::OperandType> regionSizes,
463                     MutableArrayRef<OpAsmParser::OperandType> indices) {
464   assert(indices.size() == 3 && "space for three indices expected");
465   SmallVector<OpAsmParser::OperandType, 3> args;
466   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
467                                      OpAsmParser::Delimiter::Paren) ||
468       parser.parseKeyword("in") || parser.parseLParen())
469     return failure();
470   std::move(args.begin(), args.end(), indices.begin());
471 
472   for (int i = 0; i < 3; ++i) {
473     if (i != 0 && parser.parseComma())
474       return failure();
475     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
476         parser.parseOperand(sizes[i]))
477       return failure();
478   }
479 
480   return parser.parseRParen();
481 }
482 
483 // Parses a Launch operation.
484 // operation ::= `gpu.launch` `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
485 //                           `threads` `(` ssa-id-list `)` `in` ssa-reassignment
486 //                            region attr-dict?
487 // ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
488 static ParseResult parseLaunchOp(OpAsmParser &parser, OperationState &result) {
489   // Sizes of the grid and block.
490   SmallVector<OpAsmParser::OperandType, LaunchOp::kNumConfigOperands> sizes(
491       LaunchOp::kNumConfigOperands);
492   MutableArrayRef<OpAsmParser::OperandType> sizesRef(sizes);
493 
494   // Actual (data) operands passed to the kernel.
495   SmallVector<OpAsmParser::OperandType, 4> dataOperands;
496 
497   // Region arguments to be created.
498   SmallVector<OpAsmParser::OperandType, 16> regionArgs(
499       LaunchOp::kNumConfigRegionAttributes);
500   MutableArrayRef<OpAsmParser::OperandType> regionArgsRef(regionArgs);
501 
502   // Parse the size assignment segments: the first segment assigns grid sizes
503   // and defines values for block identifiers; the second segment assigns block
504   // sizes and defines values for thread identifiers.  In the region argument
505   // list, identifiers precede sizes, and block-related values precede
506   // thread-related values.
507   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
508       parseSizeAssignment(parser, sizesRef.take_front(3),
509                           regionArgsRef.slice(6, 3),
510                           regionArgsRef.slice(0, 3)) ||
511       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
512       parseSizeAssignment(parser, sizesRef.drop_front(3),
513                           regionArgsRef.slice(9, 3),
514                           regionArgsRef.slice(3, 3)) ||
515       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
516                              result.operands))
517     return failure();
518 
519   // Introduce the body region and parse it. The region has
520   // kNumConfigRegionAttributes arguments that correspond to
521   // block/thread identifiers and grid/block sizes, all of the `index` type.
522   Type index = parser.getBuilder().getIndexType();
523   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
524       LaunchOp::kNumConfigRegionAttributes, index);
525   Region *body = result.addRegion();
526   return failure(parser.parseRegion(*body, regionArgs, dataTypes) ||
527                  parser.parseOptionalAttrDict(result.attributes));
528 }
529 
530 //===----------------------------------------------------------------------===//
531 // LaunchFuncOp
532 //===----------------------------------------------------------------------===//
533 
534 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
535                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
536                          KernelDim3 blockSize, ValueRange kernelOperands) {
537   // Add grid and block sizes as op operands, followed by the data operands.
538   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
539                       blockSize.y, blockSize.z});
540   result.addOperands(kernelOperands);
541   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
542   auto kernelSymbol = builder.getSymbolRefAttr(
543       kernelModule.getName(), {builder.getSymbolRefAttr(kernelFunc.getName())});
544   result.addAttribute(getKernelAttrName(), kernelSymbol);
545   SmallVector<int32_t, 8> segmentSizes(8, 1);
546   segmentSizes.front() = 0; // Initially no async dependencies.
547   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
548   result.addAttribute(getOperandSegmentSizeAttr(),
549                       builder.getI32VectorAttr(segmentSizes));
550 }
551 
552 unsigned LaunchFuncOp::getNumKernelOperands() {
553   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands;
554 }
555 
556 StringRef LaunchFuncOp::getKernelModuleName() {
557   return kernel().getRootReference();
558 }
559 
560 StringRef LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
561 
562 Value LaunchFuncOp::getKernelOperand(unsigned i) {
563   return getOperand(asyncDependencies().size() + kNumConfigOperands + i);
564 }
565 
566 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
567   auto operands = getOperands().drop_front(asyncDependencies().size());
568   return KernelDim3{operands[0], operands[1], operands[2]};
569 }
570 
571 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
572   auto operands = getOperands().drop_front(asyncDependencies().size());
573   return KernelDim3{operands[3], operands[4], operands[5]};
574 }
575 
576 static LogicalResult verify(LaunchFuncOp op) {
577   auto module = op->getParentOfType<ModuleOp>();
578   if (!module)
579     return op.emitOpError("expected to belong to a module");
580 
581   if (!module->getAttrOfType<UnitAttr>(
582           GPUDialect::getContainerModuleAttrName()))
583     return op.emitOpError(
584         "expected the closest surrounding module to have the '" +
585         GPUDialect::getContainerModuleAttrName() + "' attribute");
586 
587   auto kernelAttr = op->getAttrOfType<SymbolRefAttr>(op.getKernelAttrName());
588   if (!kernelAttr)
589     return op.emitOpError("symbol reference attribute '" +
590                           op.getKernelAttrName() + "' must be specified");
591 
592   return success();
593 }
594 
595 static ParseResult
596 parseLaunchFuncOperands(OpAsmParser &parser,
597                         SmallVectorImpl<OpAsmParser::OperandType> &argNames,
598                         SmallVectorImpl<Type> &argTypes) {
599   if (parser.parseOptionalKeyword("args"))
600     return success();
601   SmallVector<NamedAttrList, 4> argAttrs;
602   bool isVariadic = false;
603   return function_like_impl::parseFunctionArgumentList(
604       parser, /*allowAttributes=*/false,
605       /*allowVariadic=*/false, argNames, argTypes, argAttrs, isVariadic);
606 }
607 
608 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
609                                     OperandRange operands, TypeRange types) {
610   if (operands.empty())
611     return;
612   printer << "args(";
613   llvm::interleaveComma(llvm::zip(operands, types), printer,
614                         [&](const auto &pair) {
615                           printer.printOperand(std::get<0>(pair));
616                           printer << " : ";
617                           printer.printType(std::get<1>(pair));
618                         });
619   printer << ")";
620 }
621 
622 //===----------------------------------------------------------------------===//
623 // GPUFuncOp
624 //===----------------------------------------------------------------------===//
625 
626 /// Adds a new block argument that corresponds to buffers located in
627 /// workgroup memory.
628 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type) {
629   auto attrName = getNumWorkgroupAttributionsAttrName();
630   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
631   (*this)->setAttr(attrName,
632                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
633   return getBody().insertArgument(getType().getNumInputs() + attr.getInt(),
634                                   type);
635 }
636 
637 /// Adds a new block argument that corresponds to buffers located in
638 /// private memory.
639 BlockArgument GPUFuncOp::addPrivateAttribution(Type type) {
640   // Buffers on the private memory always come after buffers on the workgroup
641   // memory.
642   return getBody().addArgument(type);
643 }
644 
645 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
646                       StringRef name, FunctionType type,
647                       TypeRange workgroupAttributions,
648                       TypeRange privateAttributions,
649                       ArrayRef<NamedAttribute> attrs) {
650   result.addAttribute(SymbolTable::getSymbolAttrName(),
651                       builder.getStringAttr(name));
652   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
653   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
654                       builder.getI64IntegerAttr(workgroupAttributions.size()));
655   result.addAttributes(attrs);
656   Region *body = result.addRegion();
657   Block *entryBlock = new Block;
658   entryBlock->addArguments(type.getInputs());
659   entryBlock->addArguments(workgroupAttributions);
660   entryBlock->addArguments(privateAttributions);
661 
662   body->getBlocks().push_back(entryBlock);
663 }
664 
665 /// Parses a GPU function memory attribution.
666 ///
667 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
668 ///                        (`private` `(` ssa-id-and-type-list `)`)?
669 ///
670 /// Note that this function parses only one of the two similar parts, with the
671 /// keyword provided as argument.
672 static ParseResult
673 parseAttributions(OpAsmParser &parser, StringRef keyword,
674                   SmallVectorImpl<OpAsmParser::OperandType> &args,
675                   SmallVectorImpl<Type> &argTypes) {
676   // If we could not parse the keyword, just assume empty list and succeed.
677   if (failed(parser.parseOptionalKeyword(keyword)))
678     return success();
679 
680   if (failed(parser.parseLParen()))
681     return failure();
682 
683   // Early exit for an empty list.
684   if (succeeded(parser.parseOptionalRParen()))
685     return success();
686 
687   do {
688     OpAsmParser::OperandType arg;
689     Type type;
690 
691     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
692       return failure();
693 
694     args.push_back(arg);
695     argTypes.push_back(type);
696   } while (succeeded(parser.parseOptionalComma()));
697 
698   return parser.parseRParen();
699 }
700 
701 /// Parses a GPU function.
702 ///
703 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
704 ///                 (`->` function-result-list)? memory-attribution `kernel`?
705 ///                 function-attributes? region
706 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) {
707   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
708   SmallVector<NamedAttrList, 1> argAttrs;
709   SmallVector<NamedAttrList, 1> resultAttrs;
710   SmallVector<Type, 8> argTypes;
711   SmallVector<Type, 4> resultTypes;
712   bool isVariadic;
713 
714   // Parse the function name.
715   StringAttr nameAttr;
716   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
717                              result.attributes))
718     return failure();
719 
720   auto signatureLocation = parser.getCurrentLocation();
721   if (failed(function_like_impl::parseFunctionSignature(
722           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
723           isVariadic, resultTypes, resultAttrs)))
724     return failure();
725 
726   if (entryArgs.empty() && !argTypes.empty())
727     return parser.emitError(signatureLocation)
728            << "gpu.func requires named arguments";
729 
730   // Construct the function type. More types will be added to the region, but
731   // not to the function type.
732   Builder &builder = parser.getBuilder();
733   auto type = builder.getFunctionType(argTypes, resultTypes);
734   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
735 
736   // Parse workgroup memory attributions.
737   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
738                                entryArgs, argTypes)))
739     return failure();
740 
741   // Store the number of operands we just parsed as the number of workgroup
742   // memory attributions.
743   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
744   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
745                       builder.getI64IntegerAttr(numWorkgroupAttrs));
746 
747   // Parse private memory attributions.
748   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
749                                entryArgs, argTypes)))
750     return failure();
751 
752   // Parse the kernel attribute if present.
753   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
754     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
755                         builder.getUnitAttr());
756 
757   // Parse attributes.
758   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
759     return failure();
760   function_like_impl::addArgAndResultAttrs(builder, result, argAttrs,
761                                            resultAttrs);
762 
763   // Parse the region. If no argument names were provided, take all names
764   // (including those of attributions) from the entry block.
765   auto *body = result.addRegion();
766   return parser.parseRegion(*body, entryArgs, argTypes);
767 }
768 
769 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
770                               ArrayRef<BlockArgument> values) {
771   if (values.empty())
772     return;
773 
774   p << ' ' << keyword << '(';
775   llvm::interleaveComma(
776       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
777   p << ')';
778 }
779 
780 /// Prints a GPU Func op.
781 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
782   p << GPUFuncOp::getOperationName() << ' ';
783   p.printSymbolName(op.getName());
784 
785   FunctionType type = op.getType();
786   function_like_impl::printFunctionSignature(
787       p, op.getOperation(), type.getInputs(),
788       /*isVariadic=*/false, type.getResults());
789 
790   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
791   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
792   if (op.isKernel())
793     p << ' ' << op.getKernelKeyword();
794 
795   function_like_impl::printFunctionAttributes(
796       p, op.getOperation(), type.getNumInputs(), type.getNumResults(),
797       {op.getNumWorkgroupAttributionsAttrName(),
798        GPUDialect::getKernelFuncAttrName()});
799   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
800 }
801 
802 /// Hook for FunctionLike verifier.
803 LogicalResult GPUFuncOp::verifyType() {
804   Type type = getTypeAttr().getValue();
805   if (!type.isa<FunctionType>())
806     return emitOpError("requires '" + getTypeAttrName() +
807                        "' attribute of function type");
808 
809   if (isKernel() && getType().getNumResults() != 0)
810     return emitOpError() << "expected void return type for kernel function";
811 
812   return success();
813 }
814 
815 static LogicalResult verifyAttributions(Operation *op,
816                                         ArrayRef<BlockArgument> attributions,
817                                         unsigned memorySpace) {
818   for (Value v : attributions) {
819     auto type = v.getType().dyn_cast<MemRefType>();
820     if (!type)
821       return op->emitOpError() << "expected memref type in attribution";
822 
823     if (type.getMemorySpaceAsInt() != memorySpace) {
824       return op->emitOpError()
825              << "expected memory space " << memorySpace << " in attribution";
826     }
827   }
828   return success();
829 }
830 
831 /// Verifies the body of the function.
832 LogicalResult GPUFuncOp::verifyBody() {
833   unsigned numFuncArguments = getNumArguments();
834   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
835   unsigned numBlockArguments = front().getNumArguments();
836   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
837     return emitOpError() << "expected at least "
838                          << numFuncArguments + numWorkgroupAttributions
839                          << " arguments to body region";
840 
841   ArrayRef<Type> funcArgTypes = getType().getInputs();
842   for (unsigned i = 0; i < numFuncArguments; ++i) {
843     Type blockArgType = front().getArgument(i).getType();
844     if (funcArgTypes[i] != blockArgType)
845       return emitOpError() << "expected body region argument #" << i
846                            << " to be of type " << funcArgTypes[i] << ", got "
847                            << blockArgType;
848   }
849 
850   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
851                                 GPUDialect::getWorkgroupAddressSpace())) ||
852       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
853                                 GPUDialect::getPrivateAddressSpace())))
854     return failure();
855 
856   return success();
857 }
858 
859 //===----------------------------------------------------------------------===//
860 // ReturnOp
861 //===----------------------------------------------------------------------===//
862 
863 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
864   llvm::SmallVector<OpAsmParser::OperandType, 4> operands;
865   llvm::SmallVector<Type, 4> types;
866   if (parser.parseOperandList(operands) ||
867       parser.parseOptionalColonTypeList(types) ||
868       parser.resolveOperands(operands, types, parser.getCurrentLocation(),
869                              result.operands))
870     return failure();
871 
872   return success();
873 }
874 
875 static LogicalResult verify(gpu::ReturnOp returnOp) {
876   GPUFuncOp function = returnOp->getParentOfType<GPUFuncOp>();
877 
878   FunctionType funType = function.getType();
879 
880   if (funType.getNumResults() != returnOp.operands().size())
881     return returnOp.emitOpError()
882         .append("expected ", funType.getNumResults(), " result operands")
883         .attachNote(function.getLoc())
884         .append("return type declared here");
885 
886   for (auto pair : llvm::enumerate(
887            llvm::zip(function.getType().getResults(), returnOp.operands()))) {
888     Type type;
889     Value operand;
890     std::tie(type, operand) = pair.value();
891     if (type != operand.getType())
892       return returnOp.emitOpError() << "unexpected type `" << operand.getType()
893                                     << "' for operand #" << pair.index();
894   }
895   return success();
896 }
897 
898 //===----------------------------------------------------------------------===//
899 // GPUModuleOp
900 //===----------------------------------------------------------------------===//
901 
902 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
903                         StringRef name) {
904   ensureTerminator(*result.addRegion(), builder, result.location);
905   result.attributes.push_back(builder.getNamedAttr(
906       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
907 }
908 
909 static ParseResult parseGPUModuleOp(OpAsmParser &parser,
910                                     OperationState &result) {
911   StringAttr nameAttr;
912   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
913                              result.attributes))
914     return failure();
915 
916   // If module attributes are present, parse them.
917   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
918     return failure();
919 
920   // Parse the module body.
921   auto *body = result.addRegion();
922   if (parser.parseRegion(*body, None, None))
923     return failure();
924 
925   // Ensure that this module has a valid terminator.
926   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
927   return success();
928 }
929 
930 static void print(OpAsmPrinter &p, GPUModuleOp op) {
931   p << op.getOperationName() << ' ';
932   p.printSymbolName(op.getName());
933   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
934                                      {SymbolTable::getSymbolAttrName()});
935   p.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
936                 /*printBlockTerminators=*/false);
937 }
938 
939 //===----------------------------------------------------------------------===//
940 // GPUMemcpyOp
941 //===----------------------------------------------------------------------===//
942 
943 static LogicalResult verify(MemcpyOp op) {
944   auto srcType = op.src().getType();
945   auto dstType = op.dst().getType();
946 
947   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
948     return op.emitOpError("arguments have incompatible element type");
949 
950   if (failed(verifyCompatibleShape(srcType, dstType)))
951     return op.emitOpError("arguments have incompatible shape");
952 
953   return success();
954 }
955 
956 static ParseResult parseAsyncDependencies(
957     OpAsmParser &parser, Type &asyncTokenType,
958     SmallVectorImpl<OpAsmParser::OperandType> &asyncDependencies) {
959   auto loc = parser.getCurrentLocation();
960   if (succeeded(parser.parseOptionalKeyword("async"))) {
961     if (parser.getNumResults() == 0)
962       return parser.emitError(loc, "needs to be named when marked 'async'");
963     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
964   }
965   return parser.parseOperandList(asyncDependencies,
966                                  OpAsmParser::Delimiter::OptionalSquare);
967 }
968 
969 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
970                                    Type asyncTokenType,
971                                    OperandRange asyncDependencies) {
972   if (asyncTokenType)
973     printer << "async ";
974   if (asyncDependencies.empty())
975     return;
976   printer << "[";
977   llvm::interleaveComma(asyncDependencies, printer);
978   printer << "]";
979 }
980 
981 //===----------------------------------------------------------------------===//
982 // GPU_SubgroupMmaLoadMatrixOp
983 //===----------------------------------------------------------------------===//
984 
985 static LogicalResult verify(SubgroupMmaLoadMatrixOp op) {
986   auto srcType = op.srcMemref().getType();
987   auto resType = op.res().getType();
988   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
989   auto operand = resMatrixType.getOperand();
990   auto srcMemrefType = srcType.cast<MemRefType>();
991   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
992 
993   if (!srcMemrefType.getAffineMaps().empty() &&
994       !srcMemrefType.getAffineMaps().front().isIdentity())
995     return op.emitError("expected identity layout map for source memref");
996 
997   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
998       srcMemSpace != kGlobalMemorySpace)
999     return op.emitError(
1000         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1001         "kGlobalMemorySpace only allowed");
1002 
1003   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1004       !operand.equals("COp"))
1005     return op.emitError("only AOp, BOp and COp can be loaded");
1006 
1007   return success();
1008 }
1009 
1010 //===----------------------------------------------------------------------===//
1011 // GPU_SubgroupMmaStoreMatrixOp
1012 //===----------------------------------------------------------------------===//
1013 
1014 static LogicalResult verify(SubgroupMmaStoreMatrixOp op) {
1015   auto srcType = op.src().getType();
1016   auto dstType = op.dstMemref().getType();
1017   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1018   auto dstMemrefType = dstType.cast<MemRefType>();
1019   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1020 
1021   if (!dstMemrefType.getAffineMaps().empty() &&
1022       !dstMemrefType.getAffineMaps().front().isIdentity())
1023     return op.emitError("expected identity layout map for destination memref");
1024 
1025   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1026       dstMemSpace != kGlobalMemorySpace)
1027     return op.emitError(
1028         "destination memorySpace of kGenericMemorySpace, "
1029         "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1030 
1031   if (!srcMatrixType.getOperand().equals("COp"))
1032     return op.emitError(
1033         "expected the operand matrix being stored to have 'COp' operand type");
1034 
1035   return success();
1036 }
1037 
1038 //===----------------------------------------------------------------------===//
1039 // GPU_SubgroupMmaComputeOp
1040 //===----------------------------------------------------------------------===//
1041 
1042 static LogicalResult verify(SubgroupMmaComputeOp op) {
1043   enum OperandMap { A, B, C };
1044   SmallVector<MMAMatrixType, 3> opTypes;
1045 
1046   auto populateOpInfo = [&opTypes, &op]() {
1047     opTypes.push_back(op.opA().getType().cast<MMAMatrixType>());
1048     opTypes.push_back(op.opB().getType().cast<MMAMatrixType>());
1049     opTypes.push_back(op.opC().getType().cast<MMAMatrixType>());
1050   };
1051   populateOpInfo();
1052 
1053   if (!opTypes[A].getOperand().equals("AOp") ||
1054       !opTypes[B].getOperand().equals("BOp") ||
1055       !opTypes[C].getOperand().equals("COp"))
1056     return op.emitError("operands must be in the order AOp, BOp, COp");
1057 
1058   ArrayRef<int64_t> aShape, bShape, cShape;
1059   aShape = opTypes[A].getShape();
1060   bShape = opTypes[B].getShape();
1061   cShape = opTypes[C].getShape();
1062 
1063   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1064       bShape[1] != cShape[1])
1065     return op.emitError("operand shapes do not satisfy matmul constraints");
1066 
1067   return success();
1068 }
1069 
1070 /// This is a common class used for patterns of the form
1071 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1072 /// into the root operation directly.
1073 static LogicalResult foldMemRefCast(Operation *op) {
1074   bool folded = false;
1075   for (OpOperand &operand : op->getOpOperands()) {
1076     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1077     if (cast) {
1078       operand.set(cast.getOperand());
1079       folded = true;
1080     }
1081   }
1082   return success(folded);
1083 }
1084 
1085 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1086                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1087   return foldMemRefCast(*this);
1088 }
1089 
1090 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1091 
1092 #define GET_OP_CLASSES
1093 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1094