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/Arithmetic/IR/Arithmetic.h"
16 #include "mlir/Dialect/MemRef/IR/MemRef.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/DialectImplementation.h"
22 #include "mlir/IR/FunctionImplementation.h"
23 #include "mlir/IR/Matchers.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/IR/PatternMatch.h"
26 #include "mlir/IR/TypeUtilities.h"
27 #include "mlir/Transforms/InliningUtils.h"
28 #include "llvm/ADT/TypeSwitch.h"
29 
30 using namespace mlir;
31 using namespace mlir::gpu;
32 
33 #include "mlir/Dialect/GPU/GPUOpsDialect.cpp.inc"
34 
35 //===----------------------------------------------------------------------===//
36 // MMAMatrixType
37 //===----------------------------------------------------------------------===//
38 
39 MMAMatrixType MMAMatrixType::get(ArrayRef<int64_t> shape, Type elementType,
40                                  StringRef operand) {
41   return Base::get(elementType.getContext(), shape, elementType, operand);
42 }
43 
44 MMAMatrixType
45 MMAMatrixType::getChecked(function_ref<InFlightDiagnostic()> emitError,
46                           ArrayRef<int64_t> shape, Type elementType,
47                           StringRef operand) {
48   return Base::getChecked(emitError, elementType.getContext(), shape,
49                           elementType, operand);
50 }
51 
52 unsigned MMAMatrixType::getNumDims() const { return getImpl()->numDims; }
53 
54 ArrayRef<int64_t> MMAMatrixType::getShape() const {
55   return getImpl()->getShape();
56 }
57 
58 Type MMAMatrixType::getElementType() const { return getImpl()->elementType; }
59 
60 StringRef MMAMatrixType::getOperand() const { return getImpl()->getOperand(); }
61 
62 bool MMAMatrixType::isValidElementType(Type elementType) {
63   return elementType.isF16() || elementType.isF32();
64 }
65 
66 LogicalResult
67 MMAMatrixType::verify(function_ref<InFlightDiagnostic()> emitError,
68                       ArrayRef<int64_t> shape, Type elementType,
69                       StringRef operand) {
70   if (!operand.equals("AOp") && !operand.equals("BOp") &&
71       !operand.equals("COp"))
72     return emitError() << "operand expected to be one of AOp, BOp or COp";
73 
74   if (shape.size() != 2)
75     return emitError() << "MMAMatrixType must have exactly two dimensions";
76 
77   if (!MMAMatrixType::isValidElementType(elementType))
78     return emitError() << "MMAMatrixType elements must be F16 or F32";
79 
80   return success();
81 }
82 
83 //===----------------------------------------------------------------------===//
84 // GPUDialect
85 //===----------------------------------------------------------------------===//
86 
87 /// GPU memory space identifiers.
88 enum GPUMemorySpace {
89   /// Generic memory space identifier.
90   kGenericMemorySpace = 0,
91 
92   /// Global memory space identifier.
93   kGlobalMemorySpace = 1,
94 
95   /// Shared memory space identifier.
96   kSharedMemorySpace = 3
97 };
98 
99 bool GPUDialect::isKernel(Operation *op) {
100   UnitAttr isKernelAttr = op->getAttrOfType<UnitAttr>(getKernelFuncAttrName());
101   return static_cast<bool>(isKernelAttr);
102 }
103 
104 namespace {
105 /// This class defines the interface for handling inlining with gpu
106 /// operations.
107 struct GPUInlinerInterface : public DialectInlinerInterface {
108   using DialectInlinerInterface::DialectInlinerInterface;
109 
110   /// All gpu dialect ops can be inlined.
111   bool isLegalToInline(Operation *, Region *, bool,
112                        BlockAndValueMapping &) const final {
113     return true;
114   }
115 };
116 } // namespace
117 
118 void GPUDialect::initialize() {
119   addTypes<AsyncTokenType>();
120   addTypes<DeviceAsyncTokenType>();
121   addTypes<MMAMatrixType>();
122   addOperations<
123 #define GET_OP_LIST
124 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
125       >();
126   addAttributes<
127 #define GET_ATTRDEF_LIST
128 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
129       >();
130   addInterfaces<GPUInlinerInterface>();
131 }
132 
133 Type GPUDialect::parseType(DialectAsmParser &parser) const {
134   // Parse the main keyword for the type.
135   StringRef keyword;
136   if (parser.parseKeyword(&keyword))
137     return Type();
138   MLIRContext *context = getContext();
139 
140   // Handle 'async token' types.
141   if (keyword == "async.token")
142     return AsyncTokenType::get(context);
143   // Handle 'device async token' types.
144   if (keyword == "device.async.token")
145     return DeviceAsyncTokenType::get(context);
146 
147   if (keyword == "mma_matrix") {
148     SMLoc beginLoc = parser.getNameLoc();
149 
150     // Parse '<'.
151     if (parser.parseLess())
152       return nullptr;
153 
154     // Parse the size and elementType.
155     SmallVector<int64_t> shape;
156     Type elementType;
157     if (parser.parseDimensionList(shape, /*allowDynamic=*/false) ||
158         parser.parseType(elementType))
159       return nullptr;
160 
161     // Parse ','
162     if (parser.parseComma())
163       return nullptr;
164 
165     // Parse operand.
166     std::string operand;
167     if (failed(parser.parseOptionalString(&operand)))
168       return nullptr;
169 
170     // Parse '>'.
171     if (parser.parseGreater())
172       return nullptr;
173 
174     return MMAMatrixType::getChecked(mlir::detail::getDefaultDiagnosticEmitFn(
175                                          parser.getEncodedSourceLoc(beginLoc)),
176                                      shape, elementType, operand);
177   }
178 
179   parser.emitError(parser.getNameLoc(), "unknown gpu type: " + keyword);
180   return Type();
181 }
182 
183 void GPUDialect::printType(Type type, DialectAsmPrinter &os) const {
184   TypeSwitch<Type>(type)
185       .Case<AsyncTokenType>([&](Type) { os << "async.token"; })
186       .Case<DeviceAsyncTokenType>([&](Type) { os << "device.async.token"; })
187       .Case<MMAMatrixType>([&](MMAMatrixType fragTy) {
188         os << "mma_matrix<";
189         auto shape = fragTy.getShape();
190         for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim)
191           os << *dim << 'x';
192         os << shape.back() << 'x' << fragTy.getElementType();
193         os << ", \"" << fragTy.getOperand() << "\"" << '>';
194       })
195       .Default([](Type) { llvm_unreachable("unexpected 'gpu' type kind"); });
196 }
197 
198 LogicalResult GPUDialect::verifyOperationAttribute(Operation *op,
199                                                    NamedAttribute attr) {
200   if (!attr.getValue().isa<UnitAttr>() ||
201       attr.getName() != getContainerModuleAttrName())
202     return success();
203 
204   auto module = dyn_cast<ModuleOp>(op);
205   if (!module)
206     return op->emitError("expected '")
207            << getContainerModuleAttrName() << "' attribute to be attached to '"
208            << ModuleOp::getOperationName() << '\'';
209 
210   auto walkResult = module.walk([&module](LaunchFuncOp launchOp) -> WalkResult {
211     // Ignore launches that are nested more or less deep than functions in the
212     // module we are currently checking.
213     if (!launchOp->getParentOp() ||
214         launchOp->getParentOp()->getParentOp() != module)
215       return success();
216 
217     // Ignore launch ops with missing attributes here. The errors will be
218     // reported by the verifiers of those ops.
219     if (!launchOp->getAttrOfType<SymbolRefAttr>(
220             LaunchFuncOp::getKernelAttrName()))
221       return success();
222 
223     // Check that `launch_func` refers to a well-formed GPU kernel module.
224     StringAttr kernelModuleName = launchOp.getKernelModuleName();
225     auto kernelModule = module.lookupSymbol<GPUModuleOp>(kernelModuleName);
226     if (!kernelModule)
227       return launchOp.emitOpError()
228              << "kernel module '" << kernelModuleName.getValue()
229              << "' is undefined";
230 
231     // Check that `launch_func` refers to a well-formed kernel function.
232     Operation *kernelFunc = module.lookupSymbol(launchOp.kernelAttr());
233     if (!kernelFunc)
234       return launchOp.emitOpError("kernel function '")
235              << launchOp.kernel() << "' is undefined";
236     auto kernelConvertedFunction = dyn_cast<FunctionOpInterface>(kernelFunc);
237     if (!kernelConvertedFunction) {
238       InFlightDiagnostic diag = launchOp.emitOpError()
239                                 << "referenced kernel '" << launchOp.kernel()
240                                 << "' is not a function";
241       diag.attachNote(kernelFunc->getLoc()) << "see the kernel definition here";
242       return diag;
243     }
244 
245     if (!kernelFunc->getAttrOfType<mlir::UnitAttr>(
246             GPUDialect::getKernelFuncAttrName()))
247       return launchOp.emitOpError("kernel function is missing the '")
248              << GPUDialect::getKernelFuncAttrName() << "' attribute";
249 
250     // TODO: If the kernel isn't a GPU function (which happens during separate
251     // compilation), do not check type correspondence as it would require the
252     // verifier to be aware of the type conversion.
253     auto kernelGPUFunction = dyn_cast<gpu::GPUFuncOp>(kernelFunc);
254     if (!kernelGPUFunction)
255       return success();
256 
257     unsigned actualNumArguments = launchOp.getNumKernelOperands();
258     unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
259     if (expectedNumArguments != actualNumArguments)
260       return launchOp.emitOpError("got ")
261              << actualNumArguments << " kernel operands but expected "
262              << expectedNumArguments;
263 
264     auto functionType = kernelGPUFunction.getFunctionType();
265     for (unsigned i = 0; i < expectedNumArguments; ++i) {
266       if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
267         return launchOp.emitOpError("type of function argument ")
268                << i << " does not match";
269       }
270     }
271 
272     return success();
273   });
274 
275   return walkResult.wasInterrupted() ? failure() : success();
276 }
277 
278 /// Parses an optional list of async operands with an optional leading keyword.
279 /// (`async`)? (`[` ssa-id-list `]`)?
280 ///
281 /// This method is used by the tablegen assembly format for async ops as well.
282 static ParseResult parseAsyncDependencies(
283     OpAsmParser &parser, Type &asyncTokenType,
284     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &asyncDependencies) {
285   auto loc = parser.getCurrentLocation();
286   if (succeeded(parser.parseOptionalKeyword("async"))) {
287     if (parser.getNumResults() == 0)
288       return parser.emitError(loc, "needs to be named when marked 'async'");
289     asyncTokenType = parser.getBuilder().getType<AsyncTokenType>();
290   }
291   return parser.parseOperandList(asyncDependencies,
292                                  OpAsmParser::Delimiter::OptionalSquare);
293 }
294 
295 /// Prints optional async dependencies with its leading keyword.
296 ///   (`async`)? (`[` ssa-id-list `]`)?
297 // Used by the tablegen assembly format for several async ops.
298 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op,
299                                    Type asyncTokenType,
300                                    OperandRange asyncDependencies) {
301   if (asyncTokenType)
302     printer << "async";
303   if (asyncDependencies.empty())
304     return;
305   if (asyncTokenType)
306     printer << ' ';
307   printer << '[';
308   llvm::interleaveComma(asyncDependencies, printer);
309   printer << ']';
310 }
311 
312 //===----------------------------------------------------------------------===//
313 // AllReduceOp
314 //===----------------------------------------------------------------------===//
315 
316 LogicalResult gpu::AllReduceOp::verifyRegions() {
317   if (body().empty() != op().hasValue())
318     return emitError("expected either an op attribute or a non-empty body");
319   if (!body().empty()) {
320     if (body().getNumArguments() != 2)
321       return emitError("expected two region arguments");
322     for (auto argument : body().getArguments()) {
323       if (argument.getType() != getType())
324         return emitError("incorrect region argument type");
325     }
326     unsigned yieldCount = 0;
327     for (Block &block : body()) {
328       if (auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
329         if (yield.getNumOperands() != 1)
330           return emitError("expected one gpu.yield operand");
331         if (yield.getOperand(0).getType() != getType())
332           return emitError("incorrect gpu.yield type");
333         ++yieldCount;
334       }
335     }
336     if (yieldCount == 0)
337       return emitError("expected gpu.yield op in region");
338   } else {
339     gpu::AllReduceOperation opName = *op();
340     if ((opName == gpu::AllReduceOperation::AND ||
341          opName == gpu::AllReduceOperation::OR ||
342          opName == gpu::AllReduceOperation::XOR) &&
343         !getType().isa<IntegerType>()) {
344       return emitError()
345              << '`' << gpu::stringifyAllReduceOperation(opName)
346              << "` accumulator is only compatible with Integer type";
347     }
348   }
349   return success();
350 }
351 
352 // TODO: Support optional custom attributes (without dialect prefix).
353 static ParseResult parseAllReduceOperation(AsmParser &parser,
354                                            AllReduceOperationAttr &attr) {
355   StringRef enumStr;
356   if (!parser.parseOptionalKeyword(&enumStr)) {
357     Optional<AllReduceOperation> op = gpu::symbolizeAllReduceOperation(enumStr);
358     if (!op)
359       return parser.emitError(parser.getCurrentLocation(), "invalid op kind");
360     attr = AllReduceOperationAttr::get(parser.getContext(), *op);
361   }
362   return success();
363 }
364 
365 static void printAllReduceOperation(AsmPrinter &printer, Operation *op,
366                                     AllReduceOperationAttr attr) {
367   if (attr)
368     attr.print(printer);
369 }
370 
371 //===----------------------------------------------------------------------===//
372 // AsyncOpInterface
373 //===----------------------------------------------------------------------===//
374 
375 void gpu::addAsyncDependency(Operation *op, Value token) {
376   op->insertOperands(0, {token});
377   if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
378     return;
379   auto attrName =
380       OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr();
381   auto sizeAttr = op->template getAttrOfType<DenseIntElementsAttr>(attrName);
382 
383   // Async dependencies is the only variadic operand.
384   if (!sizeAttr)
385     return;
386 
387   SmallVector<int32_t, 8> sizes(sizeAttr.getValues<int32_t>());
388   ++sizes.front();
389   op->setAttr(attrName, Builder(op->getContext()).getI32VectorAttr(sizes));
390 }
391 
392 //===----------------------------------------------------------------------===//
393 // LaunchOp
394 //===----------------------------------------------------------------------===//
395 
396 void LaunchOp::build(OpBuilder &builder, OperationState &result,
397                      Value gridSizeX, Value gridSizeY, Value gridSizeZ,
398                      Value blockSizeX, Value blockSizeY, Value blockSizeZ,
399                      Value dynamicSharedMemorySize, Type asyncTokenType,
400                      ValueRange asyncDependencies) {
401   result.addOperands(asyncDependencies);
402   if (asyncTokenType)
403     result.types.push_back(builder.getType<AsyncTokenType>());
404 
405   // Add grid and block sizes as op operands, followed by the data operands.
406   result.addOperands(
407       {gridSizeX, gridSizeY, gridSizeZ, blockSizeX, blockSizeY, blockSizeZ});
408   if (dynamicSharedMemorySize)
409     result.addOperands(dynamicSharedMemorySize);
410 
411   // Create a kernel body region with kNumConfigRegionAttributes + N arguments,
412   // where the first kNumConfigRegionAttributes arguments have `index` type and
413   // the rest have the same types as the data operands.
414   Region *kernelRegion = result.addRegion();
415   Block *body = new Block();
416   for (unsigned i = 0; i < kNumConfigRegionAttributes; ++i)
417     body->addArgument(builder.getIndexType(), result.location);
418   kernelRegion->push_back(body);
419   SmallVector<int32_t, 8> segmentSizes(8, 1);
420   segmentSizes.front() = asyncDependencies.size();
421   segmentSizes.back() = dynamicSharedMemorySize ? 1 : 0;
422   result.addAttribute(getOperandSegmentSizeAttr(),
423                       builder.getI32VectorAttr(segmentSizes));
424 }
425 
426 KernelDim3 LaunchOp::getBlockIds() {
427   assert(!body().empty() && "LaunchOp body must not be empty.");
428   auto args = body().getArguments();
429   return KernelDim3{args[0], args[1], args[2]};
430 }
431 
432 KernelDim3 LaunchOp::getThreadIds() {
433   assert(!body().empty() && "LaunchOp body must not be empty.");
434   auto args = body().getArguments();
435   return KernelDim3{args[3], args[4], args[5]};
436 }
437 
438 KernelDim3 LaunchOp::getGridSize() {
439   assert(!body().empty() && "LaunchOp body must not be empty.");
440   auto args = body().getArguments();
441   return KernelDim3{args[6], args[7], args[8]};
442 }
443 
444 KernelDim3 LaunchOp::getBlockSize() {
445   assert(!body().empty() && "LaunchOp body must not be empty.");
446   auto args = body().getArguments();
447   return KernelDim3{args[9], args[10], args[11]};
448 }
449 
450 KernelDim3 LaunchOp::getGridSizeOperandValues() {
451   auto operands = getOperands().drop_front(asyncDependencies().size());
452   return KernelDim3{operands[0], operands[1], operands[2]};
453 }
454 
455 KernelDim3 LaunchOp::getBlockSizeOperandValues() {
456   auto operands = getOperands().drop_front(asyncDependencies().size());
457   return KernelDim3{operands[3], operands[4], operands[5]};
458 }
459 
460 LogicalResult LaunchOp::verifyRegions() {
461   // Kernel launch takes kNumConfigOperands leading operands for grid/block
462   // sizes and transforms them into kNumConfigRegionAttributes region arguments
463   // for block/thread identifiers and grid/block sizes.
464   if (!body().empty()) {
465     if (body().getNumArguments() !=
466         LaunchOp::kNumConfigOperands + getNumOperands() -
467             (dynamicSharedMemorySize() ? 1 : 0) - asyncDependencies().size())
468       return emitOpError("unexpected number of region arguments");
469   }
470 
471   // Block terminators without successors are expected to exit the kernel region
472   // and must be `gpu.terminator`.
473   for (Block &block : body()) {
474     if (block.empty())
475       continue;
476     if (block.back().getNumSuccessors() != 0)
477       continue;
478     if (!isa<gpu::TerminatorOp>(&block.back())) {
479       return block.back()
480           .emitError()
481           .append("expected '", gpu::TerminatorOp::getOperationName(),
482                   "' or a terminator with successors")
483           .attachNote(getLoc())
484           .append("in '", LaunchOp::getOperationName(), "' body region");
485     }
486   }
487 
488   if (getNumResults() == 0 && asyncToken())
489     return emitOpError("needs to be named when async keyword is specified");
490 
491   return success();
492 }
493 
494 // Pretty-print the kernel grid/block size assignment as
495 //   (%iter-x, %iter-y, %iter-z) in
496 //   (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use)
497 // where %size-* and %iter-* will correspond to the body region arguments.
498 static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size,
499                                 KernelDim3 operands, KernelDim3 ids) {
500   p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (";
501   p << size.x << " = " << operands.x << ", ";
502   p << size.y << " = " << operands.y << ", ";
503   p << size.z << " = " << operands.z << ')';
504 }
505 
506 void LaunchOp::print(OpAsmPrinter &p) {
507   if (asyncToken()) {
508     p << " async";
509     if (!asyncDependencies().empty())
510       p << " [" << asyncDependencies() << ']';
511   }
512   // Print the launch configuration.
513   p << ' ' << getBlocksKeyword();
514   printSizeAssignment(p, getGridSize(), getGridSizeOperandValues(),
515                       getBlockIds());
516   p << ' ' << getThreadsKeyword();
517   printSizeAssignment(p, getBlockSize(), getBlockSizeOperandValues(),
518                       getThreadIds());
519   if (dynamicSharedMemorySize())
520     p << ' ' << getDynamicSharedMemorySizeKeyword() << ' '
521       << dynamicSharedMemorySize();
522 
523   p << ' ';
524   p.printRegion(body(), /*printEntryBlockArgs=*/false);
525   p.printOptionalAttrDict((*this)->getAttrs(), /*elidedAttrs=*/{
526                               LaunchOp::getOperandSegmentSizeAttr()});
527 }
528 
529 // Parse the size assignment blocks for blocks and threads.  These have the form
530 //   (%region_arg, %region_arg, %region_arg) in
531 //   (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand)
532 // where %region_arg are percent-identifiers for the region arguments to be
533 // introduced further (SSA defs), and %operand are percent-identifiers for the
534 // SSA value uses.
535 static ParseResult
536 parseSizeAssignment(OpAsmParser &parser,
537                     MutableArrayRef<OpAsmParser::UnresolvedOperand> sizes,
538                     MutableArrayRef<OpAsmParser::UnresolvedOperand> regionSizes,
539                     MutableArrayRef<OpAsmParser::UnresolvedOperand> indices) {
540   assert(indices.size() == 3 && "space for three indices expected");
541   SmallVector<OpAsmParser::UnresolvedOperand, 3> args;
542   if (parser.parseRegionArgumentList(args, /*requiredOperandCount=*/3,
543                                      OpAsmParser::Delimiter::Paren) ||
544       parser.parseKeyword("in") || parser.parseLParen())
545     return failure();
546   std::move(args.begin(), args.end(), indices.begin());
547 
548   for (int i = 0; i < 3; ++i) {
549     if (i != 0 && parser.parseComma())
550       return failure();
551     if (parser.parseRegionArgument(regionSizes[i]) || parser.parseEqual() ||
552         parser.parseOperand(sizes[i]))
553       return failure();
554   }
555 
556   return parser.parseRParen();
557 }
558 
559 /// Parses a Launch operation.
560 /// operation ::= `gpu.launch` (`async` `[` ssa-id-list `]`)?
561 //        `blocks` `(` ssa-id-list `)` `in` ssa-reassignment
562 ///       `threads` `(` ssa-id-list `)` `in` ssa-reassignment
563 ///       region attr-dict?
564 /// ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)`
565 ParseResult LaunchOp::parse(OpAsmParser &parser, OperationState &result) {
566   // Sizes of the grid and block.
567   SmallVector<OpAsmParser::UnresolvedOperand, LaunchOp::kNumConfigOperands>
568       sizes(LaunchOp::kNumConfigOperands);
569   MutableArrayRef<OpAsmParser::UnresolvedOperand> sizesRef(sizes);
570 
571   // Actual (data) operands passed to the kernel.
572   SmallVector<OpAsmParser::UnresolvedOperand, 4> dataOperands;
573 
574   // Region arguments to be created.
575   SmallVector<OpAsmParser::UnresolvedOperand, 16> regionArgs(
576       LaunchOp::kNumConfigRegionAttributes);
577   MutableArrayRef<OpAsmParser::UnresolvedOperand> regionArgsRef(regionArgs);
578 
579   // Parse optional async dependencies.
580   SmallVector<OpAsmParser::UnresolvedOperand, 4> asyncDependencies;
581   Type asyncTokenType;
582   if (failed(
583           parseAsyncDependencies(parser, asyncTokenType, asyncDependencies)) ||
584       parser.resolveOperands(asyncDependencies, asyncTokenType,
585                              result.operands))
586     return failure();
587   if (parser.getNumResults() > 0)
588     result.types.push_back(asyncTokenType);
589 
590   // Parse the size assignment segments: the first segment assigns grid sizes
591   // and defines values for block identifiers; the second segment assigns block
592   // sizes and defines values for thread identifiers.  In the region argument
593   // list, identifiers precede sizes, and block-related values precede
594   // thread-related values.
595   if (parser.parseKeyword(LaunchOp::getBlocksKeyword().data()) ||
596       parseSizeAssignment(parser, sizesRef.take_front(3),
597                           regionArgsRef.slice(6, 3),
598                           regionArgsRef.slice(0, 3)) ||
599       parser.parseKeyword(LaunchOp::getThreadsKeyword().data()) ||
600       parseSizeAssignment(parser, sizesRef.drop_front(3),
601                           regionArgsRef.slice(9, 3),
602                           regionArgsRef.slice(3, 3)) ||
603       parser.resolveOperands(sizes, parser.getBuilder().getIndexType(),
604                              result.operands))
605     return failure();
606 
607   OpAsmParser::UnresolvedOperand dynamicSharedMemorySize;
608   bool hasDynamicSharedMemorySize = false;
609   if (!parser.parseOptionalKeyword(
610           LaunchOp::getDynamicSharedMemorySizeKeyword())) {
611     hasDynamicSharedMemorySize = true;
612     if (parser.parseOperand(dynamicSharedMemorySize) ||
613         parser.resolveOperand(dynamicSharedMemorySize,
614                               parser.getBuilder().getI32Type(),
615                               result.operands))
616       return failure();
617   }
618 
619   // Introduce the body region and parse it. The region has
620   // kNumConfigRegionAttributes arguments that correspond to
621   // block/thread identifiers and grid/block sizes, all of the `index` type.
622   Type index = parser.getBuilder().getIndexType();
623   SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes(
624       LaunchOp::kNumConfigRegionAttributes, index);
625   Region *body = result.addRegion();
626   if (parser.parseRegion(*body, regionArgs, dataTypes) ||
627       parser.parseOptionalAttrDict(result.attributes))
628     return failure();
629 
630   SmallVector<int32_t, 8> segmentSizes(8, 1);
631   segmentSizes.front() = asyncDependencies.size();
632   segmentSizes.back() = hasDynamicSharedMemorySize ? 1 : 0;
633   result.addAttribute(LaunchOp::getOperandSegmentSizeAttr(),
634                       parser.getBuilder().getI32VectorAttr(segmentSizes));
635   return success();
636 }
637 
638 /// Simplify the gpu.launch when the range of a thread or block ID is
639 /// trivially known to be one.
640 struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> {
641   using OpRewritePattern<LaunchOp>::OpRewritePattern;
642   LogicalResult matchAndRewrite(LaunchOp op,
643                                 PatternRewriter &rewriter) const override {
644     // If the range implies a single value for `id`, replace `id`'s uses by
645     // zero.
646     Value zero;
647     bool simplified = false;
648     auto constPropIdUses = [&](Value id, Value size) {
649       // Check if size is trivially one.
650       if (!matchPattern(size, m_One()))
651         return;
652       if (!simplified) {
653         // Create a zero value the first time.
654         OpBuilder::InsertionGuard guard(rewriter);
655         rewriter.setInsertionPointToStart(&op.body().front());
656         zero =
657             rewriter.create<arith::ConstantIndexOp>(op.getLoc(), /*value=*/0);
658       }
659       id.replaceAllUsesWith(zero);
660       simplified = true;
661     };
662     constPropIdUses(op.getBlockIds().x, op.gridSizeX());
663     constPropIdUses(op.getBlockIds().y, op.gridSizeY());
664     constPropIdUses(op.getBlockIds().z, op.gridSizeZ());
665     constPropIdUses(op.getThreadIds().x, op.blockSizeX());
666     constPropIdUses(op.getThreadIds().y, op.blockSizeY());
667     constPropIdUses(op.getThreadIds().z, op.blockSizeZ());
668 
669     return success(simplified);
670   }
671 };
672 
673 void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites,
674                                            MLIRContext *context) {
675   rewrites.add<FoldLaunchArguments>(context);
676 }
677 
678 //===----------------------------------------------------------------------===//
679 // LaunchFuncOp
680 //===----------------------------------------------------------------------===//
681 
682 void LaunchFuncOp::build(OpBuilder &builder, OperationState &result,
683                          GPUFuncOp kernelFunc, KernelDim3 gridSize,
684                          KernelDim3 blockSize, Value dynamicSharedMemorySize,
685                          ValueRange kernelOperands, Type asyncTokenType,
686                          ValueRange asyncDependencies) {
687   result.addOperands(asyncDependencies);
688   if (asyncTokenType)
689     result.types.push_back(builder.getType<AsyncTokenType>());
690 
691   // Add grid and block sizes as op operands, followed by the data operands.
692   result.addOperands({gridSize.x, gridSize.y, gridSize.z, blockSize.x,
693                       blockSize.y, blockSize.z});
694   if (dynamicSharedMemorySize)
695     result.addOperands(dynamicSharedMemorySize);
696   result.addOperands(kernelOperands);
697   auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
698   auto kernelSymbol =
699       SymbolRefAttr::get(kernelModule.getNameAttr(),
700                          {SymbolRefAttr::get(kernelFunc.getNameAttr())});
701   result.addAttribute(getKernelAttrName(), kernelSymbol);
702   SmallVector<int32_t, 9> segmentSizes(9, 1);
703   segmentSizes.front() = asyncDependencies.size();
704   segmentSizes[segmentSizes.size() - 2] = dynamicSharedMemorySize ? 1 : 0;
705   segmentSizes.back() = static_cast<int32_t>(kernelOperands.size());
706   result.addAttribute(getOperandSegmentSizeAttr(),
707                       builder.getI32VectorAttr(segmentSizes));
708 }
709 
710 unsigned LaunchFuncOp::getNumKernelOperands() {
711   return getNumOperands() - asyncDependencies().size() - kNumConfigOperands -
712          (dynamicSharedMemorySize() ? 1 : 0);
713 }
714 
715 StringAttr LaunchFuncOp::getKernelModuleName() {
716   return kernel().getRootReference();
717 }
718 
719 StringAttr LaunchFuncOp::getKernelName() { return kernel().getLeafReference(); }
720 
721 Value LaunchFuncOp::getKernelOperand(unsigned i) {
722   return getOperand(asyncDependencies().size() + kNumConfigOperands +
723                     (dynamicSharedMemorySize() ? 1 : 0) + i);
724 }
725 
726 KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
727   auto operands = getOperands().drop_front(asyncDependencies().size());
728   return KernelDim3{operands[0], operands[1], operands[2]};
729 }
730 
731 KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
732   auto operands = getOperands().drop_front(asyncDependencies().size());
733   return KernelDim3{operands[3], operands[4], operands[5]};
734 }
735 
736 LogicalResult LaunchFuncOp::verify() {
737   auto module = (*this)->getParentOfType<ModuleOp>();
738   if (!module)
739     return emitOpError("expected to belong to a module");
740 
741   if (!module->getAttrOfType<UnitAttr>(
742           GPUDialect::getContainerModuleAttrName()))
743     return emitOpError("expected the closest surrounding module to have the '" +
744                        GPUDialect::getContainerModuleAttrName() +
745                        "' attribute");
746 
747   auto kernelAttr = (*this)->getAttrOfType<SymbolRefAttr>(getKernelAttrName());
748   if (!kernelAttr)
749     return emitOpError("symbol reference attribute '" + getKernelAttrName() +
750                        "' must be specified");
751 
752   return success();
753 }
754 
755 static ParseResult parseLaunchFuncOperands(
756     OpAsmParser &parser,
757     SmallVectorImpl<OpAsmParser::UnresolvedOperand> &argNames,
758     SmallVectorImpl<Type> &argTypes) {
759   if (parser.parseOptionalKeyword("args"))
760     return success();
761   SmallVector<NamedAttrList> argAttrs;
762   SmallVector<Location> argLocations;
763   bool isVariadic = false;
764   return function_interface_impl::parseFunctionArgumentList(
765       parser, /*allowAttributes=*/false,
766       /*allowVariadic=*/false, argNames, argTypes, argAttrs, argLocations,
767       isVariadic);
768 }
769 
770 static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *,
771                                     OperandRange operands, TypeRange types) {
772   if (operands.empty())
773     return;
774   printer << "args(";
775   llvm::interleaveComma(llvm::zip(operands, types), printer,
776                         [&](const auto &pair) {
777                           printer.printOperand(std::get<0>(pair));
778                           printer << " : ";
779                           printer.printType(std::get<1>(pair));
780                         });
781   printer << ")";
782 }
783 
784 //
785 
786 //===----------------------------------------------------------------------===//
787 // ShuffleOp
788 //===----------------------------------------------------------------------===//
789 
790 void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value value,
791                       int32_t offset, int32_t width, ShuffleMode mode) {
792   build(builder, result, value,
793         builder.create<arith::ConstantOp>(result.location,
794                                           builder.getI32IntegerAttr(offset)),
795         builder.create<arith::ConstantOp>(result.location,
796                                           builder.getI32IntegerAttr(width)),
797         mode);
798 }
799 
800 //===----------------------------------------------------------------------===//
801 // GPUFuncOp
802 //===----------------------------------------------------------------------===//
803 
804 /// Adds a new block argument that corresponds to buffers located in
805 /// workgroup memory.
806 BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type, Location loc) {
807   auto attrName = getNumWorkgroupAttributionsAttrName();
808   auto attr = (*this)->getAttrOfType<IntegerAttr>(attrName);
809   (*this)->setAttr(attrName,
810                    IntegerAttr::get(attr.getType(), attr.getValue() + 1));
811   return getBody().insertArgument(
812       getFunctionType().getNumInputs() + attr.getInt(), type, loc);
813 }
814 
815 /// Adds a new block argument that corresponds to buffers located in
816 /// private memory.
817 BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) {
818   // Buffers on the private memory always come after buffers on the workgroup
819   // memory.
820   return getBody().addArgument(type, loc);
821 }
822 
823 void GPUFuncOp::build(OpBuilder &builder, OperationState &result,
824                       StringRef name, FunctionType type,
825                       TypeRange workgroupAttributions,
826                       TypeRange privateAttributions,
827                       ArrayRef<NamedAttribute> attrs) {
828   result.addAttribute(SymbolTable::getSymbolAttrName(),
829                       builder.getStringAttr(name));
830   result.addAttribute(getTypeAttrName(), TypeAttr::get(type));
831   result.addAttribute(getNumWorkgroupAttributionsAttrName(),
832                       builder.getI64IntegerAttr(workgroupAttributions.size()));
833   result.addAttributes(attrs);
834   Region *body = result.addRegion();
835   Block *entryBlock = new Block;
836 
837   // TODO: Allow passing in proper locations here.
838   for (Type argTy : type.getInputs())
839     entryBlock->addArgument(argTy, result.location);
840   for (Type argTy : workgroupAttributions)
841     entryBlock->addArgument(argTy, result.location);
842   for (Type argTy : privateAttributions)
843     entryBlock->addArgument(argTy, result.location);
844 
845   body->getBlocks().push_back(entryBlock);
846 }
847 
848 /// Parses a GPU function memory attribution.
849 ///
850 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)?
851 ///                        (`private` `(` ssa-id-and-type-list `)`)?
852 ///
853 /// Note that this function parses only one of the two similar parts, with the
854 /// keyword provided as argument.
855 static ParseResult
856 parseAttributions(OpAsmParser &parser, StringRef keyword,
857                   SmallVectorImpl<OpAsmParser::UnresolvedOperand> &args,
858                   SmallVectorImpl<Type> &argTypes) {
859   // If we could not parse the keyword, just assume empty list and succeed.
860   if (failed(parser.parseOptionalKeyword(keyword)))
861     return success();
862 
863   if (failed(parser.parseLParen()))
864     return failure();
865 
866   // Early exit for an empty list.
867   if (succeeded(parser.parseOptionalRParen()))
868     return success();
869 
870   do {
871     OpAsmParser::UnresolvedOperand arg;
872     Type type;
873 
874     if (parser.parseRegionArgument(arg) || parser.parseColonType(type))
875       return failure();
876 
877     args.push_back(arg);
878     argTypes.push_back(type);
879   } while (succeeded(parser.parseOptionalComma()));
880 
881   return parser.parseRParen();
882 }
883 
884 /// Parses a GPU function.
885 ///
886 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)`
887 ///                 (`->` function-result-list)? memory-attribution `kernel`?
888 ///                 function-attributes? region
889 ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) {
890   SmallVector<OpAsmParser::UnresolvedOperand> entryArgs;
891   SmallVector<NamedAttrList> argAttrs;
892   SmallVector<NamedAttrList> resultAttrs;
893   SmallVector<Type> argTypes;
894   SmallVector<Type> resultTypes;
895   SmallVector<Location> argLocations;
896   bool isVariadic;
897 
898   // Parse the function name.
899   StringAttr nameAttr;
900   if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(),
901                              result.attributes))
902     return failure();
903 
904   auto signatureLocation = parser.getCurrentLocation();
905   if (failed(function_interface_impl::parseFunctionSignature(
906           parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs,
907           argLocations, isVariadic, resultTypes, resultAttrs)))
908     return failure();
909 
910   if (entryArgs.empty() && !argTypes.empty())
911     return parser.emitError(signatureLocation)
912            << "gpu.func requires named arguments";
913 
914   // Construct the function type. More types will be added to the region, but
915   // not to the function type.
916   Builder &builder = parser.getBuilder();
917   auto type = builder.getFunctionType(argTypes, resultTypes);
918   result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type));
919 
920   // Parse workgroup memory attributions.
921   if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(),
922                                entryArgs, argTypes)))
923     return failure();
924 
925   // Store the number of operands we just parsed as the number of workgroup
926   // memory attributions.
927   unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs();
928   result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(),
929                       builder.getI64IntegerAttr(numWorkgroupAttrs));
930 
931   // Parse private memory attributions.
932   if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(),
933                                entryArgs, argTypes)))
934     return failure();
935 
936   // Parse the kernel attribute if present.
937   if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword())))
938     result.addAttribute(GPUDialect::getKernelFuncAttrName(),
939                         builder.getUnitAttr());
940 
941   // Parse attributes.
942   if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
943     return failure();
944   function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs,
945                                                 resultAttrs);
946 
947   // Parse the region. If no argument names were provided, take all names
948   // (including those of attributions) from the entry block.
949   auto *body = result.addRegion();
950   return parser.parseRegion(*body, entryArgs, argTypes);
951 }
952 
953 static void printAttributions(OpAsmPrinter &p, StringRef keyword,
954                               ArrayRef<BlockArgument> values) {
955   if (values.empty())
956     return;
957 
958   p << ' ' << keyword << '(';
959   llvm::interleaveComma(
960       values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); });
961   p << ')';
962 }
963 
964 void GPUFuncOp::print(OpAsmPrinter &p) {
965   p << ' ';
966   p.printSymbolName(getName());
967 
968   FunctionType type = getFunctionType();
969   function_interface_impl::printFunctionSignature(p, *this, type.getInputs(),
970                                                   /*isVariadic=*/false,
971                                                   type.getResults());
972 
973   printAttributions(p, getWorkgroupKeyword(), getWorkgroupAttributions());
974   printAttributions(p, getPrivateKeyword(), getPrivateAttributions());
975   if (isKernel())
976     p << ' ' << getKernelKeyword();
977 
978   function_interface_impl::printFunctionAttributes(
979       p, *this, type.getNumInputs(), type.getNumResults(),
980       {getNumWorkgroupAttributionsAttrName(),
981        GPUDialect::getKernelFuncAttrName()});
982   p << ' ';
983   p.printRegion(getBody(), /*printEntryBlockArgs=*/false);
984 }
985 
986 LogicalResult GPUFuncOp::verifyType() {
987   Type type = getFunctionTypeAttr().getValue();
988   if (!type.isa<FunctionType>())
989     return emitOpError("requires '" + getTypeAttrName() +
990                        "' attribute of function type");
991 
992   if (isKernel() && getFunctionType().getNumResults() != 0)
993     return emitOpError() << "expected void return type for kernel function";
994 
995   return success();
996 }
997 
998 static LogicalResult verifyAttributions(Operation *op,
999                                         ArrayRef<BlockArgument> attributions,
1000                                         unsigned memorySpace) {
1001   for (Value v : attributions) {
1002     auto type = v.getType().dyn_cast<MemRefType>();
1003     if (!type)
1004       return op->emitOpError() << "expected memref type in attribution";
1005 
1006     if (type.getMemorySpaceAsInt() != memorySpace) {
1007       return op->emitOpError()
1008              << "expected memory space " << memorySpace << " in attribution";
1009     }
1010   }
1011   return success();
1012 }
1013 
1014 /// Verifies the body of the function.
1015 LogicalResult GPUFuncOp::verifyBody() {
1016   unsigned numFuncArguments = getNumArguments();
1017   unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
1018   unsigned numBlockArguments = front().getNumArguments();
1019   if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
1020     return emitOpError() << "expected at least "
1021                          << numFuncArguments + numWorkgroupAttributions
1022                          << " arguments to body region";
1023 
1024   ArrayRef<Type> funcArgTypes = getFunctionType().getInputs();
1025   for (unsigned i = 0; i < numFuncArguments; ++i) {
1026     Type blockArgType = front().getArgument(i).getType();
1027     if (funcArgTypes[i] != blockArgType)
1028       return emitOpError() << "expected body region argument #" << i
1029                            << " to be of type " << funcArgTypes[i] << ", got "
1030                            << blockArgType;
1031   }
1032 
1033   if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(),
1034                                 GPUDialect::getWorkgroupAddressSpace())) ||
1035       failed(verifyAttributions(getOperation(), getPrivateAttributions(),
1036                                 GPUDialect::getPrivateAddressSpace())))
1037     return failure();
1038 
1039   return success();
1040 }
1041 
1042 //===----------------------------------------------------------------------===//
1043 // ReturnOp
1044 //===----------------------------------------------------------------------===//
1045 
1046 LogicalResult gpu::ReturnOp::verify() {
1047   GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>();
1048 
1049   FunctionType funType = function.getFunctionType();
1050 
1051   if (funType.getNumResults() != operands().size())
1052     return emitOpError()
1053         .append("expected ", funType.getNumResults(), " result operands")
1054         .attachNote(function.getLoc())
1055         .append("return type declared here");
1056 
1057   for (const auto &pair : llvm::enumerate(
1058            llvm::zip(function.getFunctionType().getResults(), operands()))) {
1059     Type type;
1060     Value operand;
1061     std::tie(type, operand) = pair.value();
1062     if (type != operand.getType())
1063       return emitOpError() << "unexpected type `" << operand.getType()
1064                            << "' for operand #" << pair.index();
1065   }
1066   return success();
1067 }
1068 
1069 //===----------------------------------------------------------------------===//
1070 // GPUModuleOp
1071 //===----------------------------------------------------------------------===//
1072 
1073 void GPUModuleOp::build(OpBuilder &builder, OperationState &result,
1074                         StringRef name) {
1075   ensureTerminator(*result.addRegion(), builder, result.location);
1076   result.attributes.push_back(builder.getNamedAttr(
1077       ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name)));
1078 }
1079 
1080 ParseResult GPUModuleOp::parse(OpAsmParser &parser, OperationState &result) {
1081   StringAttr nameAttr;
1082   if (parser.parseSymbolName(nameAttr, mlir::SymbolTable::getSymbolAttrName(),
1083                              result.attributes))
1084     return failure();
1085 
1086   // If module attributes are present, parse them.
1087   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1088     return failure();
1089 
1090   // Parse the module body.
1091   auto *body = result.addRegion();
1092   if (parser.parseRegion(*body, None, None))
1093     return failure();
1094 
1095   // Ensure that this module has a valid terminator.
1096   GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location);
1097   return success();
1098 }
1099 
1100 void GPUModuleOp::print(OpAsmPrinter &p) {
1101   p << ' ';
1102   p.printSymbolName(getName());
1103   p.printOptionalAttrDictWithKeyword((*this)->getAttrs(),
1104                                      {mlir::SymbolTable::getSymbolAttrName()});
1105   p << ' ';
1106   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
1107                 /*printBlockTerminators=*/false);
1108 }
1109 
1110 //===----------------------------------------------------------------------===//
1111 // GPUMemcpyOp
1112 //===----------------------------------------------------------------------===//
1113 
1114 LogicalResult MemcpyOp::verify() {
1115   auto srcType = src().getType();
1116   auto dstType = dst().getType();
1117 
1118   if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType))
1119     return emitOpError("arguments have incompatible element type");
1120 
1121   if (failed(verifyCompatibleShape(srcType, dstType)))
1122     return emitOpError("arguments have incompatible shape");
1123 
1124   return success();
1125 }
1126 
1127 namespace {
1128 
1129 /// Erases a common case of copy ops where a destination value is used only by
1130 /// the copy op, alloc and dealloc ops.
1131 struct EraseTrivialCopyOp : public OpRewritePattern<MemcpyOp> {
1132   using OpRewritePattern<MemcpyOp>::OpRewritePattern;
1133 
1134   LogicalResult matchAndRewrite(MemcpyOp op,
1135                                 PatternRewriter &rewriter) const override {
1136     Value dest = op.dst();
1137     // If `dest` is a block argument, we cannot remove `op`.
1138     if (dest.isa<BlockArgument>())
1139       return failure();
1140     auto isDeallocLikeOpActingOnVal = [](Operation *op, Value val) {
1141       auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
1142       if (!memOp)
1143         return false;
1144       llvm::SmallVector<SideEffects::EffectInstance<MemoryEffects::Effect>, 4>
1145           memOpEffects;
1146       memOp.getEffects(memOpEffects);
1147       return llvm::none_of(memOpEffects, [val](auto &effect) {
1148         return effect.getValue() == val &&
1149                !isa<MemoryEffects::Free>(effect.getEffect());
1150       });
1151     };
1152     // We can erase `op` iff `dest` has no other use apart from its
1153     // use by `op` and dealloc ops.
1154     if (llvm::any_of(dest.getUsers(), [isDeallocLikeOpActingOnVal, op,
1155                                        dest](Operation *user) {
1156           return user != op && !isDeallocLikeOpActingOnVal(user, dest);
1157         }))
1158       return failure();
1159 
1160     if (op.asyncDependencies().size() > 1 ||
1161         ((op.asyncDependencies().empty() && op.asyncToken()) ||
1162          (!op.asyncDependencies().empty() && !op.asyncToken())))
1163       return failure();
1164     rewriter.replaceOp(op, op.asyncDependencies());
1165     return success();
1166   }
1167 };
1168 
1169 } // end anonymous namespace
1170 
1171 void MemcpyOp::getCanonicalizationPatterns(RewritePatternSet &results,
1172                                            MLIRContext *context) {
1173   results.add<EraseTrivialCopyOp>(context);
1174 }
1175 
1176 //===----------------------------------------------------------------------===//
1177 // GPU_SubgroupMmaLoadMatrixOp
1178 //===----------------------------------------------------------------------===//
1179 
1180 /// Return true if the last dimension of the MemRefType has unit stride. Also
1181 /// return true for memrefs with no strides.
1182 static bool isLastMemrefDimUnitStride(MemRefType type) {
1183   int64_t offset;
1184   SmallVector<int64_t> strides;
1185   if (failed(getStridesAndOffset(type, strides, offset))) {
1186     return false;
1187   }
1188   return strides.back() == 1;
1189 }
1190 
1191 LogicalResult SubgroupMmaLoadMatrixOp::verify() {
1192   auto srcType = srcMemref().getType();
1193   auto resType = res().getType();
1194   auto resMatrixType = resType.cast<gpu::MMAMatrixType>();
1195   auto operand = resMatrixType.getOperand();
1196   auto srcMemrefType = srcType.cast<MemRefType>();
1197   auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt();
1198 
1199   if (!isLastMemrefDimUnitStride(srcMemrefType))
1200     return emitError(
1201         "expected source memref most minor dim must have unit stride");
1202 
1203   if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace &&
1204       srcMemSpace != kGlobalMemorySpace)
1205     return emitError(
1206         "source memorySpace kGenericMemorySpace, kSharedMemorySpace or "
1207         "kGlobalMemorySpace only allowed");
1208 
1209   if (!operand.equals("AOp") && !operand.equals("BOp") &&
1210       !operand.equals("COp"))
1211     return emitError("only AOp, BOp and COp can be loaded");
1212 
1213   return success();
1214 }
1215 
1216 //===----------------------------------------------------------------------===//
1217 // GPU_SubgroupMmaStoreMatrixOp
1218 //===----------------------------------------------------------------------===//
1219 
1220 LogicalResult SubgroupMmaStoreMatrixOp::verify() {
1221   auto srcType = src().getType();
1222   auto dstType = dstMemref().getType();
1223   auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>();
1224   auto dstMemrefType = dstType.cast<MemRefType>();
1225   auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt();
1226 
1227   if (!isLastMemrefDimUnitStride(dstMemrefType))
1228     return emitError(
1229         "expected destination memref most minor dim must have unit stride");
1230 
1231   if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace &&
1232       dstMemSpace != kGlobalMemorySpace)
1233     return emitError("destination memorySpace of kGenericMemorySpace, "
1234                      "kGlobalMemorySpace or kSharedMemorySpace only allowed");
1235 
1236   if (!srcMatrixType.getOperand().equals("COp"))
1237     return emitError(
1238         "expected the operand matrix being stored to have 'COp' operand type");
1239 
1240   return success();
1241 }
1242 
1243 //===----------------------------------------------------------------------===//
1244 // GPU_SubgroupMmaComputeOp
1245 //===----------------------------------------------------------------------===//
1246 
1247 LogicalResult SubgroupMmaComputeOp::verify() {
1248   enum OperandMap { A, B, C };
1249   SmallVector<MMAMatrixType, 3> opTypes;
1250   opTypes.push_back(opA().getType().cast<MMAMatrixType>());
1251   opTypes.push_back(opB().getType().cast<MMAMatrixType>());
1252   opTypes.push_back(opC().getType().cast<MMAMatrixType>());
1253 
1254   if (!opTypes[A].getOperand().equals("AOp") ||
1255       !opTypes[B].getOperand().equals("BOp") ||
1256       !opTypes[C].getOperand().equals("COp"))
1257     return emitError("operands must be in the order AOp, BOp, COp");
1258 
1259   ArrayRef<int64_t> aShape, bShape, cShape;
1260   aShape = opTypes[A].getShape();
1261   bShape = opTypes[B].getShape();
1262   cShape = opTypes[C].getShape();
1263 
1264   if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
1265       bShape[1] != cShape[1])
1266     return emitError("operand shapes do not satisfy matmul constraints");
1267 
1268   return success();
1269 }
1270 
1271 /// This is a common class used for patterns of the form
1272 /// "someop(memrefcast) -> someop".  It folds the source of any memref.cast
1273 /// into the root operation directly.
1274 static LogicalResult foldMemRefCast(Operation *op) {
1275   bool folded = false;
1276   for (OpOperand &operand : op->getOpOperands()) {
1277     auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>();
1278     if (cast) {
1279       operand.set(cast.getOperand());
1280       folded = true;
1281     }
1282   }
1283   return success(folded);
1284 }
1285 
1286 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands,
1287                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1288   return foldMemRefCast(*this);
1289 }
1290 
1291 LogicalResult MemsetOp::fold(ArrayRef<Attribute> operands,
1292                              SmallVectorImpl<::mlir::OpFoldResult> &results) {
1293   return foldMemRefCast(*this);
1294 }
1295 
1296 //===----------------------------------------------------------------------===//
1297 // GPU_WaitOp
1298 //===----------------------------------------------------------------------===//
1299 
1300 namespace {
1301 
1302 /// Remove gpu.wait op use of gpu.wait op def without async dependencies.
1303 /// %t = gpu.wait async []       // No async dependencies.
1304 /// ...  gpu.wait ... [%t, ...]  // %t can be removed.
1305 struct EraseRedundantGpuWaitOpPairs : public OpRewritePattern<WaitOp> {
1306 public:
1307   using OpRewritePattern::OpRewritePattern;
1308 
1309   LogicalResult matchAndRewrite(WaitOp op,
1310                                 PatternRewriter &rewriter) const final {
1311     auto predicate = [](Value value) {
1312       auto waitOp = value.getDefiningOp<WaitOp>();
1313       return waitOp && waitOp->getNumOperands() == 0;
1314     };
1315     if (llvm::none_of(op.asyncDependencies(), predicate))
1316       return failure();
1317     SmallVector<Value> validOperands;
1318     for (Value operand : op->getOperands()) {
1319       if (predicate(operand))
1320         continue;
1321       validOperands.push_back(operand);
1322     }
1323     op->setOperands(validOperands);
1324     return success();
1325   }
1326 };
1327 
1328 /// Simplify trivial gpu.wait ops for the following patterns.
1329 /// 1. %t = gpu.wait async ... ops, where %t has no uses (regardless of async
1330 /// dependencies).
1331 /// 2. %t1 = gpu.wait async [%t0], in this case, we can replace uses of %t1 with
1332 /// %t0.
1333 /// 3. gpu.wait [] ops, i.e gpu.wait ops that neither have any async
1334 /// dependencies nor return any token.
1335 struct SimplifyGpuWaitOp : public OpRewritePattern<WaitOp> {
1336 public:
1337   using OpRewritePattern::OpRewritePattern;
1338 
1339   LogicalResult matchAndRewrite(WaitOp op,
1340                                 PatternRewriter &rewriter) const final {
1341     // Erase gpu.wait ops that neither have any async dependencies nor return
1342     // any async token.
1343     if (op.asyncDependencies().empty() && !op.asyncToken()) {
1344       rewriter.eraseOp(op);
1345       return success();
1346     }
1347     // Replace uses of %t1 = gpu.wait async [%t0] ops with %t0 and erase the op.
1348     if (llvm::hasSingleElement(op.asyncDependencies()) && op.asyncToken()) {
1349       rewriter.replaceOp(op, op.asyncDependencies());
1350       return success();
1351     }
1352     // Erase %t = gpu.wait async ... ops, where %t has no uses.
1353     if (op.asyncToken() && op.asyncToken().use_empty()) {
1354       rewriter.eraseOp(op);
1355       return success();
1356     }
1357     return failure();
1358   }
1359 };
1360 
1361 } // end anonymous namespace
1362 
1363 void WaitOp::getCanonicalizationPatterns(RewritePatternSet &results,
1364                                          MLIRContext *context) {
1365   results.add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(context);
1366 }
1367 
1368 //===----------------------------------------------------------------------===//
1369 // GPU_AllocOp
1370 //===----------------------------------------------------------------------===//
1371 
1372 LogicalResult AllocOp::verify() {
1373   auto memRefType = memref().getType().cast<MemRefType>();
1374 
1375   if (static_cast<int64_t>(dynamicSizes().size()) !=
1376       memRefType.getNumDynamicDims())
1377     return emitOpError("dimension operand count does not equal memref "
1378                        "dynamic dimension count");
1379 
1380   unsigned numSymbols = 0;
1381   if (!memRefType.getLayout().isIdentity())
1382     numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols();
1383   if (symbolOperands().size() != numSymbols) {
1384     return emitOpError(
1385         "symbol operand count does not equal memref symbol count");
1386   }
1387 
1388   return success();
1389 }
1390 
1391 namespace {
1392 
1393 /// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to
1394 /// `memref::AllocOp`.
1395 struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> {
1396   using OpRewritePattern<memref::DimOp>::OpRewritePattern;
1397 
1398   LogicalResult matchAndRewrite(memref::DimOp dimOp,
1399                                 PatternRewriter &rewriter) const override {
1400     auto index = dimOp.index().getDefiningOp<arith::ConstantIndexOp>();
1401     if (!index)
1402       return failure();
1403 
1404     auto memrefType = dimOp.source().getType().dyn_cast<MemRefType>();
1405     if (!memrefType || !memrefType.isDynamicDim(index.value()))
1406       return failure();
1407 
1408     auto alloc = dimOp.source().getDefiningOp<AllocOp>();
1409     if (!alloc)
1410       return failure();
1411 
1412     Value substituteOp = *(alloc.dynamicSizes().begin() +
1413                            memrefType.getDynamicDimIndex(index.value()));
1414     rewriter.replaceOp(dimOp, substituteOp);
1415     return success();
1416   }
1417 };
1418 
1419 } // namespace
1420 
1421 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results,
1422                                           MLIRContext *context) {
1423   results.add<SimplifyDimOfAllocOp>(context);
1424 }
1425 
1426 //===----------------------------------------------------------------------===//
1427 // GPU_DeviceAsyncCopyOp
1428 //===----------------------------------------------------------------------===//
1429 
1430 LogicalResult DeviceAsyncCopyOp::verify() {
1431   auto srcMemref = src().getType().cast<MemRefType>();
1432   auto dstMemref = dst().getType().cast<MemRefType>();
1433   unsigned workgroupAddressSpace = GPUDialect::getWorkgroupAddressSpace();
1434   if (!isLastMemrefDimUnitStride(srcMemref))
1435     return emitError("source memref most minor dim must have unit stride");
1436   if (!isLastMemrefDimUnitStride(dstMemref))
1437     return emitError("destination memref most minor dim must have unit stride");
1438   if (dstMemref.getMemorySpaceAsInt() != workgroupAddressSpace)
1439     return emitError("destination memref must have memory space ")
1440            << workgroupAddressSpace;
1441   if (dstMemref.getElementType() != srcMemref.getElementType())
1442     return emitError("source and destination must have the same element type");
1443   if (size_t(srcMemref.getRank()) != srcIndices().size())
1444     return emitOpError() << "expected " << srcMemref.getRank()
1445                          << " source indices, got " << srcIndices().size();
1446   if (size_t(dstMemref.getRank()) != dstIndices().size())
1447     return emitOpError() << "expected " << dstMemref.getRank()
1448                          << " destination indices, got " << dstIndices().size();
1449   return success();
1450 }
1451 
1452 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc"
1453 #include "mlir/Dialect/GPU/GPUOpsEnums.cpp.inc"
1454 
1455 #define GET_ATTRDEF_CLASSES
1456 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc"
1457 
1458 #define GET_OP_CLASSES
1459 #include "mlir/Dialect/GPU/GPUOps.cpp.inc"
1460