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 << ShuffleOp::getOperationName() << ' ' << op.getOperands() << ' '
304     << op.mode() << " : " << 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 << LaunchOp::getOperationName() << ' ' << 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 = builder.getSymbolRefAttr(
546       kernelModule.getName(), {builder.getSymbolRefAttr(kernelFunc.getName())});
547   result.addAttribute(getKernelAttrName(), kernelSymbol);
548   SmallVector<int32_t, 8> segmentSizes(8, 1);
549   segmentSizes.front() = 0; // Initially no async dependencies.
550   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
551   result.addAttribute(getOperandSegmentSizeAttr(),
552                       builder.getI32VectorAttr(segmentSizes));
553 }
554 
555 unsigned LaunchFuncOp::getNumKernelOperands() {
556   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands;
557 }
558 
559 StringAttr LaunchFuncOp::getKernelModuleName() {
560   return kernel().getRootReference();
561 }
562 
563 StringAttr LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
564 
565 Value LaunchFuncOp::getKernelOperand(unsigned i) {
566   return getOperand(asyncDependencies().size() + kNumConfigOperands + i);
567 }
568 
569 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
570   auto operands = getOperands().drop_front(asyncDependencies().size());
571   return KernelDim3{operands[0], operands[1], operands[2]};
572 }
573 
574 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
575   auto operands = getOperands().drop_front(asyncDependencies().size());
576   return KernelDim3{operands[3], operands[4], operands[5]};
577 }
578 
579 static LogicalResult verify(LaunchFuncOp op) {
580   auto module = op->getParentOfType<ModuleOp>();
581   if (!module)
582     return op.emitOpError("expected to belong to a module");
583 
584   if (!module->getAttrOfType<UnitAttr>(
585           GPUDialect::getContainerModuleAttrName()))
586     return op.emitOpError(
587         "expected the closest surrounding module to have the '" +
588         GPUDialect::getContainerModuleAttrName() + "' attribute");
589 
590   auto kernelAttr = op->getAttrOfType<SymbolRefAttr>(op.getKernelAttrName());
591   if (!kernelAttr)
592     return op.emitOpError("symbol reference attribute '" +
593                           op.getKernelAttrName() + "' must be specified");
594 
595   return success();
596 }
597 
598 static ParseResult
599 parseLaunchFuncOperands(OpAsmParser &parser,
600                         SmallVectorImpl<OpAsmParser::OperandType> &argNames,
601                         SmallVectorImpl<Type> &argTypes) {
602   if (parser.parseOptionalKeyword("args"))
603     return success();
604   SmallVector<NamedAttrList, 4> argAttrs;
605   bool isVariadic = false;
606   return function_like_impl::parseFunctionArgumentList(
607       parser, /*allowAttributes=*/false,
608       /*allowVariadic=*/false, argNames, argTypes, argAttrs, isVariadic);
609 }
610 
611 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
612                                     OperandRange operands, TypeRange types) {
613   if (operands.empty())
614     return;
615   printer << "args(";
616   llvm::interleaveComma(llvm::zip(operands, types), printer,
617                         [&](const auto &pair) {
618                           printer.printOperand(std::get<0>(pair));
619                           printer << " : ";
620                           printer.printType(std::get<1>(pair));
621                         });
622   printer << ")";
623 }
624 
625 //===----------------------------------------------------------------------===//
626 // GPUFuncOp
627 //===----------------------------------------------------------------------===//
628 
629 /// Adds a new block argument that corresponds to buffers located in
630 /// workgroup memory.
631 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type) {
632   auto attrName = getNumWorkgroupAttributionsAttrName();
633   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
634   (*this)->setAttr(attrName,
635                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
636   return getBody().insertArgument(getType().getNumInputs() + attr.getInt(),
637                                   type);
638 }
639 
640 /// Adds a new block argument that corresponds to buffers located in
641 /// private memory.
642 BlockArgument GPUFuncOp::addPrivateAttribution(Type type) {
643   // Buffers on the private memory always come after buffers on the workgroup
644   // memory.
645   return getBody().addArgument(type);
646 }
647 
648 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
649                       StringRef name, FunctionType type,
650                       TypeRange workgroupAttributions,
651                       TypeRange privateAttributions,
652                       ArrayRef<NamedAttribute> attrs) {
653   result.addAttribute(SymbolTable::getSymbolAttrName(),
654                       builder.getStringAttr(name));
655   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
656   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
657                       builder.getI64IntegerAttr(workgroupAttributions.size()));
658   result.addAttributes(attrs);
659   Region *body = result.addRegion();
660   Block *entryBlock = new Block;
661   entryBlock->addArguments(type.getInputs());
662   entryBlock->addArguments(workgroupAttributions);
663   entryBlock->addArguments(privateAttributions);
664 
665   body->getBlocks().push_back(entryBlock);
666 }
667 
668 /// Parses a GPU function memory attribution.
669 ///
670 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
671 ///                        (`private` `(` ssa-id-and-type-list `)`)?
672 ///
673 /// Note that this function parses only one of the two similar parts, with the
674 /// keyword provided as argument.
675 static ParseResult
676 parseAttributions(OpAsmParser &parser, StringRef keyword,
677                   SmallVectorImpl<OpAsmParser::OperandType> &args,
678                   SmallVectorImpl<Type> &argTypes) {
679   // If we could not parse the keyword, just assume empty list and succeed.
680   if (failed(parser.parseOptionalKeyword(keyword)))
681     return success();
682 
683   if (failed(parser.parseLParen()))
684     return failure();
685 
686   // Early exit for an empty list.
687   if (succeeded(parser.parseOptionalRParen()))
688     return success();
689 
690   do {
691     OpAsmParser::OperandType arg;
692     Type type;
693 
694     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
695       return failure();
696 
697     args.push_back(arg);
698     argTypes.push_back(type);
699   } while (succeeded(parser.parseOptionalComma()));
700 
701   return parser.parseRParen();
702 }
703 
704 /// Parses a GPU function.
705 ///
706 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
707 ///                 (`->` function-result-list)? memory-attribution `kernel`?
708 ///                 function-attributes? region
709 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) {
710   SmallVector<OpAsmParser::OperandType, 8> entryArgs;
711   SmallVector<NamedAttrList, 1> argAttrs;
712   SmallVector<NamedAttrList, 1> resultAttrs;
713   SmallVector<Type, 8> argTypes;
714   SmallVector<Type, 4> resultTypes;
715   bool isVariadic;
716 
717   // Parse the function name.
718   StringAttr nameAttr;
719   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
720                              result.attributes))
721     return failure();
722 
723   auto signatureLocation = parser.getCurrentLocation();
724   if (failed(function_like_impl::parseFunctionSignature(
725           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
726           isVariadic, resultTypes, resultAttrs)))
727     return failure();
728 
729   if (entryArgs.empty() && !argTypes.empty())
730     return parser.emitError(signatureLocation)
731            << "gpu.func requires named arguments";
732 
733   // Construct the function type. More types will be added to the region, but
734   // not to the function type.
735   Builder &builder = parser.getBuilder();
736   auto type = builder.getFunctionType(argTypes, resultTypes);
737   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
738 
739   // Parse workgroup memory attributions.
740   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
741                                entryArgs, argTypes)))
742     return failure();
743 
744   // Store the number of operands we just parsed as the number of workgroup
745   // memory attributions.
746   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
747   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
748                       builder.getI64IntegerAttr(numWorkgroupAttrs));
749 
750   // Parse private memory attributions.
751   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
752                                entryArgs, argTypes)))
753     return failure();
754 
755   // Parse the kernel attribute if present.
756   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
757     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
758                         builder.getUnitAttr());
759 
760   // Parse attributes.
761   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
762     return failure();
763   function_like_impl::addArgAndResultAttrs(builder, result, argAttrs,
764                                            resultAttrs);
765 
766   // Parse the region. If no argument names were provided, take all names
767   // (including those of attributions) from the entry block.
768   auto *body = result.addRegion();
769   return parser.parseRegion(*body, entryArgs, argTypes);
770 }
771 
772 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
773                               ArrayRef<BlockArgument> values) {
774   if (values.empty())
775     return;
776 
777   p << ' ' << keyword << '(';
778   llvm::interleaveComma(
779       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
780   p << ')';
781 }
782 
783 /// Prints a GPU Func op.
784 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) {
785   p << GPUFuncOp::getOperationName() << ' ';
786   p.printSymbolName(op.getName());
787 
788   FunctionType type = op.getType();
789   function_like_impl::printFunctionSignature(
790       p, op.getOperation(), type.getInputs(),
791       /*isVariadic=*/false, type.getResults());
792 
793   printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions());
794   printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions());
795   if (op.isKernel())
796     p << ' ' << op.getKernelKeyword();
797 
798   function_like_impl::printFunctionAttributes(
799       p, op.getOperation(), type.getNumInputs(), type.getNumResults(),
800       {op.getNumWorkgroupAttributionsAttrName(),
801        GPUDialect::getKernelFuncAttrName()});
802   p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false);
803 }
804 
805 /// Hook for FunctionLike verifier.
806 LogicalResult GPUFuncOp::verifyType() {
807   Type type = getTypeAttr().getValue();
808   if (!type.isa<FunctionType>())
809     return emitOpError("requires '" + getTypeAttrName() +
810                        "' attribute of function type");
811 
812   if (isKernel() && getType().getNumResults() != 0)
813     return emitOpError() << "expected void return type for kernel function";
814 
815   return success();
816 }
817 
818 static LogicalResult verifyAttributions(Operation *op,
819                                         ArrayRef<BlockArgument> attributions,
820                                         unsigned memorySpace) {
821   for (Value v : attributions) {
822     auto type = v.getType().dyn_cast<MemRefType>();
823     if (!type)
824       return op->emitOpError() << "expected memref type in attribution";
825 
826     if (type.getMemorySpaceAsInt() != memorySpace) {
827       return op->emitOpError()
828              << "expected memory space " << memorySpace << " in attribution";
829     }
830   }
831   return success();
832 }
833 
834 /// Verifies the body of the function.
835 LogicalResult GPUFuncOp::verifyBody() {
836   unsigned numFuncArguments = getNumArguments();
837   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
838   unsigned numBlockArguments = front().getNumArguments();
839   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
840     return emitOpError() << "expected at least "
841                          << numFuncArguments + numWorkgroupAttributions
842                          << " arguments to body region";
843 
844   ArrayRef<Type> funcArgTypes = getType().getInputs();
845   for (unsigned i = 0; i < numFuncArguments; ++i) {
846     Type blockArgType = front().getArgument(i).getType();
847     if (funcArgTypes[i] != blockArgType)
848       return emitOpError() << "expected body region argument #" << i
849                            << " to be of type " << funcArgTypes[i] << ", got "
850                            << blockArgType;
851   }
852 
853   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
854                                 GPUDialect::getWorkgroupAddressSpace())) ||
855       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
856                                 GPUDialect::getPrivateAddressSpace())))
857     return failure();
858 
859   return success();
860 }
861 
862 //===----------------------------------------------------------------------===//
863 // ReturnOp
864 //===----------------------------------------------------------------------===//
865 
866 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) {
867   llvm::SmallVector<OpAsmParser::OperandType, 4> operands;
868   llvm::SmallVector<Type, 4> types;
869   if (parser.parseOperandList(operands) ||
870       parser.parseOptionalColonTypeList(types) ||
871       parser.resolveOperands(operands, types, parser.getCurrentLocation(),
872                              result.operands))
873     return failure();
874 
875   return success();
876 }
877 
878 static LogicalResult verify(gpu::ReturnOp returnOp) {
879   GPUFuncOp function = returnOp->getParentOfType<GPUFuncOp>();
880 
881   FunctionType funType = function.getType();
882 
883   if (funType.getNumResults() != returnOp.operands().size())
884     return returnOp.emitOpError()
885         .append("expected ", funType.getNumResults(), " result operands")
886         .attachNote(function.getLoc())
887         .append("return type declared here");
888 
889   for (auto pair : llvm::enumerate(
890            llvm::zip(function.getType().getResults(), returnOp.operands()))) {
891     Type type;
892     Value operand;
893     std::tie(type, operand) = pair.value();
894     if (type != operand.getType())
895       return returnOp.emitOpError() << "unexpected type `" << operand.getType()
896                                     << "' for operand #" << pair.index();
897   }
898   return success();
899 }
900 
901 //===----------------------------------------------------------------------===//
902 // GPUModuleOp
903 //===----------------------------------------------------------------------===//
904 
905 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
906                         StringRef name) {
907   ensureTerminator(*result.addRegion(), builder, result.location);
908   result.attributes.push_back(builder.getNamedAttr(
909       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
910 }
911 
912 static ParseResult parseGPUModuleOp(OpAsmParser &parser,
913                                     OperationState &result) {
914   StringAttr nameAttr;
915   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
916                              result.attributes))
917     return failure();
918 
919   // If module attributes are present, parse them.
920   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
921     return failure();
922 
923   // Parse the module body.
924   auto *body = result.addRegion();
925   if (parser.parseRegion(*body, None, None))
926     return failure();
927 
928   // Ensure that this module has a valid terminator.
929   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
930   return success();
931 }
932 
933 static void print(OpAsmPrinter &p, GPUModuleOp op) {
934   p << op.getOperationName() << ' ';
935   p.printSymbolName(op.getName());
936   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
937                                      {SymbolTable::getSymbolAttrName()});
938   p.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false,
939                 /*printBlockTerminators=*/false);
940 }
941 
942 //===----------------------------------------------------------------------===//
943 // GPUMemcpyOp
944 //===----------------------------------------------------------------------===//
945 
946 static LogicalResult verify(MemcpyOp op) {
947   auto srcType = op.src().getType();
948   auto dstType = op.dst().getType();
949 
950   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
951     return op.emitOpError("arguments have incompatible element type");
952 
953   if (failed(verifyCompatibleShape(srcType, dstType)))
954     return op.emitOpError("arguments have incompatible shape");
955 
956   return success();
957 }
958 
959 static ParseResult parseAsyncDependencies(
960     OpAsmParser &parser, Type &asyncTokenType,
961     SmallVectorImpl<OpAsmParser::OperandType> &asyncDependencies) {
962   auto loc = parser.getCurrentLocation();
963   if (succeeded(parser.parseOptionalKeyword("async"))) {
964     if (parser.getNumResults() == 0)
965       return parser.emitError(loc, "needs to be named when marked 'async'");
966     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
967   }
968   return parser.parseOperandList(asyncDependencies,
969                                  OpAsmParser::Delimiter::OptionalSquare);
970 }
971 
972 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
973                                    Type asyncTokenType,
974                                    OperandRange asyncDependencies) {
975   if (asyncTokenType)
976     printer << "async ";
977   if (asyncDependencies.empty())
978     return;
979   printer << "[";
980   llvm::interleaveComma(asyncDependencies, printer);
981   printer << "]";
982 }
983 
984 //===----------------------------------------------------------------------===//
985 // GPU_SubgroupMmaLoadMatrixOp
986 //===----------------------------------------------------------------------===//
987 
988 static LogicalResult verify(SubgroupMmaLoadMatrixOp op) {
989   auto srcType = op.srcMemref().getType();
990   auto resType = op.res().getType();
991   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
992   auto operand = resMatrixType.getOperand();
993   auto srcMemrefType = srcType.cast<MemRefType>();
994   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
995 
996   if (!srcMemrefType.getAffineMaps().empty() &&
997       !srcMemrefType.getAffineMaps().front().isIdentity())
998     return op.emitError("expected identity layout map for source memref");
999 
1000   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1001       srcMemSpace != kGlobalMemorySpace)
1002     return op.emitError(
1003         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1004         "kGlobalMemorySpace only allowed");
1005 
1006   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1007       !operand.equals("COp"))
1008     return op.emitError("only AOp, BOp and COp can be loaded");
1009 
1010   return success();
1011 }
1012 
1013 //===----------------------------------------------------------------------===//
1014 // GPU_SubgroupMmaStoreMatrixOp
1015 //===----------------------------------------------------------------------===//
1016 
1017 static LogicalResult verify(SubgroupMmaStoreMatrixOp op) {
1018   auto srcType = op.src().getType();
1019   auto dstType = op.dstMemref().getType();
1020   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1021   auto dstMemrefType = dstType.cast<MemRefType>();
1022   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1023 
1024   if (!dstMemrefType.getAffineMaps().empty() &&
1025       !dstMemrefType.getAffineMaps().front().isIdentity())
1026     return op.emitError("expected identity layout map for destination memref");
1027 
1028   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1029       dstMemSpace != kGlobalMemorySpace)
1030     return op.emitError(
1031         "destination memorySpace of kGenericMemorySpace, "
1032         "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1033 
1034   if (!srcMatrixType.getOperand().equals("COp"))
1035     return op.emitError(
1036         "expected the operand matrix being stored to have 'COp' operand type");
1037 
1038   return success();
1039 }
1040 
1041 //===----------------------------------------------------------------------===//
1042 // GPU_SubgroupMmaComputeOp
1043 //===----------------------------------------------------------------------===//
1044 
1045 static LogicalResult verify(SubgroupMmaComputeOp op) {
1046   enum OperandMap { A, B, C };
1047   SmallVector<MMAMatrixType, 3> opTypes;
1048 
1049   auto populateOpInfo = [&opTypes, &op]() {
1050     opTypes.push_back(op.opA().getType().cast<MMAMatrixType>());
1051     opTypes.push_back(op.opB().getType().cast<MMAMatrixType>());
1052     opTypes.push_back(op.opC().getType().cast<MMAMatrixType>());
1053   };
1054   populateOpInfo();
1055 
1056   if (!opTypes[A].getOperand().equals("AOp") ||
1057       !opTypes[B].getOperand().equals("BOp") ||
1058       !opTypes[C].getOperand().equals("COp"))
1059     return op.emitError("operands must be in the order AOp, BOp, COp");
1060 
1061   ArrayRef<int64_t> aShape, bShape, cShape;
1062   aShape = opTypes[A].getShape();
1063   bShape = opTypes[B].getShape();
1064   cShape = opTypes[C].getShape();
1065 
1066   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1067       bShape[1] != cShape[1])
1068     return op.emitError("operand shapes do not satisfy matmul constraints");
1069 
1070   return success();
1071 }
1072 
1073 /// This is a common class used for patterns of the form
1074 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1075 /// into the root operation directly.
1076 static LogicalResult foldMemRefCast(Operation *op) {
1077   bool folded = false;
1078   for (OpOperand &operand : op->getOpOperands()) {
1079     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1080     if (cast) {
1081       operand.set(cast.getOperand());
1082       folded = true;
1083     }
1084   }
1085   return success(folded);
1086 }
1087 
1088 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1089                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1090   return foldMemRefCast(*this);
1091 }
1092 
1093 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1094 
1095 #define GET_OP_CLASSES
1096 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1097