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