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 for (unsigned i = 0; i < kNumConfigRegionAttributes; ++i) 373 body->addArgument(builder.getIndexType(), result.location); 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<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, Location loc) { 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, loc); 709 } 710 711 /// Adds a new block argument that corresponds to buffers located in 712 /// private memory. 713 BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) { 714 // Buffers on the private memory always come after buffers on the workgroup 715 // memory. 716 return getBody().addArgument(type, loc); 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 733 // TODO: Allow passing in proper locations here. 734 for (Type argTy : type.getInputs()) 735 entryBlock->addArgument(argTy, result.location); 736 for (Type argTy : workgroupAttributions) 737 entryBlock->addArgument(argTy, result.location); 738 for (Type argTy : privateAttributions) 739 entryBlock->addArgument(argTy, result.location); 740 741 body->getBlocks().push_back(entryBlock); 742 } 743 744 /// Parses a GPU function memory attribution. 745 /// 746 /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)? 747 /// (`private` `(` ssa-id-and-type-list `)`)? 748 /// 749 /// Note that this function parses only one of the two similar parts, with the 750 /// keyword provided as argument. 751 static ParseResult 752 parseAttributions(OpAsmParser &parser, StringRef keyword, 753 SmallVectorImpl<OpAsmParser::OperandType> &args, 754 SmallVectorImpl<Type> &argTypes) { 755 // If we could not parse the keyword, just assume empty list and succeed. 756 if (failed(parser.parseOptionalKeyword(keyword))) 757 return success(); 758 759 if (failed(parser.parseLParen())) 760 return failure(); 761 762 // Early exit for an empty list. 763 if (succeeded(parser.parseOptionalRParen())) 764 return success(); 765 766 do { 767 OpAsmParser::OperandType arg; 768 Type type; 769 770 if (parser.parseRegionArgument(arg) || parser.parseColonType(type)) 771 return failure(); 772 773 args.push_back(arg); 774 argTypes.push_back(type); 775 } while (succeeded(parser.parseOptionalComma())); 776 777 return parser.parseRParen(); 778 } 779 780 /// Parses a GPU function. 781 /// 782 /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)` 783 /// (`->` function-result-list)? memory-attribution `kernel`? 784 /// function-attributes? region 785 static ParseResult parseGPUFuncOp(OpAsmParser &parser, OperationState &result) { 786 SmallVector<OpAsmParser::OperandType> entryArgs; 787 SmallVector<NamedAttrList> argAttrs; 788 SmallVector<NamedAttrList> resultAttrs; 789 SmallVector<Type> argTypes; 790 SmallVector<Type> resultTypes; 791 SmallVector<Location> argLocations; 792 bool isVariadic; 793 794 // Parse the function name. 795 StringAttr nameAttr; 796 if (parser.parseSymbolName(nameAttr, ::mlir::SymbolTable::getSymbolAttrName(), 797 result.attributes)) 798 return failure(); 799 800 auto signatureLocation = parser.getCurrentLocation(); 801 if (failed(function_interface_impl::parseFunctionSignature( 802 parser, /*allowVariadic=*/false, entryArgs, argTypes, argAttrs, 803 argLocations, isVariadic, resultTypes, resultAttrs))) 804 return failure(); 805 806 if (entryArgs.empty() && !argTypes.empty()) 807 return parser.emitError(signatureLocation) 808 << "gpu.func requires named arguments"; 809 810 // Construct the function type. More types will be added to the region, but 811 // not to the function type. 812 Builder &builder = parser.getBuilder(); 813 auto type = builder.getFunctionType(argTypes, resultTypes); 814 result.addAttribute(GPUFuncOp::getTypeAttrName(), TypeAttr::get(type)); 815 816 // Parse workgroup memory attributions. 817 if (failed(parseAttributions(parser, GPUFuncOp::getWorkgroupKeyword(), 818 entryArgs, argTypes))) 819 return failure(); 820 821 // Store the number of operands we just parsed as the number of workgroup 822 // memory attributions. 823 unsigned numWorkgroupAttrs = argTypes.size() - type.getNumInputs(); 824 result.addAttribute(GPUFuncOp::getNumWorkgroupAttributionsAttrName(), 825 builder.getI64IntegerAttr(numWorkgroupAttrs)); 826 827 // Parse private memory attributions. 828 if (failed(parseAttributions(parser, GPUFuncOp::getPrivateKeyword(), 829 entryArgs, argTypes))) 830 return failure(); 831 832 // Parse the kernel attribute if present. 833 if (succeeded(parser.parseOptionalKeyword(GPUFuncOp::getKernelKeyword()))) 834 result.addAttribute(GPUDialect::getKernelFuncAttrName(), 835 builder.getUnitAttr()); 836 837 // Parse attributes. 838 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes))) 839 return failure(); 840 function_interface_impl::addArgAndResultAttrs(builder, result, argAttrs, 841 resultAttrs); 842 843 // Parse the region. If no argument names were provided, take all names 844 // (including those of attributions) from the entry block. 845 auto *body = result.addRegion(); 846 return parser.parseRegion(*body, entryArgs, argTypes); 847 } 848 849 static void printAttributions(OpAsmPrinter &p, StringRef keyword, 850 ArrayRef<BlockArgument> values) { 851 if (values.empty()) 852 return; 853 854 p << ' ' << keyword << '('; 855 llvm::interleaveComma( 856 values, p, [&p](BlockArgument v) { p << v << " : " << v.getType(); }); 857 p << ')'; 858 } 859 860 /// Prints a GPU Func op. 861 static void printGPUFuncOp(OpAsmPrinter &p, GPUFuncOp op) { 862 p << ' '; 863 p.printSymbolName(op.getName()); 864 865 FunctionType type = op.getType(); 866 function_interface_impl::printFunctionSignature( 867 p, op.getOperation(), type.getInputs(), 868 /*isVariadic=*/false, type.getResults()); 869 870 printAttributions(p, op.getWorkgroupKeyword(), op.getWorkgroupAttributions()); 871 printAttributions(p, op.getPrivateKeyword(), op.getPrivateAttributions()); 872 if (op.isKernel()) 873 p << ' ' << op.getKernelKeyword(); 874 875 function_interface_impl::printFunctionAttributes( 876 p, op.getOperation(), type.getNumInputs(), type.getNumResults(), 877 {op.getNumWorkgroupAttributionsAttrName(), 878 GPUDialect::getKernelFuncAttrName()}); 879 p << ' '; 880 p.printRegion(op.getBody(), /*printEntryBlockArgs=*/false); 881 } 882 883 LogicalResult GPUFuncOp::verifyType() { 884 Type type = getTypeAttr().getValue(); 885 if (!type.isa<FunctionType>()) 886 return emitOpError("requires '" + getTypeAttrName() + 887 "' attribute of function type"); 888 889 if (isKernel() && getType().getNumResults() != 0) 890 return emitOpError() << "expected void return type for kernel function"; 891 892 return success(); 893 } 894 895 static LogicalResult verifyAttributions(Operation *op, 896 ArrayRef<BlockArgument> attributions, 897 unsigned memorySpace) { 898 for (Value v : attributions) { 899 auto type = v.getType().dyn_cast<MemRefType>(); 900 if (!type) 901 return op->emitOpError() << "expected memref type in attribution"; 902 903 if (type.getMemorySpaceAsInt() != memorySpace) { 904 return op->emitOpError() 905 << "expected memory space " << memorySpace << " in attribution"; 906 } 907 } 908 return success(); 909 } 910 911 /// Verifies the body of the function. 912 LogicalResult GPUFuncOp::verifyBody() { 913 unsigned numFuncArguments = getNumArguments(); 914 unsigned numWorkgroupAttributions = getNumWorkgroupAttributions(); 915 unsigned numBlockArguments = front().getNumArguments(); 916 if (numBlockArguments < numFuncArguments + numWorkgroupAttributions) 917 return emitOpError() << "expected at least " 918 << numFuncArguments + numWorkgroupAttributions 919 << " arguments to body region"; 920 921 ArrayRef<Type> funcArgTypes = getType().getInputs(); 922 for (unsigned i = 0; i < numFuncArguments; ++i) { 923 Type blockArgType = front().getArgument(i).getType(); 924 if (funcArgTypes[i] != blockArgType) 925 return emitOpError() << "expected body region argument #" << i 926 << " to be of type " << funcArgTypes[i] << ", got " 927 << blockArgType; 928 } 929 930 if (failed(verifyAttributions(getOperation(), getWorkgroupAttributions(), 931 GPUDialect::getWorkgroupAddressSpace())) || 932 failed(verifyAttributions(getOperation(), getPrivateAttributions(), 933 GPUDialect::getPrivateAddressSpace()))) 934 return failure(); 935 936 return success(); 937 } 938 939 //===----------------------------------------------------------------------===// 940 // ReturnOp 941 //===----------------------------------------------------------------------===// 942 943 static LogicalResult verify(gpu::ReturnOp returnOp) { 944 GPUFuncOp function = returnOp->getParentOfType<GPUFuncOp>(); 945 946 FunctionType funType = function.getType(); 947 948 if (funType.getNumResults() != returnOp.operands().size()) 949 return returnOp.emitOpError() 950 .append("expected ", funType.getNumResults(), " result operands") 951 .attachNote(function.getLoc()) 952 .append("return type declared here"); 953 954 for (const auto &pair : llvm::enumerate( 955 llvm::zip(function.getType().getResults(), returnOp.operands()))) { 956 Type type; 957 Value operand; 958 std::tie(type, operand) = pair.value(); 959 if (type != operand.getType()) 960 return returnOp.emitOpError() << "unexpected type `" << operand.getType() 961 << "' for operand #" << pair.index(); 962 } 963 return success(); 964 } 965 966 //===----------------------------------------------------------------------===// 967 // GPUModuleOp 968 //===----------------------------------------------------------------------===// 969 970 void GPUModuleOp::build(OpBuilder &builder, OperationState &result, 971 StringRef name) { 972 ensureTerminator(*result.addRegion(), builder, result.location); 973 result.attributes.push_back(builder.getNamedAttr( 974 ::mlir::SymbolTable::getSymbolAttrName(), builder.getStringAttr(name))); 975 } 976 977 static ParseResult parseGPUModuleOp(OpAsmParser &parser, 978 OperationState &result) { 979 StringAttr nameAttr; 980 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 981 result.attributes)) 982 return failure(); 983 984 // If module attributes are present, parse them. 985 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 986 return failure(); 987 988 // Parse the module body. 989 auto *body = result.addRegion(); 990 if (parser.parseRegion(*body, None, None)) 991 return failure(); 992 993 // Ensure that this module has a valid terminator. 994 GPUModuleOp::ensureTerminator(*body, parser.getBuilder(), result.location); 995 return success(); 996 } 997 998 static void print(OpAsmPrinter &p, GPUModuleOp op) { 999 p << ' '; 1000 p.printSymbolName(op.getName()); 1001 p.printOptionalAttrDictWithKeyword(op->getAttrs(), 1002 {SymbolTable::getSymbolAttrName()}); 1003 p << ' '; 1004 p.printRegion(op->getRegion(0), /*printEntryBlockArgs=*/false, 1005 /*printBlockTerminators=*/false); 1006 } 1007 1008 //===----------------------------------------------------------------------===// 1009 // GPUMemcpyOp 1010 //===----------------------------------------------------------------------===// 1011 1012 static LogicalResult verify(MemcpyOp op) { 1013 auto srcType = op.src().getType(); 1014 auto dstType = op.dst().getType(); 1015 1016 if (getElementTypeOrSelf(srcType) != getElementTypeOrSelf(dstType)) 1017 return op.emitOpError("arguments have incompatible element type"); 1018 1019 if (failed(verifyCompatibleShape(srcType, dstType))) 1020 return op.emitOpError("arguments have incompatible shape"); 1021 1022 return success(); 1023 } 1024 1025 static ParseResult parseAsyncDependencies( 1026 OpAsmParser &parser, Type &asyncTokenType, 1027 SmallVectorImpl<OpAsmParser::OperandType> &asyncDependencies) { 1028 auto loc = parser.getCurrentLocation(); 1029 if (succeeded(parser.parseOptionalKeyword("async"))) { 1030 if (parser.getNumResults() == 0) 1031 return parser.emitError(loc, "needs to be named when marked 'async'"); 1032 asyncTokenType = parser.getBuilder().getType<AsyncTokenType>(); 1033 } 1034 return parser.parseOperandList(asyncDependencies, 1035 OpAsmParser::Delimiter::OptionalSquare); 1036 } 1037 1038 static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op, 1039 Type asyncTokenType, 1040 OperandRange asyncDependencies) { 1041 if (asyncTokenType) 1042 printer << "async "; 1043 if (asyncDependencies.empty()) 1044 return; 1045 printer << "["; 1046 llvm::interleaveComma(asyncDependencies, printer); 1047 printer << "]"; 1048 } 1049 1050 //===----------------------------------------------------------------------===// 1051 // GPU_SubgroupMmaLoadMatrixOp 1052 //===----------------------------------------------------------------------===// 1053 1054 static LogicalResult verify(SubgroupMmaLoadMatrixOp op) { 1055 auto srcType = op.srcMemref().getType(); 1056 auto resType = op.res().getType(); 1057 auto resMatrixType = resType.cast<gpu::MMAMatrixType>(); 1058 auto operand = resMatrixType.getOperand(); 1059 auto srcMemrefType = srcType.cast<MemRefType>(); 1060 auto srcMemSpace = srcMemrefType.getMemorySpaceAsInt(); 1061 1062 if (!srcMemrefType.getLayout().isIdentity()) 1063 return op.emitError("expected identity layout map for source memref"); 1064 1065 if (srcMemSpace != kGenericMemorySpace && srcMemSpace != kSharedMemorySpace && 1066 srcMemSpace != kGlobalMemorySpace) 1067 return op.emitError( 1068 "source memorySpace kGenericMemorySpace, kSharedMemorySpace or " 1069 "kGlobalMemorySpace only allowed"); 1070 1071 if (!operand.equals("AOp") && !operand.equals("BOp") && 1072 !operand.equals("COp")) 1073 return op.emitError("only AOp, BOp and COp can be loaded"); 1074 1075 return success(); 1076 } 1077 1078 //===----------------------------------------------------------------------===// 1079 // GPU_SubgroupMmaStoreMatrixOp 1080 //===----------------------------------------------------------------------===// 1081 1082 static LogicalResult verify(SubgroupMmaStoreMatrixOp op) { 1083 auto srcType = op.src().getType(); 1084 auto dstType = op.dstMemref().getType(); 1085 auto srcMatrixType = srcType.cast<gpu::MMAMatrixType>(); 1086 auto dstMemrefType = dstType.cast<MemRefType>(); 1087 auto dstMemSpace = dstMemrefType.getMemorySpaceAsInt(); 1088 if (!dstMemrefType.getLayout().isIdentity()) 1089 return op.emitError("expected identity layout map for destination memref"); 1090 1091 if (dstMemSpace != kGenericMemorySpace && dstMemSpace != kSharedMemorySpace && 1092 dstMemSpace != kGlobalMemorySpace) 1093 return op.emitError( 1094 "destination memorySpace of kGenericMemorySpace, " 1095 "kGlobalMemorySpace or kSharedMemorySpace only allowed"); 1096 1097 if (!srcMatrixType.getOperand().equals("COp")) 1098 return op.emitError( 1099 "expected the operand matrix being stored to have 'COp' operand type"); 1100 1101 return success(); 1102 } 1103 1104 //===----------------------------------------------------------------------===// 1105 // GPU_SubgroupMmaComputeOp 1106 //===----------------------------------------------------------------------===// 1107 1108 static LogicalResult verify(SubgroupMmaComputeOp op) { 1109 enum OperandMap { A, B, C }; 1110 SmallVector<MMAMatrixType, 3> opTypes; 1111 1112 auto populateOpInfo = [&opTypes, &op]() { 1113 opTypes.push_back(op.opA().getType().cast<MMAMatrixType>()); 1114 opTypes.push_back(op.opB().getType().cast<MMAMatrixType>()); 1115 opTypes.push_back(op.opC().getType().cast<MMAMatrixType>()); 1116 }; 1117 populateOpInfo(); 1118 1119 if (!opTypes[A].getOperand().equals("AOp") || 1120 !opTypes[B].getOperand().equals("BOp") || 1121 !opTypes[C].getOperand().equals("COp")) 1122 return op.emitError("operands must be in the order AOp, BOp, COp"); 1123 1124 ArrayRef<int64_t> aShape, bShape, cShape; 1125 aShape = opTypes[A].getShape(); 1126 bShape = opTypes[B].getShape(); 1127 cShape = opTypes[C].getShape(); 1128 1129 if (aShape[1] != bShape[0] || aShape[0] != cShape[0] || 1130 bShape[1] != cShape[1]) 1131 return op.emitError("operand shapes do not satisfy matmul constraints"); 1132 1133 return success(); 1134 } 1135 1136 /// This is a common class used for patterns of the form 1137 /// "someop(memrefcast) -> someop". It folds the source of any memref.cast 1138 /// into the root operation directly. 1139 static LogicalResult foldMemRefCast(Operation *op) { 1140 bool folded = false; 1141 for (OpOperand &operand : op->getOpOperands()) { 1142 auto cast = operand.get().getDefiningOp<mlir::memref::CastOp>(); 1143 if (cast) { 1144 operand.set(cast.getOperand()); 1145 folded = true; 1146 } 1147 } 1148 return success(folded); 1149 } 1150 1151 LogicalResult MemcpyOp::fold(ArrayRef<Attribute> operands, 1152 SmallVectorImpl<::mlir::OpFoldResult> &results) { 1153 return foldMemRefCast(*this); 1154 } 1155 1156 LogicalResult MemsetOp::fold(ArrayRef<Attribute> operands, 1157 SmallVectorImpl<::mlir::OpFoldResult> &results) { 1158 return foldMemRefCast(*this); 1159 } 1160 1161 //===----------------------------------------------------------------------===// 1162 // GPU_AllocOp 1163 //===----------------------------------------------------------------------===// 1164 namespace { 1165 1166 /// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to 1167 /// `memref::AllocOp`. 1168 struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> { 1169 using OpRewritePattern<memref::DimOp>::OpRewritePattern; 1170 1171 LogicalResult matchAndRewrite(memref::DimOp dimOp, 1172 PatternRewriter &rewriter) const override { 1173 auto index = dimOp.index().getDefiningOp<arith::ConstantIndexOp>(); 1174 if (!index) 1175 return failure(); 1176 1177 auto memrefType = dimOp.source().getType().dyn_cast<MemRefType>(); 1178 if (!memrefType || !memrefType.isDynamicDim(index.value())) 1179 return failure(); 1180 1181 auto alloc = dimOp.source().getDefiningOp<AllocOp>(); 1182 if (!alloc) 1183 return failure(); 1184 1185 Value substituteOp = *(alloc.dynamicSizes().begin() + 1186 memrefType.getDynamicDimIndex(index.value())); 1187 rewriter.replaceOp(dimOp, substituteOp); 1188 return success(); 1189 } 1190 }; 1191 1192 } // namespace 1193 1194 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results, 1195 MLIRContext *context) { 1196 results.add<SimplifyDimOfAllocOp>(context); 1197 } 1198 1199 #include "mlir/Dialect/GPU/GPUOpInterfaces.cpp.inc" 1200 #include "mlir/Dialect/GPU/GPUOpsEnums.cpp.inc" 1201 1202 #define GET_ATTRDEF_CLASSES 1203 #include "mlir/Dialect/GPU/GPUOpsAttributes.cpp.inc" 1204 1205 #define GET_OP_CLASSES 1206 #include "mlir/Dialect/GPU/GPUOps.cpp.inc" 1207