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