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