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