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