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