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