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