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