| 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/IR/GPUDialect.h" |
| 14 | |
| 15 | #include "mlir/Bytecode/Encoding.h" |
| 16 | #include "mlir/Dialect/Arith/IR/Arith.h" |
| 17 | #include "mlir/Dialect/Bufferization/IR/BufferDeallocationOpInterface.h" |
| 18 | #include "mlir/Dialect/Math/IR/Math.h" |
| 19 | #include "mlir/Dialect/MemRef/IR/MemRef.h" |
| 20 | #include "mlir/Dialect/Utils/VerificationUtils.h" |
| 21 | #include "mlir/IR/Attributes.h" |
| 22 | #include "mlir/IR/Builders.h" |
| 23 | #include "mlir/IR/BuiltinAttributes.h" |
| 24 | #include "mlir/IR/BuiltinOps.h" |
| 25 | #include "mlir/IR/BuiltinTypes.h" |
| 26 | #include "mlir/IR/Diagnostics.h" |
| 27 | #include "mlir/IR/DialectImplementation.h" |
| 28 | #include "mlir/IR/Matchers.h" |
| 29 | #include "mlir/IR/OpImplementation.h" |
| 30 | #include "mlir/IR/PatternMatch.h" |
| 31 | #include "mlir/IR/SymbolTable.h" |
| 32 | #include "mlir/IR/TypeUtilities.h" |
| 33 | #include "mlir/Interfaces/FunctionImplementation.h" |
| 34 | #include "mlir/Interfaces/SideEffectInterfaces.h" |
| 35 | #include "mlir/Interfaces/ValueBoundsOpInterface.h" |
| 36 | #include "mlir/Transforms/InliningUtils.h" |
| 37 | #include "llvm/ADT/STLExtras.h" |
| 38 | #include "llvm/ADT/TypeSwitch.h" |
| 39 | #include "llvm/Support/ErrorHandling.h" |
| 40 | #include "llvm/Support/FormatVariadic.h" |
| 41 | #include "llvm/Support/InterleavedRange.h" |
| 42 | #include <cassert> |
| 43 | #include <numeric> |
| 44 | #include <optional> |
| 45 | |
| 46 | using namespace mlir; |
| 47 | using namespace mlir::gpu; |
| 48 | |
| 49 | #include "mlir/Dialect/GPU/IR/GPUOpsDialect.cpp.inc" |
| 50 | |
| 51 | namespace { |
| 52 | // Attribute storage definitions live in MLIRGPUBase. Keep interface metadata |
| 53 | // here: some attribute interfaces build GPU/Arith/Math IR, and their models |
| 54 | // belong with the operation implementation rather than the representations. |
| 55 | template <typename... Attrs> |
| 56 | void registerAttributeMetadata( |
| 57 | Dialect &dialect, |
| 58 | function_ref<void(TypeID, AbstractAttribute &&)> addAttribute) { |
| 59 | (addAttribute(Attrs::getTypeID(), AbstractAttribute::get<Attrs>(dialect)), |
| 60 | ...); |
| 61 | } |
| 62 | |
| 63 | struct GPUDialectBytecodeInterface : BytecodeDialectInterface { |
| 64 | using BytecodeDialectInterface::BytecodeDialectInterface; |
| 65 | |
| 66 | void writeVersion(DialectBytecodeWriter &writer) const override { |
| 67 | writer.writeVarInt(value: 1); |
| 68 | } |
| 69 | |
| 70 | std::unique_ptr<DialectVersion> |
| 71 | readVersion(DialectBytecodeReader &reader) const override { |
| 72 | uint64_t version; |
| 73 | if (failed(Result: reader.readVarInt(result&: version))) |
| 74 | return nullptr; |
| 75 | if (version != 1) { |
| 76 | reader.emitError(msg: "unsupported gpu dialect bytecode version" ); |
| 77 | return nullptr; |
| 78 | } |
| 79 | return std::make_unique<DialectVersion>(); |
| 80 | } |
| 81 | }; |
| 82 | } // namespace |
| 83 | |
| 84 | int64_t GPUMappingMaskAttr::getMaxNumPhysicalIds() const { return 64; } |
| 85 | |
| 86 | /// 8 4 0 |
| 87 | /// Example mask : 0 0 0 1 1 0 1 0 0 |
| 88 | /// |
| 89 | /// Active physical (resp. logical) is 2 (0), 4 (1) and 5 (2). |
| 90 | /// Logical id for e.g. 5 (2) constructs filter (1 << 5 - 1). |
| 91 | /// |
| 92 | /// Example mask : 0 0 0 1 1 0 1 0 0 |
| 93 | /// Example filter: 0 0 0 0 1 1 1 1 1 |
| 94 | /// Intersection : 0 0 0 0 1 0 1 0 0 |
| 95 | /// PopCnt : 2 |
| 96 | Value GPUMappingMaskAttr::createLogicalLinearMappingId( |
| 97 | OpBuilder &b, Value physicalLinearMappingId) const { |
| 98 | Location loc = physicalLinearMappingId.getLoc(); |
| 99 | Value mask = |
| 100 | arith::ConstantOp::create(builder&: b, location: loc, value: b.getI64IntegerAttr(value: getMask())); |
| 101 | Value one = arith::ConstantOp::create(builder&: b, location: loc, value: b.getI64IntegerAttr(value: 1)); |
| 102 | Value filter = arith::ShLIOp::create(builder&: b, location: loc, lhs: one, rhs: physicalLinearMappingId); |
| 103 | filter = arith::SubIOp::create(builder&: b, location: loc, lhs: filter, rhs: one); |
| 104 | Value filteredId = arith::AndIOp::create(builder&: b, location: loc, lhs: mask, rhs: filter); |
| 105 | return math::CtPopOp::create(builder&: b, location: loc, operand: filteredId); |
| 106 | } |
| 107 | |
| 108 | /// 8 4 0 |
| 109 | /// Example mask : 0 0 0 1 1 0 1 0 0 |
| 110 | /// |
| 111 | /// Active physical (resp. logical) is 2 (0), 4 (1) and 5 (2). |
| 112 | /// Logical id for e.g. 5 (2) constructs filter (1 << 5). |
| 113 | /// |
| 114 | /// Example mask : 0 0 0 1 1 0 1 0 0 |
| 115 | /// Example filter: 0 0 0 1 0 0 0 0 0 |
| 116 | /// Intersection : 0 0 0 1 0 0 0 0 0 |
| 117 | /// Cmp : 1 |
| 118 | Value GPUMappingMaskAttr::createIsActiveIdPredicate( |
| 119 | OpBuilder &b, Value physicalLinearMappingId) const { |
| 120 | Location loc = physicalLinearMappingId.getLoc(); |
| 121 | Value mask = |
| 122 | arith::ConstantOp::create(builder&: b, location: loc, value: b.getI64IntegerAttr(value: getMask())); |
| 123 | Value one = arith::ConstantOp::create(builder&: b, location: loc, value: b.getI64IntegerAttr(value: 1)); |
| 124 | Value filter = arith::ShLIOp::create(builder&: b, location: loc, lhs: one, rhs: physicalLinearMappingId); |
| 125 | Value filtered = arith::AndIOp::create(builder&: b, location: loc, lhs: mask, rhs: filter); |
| 126 | Value zero = arith::ConstantOp::create(builder&: b, location: loc, value: b.getI64IntegerAttr(value: 0)); |
| 127 | return arith::CmpIOp::create(builder&: b, location: loc, predicate: arith::CmpIPredicate::ne, lhs: filtered, |
| 128 | rhs: zero); |
| 129 | } |
| 130 | |
| 131 | bool GPUDialect::isKernel(Operation *op) { |
| 132 | if (auto gpuFunc = dyn_cast<GPUFuncOp>(Val: op)) |
| 133 | return gpuFunc.isKernel(); |
| 134 | return static_cast<bool>( |
| 135 | op->getDiscardableAttrOfType<UnitAttr>(name: getKernelFuncAttrName())); |
| 136 | } |
| 137 | |
| 138 | namespace { |
| 139 | /// This class defines the interface for handling inlining with gpu |
| 140 | /// operations. |
| 141 | struct GPUInlinerInterface : public DialectInlinerInterface { |
| 142 | using DialectInlinerInterface::DialectInlinerInterface; |
| 143 | |
| 144 | /// All gpu dialect ops can be inlined. |
| 145 | bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final { |
| 146 | return true; |
| 147 | } |
| 148 | }; |
| 149 | } // namespace |
| 150 | |
| 151 | void GPUDialect::initialize() { |
| 152 | addInterfaces<GPUDialectBytecodeInterface>(); |
| 153 | addTypes<AsyncTokenType>(); |
| 154 | addTypes<MMAMatrixType>(); |
| 155 | addTypes<NamedBarrierType>(); |
| 156 | addTypes<SparseDnTensorHandleType>(); |
| 157 | addTypes<SparseSpMatHandleType>(); |
| 158 | addTypes<SparseSpGEMMOpHandleType>(); |
| 159 | addOperations< |
| 160 | #define GET_OP_LIST |
| 161 | #include "mlir/Dialect/GPU/IR/GPUOps.cpp.inc" |
| 162 | >(); |
| 163 | // Match addAttributes while keeping the storage and interface instantiations |
| 164 | // in their respective implementation libraries. |
| 165 | registerAttributeMetadata< |
| 166 | #define GET_ATTRDEF_LIST |
| 167 | #include "mlir/Dialect/GPU/IR/GPUOpsAttributes.cpp.inc" |
| 168 | >(dialect&: *this, addAttribute: [this](TypeID id, AbstractAttribute &&attribute) { |
| 169 | addAttribute(typeID: id, attrInfo: std::move(attribute)); |
| 170 | }); |
| 171 | gpu::detail::registerAttributeStorage(context: getContext()); |
| 172 | addInterfaces<GPUInlinerInterface>(); |
| 173 | declarePromisedInterface<bufferization::BufferDeallocationOpInterface, |
| 174 | TerminatorOp>(); |
| 175 | declarePromisedInterfaces<ValueBoundsOpInterface, ClusterDimOp, |
| 176 | ClusterDimBlocksOp, ClusterIdOp, ClusterBlockIdOp, |
| 177 | BlockDimOp, BlockIdOp, GridDimOp, ThreadIdOp, |
| 178 | LaneIdOp, SubgroupIdOp, GlobalIdOp, NumSubgroupsOp, |
| 179 | SubgroupSizeOp, LaunchOp, SubgroupBroadcastOp>(); |
| 180 | declarePromisedInterfaces<memref::IndexedAccessOpInterface, |
| 181 | SubgroupMmaLoadMatrixOp, |
| 182 | SubgroupMmaStoreMatrixOp>(); |
| 183 | } |
| 184 | |
| 185 | static std::string getSparseHandleKeyword(SparseHandleKind kind) { |
| 186 | switch (kind) { |
| 187 | case SparseHandleKind::DnTensor: |
| 188 | return "sparse.dntensor_handle" ; |
| 189 | case SparseHandleKind::SpMat: |
| 190 | return "sparse.spmat_handle" ; |
| 191 | case SparseHandleKind::SpGEMMOp: |
| 192 | return "sparse.spgemmop_handle" ; |
| 193 | } |
| 194 | llvm_unreachable("unknown sparse handle kind" ); |
| 195 | return "" ; |
| 196 | } |
| 197 | |
| 198 | Type GPUDialect::parseType(DialectAsmParser &parser) const { |
| 199 | // Parse the main keyword for the type. |
| 200 | StringRef keyword; |
| 201 | if (parser.parseKeyword(keyword: &keyword)) |
| 202 | return Type(); |
| 203 | MLIRContext *context = getContext(); |
| 204 | |
| 205 | // Handle 'async token' types. |
| 206 | if (keyword == "async.token" ) |
| 207 | return AsyncTokenType::get(ctx: context); |
| 208 | |
| 209 | if (keyword == "mma_matrix" ) { |
| 210 | SMLoc beginLoc = parser.getNameLoc(); |
| 211 | |
| 212 | // Parse '<'. |
| 213 | if (parser.parseLess()) |
| 214 | return nullptr; |
| 215 | |
| 216 | // Parse the size and elementType. |
| 217 | SmallVector<int64_t> shape; |
| 218 | Type elementType; |
| 219 | if (parser.parseDimensionList(dimensions&: shape, /*allowDynamic=*/false) || |
| 220 | parser.parseType(result&: elementType)) |
| 221 | return nullptr; |
| 222 | |
| 223 | // Parse ',' |
| 224 | if (parser.parseComma()) |
| 225 | return nullptr; |
| 226 | |
| 227 | // Parse operand. |
| 228 | std::string operand; |
| 229 | if (failed(Result: parser.parseOptionalString(string: &operand))) |
| 230 | return nullptr; |
| 231 | |
| 232 | // Parse '>'. |
| 233 | if (parser.parseGreater()) |
| 234 | return nullptr; |
| 235 | |
| 236 | return MMAMatrixType::getChecked(emitError: mlir::detail::getDefaultDiagnosticEmitFn( |
| 237 | loc: parser.getEncodedSourceLoc(loc: beginLoc)), |
| 238 | shape, elementType, operand); |
| 239 | } |
| 240 | |
| 241 | if (keyword == "named_barrier" ) |
| 242 | return NamedBarrierType::get(ctx: context); |
| 243 | |
| 244 | if (keyword == getSparseHandleKeyword(kind: SparseHandleKind::DnTensor)) |
| 245 | return SparseDnTensorHandleType::get(ctx: context); |
| 246 | if (keyword == getSparseHandleKeyword(kind: SparseHandleKind::SpMat)) |
| 247 | return SparseSpMatHandleType::get(ctx: context); |
| 248 | if (keyword == getSparseHandleKeyword(kind: SparseHandleKind::SpGEMMOp)) |
| 249 | return SparseSpGEMMOpHandleType::get(ctx: context); |
| 250 | |
| 251 | parser.emitError(loc: parser.getNameLoc(), message: "unknown gpu type: " + keyword); |
| 252 | return Type(); |
| 253 | } |
| 254 | // TODO: print refined type here. Notice that should be corresponding to the |
| 255 | // parser |
| 256 | void GPUDialect::printType(Type type, DialectAsmPrinter &os) const { |
| 257 | TypeSwitch<Type>(type) |
| 258 | .Case<AsyncTokenType>(caseFn: [&](Type) { os << "async.token" ; }) |
| 259 | .Case<NamedBarrierType>(caseFn: [&](Type) { os << "named_barrier" ; }) |
| 260 | .Case<SparseDnTensorHandleType>(caseFn: [&](Type) { |
| 261 | os << getSparseHandleKeyword(kind: SparseHandleKind::DnTensor); |
| 262 | }) |
| 263 | .Case<SparseSpMatHandleType>( |
| 264 | caseFn: [&](Type) { os << getSparseHandleKeyword(kind: SparseHandleKind::SpMat); }) |
| 265 | .Case<SparseSpGEMMOpHandleType>(caseFn: [&](Type) { |
| 266 | os << getSparseHandleKeyword(kind: SparseHandleKind::SpGEMMOp); |
| 267 | }) |
| 268 | .Case(caseFn: [&](MMAMatrixType fragTy) { |
| 269 | os << "mma_matrix<" ; |
| 270 | auto shape = fragTy.getShape(); |
| 271 | for (auto dim = shape.begin(), e = shape.end() - 1; dim != e; ++dim) |
| 272 | os << *dim << 'x'; |
| 273 | os << shape.back() << 'x' << fragTy.getElementType(); |
| 274 | os << ", \"" << fragTy.getOperand() << "\"" << '>'; |
| 275 | }) |
| 276 | .DefaultUnreachable(message: "unexpected 'gpu' type kind" ); |
| 277 | } |
| 278 | |
| 279 | static LogicalResult verifyKnownLaunchSizeAttr(Operation *op, |
| 280 | NamedAttribute attr) { |
| 281 | auto array = dyn_cast<DenseI32ArrayAttr>(Val: attr.getValue()); |
| 282 | if (!array) |
| 283 | return op->emitOpError(message: Twine(attr.getName()) + |
| 284 | " must be a dense i32 array" ); |
| 285 | if (array.size() != 3) |
| 286 | return op->emitOpError(message: Twine(attr.getName()) + |
| 287 | " must contain exactly 3 elements" ); |
| 288 | return success(); |
| 289 | } |
| 290 | |
| 291 | LogicalResult GPUDialect::verifyOperationAttribute(Operation *op, |
| 292 | NamedAttribute attr) { |
| 293 | if (attr.getName() == getKnownBlockSizeAttrHelper().getName()) |
| 294 | return verifyKnownLaunchSizeAttr(op, attr); |
| 295 | if (attr.getName() == getKnownGridSizeAttrHelper().getName()) |
| 296 | return verifyKnownLaunchSizeAttr(op, attr); |
| 297 | if (attr.getName() == getKnownClusterSizeAttrHelper().getName()) |
| 298 | return verifyKnownLaunchSizeAttr(op, attr); |
| 299 | if (!llvm::isa<UnitAttr>(Val: attr.getValue()) || |
| 300 | attr.getName() != getContainerModuleAttrName()) |
| 301 | return success(); |
| 302 | |
| 303 | auto module = dyn_cast<ModuleOp>(Val: op); |
| 304 | if (!module) |
| 305 | return op->emitError(message: "expected '" ) |
| 306 | << getContainerModuleAttrName() << "' attribute to be attached to '" |
| 307 | << ModuleOp::getOperationName() << '\''; |
| 308 | return success(); |
| 309 | } |
| 310 | |
| 311 | /// Parses an optional list of async operands with an optional leading keyword. |
| 312 | /// (`async`)? (`[` ssa-id-list `]`)? |
| 313 | /// |
| 314 | /// This method is used by the tablegen assembly format for async ops as well. |
| 315 | static ParseResult parseAsyncDependencies( |
| 316 | OpAsmParser &parser, Type &asyncTokenType, |
| 317 | SmallVectorImpl<OpAsmParser::UnresolvedOperand> &asyncDependencies) { |
| 318 | auto loc = parser.getCurrentLocation(); |
| 319 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "async" ))) { |
| 320 | if (parser.getNumResults() == 0) |
| 321 | return parser.emitError(loc, message: "needs to be named when marked 'async'" ); |
| 322 | asyncTokenType = parser.getBuilder().getType<AsyncTokenType>(); |
| 323 | } |
| 324 | return parser.parseOperandList(result&: asyncDependencies, |
| 325 | delimiter: OpAsmParser::Delimiter::OptionalSquare); |
| 326 | } |
| 327 | |
| 328 | /// Prints optional async dependencies with its leading keyword. |
| 329 | /// (`async`)? (`[` ssa-id-list `]`)? |
| 330 | // Used by the tablegen assembly format for several async ops. |
| 331 | static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op, |
| 332 | Type asyncTokenType, |
| 333 | OperandRange asyncDependencies) { |
| 334 | if (asyncTokenType) |
| 335 | printer << "async" ; |
| 336 | if (asyncDependencies.empty()) |
| 337 | return; |
| 338 | if (asyncTokenType) |
| 339 | printer << ' '; |
| 340 | printer << llvm::interleaved_array(R: asyncDependencies); |
| 341 | } |
| 342 | |
| 343 | // GPU Memory attributions functions shared by LaunchOp and GPUFuncOp. |
| 344 | /// Parses a GPU function memory attribution. |
| 345 | /// |
| 346 | /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)? |
| 347 | /// (`private` `(` ssa-id-and-type-list `)`)? |
| 348 | /// |
| 349 | /// Note that this function parses only one of the two similar parts, with the |
| 350 | /// keyword provided as argument. |
| 351 | static ParseResult |
| 352 | parseAttributions(OpAsmParser &parser, StringRef keyword, |
| 353 | SmallVectorImpl<OpAsmParser::Argument> &args) { |
| 354 | // If we could not parse the keyword, just assume empty list and succeed. |
| 355 | if (failed(Result: parser.parseOptionalKeyword(keyword))) |
| 356 | return success(); |
| 357 | |
| 358 | return parser.parseArgumentList(result&: args, delimiter: OpAsmParser::Delimiter::Paren, |
| 359 | /*allowType=*/true); |
| 360 | } |
| 361 | |
| 362 | static void printAttributions(OpAsmPrinter &p, StringRef keyword, |
| 363 | ArrayRef<BlockArgument> values, |
| 364 | ArrayAttr attributes = {}) { |
| 365 | if (values.empty()) |
| 366 | return; |
| 367 | |
| 368 | p << ' ' << keyword << '('; |
| 369 | llvm::interleaveComma( |
| 370 | c: llvm::enumerate(First&: values), os&: p, each_fn: [&p, attributes](auto pair) { |
| 371 | BlockArgument v = pair.value(); |
| 372 | p << v << " : " << v.getType(); |
| 373 | |
| 374 | size_t attributionIndex = pair.index(); |
| 375 | DictionaryAttr attrs; |
| 376 | if (attributes && attributionIndex < attributes.size()) |
| 377 | attrs = llvm::cast<DictionaryAttr>(Val: attributes[attributionIndex]); |
| 378 | if (attrs) |
| 379 | p.printOptionalAttrDict(attrs: attrs.getValue()); |
| 380 | }); |
| 381 | p << ')'; |
| 382 | } |
| 383 | |
| 384 | /// Verifies a GPU function memory attribution. |
| 385 | static LogicalResult verifyAttributions(Operation *op, |
| 386 | ArrayRef<BlockArgument> attributions, |
| 387 | gpu::AddressSpace memorySpace) { |
| 388 | for (Value v : attributions) { |
| 389 | auto type = llvm::dyn_cast<MemRefType>(Val: v.getType()); |
| 390 | if (!type) |
| 391 | return op->emitOpError() << "expected memref type in attribution" ; |
| 392 | |
| 393 | // We can only verify the address space if it hasn't already been lowered |
| 394 | // from the AddressSpaceAttr to a target-specific numeric value. |
| 395 | auto addressSpace = |
| 396 | llvm::dyn_cast_or_null<gpu::AddressSpaceAttr>(Val: type.getMemorySpace()); |
| 397 | if (!addressSpace) |
| 398 | continue; |
| 399 | if (addressSpace.getValue() != memorySpace) |
| 400 | return op->emitOpError() |
| 401 | << "expected memory space " << stringifyAddressSpace(memorySpace) |
| 402 | << " in attribution" ; |
| 403 | } |
| 404 | return success(); |
| 405 | } |
| 406 | |
| 407 | //===----------------------------------------------------------------------===// |
| 408 | // AllReduceOp |
| 409 | //===----------------------------------------------------------------------===// |
| 410 | |
| 411 | static LogicalResult verifyReduceOpAndType(gpu::AllReduceOperation opName, |
| 412 | Type resType) { |
| 413 | using Kind = gpu::AllReduceOperation; |
| 414 | if (llvm::is_contained(Set: {Kind::MINNUMF, Kind::MAXNUMF, Kind::MINIMUMF, |
| 415 | Kind::MAXIMUMF, Kind::MINIMUMNUMF, Kind::MAXIMUMNUMF}, |
| 416 | Element: opName)) { |
| 417 | if (!isa<FloatType>(Val: resType)) |
| 418 | return failure(); |
| 419 | } |
| 420 | |
| 421 | if (llvm::is_contained(Set: {Kind::MINSI, Kind::MINUI, Kind::MAXSI, Kind::MAXUI, |
| 422 | Kind::AND, Kind::OR, Kind::XOR}, |
| 423 | Element: opName)) { |
| 424 | if (!isa<IntegerType>(Val: resType)) |
| 425 | return failure(); |
| 426 | } |
| 427 | |
| 428 | return success(); |
| 429 | } |
| 430 | |
| 431 | LogicalResult gpu::AllReduceOp::verifyRegions() { |
| 432 | if (getBody().empty() != getOp().has_value()) |
| 433 | return emitError(message: "expected either an op attribute or a non-empty body" ); |
| 434 | if (!getBody().empty()) { |
| 435 | if (getBody().getNumArguments() != 2) |
| 436 | return emitError(message: "expected two region arguments" ); |
| 437 | for (auto argument : getBody().getArguments()) { |
| 438 | if (argument.getType() != getType()) |
| 439 | return emitError(message: "incorrect region argument type" ); |
| 440 | } |
| 441 | unsigned yieldCount = 0; |
| 442 | for (Block &block : getBody()) { |
| 443 | if (auto yield = dyn_cast<gpu::YieldOp>(Val: block.getTerminator())) { |
| 444 | if (yield.getNumOperands() != 1) |
| 445 | return emitError(message: "expected one gpu.yield operand" ); |
| 446 | if (yield.getOperand(i: 0).getType() != getType()) |
| 447 | return emitError(message: "incorrect gpu.yield type" ); |
| 448 | ++yieldCount; |
| 449 | } |
| 450 | } |
| 451 | if (yieldCount == 0) |
| 452 | return emitError(message: "expected gpu.yield op in region" ); |
| 453 | } else { |
| 454 | gpu::AllReduceOperation opName = *getOp(); |
| 455 | if (failed(Result: verifyReduceOpAndType(opName, resType: getType()))) { |
| 456 | return emitError() << '`' << gpu::stringifyAllReduceOperation(opName) |
| 457 | << "` reduction operation is not compatible with type " |
| 458 | << getType(); |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | return success(); |
| 463 | } |
| 464 | |
| 465 | static bool canMakeGroupOpUniform(Operation *op) { |
| 466 | auto launchOp = dyn_cast<gpu::LaunchOp>(Val: op->getParentOp()); |
| 467 | if (!launchOp) |
| 468 | return false; |
| 469 | |
| 470 | Region &body = launchOp.getBody(); |
| 471 | assert(!body.empty() && "Invalid region" ); |
| 472 | |
| 473 | // Only convert ops in gpu::launch entry block for now. |
| 474 | return op->getBlock() == &body.front(); |
| 475 | } |
| 476 | |
| 477 | OpFoldResult gpu::AllReduceOp::fold(FoldAdaptor /*adaptor*/) { |
| 478 | if (!getUniform() && canMakeGroupOpUniform(op: *this)) { |
| 479 | setUniform(true); |
| 480 | return getResult(); |
| 481 | } |
| 482 | |
| 483 | return nullptr; |
| 484 | } |
| 485 | |
| 486 | //===----------------------------------------------------------------------===// |
| 487 | // SubgroupReduceOp |
| 488 | //===----------------------------------------------------------------------===// |
| 489 | |
| 490 | LogicalResult gpu::SubgroupReduceOp::verify() { |
| 491 | Type elemType = getType(); |
| 492 | if (auto vecTy = dyn_cast<VectorType>(Val&: elemType)) { |
| 493 | if (vecTy.isScalable()) |
| 494 | return emitOpError() << "is not compatible with scalable vector types" ; |
| 495 | |
| 496 | elemType = vecTy.getElementType(); |
| 497 | } |
| 498 | |
| 499 | gpu::AllReduceOperation opName = getOp(); |
| 500 | if (failed(Result: verifyReduceOpAndType(opName, resType: elemType))) { |
| 501 | return emitError() << '`' << gpu::stringifyAllReduceOperation(opName) |
| 502 | << "` reduction operation is not compatible with type " |
| 503 | << getType(); |
| 504 | } |
| 505 | |
| 506 | auto clusterSize = getClusterSize(); |
| 507 | if (clusterSize) { |
| 508 | uint32_t size = *clusterSize; |
| 509 | if (!llvm::isPowerOf2_32(Value: size)) { |
| 510 | return emitOpError() << "cluster size " << size |
| 511 | << " is not a power of two" ; |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | uint32_t stride = getClusterStride(); |
| 516 | if (stride != 1 && !clusterSize) { |
| 517 | return emitOpError() << "cluster stride can only be specified if cluster " |
| 518 | "size is specified" ; |
| 519 | } |
| 520 | if (!llvm::isPowerOf2_32(Value: stride)) { |
| 521 | return emitOpError() << "cluster stride " << stride |
| 522 | << " is not a power of two" ; |
| 523 | } |
| 524 | |
| 525 | return success(); |
| 526 | } |
| 527 | |
| 528 | OpFoldResult gpu::SubgroupReduceOp::fold(FoldAdaptor /*adaptor*/) { |
| 529 | if (getClusterSize() == 1) |
| 530 | return getValue(); |
| 531 | |
| 532 | if (!getUniform() && canMakeGroupOpUniform(op: *this)) { |
| 533 | setUniform(true); |
| 534 | return getResult(); |
| 535 | } |
| 536 | |
| 537 | return nullptr; |
| 538 | } |
| 539 | |
| 540 | //===----------------------------------------------------------------------===// |
| 541 | // AsyncOpInterface |
| 542 | //===----------------------------------------------------------------------===// |
| 543 | |
| 544 | void gpu::addAsyncDependency(Operation *op, Value token) { |
| 545 | op->insertOperands(index: 0, operands: {token}); |
| 546 | if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>()) |
| 547 | return; |
| 548 | auto attrName = |
| 549 | OpTrait::AttrSizedOperandSegments<void>::getOperandSegmentSizeAttr(); |
| 550 | auto sizeAttr = dyn_cast_or_null<DenseI32ArrayAttr>( |
| 551 | Val: op->getInherentAttr(name: attrName).value_or(u: Attribute{})); |
| 552 | |
| 553 | // Async dependencies is the only variadic operand. |
| 554 | if (!sizeAttr) |
| 555 | return; |
| 556 | |
| 557 | SmallVector<int32_t, 8> sizes(sizeAttr.asArrayRef()); |
| 558 | ++sizes.front(); |
| 559 | op->setInherentAttr(name: StringAttr::get(context: op->getContext(), bytes: attrName), |
| 560 | value: Builder(op->getContext()).getDenseI32ArrayAttr(values: sizes)); |
| 561 | } |
| 562 | |
| 563 | //===----------------------------------------------------------------------===// |
| 564 | // LaunchOp |
| 565 | //===----------------------------------------------------------------------===// |
| 566 | |
| 567 | void LaunchOp::build(OpBuilder &builder, OperationState &result, |
| 568 | Value gridSizeX, Value gridSizeY, Value gridSizeZ, |
| 569 | Value getBlockSizeX, Value getBlockSizeY, |
| 570 | Value getBlockSizeZ, Value dynamicSharedMemorySize, |
| 571 | Type asyncTokenType, ValueRange asyncDependencies, |
| 572 | Value asyncObject, TypeRange workgroupAttributions, |
| 573 | TypeRange privateAttributions, Value clusterSizeX, |
| 574 | Value clusterSizeY, Value clusterSizeZ, |
| 575 | FlatSymbolRefAttr module, FlatSymbolRefAttr function) { |
| 576 | OpBuilder::InsertionGuard g(builder); |
| 577 | |
| 578 | if (!workgroupAttributions.empty()) |
| 579 | result.addAttribute( |
| 580 | name: getWorkgroupAttributionsAttrName(name: result.name), |
| 581 | attr: builder.getI64IntegerAttr(value: workgroupAttributions.size())); |
| 582 | |
| 583 | // Add Op operands. |
| 584 | result.addOperands(newOperands: asyncDependencies); |
| 585 | if (asyncTokenType) |
| 586 | result.types.push_back(Elt: builder.getType<AsyncTokenType>()); |
| 587 | |
| 588 | // Add grid and block sizes as op operands, followed by the data operands. |
| 589 | result.addOperands(newOperands: {gridSizeX, gridSizeY, gridSizeZ, getBlockSizeX, |
| 590 | getBlockSizeY, getBlockSizeZ}); |
| 591 | if (clusterSizeX) |
| 592 | result.addOperands(newOperands: clusterSizeX); |
| 593 | if (clusterSizeY) |
| 594 | result.addOperands(newOperands: clusterSizeY); |
| 595 | if (clusterSizeZ) |
| 596 | result.addOperands(newOperands: clusterSizeZ); |
| 597 | if (dynamicSharedMemorySize) |
| 598 | result.addOperands(newOperands: dynamicSharedMemorySize); |
| 599 | if (asyncObject) |
| 600 | result.addOperands(newOperands: asyncObject); |
| 601 | |
| 602 | // Add optional module and function attributes. |
| 603 | if (module) |
| 604 | result.addAttribute(name: getModuleAttrName(name: result.name), attr: module); |
| 605 | if (function) |
| 606 | result.addAttribute(name: getFunctionAttrName(name: result.name), attr: function); |
| 607 | |
| 608 | // Create a kernel body region with kNumConfigRegionAttributes + N memory |
| 609 | // attributions, where the first kNumConfigRegionAttributes arguments have |
| 610 | // `index` type and the rest have the same types as the data operands. |
| 611 | Region *kernelRegion = result.addRegion(); |
| 612 | Block *body = builder.createBlock(parent: kernelRegion); |
| 613 | // TODO: Allow passing in proper locations here. |
| 614 | for (unsigned i = 0; i < kNumConfigRegionAttributes; ++i) |
| 615 | body->addArgument(type: builder.getIndexType(), loc: result.location); |
| 616 | // Add WorkGroup & Private attributions to the region arguments. |
| 617 | for (Type argTy : workgroupAttributions) |
| 618 | body->addArgument(type: argTy, loc: result.location); |
| 619 | for (Type argTy : privateAttributions) |
| 620 | body->addArgument(type: argTy, loc: result.location); |
| 621 | // Fill OperandSegmentSize Attribute. |
| 622 | SmallVector<int32_t, 12> segmentSizes(12, 1); |
| 623 | segmentSizes.front() = asyncDependencies.size(); |
| 624 | segmentSizes[7] = clusterSizeX ? 1 : 0; |
| 625 | segmentSizes[8] = clusterSizeY ? 1 : 0; |
| 626 | segmentSizes[9] = clusterSizeZ ? 1 : 0; |
| 627 | segmentSizes[10] = dynamicSharedMemorySize ? 1 : 0; |
| 628 | segmentSizes[11] = asyncObject ? 1 : 0; |
| 629 | result.addAttribute(name: getOperandSegmentSizeAttr(), |
| 630 | attr: builder.getDenseI32ArrayAttr(values: segmentSizes)); |
| 631 | } |
| 632 | |
| 633 | KernelDim3 LaunchOp::getBlockIds() { |
| 634 | assert(!getBody().empty() && "LaunchOp body must not be empty." ); |
| 635 | auto args = getBody().getArguments(); |
| 636 | return KernelDim3{.x: args[0], .y: args[1], .z: args[2]}; |
| 637 | } |
| 638 | |
| 639 | KernelDim3 LaunchOp::getThreadIds() { |
| 640 | assert(!getBody().empty() && "LaunchOp body must not be empty." ); |
| 641 | auto args = getBody().getArguments(); |
| 642 | return KernelDim3{.x: args[3], .y: args[4], .z: args[5]}; |
| 643 | } |
| 644 | |
| 645 | KernelDim3 LaunchOp::getGridSize() { |
| 646 | assert(!getBody().empty() && "LaunchOp body must not be empty." ); |
| 647 | auto args = getBody().getArguments(); |
| 648 | return KernelDim3{.x: args[6], .y: args[7], .z: args[8]}; |
| 649 | } |
| 650 | |
| 651 | KernelDim3 LaunchOp::getBlockSize() { |
| 652 | assert(!getBody().empty() && "LaunchOp body must not be empty." ); |
| 653 | auto args = getBody().getArguments(); |
| 654 | return KernelDim3{.x: args[9], .y: args[10], .z: args[11]}; |
| 655 | } |
| 656 | |
| 657 | std::optional<KernelDim3> LaunchOp::getClusterIds() { |
| 658 | assert(!getBody().empty() && "LaunchOp body must not be empty." ); |
| 659 | if (!hasClusterSize()) |
| 660 | return std::nullopt; |
| 661 | auto args = getBody().getArguments(); |
| 662 | return KernelDim3{.x: args[12], .y: args[13], .z: args[14]}; |
| 663 | } |
| 664 | |
| 665 | std::optional<KernelDim3> LaunchOp::getClusterSize() { |
| 666 | assert(!getBody().empty() && "LaunchOp body must not be empty." ); |
| 667 | if (!hasClusterSize()) |
| 668 | return std::nullopt; |
| 669 | auto args = getBody().getArguments(); |
| 670 | return KernelDim3{.x: args[15], .y: args[16], .z: args[17]}; |
| 671 | } |
| 672 | |
| 673 | KernelDim3 LaunchOp::getGridSizeOperandValues() { |
| 674 | auto operands = getOperands().drop_front(n: getAsyncDependencies().size()); |
| 675 | return KernelDim3{.x: operands[0], .y: operands[1], .z: operands[2]}; |
| 676 | } |
| 677 | |
| 678 | KernelDim3 LaunchOp::getBlockSizeOperandValues() { |
| 679 | auto operands = getOperands().drop_front(n: getAsyncDependencies().size()); |
| 680 | return KernelDim3{.x: operands[3], .y: operands[4], .z: operands[5]}; |
| 681 | } |
| 682 | |
| 683 | std::optional<KernelDim3> LaunchOp::getClusterSizeOperandValues() { |
| 684 | auto operands = getOperands().drop_front(n: getAsyncDependencies().size()); |
| 685 | if (!hasClusterSize()) |
| 686 | return std::nullopt; |
| 687 | return KernelDim3{.x: operands[6], .y: operands[7], .z: operands[8]}; |
| 688 | } |
| 689 | |
| 690 | template <typename OpTy> |
| 691 | static LogicalResult verifyLaunchAsyncModel(OpTy op) { |
| 692 | if (!op.getAsyncDependencies().empty() && !op.getAsyncToken()) |
| 693 | return op.emitOpError("dependency operands require the dependency-based " |
| 694 | "async model i.e. returning a token" ); |
| 695 | if (op.getAsyncToken() && op.getAsyncObject()) |
| 696 | return op.emitOpError("stream-based and dependency-based async models are " |
| 697 | "mutually exclusive" ); |
| 698 | if (op.getNumResults() == 0 && op.getAsyncToken()) |
| 699 | return op.emitOpError("needs to be named when async keyword is specified" ); |
| 700 | return success(); |
| 701 | } |
| 702 | |
| 703 | LogicalResult LaunchOp::verify() { |
| 704 | if (verifyLaunchAsyncModel(op: *this).failed()) |
| 705 | return failure(); |
| 706 | |
| 707 | if (!(hasClusterSize()) && |
| 708 | (getClusterSizeX() || getClusterSizeY() || getClusterSizeZ())) |
| 709 | return emitOpError() << "cluster size must be all present" ; |
| 710 | return success(); |
| 711 | } |
| 712 | |
| 713 | LogicalResult LaunchOp::verifyRegions() { |
| 714 | // Kernel launch takes kNumConfigOperands leading operands for grid/block |
| 715 | // sizes and transforms them into kNumConfigRegionAttributes region arguments |
| 716 | // for block/thread identifiers and grid/block sizes. |
| 717 | if (getBody().empty()) { |
| 718 | return emitOpError(message: "body region is empty" ); |
| 719 | } |
| 720 | unsigned actualNumRegionArgs = getBody().getNumArguments(); |
| 721 | unsigned expectedNumRegionArgs = |
| 722 | getNumConfigRegionAttributes() + getNumWorkgroupAttributions(); |
| 723 | if (actualNumRegionArgs < expectedNumRegionArgs) { |
| 724 | return emitOpError(message: "expected at least " ) |
| 725 | << expectedNumRegionArgs << " region arguments, but got " |
| 726 | << actualNumRegionArgs; |
| 727 | } |
| 728 | |
| 729 | // Verify Attributions Address Spaces. |
| 730 | if (failed(Result: verifyAttributions(op: getOperation(), attributions: getWorkgroupAttributionBBArgs(), |
| 731 | memorySpace: GPUDialect::getWorkgroupAddressSpace())) || |
| 732 | failed(Result: verifyAttributions(op: getOperation(), attributions: getPrivateAttributions(), |
| 733 | memorySpace: GPUDialect::getPrivateAddressSpace()))) |
| 734 | return failure(); |
| 735 | |
| 736 | // Block terminators without successors are expected to exit the kernel region |
| 737 | // and must be `gpu.terminator`. |
| 738 | for (Block &block : getBody()) { |
| 739 | if (block.empty()) |
| 740 | continue; |
| 741 | if (block.back().getNumSuccessors() != 0) |
| 742 | continue; |
| 743 | if (!isa<gpu::TerminatorOp>(Val: &block.back())) { |
| 744 | return block.back() |
| 745 | .emitError() |
| 746 | .append(args: "expected '" , args: gpu::TerminatorOp::getOperationName(), |
| 747 | args: "' or a terminator with successors" ) |
| 748 | .attachNote(noteLoc: getLoc()) |
| 749 | .append(arg1: "in '" , arg2: LaunchOp::getOperationName(), args: "' body region" ); |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | return success(); |
| 754 | } |
| 755 | |
| 756 | // Pretty-print the kernel grid/block size assignment as |
| 757 | // (%iter-x, %iter-y, %iter-z) in |
| 758 | // (%size-x = %ssa-use, %size-y = %ssa-use, %size-z = %ssa-use) |
| 759 | // where %size-* and %iter-* will correspond to the body region arguments. |
| 760 | static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size, |
| 761 | KernelDim3 operands, KernelDim3 ids) { |
| 762 | p << '(' << ids.x << ", " << ids.y << ", " << ids.z << ") in (" ; |
| 763 | p << size.x << " = " << operands.x << ", " ; |
| 764 | p << size.y << " = " << operands.y << ", " ; |
| 765 | p << size.z << " = " << operands.z << ')'; |
| 766 | } |
| 767 | |
| 768 | void LaunchOp::print(OpAsmPrinter &p) { |
| 769 | if (auto asyncObject = getAsyncObject()) { |
| 770 | p << " <" << asyncObject << " : " << asyncObject.getType() << ">" ; |
| 771 | } |
| 772 | if (getAsyncToken()) { |
| 773 | p << " async" ; |
| 774 | if (!getAsyncDependencies().empty()) |
| 775 | p << " [" << getAsyncDependencies() << ']'; |
| 776 | } |
| 777 | // Print the launch configuration. |
| 778 | if (hasClusterSize()) { |
| 779 | p << ' ' << getClustersKeyword(); |
| 780 | printSizeAssignment(p, size: getClusterSize().value(), |
| 781 | operands: getClusterSizeOperandValues().value(), |
| 782 | ids: getClusterIds().value()); |
| 783 | } |
| 784 | p << ' ' << getBlocksKeyword(); |
| 785 | printSizeAssignment(p, size: getGridSize(), operands: getGridSizeOperandValues(), |
| 786 | ids: getBlockIds()); |
| 787 | p << ' ' << getThreadsKeyword(); |
| 788 | printSizeAssignment(p, size: getBlockSize(), operands: getBlockSizeOperandValues(), |
| 789 | ids: getThreadIds()); |
| 790 | if (getDynamicSharedMemorySize()) |
| 791 | p << ' ' << getDynamicSharedMemorySizeKeyword() << ' ' |
| 792 | << getDynamicSharedMemorySize(); |
| 793 | |
| 794 | // Print optional module attribute. |
| 795 | StringRef moduleAttrName = getModuleAttrName(); |
| 796 | if (auto module = getModule()) { |
| 797 | p << ' ' << moduleAttrName << '('; |
| 798 | p.printSymbolName(symbolRef: *module); |
| 799 | p << ')'; |
| 800 | } |
| 801 | // Print optional function attribute. |
| 802 | StringRef functionAttrName = getFunctionAttrName(); |
| 803 | if (auto function = getFunction()) { |
| 804 | p << ' ' << functionAttrName << '('; |
| 805 | p.printSymbolName(symbolRef: *function); |
| 806 | p << ')'; |
| 807 | } |
| 808 | |
| 809 | if (getCooperative()) |
| 810 | p << " cooperative" ; |
| 811 | |
| 812 | printAttributions(p, keyword: getWorkgroupKeyword(), values: getWorkgroupAttributionBBArgs()); |
| 813 | printAttributions(p, keyword: getPrivateKeyword(), values: getPrivateAttributions()); |
| 814 | |
| 815 | p << ' '; |
| 816 | |
| 817 | p.printRegion(blocks&: getBody(), /*printEntryBlockArgs=*/false); |
| 818 | p.printOptionalAttrDict( |
| 819 | attrs: (*this)->getDiscardableAttrDictionary().getValue(), /*elidedAttrs=*/{ |
| 820 | LaunchOp::getOperandSegmentSizeAttr(), |
| 821 | getWorkgroupAttributionsAttrName(), getCooperativeAttrName(), |
| 822 | moduleAttrName, functionAttrName}); |
| 823 | } |
| 824 | |
| 825 | // Parse the size assignment blocks for blocks and threads. These have the form |
| 826 | // (%region_arg, %region_arg, %region_arg) in |
| 827 | // (%region_arg = %operand, %region_arg = %operand, %region_arg = %operand) |
| 828 | // where %region_arg are percent-identifiers for the region arguments to be |
| 829 | // introduced further (SSA defs), and %operand are percent-identifiers for the |
| 830 | // SSA value uses. |
| 831 | static ParseResult |
| 832 | parseSizeAssignment(OpAsmParser &parser, |
| 833 | MutableArrayRef<OpAsmParser::UnresolvedOperand> sizes, |
| 834 | MutableArrayRef<OpAsmParser::UnresolvedOperand> regionSizes, |
| 835 | MutableArrayRef<OpAsmParser::UnresolvedOperand> indices, |
| 836 | StringRef keyword) { |
| 837 | assert(indices.size() == 3 && "space for three indices expected" ); |
| 838 | SmallVector<OpAsmParser::UnresolvedOperand, 3> args; |
| 839 | if (parser.parseOperandList(result&: args, delimiter: OpAsmParser::Delimiter::Paren, |
| 840 | /*allowResultNumber=*/false) || |
| 841 | parser.parseKeyword(keyword: "in" ) || parser.parseLParen()) |
| 842 | return failure(); |
| 843 | |
| 844 | if (args.size() != 3) { |
| 845 | return parser.emitError(loc: parser.getNameLoc()) |
| 846 | << keyword << " expects 3 arguments, but got " << args.size(); |
| 847 | } |
| 848 | std::move(first: args.begin(), last: args.end(), result: indices.begin()); |
| 849 | |
| 850 | for (int i = 0; i < 3; ++i) { |
| 851 | if (i != 0 && parser.parseComma()) |
| 852 | return failure(); |
| 853 | if (parser.parseOperand(result&: regionSizes[i], /*allowResultNumber=*/false) || |
| 854 | parser.parseEqual() || parser.parseOperand(result&: sizes[i])) |
| 855 | return failure(); |
| 856 | } |
| 857 | |
| 858 | return parser.parseRParen(); |
| 859 | } |
| 860 | |
| 861 | /// Parses a Launch operation. |
| 862 | /// operation ::= `gpu.launch` (`<` ssa-use `:` type `>`)? |
| 863 | /// (`async` `[` ssa-id-list `]`)? |
| 864 | /// (`clusters` `(` ssa-id-list `)` `in` ssa-reassignment)? |
| 865 | /// `blocks` `(` ssa-id-list `)` `in` ssa-reassignment |
| 866 | /// `threads` `(` ssa-id-list `)` `in` ssa-reassignment |
| 867 | /// (`dynamic_shared_memory_size` ssa-use)? |
| 868 | /// (`module(` symbol-ref-id `)`)? |
| 869 | /// (`function(` symbol-ref-id `)`)? |
| 870 | /// memory-attribution |
| 871 | /// region attr-dict? |
| 872 | /// ssa-reassignment ::= `(` ssa-id `=` ssa-use (`,` ssa-id `=` ssa-use)* `)` |
| 873 | ParseResult LaunchOp::parse(OpAsmParser &parser, OperationState &result) { |
| 874 | // Sizes of the grid and block. |
| 875 | SmallVector<OpAsmParser::UnresolvedOperand, LaunchOp::kNumConfigOperands> |
| 876 | sizes(LaunchOp::kNumConfigOperands); |
| 877 | |
| 878 | // Region arguments to be created. |
| 879 | SmallVector<OpAsmParser::UnresolvedOperand, 16> regionArgs( |
| 880 | LaunchOp::kNumConfigRegionAttributes); |
| 881 | |
| 882 | // Parse optional asyncObject: < value : type > |
| 883 | OpAsmParser::UnresolvedOperand asyncObjectOperand; |
| 884 | Type asyncObjectType; |
| 885 | bool hasAsyncObject = false; |
| 886 | if (succeeded(Result: parser.parseOptionalLess())) { |
| 887 | hasAsyncObject = true; |
| 888 | if (parser.parseOperand(result&: asyncObjectOperand) || parser.parseColon() || |
| 889 | parser.parseType(result&: asyncObjectType) || parser.parseGreater()) |
| 890 | return failure(); |
| 891 | } |
| 892 | |
| 893 | // Parse optional async dependencies. |
| 894 | SmallVector<OpAsmParser::UnresolvedOperand, 4> asyncDependencies; |
| 895 | Type asyncTokenType; |
| 896 | if (failed( |
| 897 | Result: parseAsyncDependencies(parser, asyncTokenType, asyncDependencies)) || |
| 898 | parser.resolveOperands(operands&: asyncDependencies, type: asyncTokenType, |
| 899 | result&: result.operands)) |
| 900 | return failure(); |
| 901 | if (parser.getNumResults() > 0) { |
| 902 | if (!asyncTokenType) |
| 903 | return parser.emitError( |
| 904 | loc: parser.getNameLoc(), |
| 905 | message: "gpu.launch requires 'async' keyword to return a value" ); |
| 906 | result.types.push_back(Elt: asyncTokenType); |
| 907 | } |
| 908 | |
| 909 | bool hasCluster = false; |
| 910 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: LaunchOp::getClustersKeyword()))) { |
| 911 | hasCluster = true; |
| 912 | sizes.resize(N: 9); |
| 913 | regionArgs.resize(N: 18); |
| 914 | } |
| 915 | MutableArrayRef<OpAsmParser::UnresolvedOperand> sizesRef(sizes); |
| 916 | MutableArrayRef<OpAsmParser::UnresolvedOperand> regionArgsRef(regionArgs); |
| 917 | |
| 918 | // Last three segment assigns the cluster size. In the region argument |
| 919 | // list, this is last 6 arguments. |
| 920 | if (hasCluster) { |
| 921 | if (parseSizeAssignment( |
| 922 | parser, sizes: sizesRef.drop_front(N: 6), regionSizes: regionArgsRef.slice(N: 15, M: 3), |
| 923 | indices: regionArgsRef.slice(N: 12, M: 3), keyword: LaunchOp::getClustersKeyword())) |
| 924 | return failure(); |
| 925 | } |
| 926 | // Parse the size assignment segments: the first segment assigns grid sizes |
| 927 | // and defines values for block identifiers; the second segment assigns block |
| 928 | // sizes and defines values for thread identifiers. In the region argument |
| 929 | // list, identifiers precede sizes, and block-related values precede |
| 930 | // thread-related values. |
| 931 | if (parser.parseKeyword(keyword: LaunchOp::getBlocksKeyword()) || |
| 932 | parseSizeAssignment(parser, sizes: sizesRef.take_front(N: 3), |
| 933 | regionSizes: regionArgsRef.slice(N: 6, M: 3), indices: regionArgsRef.slice(N: 0, M: 3), |
| 934 | keyword: LaunchOp::getBlocksKeyword()) || |
| 935 | parser.parseKeyword(keyword: LaunchOp::getThreadsKeyword()) || |
| 936 | parseSizeAssignment(parser, sizes: sizesRef.drop_front(N: 3), |
| 937 | regionSizes: regionArgsRef.slice(N: 9, M: 3), indices: regionArgsRef.slice(N: 3, M: 3), |
| 938 | keyword: LaunchOp::getThreadsKeyword()) || |
| 939 | parser.resolveOperands(operands&: sizes, type: parser.getBuilder().getIndexType(), |
| 940 | result&: result.operands)) |
| 941 | return failure(); |
| 942 | |
| 943 | OpAsmParser::UnresolvedOperand dynamicSharedMemorySize; |
| 944 | bool hasDynamicSharedMemorySize = false; |
| 945 | if (!parser.parseOptionalKeyword( |
| 946 | keyword: LaunchOp::getDynamicSharedMemorySizeKeyword())) { |
| 947 | hasDynamicSharedMemorySize = true; |
| 948 | if (parser.parseOperand(result&: dynamicSharedMemorySize) || |
| 949 | parser.resolveOperand(operand: dynamicSharedMemorySize, |
| 950 | type: parser.getBuilder().getI32Type(), |
| 951 | result&: result.operands)) |
| 952 | return failure(); |
| 953 | } |
| 954 | |
| 955 | // Resolve the asyncObject operand |
| 956 | if (hasAsyncObject && parser.resolveOperand(operand: asyncObjectOperand, |
| 957 | type: asyncObjectType, result&: result.operands)) |
| 958 | return failure(); |
| 959 | |
| 960 | // Parse optional module attribute. |
| 961 | StringRef moduleAttrName = getModuleAttrName(name: result.name); |
| 962 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: moduleAttrName))) { |
| 963 | FlatSymbolRefAttr moduleSymbol; |
| 964 | if (parser.parseLParen() || |
| 965 | parser.parseAttribute(result&: moduleSymbol, type: Type(), attrName: moduleAttrName, |
| 966 | attrs&: result.attributes) || |
| 967 | parser.parseRParen()) |
| 968 | return failure(); |
| 969 | } |
| 970 | // Parse optional function attribute. |
| 971 | StringRef functionAttrName = getFunctionAttrName(name: result.name); |
| 972 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: functionAttrName))) { |
| 973 | FlatSymbolRefAttr funcSymbol; |
| 974 | if (parser.parseLParen() || |
| 975 | parser.parseAttribute(result&: funcSymbol, type: Type(), attrName: functionAttrName, |
| 976 | attrs&: result.attributes) || |
| 977 | parser.parseRParen()) |
| 978 | return failure(); |
| 979 | } |
| 980 | |
| 981 | // Parse optional cooperative keyword. |
| 982 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "cooperative" ))) |
| 983 | result.addAttribute(name: "cooperative" , attr: parser.getBuilder().getUnitAttr()); |
| 984 | |
| 985 | // Create the region arguments: fixed launch-config args (`index`), then |
| 986 | // workgroup / private attribution args. The workgroup count is stored in the |
| 987 | // inherent `workgroup_attributions` attribute when non-zero. |
| 988 | Type index = parser.getBuilder().getIndexType(); |
| 989 | SmallVector<Type, LaunchOp::kNumConfigRegionAttributes> dataTypes( |
| 990 | LaunchOp::kNumConfigRegionAttributes + 6, index); |
| 991 | |
| 992 | SmallVector<OpAsmParser::Argument> regionArguments; |
| 993 | for (auto ssaValueAndType : llvm::zip(t&: regionArgs, u&: dataTypes)) { |
| 994 | OpAsmParser::Argument arg; |
| 995 | arg.ssaName = std::get<0>(t&: ssaValueAndType); |
| 996 | arg.type = std::get<1>(t&: ssaValueAndType); |
| 997 | regionArguments.push_back(Elt: arg); |
| 998 | } |
| 999 | |
| 1000 | Builder &builder = parser.getBuilder(); |
| 1001 | // Parse workgroup memory attributions. |
| 1002 | if (failed(Result: parseAttributions(parser, keyword: LaunchOp::getWorkgroupKeyword(), |
| 1003 | args&: regionArguments))) |
| 1004 | return failure(); |
| 1005 | |
| 1006 | // Store the number of operands we just parsed as the number of workgroup |
| 1007 | // memory attributions. |
| 1008 | unsigned numWorkgroupAttrs = regionArguments.size() - |
| 1009 | LaunchOp::kNumConfigRegionAttributes - |
| 1010 | (hasCluster ? 6 : 0); |
| 1011 | if (numWorkgroupAttrs != 0) |
| 1012 | result.addAttribute(name: LaunchOp::getWorkgroupAttributionsAttrName(name: result.name), |
| 1013 | attr: builder.getI64IntegerAttr(value: numWorkgroupAttrs)); |
| 1014 | |
| 1015 | // Parse private memory attributions. |
| 1016 | if (failed(Result: parseAttributions(parser, keyword: LaunchOp::getPrivateKeyword(), |
| 1017 | args&: regionArguments))) |
| 1018 | return failure(); |
| 1019 | |
| 1020 | // Introduce the body region and parse it. The region has |
| 1021 | // kNumConfigRegionAttributes arguments that correspond to |
| 1022 | // block/thread identifiers and grid/block sizes, all having `index` type. |
| 1023 | Region *body = result.addRegion(); |
| 1024 | if (parser.parseRegion(region&: *body, arguments: regionArguments) || |
| 1025 | parser.parseOptionalAttrDict(result&: result.attributes)) |
| 1026 | return failure(); |
| 1027 | |
| 1028 | SmallVector<int32_t, 12> segmentSizes(12, 1); |
| 1029 | segmentSizes.front() = asyncDependencies.size(); |
| 1030 | |
| 1031 | if (!hasCluster) { |
| 1032 | segmentSizes[7] = 0; |
| 1033 | segmentSizes[8] = 0; |
| 1034 | segmentSizes[9] = 0; |
| 1035 | } |
| 1036 | segmentSizes[10] = hasDynamicSharedMemorySize ? 1 : 0; |
| 1037 | segmentSizes[11] = hasAsyncObject ? 1 : 0; |
| 1038 | result.addAttribute(name: LaunchOp::getOperandSegmentSizeAttr(), |
| 1039 | attr: parser.getBuilder().getDenseI32ArrayAttr(values: segmentSizes)); |
| 1040 | return success(); |
| 1041 | } |
| 1042 | |
| 1043 | /// Simplify the gpu.launch when the range of a thread or block ID is |
| 1044 | /// trivially known to be one. |
| 1045 | struct FoldLaunchArguments : public OpRewritePattern<LaunchOp> { |
| 1046 | using OpRewritePattern<LaunchOp>::OpRewritePattern; |
| 1047 | LogicalResult matchAndRewrite(LaunchOp op, |
| 1048 | PatternRewriter &rewriter) const override { |
| 1049 | // If the range implies a single value for `id`, replace `id`'s uses by |
| 1050 | // zero. |
| 1051 | Value zero; |
| 1052 | bool simplified = false; |
| 1053 | auto constPropIdUses = [&](Value id, Value size) { |
| 1054 | // Check if size is trivially one. |
| 1055 | if (!matchPattern(value: size, pattern: m_One())) |
| 1056 | return; |
| 1057 | if (id.getUses().empty()) |
| 1058 | return; |
| 1059 | if (!simplified) { |
| 1060 | // Create a zero value the first time. |
| 1061 | OpBuilder::InsertionGuard guard(rewriter); |
| 1062 | rewriter.setInsertionPointToStart(&op.getBody().front()); |
| 1063 | zero = |
| 1064 | arith::ConstantIndexOp::create(builder&: rewriter, location: op.getLoc(), /*value=*/0); |
| 1065 | } |
| 1066 | rewriter.replaceAllUsesWith(from: id, to: zero); |
| 1067 | simplified = true; |
| 1068 | }; |
| 1069 | constPropIdUses(op.getBlockIds().x, op.getGridSizeX()); |
| 1070 | constPropIdUses(op.getBlockIds().y, op.getGridSizeY()); |
| 1071 | constPropIdUses(op.getBlockIds().z, op.getGridSizeZ()); |
| 1072 | constPropIdUses(op.getThreadIds().x, op.getBlockSizeX()); |
| 1073 | constPropIdUses(op.getThreadIds().y, op.getBlockSizeY()); |
| 1074 | constPropIdUses(op.getThreadIds().z, op.getBlockSizeZ()); |
| 1075 | |
| 1076 | return success(IsSuccess: simplified); |
| 1077 | } |
| 1078 | }; |
| 1079 | |
| 1080 | void LaunchOp::getCanonicalizationPatterns(RewritePatternSet &rewrites, |
| 1081 | MLIRContext *context) { |
| 1082 | rewrites.add<FoldLaunchArguments>(arg&: context); |
| 1083 | } |
| 1084 | |
| 1085 | /// Adds a new block argument that corresponds to buffers located in |
| 1086 | /// workgroup memory. |
| 1087 | BlockArgument LaunchOp::addWorkgroupAttribution(Type type, Location loc) { |
| 1088 | int64_t cur = getWorkgroupAttributions().value_or(u: 0); |
| 1089 | setWorkgroupAttributions(std::optional<int64_t>(cur + 1)); |
| 1090 | return getBody().insertArgument( |
| 1091 | index: getNumConfigRegionAttributes() + static_cast<unsigned>(cur), type, loc); |
| 1092 | } |
| 1093 | |
| 1094 | /// Adds a new block argument that corresponds to buffers located in |
| 1095 | /// private memory. |
| 1096 | BlockArgument LaunchOp::addPrivateAttribution(Type type, Location loc) { |
| 1097 | // Buffers on the private memory always come after buffers on the workgroup |
| 1098 | // memory. |
| 1099 | return getBody().addArgument(type, loc); |
| 1100 | } |
| 1101 | |
| 1102 | //===----------------------------------------------------------------------===// |
| 1103 | // LaunchFuncOp |
| 1104 | //===----------------------------------------------------------------------===// |
| 1105 | |
| 1106 | void LaunchFuncOp::build(OpBuilder &builder, OperationState &result, |
| 1107 | SymbolRefAttr kernelSymbol, KernelDim3 gridSize, |
| 1108 | KernelDim3 getBlockSize, Value dynamicSharedMemorySize, |
| 1109 | ValueRange kernelOperands, Type asyncTokenType, |
| 1110 | ValueRange asyncDependencies, Value asyncObject, |
| 1111 | std::optional<KernelDim3> clusterSize) { |
| 1112 | assert(kernelSymbol.getNestedReferences().size() == 1 && |
| 1113 | "expected a symbol reference with a single nested reference" ); |
| 1114 | result.addOperands(newOperands: asyncDependencies); |
| 1115 | if (asyncTokenType) |
| 1116 | result.types.push_back(Elt: builder.getType<AsyncTokenType>()); |
| 1117 | |
| 1118 | // Add grid and block sizes as op operands, followed by the data operands. |
| 1119 | result.addOperands(newOperands: {gridSize.x, gridSize.y, gridSize.z, getBlockSize.x, |
| 1120 | getBlockSize.y, getBlockSize.z}); |
| 1121 | if (clusterSize.has_value()) |
| 1122 | result.addOperands(newOperands: {clusterSize->x, clusterSize->y, clusterSize->z}); |
| 1123 | if (dynamicSharedMemorySize) |
| 1124 | result.addOperands(newOperands: dynamicSharedMemorySize); |
| 1125 | result.addOperands(newOperands: kernelOperands); |
| 1126 | if (asyncObject) |
| 1127 | result.addOperands(newOperands: asyncObject); |
| 1128 | |
| 1129 | Properties &prop = result.getOrAddProperties<Properties>(); |
| 1130 | prop.kernel = kernelSymbol; |
| 1131 | size_t segmentSizesLen = std::size(cont: prop.operandSegmentSizes); |
| 1132 | // Initialize the segment sizes to 1. |
| 1133 | llvm::fill(Range&: prop.operandSegmentSizes, Value: 1); |
| 1134 | prop.operandSegmentSizes[0] = asyncDependencies.size(); |
| 1135 | if (!clusterSize.has_value()) { |
| 1136 | prop.operandSegmentSizes[segmentSizesLen - 4] = 0; |
| 1137 | prop.operandSegmentSizes[segmentSizesLen - 5] = 0; |
| 1138 | prop.operandSegmentSizes[segmentSizesLen - 6] = 0; |
| 1139 | } |
| 1140 | prop.operandSegmentSizes[segmentSizesLen - 3] = |
| 1141 | dynamicSharedMemorySize ? 1 : 0; |
| 1142 | prop.operandSegmentSizes[segmentSizesLen - 2] = |
| 1143 | static_cast<int32_t>(kernelOperands.size()); |
| 1144 | prop.operandSegmentSizes[segmentSizesLen - 1] = asyncObject ? 1 : 0; |
| 1145 | } |
| 1146 | |
| 1147 | void LaunchFuncOp::build(OpBuilder &builder, OperationState &result, |
| 1148 | GPUFuncOp kernelFunc, KernelDim3 gridSize, |
| 1149 | KernelDim3 getBlockSize, Value dynamicSharedMemorySize, |
| 1150 | ValueRange kernelOperands, Type asyncTokenType, |
| 1151 | ValueRange asyncDependencies, Value asyncObject, |
| 1152 | std::optional<KernelDim3> clusterSize) { |
| 1153 | auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>(); |
| 1154 | auto kernelSymbol = |
| 1155 | SymbolRefAttr::get(rootReference: kernelModule.getNameAttr(), |
| 1156 | nestedReferences: {SymbolRefAttr::get(value: kernelFunc.getNameAttr())}); |
| 1157 | build(builder, result, kernelSymbol, gridSize, getBlockSize, |
| 1158 | dynamicSharedMemorySize, kernelOperands, asyncTokenType, |
| 1159 | asyncDependencies, asyncObject, clusterSize); |
| 1160 | } |
| 1161 | |
| 1162 | StringAttr LaunchFuncOp::getKernelModuleName() { |
| 1163 | return getKernel().getRootReference(); |
| 1164 | } |
| 1165 | |
| 1166 | StringAttr LaunchFuncOp::getKernelName() { |
| 1167 | return getKernel().getLeafReference(); |
| 1168 | } |
| 1169 | |
| 1170 | unsigned LaunchFuncOp::getNumKernelOperands() { |
| 1171 | return getKernelOperands().size(); |
| 1172 | } |
| 1173 | |
| 1174 | Value LaunchFuncOp::getKernelOperand(unsigned i) { |
| 1175 | return getKernelOperands()[i]; |
| 1176 | } |
| 1177 | |
| 1178 | KernelDim3 LaunchFuncOp::getGridSizeOperandValues() { |
| 1179 | auto operands = getOperands().drop_front(n: getAsyncDependencies().size()); |
| 1180 | return KernelDim3{.x: operands[0], .y: operands[1], .z: operands[2]}; |
| 1181 | } |
| 1182 | |
| 1183 | KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() { |
| 1184 | auto operands = getOperands().drop_front(n: getAsyncDependencies().size()); |
| 1185 | return KernelDim3{.x: operands[3], .y: operands[4], .z: operands[5]}; |
| 1186 | } |
| 1187 | |
| 1188 | KernelDim3 LaunchFuncOp::getClusterSizeOperandValues() { |
| 1189 | assert(hasClusterSize() && |
| 1190 | "cluster size is not set, check hasClusterSize() first" ); |
| 1191 | auto operands = getOperands().drop_front(n: getAsyncDependencies().size()); |
| 1192 | return KernelDim3{.x: operands[6], .y: operands[7], .z: operands[8]}; |
| 1193 | } |
| 1194 | |
| 1195 | LogicalResult LaunchFuncOp::verify() { |
| 1196 | if (verifyLaunchAsyncModel(op: *this).failed()) |
| 1197 | return failure(); |
| 1198 | |
| 1199 | auto module = (*this)->getParentOfType<ModuleOp>(); |
| 1200 | if (!module) |
| 1201 | return emitOpError(message: "expected to belong to a module" ); |
| 1202 | |
| 1203 | if (!module->getDiscardableAttrOfType<UnitAttr>( |
| 1204 | name: GPUDialect::getContainerModuleAttrName())) |
| 1205 | return emitOpError(message: "expected the closest surrounding module to have the '" + |
| 1206 | GPUDialect::getContainerModuleAttrName() + |
| 1207 | "' attribute" ); |
| 1208 | |
| 1209 | if (hasClusterSize()) { |
| 1210 | if (getClusterSizeY().getType() != getClusterSizeX().getType() || |
| 1211 | getClusterSizeZ().getType() != getClusterSizeX().getType()) |
| 1212 | return emitOpError() |
| 1213 | << "expects types of the cluster dimensions must be the same" ; |
| 1214 | } |
| 1215 | |
| 1216 | return success(); |
| 1217 | } |
| 1218 | |
| 1219 | LogicalResult |
| 1220 | LaunchFuncOp::verifySymbolUses(SymbolTableCollection &symbolTable) { |
| 1221 | LaunchFuncOp launchOp = *this; |
| 1222 | Operation *table = SymbolTable::getNearestSymbolTable(from: launchOp); |
| 1223 | // GPU modules cannot be nested within each other, escape to resolve the name. |
| 1224 | if (isa<GPUModuleOp>(Val: table)) |
| 1225 | table = SymbolTable::getNearestSymbolTable(from: table->getParentOp()); |
| 1226 | |
| 1227 | // Ignore launches that are nested more or less deep than functions in the |
| 1228 | // module we are currently checking. |
| 1229 | if (!launchOp->getParentOp() || |
| 1230 | launchOp->getParentOp()->getParentOp() != table) |
| 1231 | return success(); |
| 1232 | |
| 1233 | // Ignore launch ops with missing attributes here. The errors will be |
| 1234 | // reported by the verifiers of those ops. |
| 1235 | if (!launchOp.getKernelAttr()) |
| 1236 | return success(); |
| 1237 | |
| 1238 | // Check that `launch_func` refers to a well-formed GPU kernel container. |
| 1239 | StringAttr kernelContainerName = launchOp.getKernelModuleName(); |
| 1240 | Operation *kernelContainer = |
| 1241 | symbolTable.lookupNearestSymbolFrom(from: table, symbol: kernelContainerName); |
| 1242 | if (!kernelContainer) |
| 1243 | return launchOp.emitOpError() |
| 1244 | << "kernel container '" << kernelContainerName.getValue() |
| 1245 | << "' is undefined" ; |
| 1246 | |
| 1247 | // If the container is a GPU binary op return success. |
| 1248 | if (isa<BinaryOp>(Val: kernelContainer)) |
| 1249 | return success(); |
| 1250 | |
| 1251 | auto kernelModule = dyn_cast<GPUModuleOp>(Val: kernelContainer); |
| 1252 | if (!kernelModule) |
| 1253 | return launchOp.emitOpError() |
| 1254 | << "kernel module '" << kernelContainerName.getValue() |
| 1255 | << "' is undefined" ; |
| 1256 | |
| 1257 | // Check that `launch_func` refers to a well-formed kernel function. |
| 1258 | Operation *kernelFunc = symbolTable.lookupNearestSymbolFrom( |
| 1259 | from: kernelModule, symbol: launchOp.getKernelName()); |
| 1260 | if (!kernelFunc) |
| 1261 | return launchOp.emitOpError(message: "kernel function '" ) |
| 1262 | << launchOp.getKernel() << "' is undefined" ; |
| 1263 | auto kernelConvertedFunction = dyn_cast<FunctionOpInterface>(Val: kernelFunc); |
| 1264 | if (!kernelConvertedFunction) { |
| 1265 | InFlightDiagnostic diag = launchOp.emitOpError() |
| 1266 | << "referenced kernel '" << launchOp.getKernel() |
| 1267 | << "' is not a function" ; |
| 1268 | diag.attachNote(noteLoc: kernelFunc->getLoc()) << "see the kernel definition here" ; |
| 1269 | return diag; |
| 1270 | } |
| 1271 | |
| 1272 | if (!GPUDialect::isKernel(op: kernelFunc)) |
| 1273 | return launchOp.emitOpError(message: "kernel function is missing the '" ) |
| 1274 | << GPUDialect::getKernelFuncAttrName() << "' attribute" ; |
| 1275 | |
| 1276 | // TODO: If the kernel isn't a GPU function (which happens during separate |
| 1277 | // compilation), do not check type correspondence as it would require the |
| 1278 | // verifier to be aware of the type conversion. |
| 1279 | auto kernelGPUFunction = dyn_cast<gpu::GPUFuncOp>(Val: kernelFunc); |
| 1280 | if (!kernelGPUFunction) |
| 1281 | return success(); |
| 1282 | |
| 1283 | unsigned actualNumArguments = launchOp.getNumKernelOperands(); |
| 1284 | unsigned expectedNumArguments = kernelGPUFunction.getNumArguments(); |
| 1285 | if (expectedNumArguments != actualNumArguments) |
| 1286 | return launchOp.emitOpError(message: "got " ) |
| 1287 | << actualNumArguments << " kernel operands but expected " |
| 1288 | << expectedNumArguments; |
| 1289 | |
| 1290 | FunctionType functionType = kernelGPUFunction.getFunctionType(); |
| 1291 | for (unsigned i = 0; i < expectedNumArguments; ++i) { |
| 1292 | if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) { |
| 1293 | return launchOp.emitOpError(message: "type of function argument " ) |
| 1294 | << i << " does not match" ; |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | return success(); |
| 1299 | } |
| 1300 | |
| 1301 | static ParseResult |
| 1302 | parseLaunchDimType(OpAsmParser &parser, Type &dimTy, |
| 1303 | std::optional<OpAsmParser::UnresolvedOperand> clusterValue, |
| 1304 | Type &clusterXTy, Type &clusterYTy, Type &clusterZTy) { |
| 1305 | if (succeeded(Result: parser.parseOptionalColon())) { |
| 1306 | if (parser.parseType(result&: dimTy)) |
| 1307 | return failure(); |
| 1308 | } else { |
| 1309 | dimTy = IndexType::get(context: parser.getContext()); |
| 1310 | } |
| 1311 | if (clusterValue.has_value()) { |
| 1312 | clusterXTy = clusterYTy = clusterZTy = dimTy; |
| 1313 | } |
| 1314 | return success(); |
| 1315 | } |
| 1316 | |
| 1317 | static void printLaunchDimType(OpAsmPrinter &printer, Operation *op, Type dimTy, |
| 1318 | Value clusterValue, Type clusterXTy, |
| 1319 | Type clusterYTy, Type clusterZTy) { |
| 1320 | if (!dimTy.isIndex()) |
| 1321 | printer << ": " << dimTy; |
| 1322 | } |
| 1323 | |
| 1324 | static ParseResult parseLaunchFuncOperands( |
| 1325 | OpAsmParser &parser, |
| 1326 | SmallVectorImpl<OpAsmParser::UnresolvedOperand> &argNames, |
| 1327 | SmallVectorImpl<Type> &argTypes) { |
| 1328 | if (parser.parseOptionalKeyword(keyword: "args" )) |
| 1329 | return success(); |
| 1330 | |
| 1331 | auto parseElement = [&]() -> ParseResult { |
| 1332 | return failure(IsFailure: parser.parseOperand(result&: argNames.emplace_back()) || |
| 1333 | parser.parseColonType(result&: argTypes.emplace_back())); |
| 1334 | }; |
| 1335 | |
| 1336 | return parser.parseCommaSeparatedList(delimiter: OpAsmParser::Delimiter::Paren, |
| 1337 | parseElementFn: parseElement, contextMessage: " in argument list" ); |
| 1338 | } |
| 1339 | |
| 1340 | static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *, |
| 1341 | OperandRange operands, TypeRange types) { |
| 1342 | if (operands.empty()) |
| 1343 | return; |
| 1344 | printer << "args(" ; |
| 1345 | llvm::interleaveComma(c: llvm::zip_equal(t&: operands, u&: types), os&: printer, |
| 1346 | each_fn: [&](const auto &pair) { |
| 1347 | auto [operand, type] = pair; |
| 1348 | printer << operand << " : " << type; |
| 1349 | }); |
| 1350 | printer << ")" ; |
| 1351 | } |
| 1352 | |
| 1353 | //===----------------------------------------------------------------------===// |
| 1354 | // ShuffleOp |
| 1355 | //===----------------------------------------------------------------------===// |
| 1356 | |
| 1357 | void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value value, |
| 1358 | int32_t offset, int32_t width, ShuffleMode mode) { |
| 1359 | build(odsBuilder&: builder, odsState&: result, value, |
| 1360 | offset: arith::ConstantOp::create(builder, location: result.location, |
| 1361 | value: builder.getI32IntegerAttr(value: offset)), |
| 1362 | width: arith::ConstantOp::create(builder, location: result.location, |
| 1363 | value: builder.getI32IntegerAttr(value: width)), |
| 1364 | mode); |
| 1365 | } |
| 1366 | |
| 1367 | //===----------------------------------------------------------------------===// |
| 1368 | // RotateOp |
| 1369 | //===----------------------------------------------------------------------===// |
| 1370 | |
| 1371 | LogicalResult RotateOp::verify() { |
| 1372 | uint32_t offset = getOffset(); |
| 1373 | uint32_t width = getWidth(); |
| 1374 | |
| 1375 | if (offset >= width) { |
| 1376 | return emitOpError() << "offset must be in the range [0, " << width << ")" ; |
| 1377 | } |
| 1378 | |
| 1379 | return success(); |
| 1380 | } |
| 1381 | |
| 1382 | //===----------------------------------------------------------------------===// |
| 1383 | // BarrierOp |
| 1384 | //===----------------------------------------------------------------------===// |
| 1385 | |
| 1386 | LogicalResult BarrierOp::verify() { |
| 1387 | BarrierScope scope = getScope(); |
| 1388 | |
| 1389 | if (getNamedBarrier() && scope != BarrierScope::Workgroup) |
| 1390 | return emitOpError(message: "named barriers require workgroup scope" ); |
| 1391 | |
| 1392 | return success(); |
| 1393 | } |
| 1394 | |
| 1395 | /// Remove gpu.barrier after gpu.barrier, the threads are already synchronized! |
| 1396 | static LogicalResult eraseRedundantGpuBarrierOps(BarrierOp op, |
| 1397 | PatternRewriter &rewriter) { |
| 1398 | auto nextOp = dyn_cast_or_null<BarrierOp>(Val: op->getNextNode()); |
| 1399 | if (!nextOp) |
| 1400 | return failure(); |
| 1401 | |
| 1402 | // Cannot merge barriers of different scopes. |
| 1403 | if (op.getScope() != nextOp.getScope()) |
| 1404 | return failure(); |
| 1405 | |
| 1406 | // Cannot merge named barriers unless both refer to the same handle. |
| 1407 | if (op.getNamedBarrier() != nextOp.getNamedBarrier()) |
| 1408 | return failure(); |
| 1409 | |
| 1410 | std::optional<ArrayAttr> thisMemfence = op.getAddressSpaces(); |
| 1411 | std::optional<ArrayAttr> nextMemfence = nextOp.getAddressSpaces(); |
| 1412 | |
| 1413 | if (thisMemfence) { |
| 1414 | rewriter.modifyOpInPlace(root: op, callable: [&]() { |
| 1415 | if (!nextMemfence) { |
| 1416 | op.removeAddressSpacesAttr(); |
| 1417 | return; |
| 1418 | } |
| 1419 | // Fast path - merge where the two barriers fence the same spaces. |
| 1420 | if (*thisMemfence == *nextMemfence) { |
| 1421 | return; |
| 1422 | } |
| 1423 | |
| 1424 | llvm::SmallSetVector<Attribute, 4> mergedSpaces; |
| 1425 | for (Attribute attr : *thisMemfence) |
| 1426 | mergedSpaces.insert(X: attr); |
| 1427 | for (Attribute attr : *nextMemfence) |
| 1428 | mergedSpaces.insert(X: attr); |
| 1429 | op.setAddressSpacesAttr(rewriter.getArrayAttr(value: mergedSpaces.takeVector())); |
| 1430 | }); |
| 1431 | } |
| 1432 | |
| 1433 | rewriter.eraseOp(op: nextOp); |
| 1434 | return success(); |
| 1435 | } |
| 1436 | |
| 1437 | void BarrierOp::getCanonicalizationPatterns(RewritePatternSet &results, |
| 1438 | MLIRContext *context) { |
| 1439 | results.add(implFn: eraseRedundantGpuBarrierOps); |
| 1440 | } |
| 1441 | |
| 1442 | void BarrierOp::build(mlir::OpBuilder &odsBuilder, |
| 1443 | mlir::OperationState &odsState, |
| 1444 | std::optional<AddressSpace> addressSpace) { |
| 1445 | ArrayAttr addressSpacesAttr; |
| 1446 | if (addressSpace) |
| 1447 | addressSpacesAttr = odsBuilder.getArrayAttr( |
| 1448 | value: AddressSpaceAttr::get(context: odsBuilder.getContext(), value: addressSpace.value())); |
| 1449 | build( |
| 1450 | odsBuilder, odsState, address_spaces: addressSpacesAttr, /*named_barrier=*/Value{}, |
| 1451 | scope: BarrierScopeAttr::get(context: odsBuilder.getContext(), value: BarrierScope::Workgroup)); |
| 1452 | } |
| 1453 | |
| 1454 | /// Builds a barrier that causes memory operations affecting `memrefToFence` to |
| 1455 | /// be completed after the barrier is concluded. Currently, this means setting |
| 1456 | /// the fenced address spaces to those of the given memref if it is a gpu |
| 1457 | /// address space. |
| 1458 | void BarrierOp::build(OpBuilder &builder, OperationState &odsState, |
| 1459 | Value memrefToFence) { |
| 1460 | std::optional<AddressSpace> addrSpaceToFence; |
| 1461 | if (auto memrefType = dyn_cast<BaseMemRefType>(Val: memrefToFence.getType())) |
| 1462 | if (auto addrSpaceAttr = dyn_cast_if_present<gpu::AddressSpaceAttr>( |
| 1463 | Val: memrefType.getMemorySpace())) |
| 1464 | addrSpaceToFence = addrSpaceAttr.getValue(); |
| 1465 | return build(odsBuilder&: builder, odsState, addressSpace: addrSpaceToFence); |
| 1466 | } |
| 1467 | |
| 1468 | //===----------------------------------------------------------------------===// |
| 1469 | // GPUFuncOp |
| 1470 | //===----------------------------------------------------------------------===// |
| 1471 | |
| 1472 | /// Adds a new block argument that corresponds to buffers located in |
| 1473 | /// workgroup memory. |
| 1474 | BlockArgument GPUFuncOp::addWorkgroupAttribution(Type type, Location loc) { |
| 1475 | int64_t cur = getWorkgroupAttributions().value_or(u: 0); |
| 1476 | setWorkgroupAttributions(std::optional<int64_t>(cur + 1)); |
| 1477 | return getBody().insertArgument( |
| 1478 | index: getFunctionType().getNumInputs() + static_cast<unsigned>(cur), type, loc); |
| 1479 | } |
| 1480 | |
| 1481 | /// Adds a new block argument that corresponds to buffers located in |
| 1482 | /// private memory. |
| 1483 | BlockArgument GPUFuncOp::addPrivateAttribution(Type type, Location loc) { |
| 1484 | // Buffers on the private memory always come after buffers on the workgroup |
| 1485 | // memory. |
| 1486 | return getBody().addArgument(type, loc); |
| 1487 | } |
| 1488 | |
| 1489 | void GPUFuncOp::build(OpBuilder &builder, OperationState &result, |
| 1490 | StringRef name, FunctionType type, |
| 1491 | TypeRange workgroupAttributions, |
| 1492 | TypeRange privateAttributions, |
| 1493 | ArrayRef<NamedAttribute> attrs) { |
| 1494 | OpBuilder::InsertionGuard g(builder); |
| 1495 | |
| 1496 | result.getOrAddProperties<Properties>().sym_name = |
| 1497 | builder.getStringAttr(bytes: name); |
| 1498 | result.addAttribute(name: getFunctionTypeAttrName(name: result.name), |
| 1499 | attr: TypeAttr::get(type)); |
| 1500 | result.addAttribute(name: getWorkgroupAttributionsAttrName(name: result.name), |
| 1501 | attr: builder.getI64IntegerAttr(value: workgroupAttributions.size())); |
| 1502 | result.addAttributes(newAttributes: attrs); |
| 1503 | Region *body = result.addRegion(); |
| 1504 | Block *entryBlock = builder.createBlock(parent: body); |
| 1505 | |
| 1506 | // TODO: Allow passing in proper locations here. |
| 1507 | for (Type argTy : type.getInputs()) |
| 1508 | entryBlock->addArgument(type: argTy, loc: result.location); |
| 1509 | for (Type argTy : workgroupAttributions) |
| 1510 | entryBlock->addArgument(type: argTy, loc: result.location); |
| 1511 | for (Type argTy : privateAttributions) |
| 1512 | entryBlock->addArgument(type: argTy, loc: result.location); |
| 1513 | } |
| 1514 | |
| 1515 | /// Parses a GPU function memory attribution. |
| 1516 | /// |
| 1517 | /// memory-attribution ::= (`workgroup` `(` ssa-id-and-type-list `)`)? |
| 1518 | /// (`private` `(` ssa-id-and-type-list `)`)? |
| 1519 | /// |
| 1520 | /// Note that this function parses only one of the two similar parts, with the |
| 1521 | /// keyword provided as argument. |
| 1522 | static ParseResult |
| 1523 | parseAttributions(OpAsmParser &parser, StringRef keyword, |
| 1524 | SmallVectorImpl<OpAsmParser::Argument> &args, |
| 1525 | Attribute &attributionAttrs) { |
| 1526 | // If we could not parse the keyword, just assume empty list and succeed. |
| 1527 | if (failed(Result: parser.parseOptionalKeyword(keyword))) |
| 1528 | return success(); |
| 1529 | |
| 1530 | size_t existingArgs = args.size(); |
| 1531 | ParseResult result = |
| 1532 | parser.parseArgumentList(result&: args, delimiter: OpAsmParser::Delimiter::Paren, |
| 1533 | /*allowType=*/true, /*allowAttrs=*/true); |
| 1534 | if (failed(Result: result)) |
| 1535 | return result; |
| 1536 | |
| 1537 | bool hadAttrs = llvm::any_of(Range: ArrayRef(args).drop_front(N: existingArgs), |
| 1538 | P: [](const OpAsmParser::Argument &arg) -> bool { |
| 1539 | return arg.attrs && !arg.attrs.empty(); |
| 1540 | }); |
| 1541 | if (!hadAttrs) { |
| 1542 | attributionAttrs = nullptr; |
| 1543 | return result; |
| 1544 | } |
| 1545 | |
| 1546 | Builder &builder = parser.getBuilder(); |
| 1547 | SmallVector<Attribute> attributionAttrsVec; |
| 1548 | for (const auto &argument : ArrayRef(args).drop_front(N: existingArgs)) { |
| 1549 | if (!argument.attrs) |
| 1550 | attributionAttrsVec.push_back(Elt: builder.getDictionaryAttr(value: {})); |
| 1551 | else |
| 1552 | attributionAttrsVec.push_back(Elt: argument.attrs); |
| 1553 | } |
| 1554 | attributionAttrs = builder.getArrayAttr(value: attributionAttrsVec); |
| 1555 | return result; |
| 1556 | } |
| 1557 | |
| 1558 | /// Parses a GPU function. |
| 1559 | /// |
| 1560 | /// <operation> ::= `gpu.func` symbol-ref-id `(` argument-list `)` |
| 1561 | /// (`->` function-result-list)? memory-attribution `kernel`? |
| 1562 | /// function-attributes? region |
| 1563 | ParseResult GPUFuncOp::parse(OpAsmParser &parser, OperationState &result) { |
| 1564 | SmallVector<OpAsmParser::Argument> entryArgs; |
| 1565 | SmallVector<DictionaryAttr> resultAttrs; |
| 1566 | SmallVector<Type> resultTypes; |
| 1567 | bool isVariadic; |
| 1568 | |
| 1569 | // Parse the function name. |
| 1570 | StringAttr nameAttr; |
| 1571 | if (parser.parseSymbolName(result&: nameAttr, attrName: getSymNameAttrName(name: result.name), |
| 1572 | attrs&: result.attributes)) |
| 1573 | return failure(); |
| 1574 | |
| 1575 | auto signatureLocation = parser.getCurrentLocation(); |
| 1576 | if (failed(Result: function_interface_impl::parseFunctionSignatureWithArguments( |
| 1577 | parser, /*allowVariadic=*/false, arguments&: entryArgs, isVariadic, resultTypes, |
| 1578 | resultAttrs))) |
| 1579 | return failure(); |
| 1580 | |
| 1581 | if (!entryArgs.empty() && entryArgs[0].ssaName.name.empty()) |
| 1582 | return parser.emitError(loc: signatureLocation) |
| 1583 | << "gpu.func requires named arguments" ; |
| 1584 | |
| 1585 | // Construct the function type. More types will be added to the region, but |
| 1586 | // not to the function type. |
| 1587 | Builder &builder = parser.getBuilder(); |
| 1588 | |
| 1589 | SmallVector<Type> argTypes; |
| 1590 | for (auto &arg : entryArgs) |
| 1591 | argTypes.push_back(Elt: arg.type); |
| 1592 | auto type = builder.getFunctionType(inputs: argTypes, results: resultTypes); |
| 1593 | result.addAttribute(name: getFunctionTypeAttrName(name: result.name), |
| 1594 | attr: TypeAttr::get(type)); |
| 1595 | |
| 1596 | call_interface_impl::addArgAndResultAttrs( |
| 1597 | builder, result, args: entryArgs, resultAttrs, argAttrsName: getArgAttrsAttrName(name: result.name), |
| 1598 | resAttrsName: getResAttrsAttrName(name: result.name)); |
| 1599 | |
| 1600 | Attribute workgroupAttributionAttrs; |
| 1601 | // Parse workgroup memory attributions. |
| 1602 | if (failed(Result: parseAttributions(parser, keyword: GPUFuncOp::getWorkgroupKeyword(), |
| 1603 | args&: entryArgs, attributionAttrs&: workgroupAttributionAttrs))) |
| 1604 | return failure(); |
| 1605 | |
| 1606 | // Store the number of operands we just parsed as the number of workgroup |
| 1607 | // memory attributions. |
| 1608 | unsigned numWorkgroupAttrs = entryArgs.size() - type.getNumInputs(); |
| 1609 | if (numWorkgroupAttrs != 0) |
| 1610 | result.addAttribute( |
| 1611 | name: GPUFuncOp::getWorkgroupAttributionsAttrName(name: result.name), |
| 1612 | attr: builder.getI64IntegerAttr(value: numWorkgroupAttrs)); |
| 1613 | if (workgroupAttributionAttrs) |
| 1614 | result.addAttribute(name: GPUFuncOp::getWorkgroupAttribAttrsAttrName(name: result.name), |
| 1615 | attr: workgroupAttributionAttrs); |
| 1616 | |
| 1617 | Attribute privateAttributionAttrs; |
| 1618 | // Parse private memory attributions. |
| 1619 | if (failed(Result: parseAttributions(parser, keyword: GPUFuncOp::getPrivateKeyword(), |
| 1620 | args&: entryArgs, attributionAttrs&: privateAttributionAttrs))) |
| 1621 | return failure(); |
| 1622 | if (privateAttributionAttrs) |
| 1623 | result.addAttribute(name: GPUFuncOp::getPrivateAttribAttrsAttrName(name: result.name), |
| 1624 | attr: privateAttributionAttrs); |
| 1625 | |
| 1626 | // Parse the kernel attribute if present. |
| 1627 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: GPUFuncOp::getKernelKeyword()))) |
| 1628 | result.addAttribute(name: GPUFuncOp::getKernelAttrName(name: result.name), |
| 1629 | attr: builder.getUnitAttr()); |
| 1630 | |
| 1631 | // Parse attributes. |
| 1632 | if (failed(Result: parser.parseOptionalAttrDictWithKeyword(result&: result.attributes))) |
| 1633 | return failure(); |
| 1634 | |
| 1635 | // Parse the region. If no argument names were provided, take all names |
| 1636 | // (including those of attributions) from the entry block. |
| 1637 | auto *body = result.addRegion(); |
| 1638 | return parser.parseRegion(region&: *body, arguments: entryArgs); |
| 1639 | } |
| 1640 | |
| 1641 | void GPUFuncOp::print(OpAsmPrinter &p) { |
| 1642 | p << ' '; |
| 1643 | p.printSymbolName(symbolRef: getName()); |
| 1644 | |
| 1645 | FunctionType type = getFunctionType(); |
| 1646 | function_interface_impl::printFunctionSignature(p, op: *this, argTypes: type.getInputs(), |
| 1647 | /*isVariadic=*/false, |
| 1648 | resultTypes: type.getResults()); |
| 1649 | |
| 1650 | printAttributions(p, keyword: getWorkgroupKeyword(), values: getWorkgroupAttributionBBArgs(), |
| 1651 | attributes: getWorkgroupAttribAttrs().value_or(u: nullptr)); |
| 1652 | printAttributions(p, keyword: getPrivateKeyword(), values: getPrivateAttributions(), |
| 1653 | attributes: getPrivateAttribAttrs().value_or(u: nullptr)); |
| 1654 | if (isKernel()) |
| 1655 | p << ' ' << getKernelKeyword(); |
| 1656 | |
| 1657 | function_interface_impl::printFunctionAttributes( |
| 1658 | p, op: *this, |
| 1659 | elided: {getWorkgroupAttributionsAttrName(), getKernelAttrName(), |
| 1660 | GPUDialect::getKernelFuncAttrName(), getFunctionTypeAttrName(), |
| 1661 | getArgAttrsAttrName(), getResAttrsAttrName(), |
| 1662 | getWorkgroupAttribAttrsAttrName(), getPrivateAttribAttrsAttrName()}); |
| 1663 | p << ' '; |
| 1664 | p.printRegion(blocks&: getBody(), /*printEntryBlockArgs=*/false); |
| 1665 | } |
| 1666 | |
| 1667 | static DictionaryAttr getAttributionAttrs(GPUFuncOp op, unsigned index, |
| 1668 | StringAttr attrName) { |
| 1669 | ArrayAttr allAttrs = attrName == op.getWorkgroupAttribAttrsAttrName() |
| 1670 | ? op.getWorkgroupAttribAttrsAttr() |
| 1671 | : op.getPrivateAttribAttrsAttr(); |
| 1672 | if (!allAttrs || index >= allAttrs.size()) |
| 1673 | return DictionaryAttr(); |
| 1674 | return llvm::cast<DictionaryAttr>(Val: allAttrs[index]); |
| 1675 | } |
| 1676 | |
| 1677 | DictionaryAttr GPUFuncOp::getworkgroupAttributionAttrs(unsigned index) { |
| 1678 | return getAttributionAttrs(op: *this, index, attrName: getWorkgroupAttribAttrsAttrName()); |
| 1679 | } |
| 1680 | |
| 1681 | DictionaryAttr GPUFuncOp::getPrivateAttributionAttrs(unsigned index) { |
| 1682 | return getAttributionAttrs(op: *this, index, attrName: getPrivateAttribAttrsAttrName()); |
| 1683 | } |
| 1684 | |
| 1685 | static void setAttributionAttrs(GPUFuncOp op, unsigned index, |
| 1686 | DictionaryAttr value, StringAttr attrName) { |
| 1687 | MLIRContext *ctx = op.getContext(); |
| 1688 | ArrayAttr allAttrs = attrName == op.getWorkgroupAttribAttrsAttrName() |
| 1689 | ? op.getWorkgroupAttribAttrsAttr() |
| 1690 | : op.getPrivateAttribAttrsAttr(); |
| 1691 | SmallVector<Attribute> elements; |
| 1692 | if (allAttrs) |
| 1693 | elements.append(in_start: allAttrs.begin(), in_end: allAttrs.end()); |
| 1694 | while (elements.size() <= index) |
| 1695 | elements.push_back(Elt: DictionaryAttr::get(context: ctx)); |
| 1696 | if (!value) |
| 1697 | elements[index] = DictionaryAttr::get(context: ctx); |
| 1698 | else |
| 1699 | elements[index] = value; |
| 1700 | ArrayAttr newValue = ArrayAttr::get(context: ctx, value: elements); |
| 1701 | if (attrName == op.getWorkgroupAttribAttrsAttrName()) |
| 1702 | op.setWorkgroupAttribAttrsAttr(newValue); |
| 1703 | else |
| 1704 | op.setPrivateAttribAttrsAttr(newValue); |
| 1705 | } |
| 1706 | |
| 1707 | void GPUFuncOp::setworkgroupAttributionAttrs(unsigned index, |
| 1708 | DictionaryAttr value) { |
| 1709 | setAttributionAttrs(op: *this, index, value, attrName: getWorkgroupAttribAttrsAttrName()); |
| 1710 | } |
| 1711 | |
| 1712 | void GPUFuncOp::setPrivateAttributionAttrs(unsigned int index, |
| 1713 | DictionaryAttr value) { |
| 1714 | setAttributionAttrs(op: *this, index, value, attrName: getPrivateAttribAttrsAttrName()); |
| 1715 | } |
| 1716 | |
| 1717 | static Attribute getAttributionAttr(GPUFuncOp op, unsigned index, |
| 1718 | StringAttr name, StringAttr attrsName) { |
| 1719 | DictionaryAttr dict = getAttributionAttrs(op, index, attrName: attrsName); |
| 1720 | if (!dict) |
| 1721 | return Attribute(); |
| 1722 | return dict.get(name); |
| 1723 | } |
| 1724 | |
| 1725 | Attribute GPUFuncOp::getWorkgroupAttributionAttr(unsigned index, |
| 1726 | StringAttr name) { |
| 1727 | assert(index < getNumWorkgroupAttributions() && |
| 1728 | "index must map to a workgroup attribution" ); |
| 1729 | return getAttributionAttr(op: *this, index, name, |
| 1730 | attrsName: getWorkgroupAttribAttrsAttrName()); |
| 1731 | } |
| 1732 | |
| 1733 | Attribute GPUFuncOp::getPrivateAttributionAttr(unsigned index, |
| 1734 | StringAttr name) { |
| 1735 | assert(index < getNumPrivateAttributions() && |
| 1736 | "index must map to a private attribution" ); |
| 1737 | return getAttributionAttr(op: *this, index, name, |
| 1738 | attrsName: getPrivateAttribAttrsAttrName()); |
| 1739 | } |
| 1740 | |
| 1741 | static void setAttributionAttr(GPUFuncOp op, unsigned index, StringAttr name, |
| 1742 | Attribute value, StringAttr attrsName) { |
| 1743 | MLIRContext *ctx = op.getContext(); |
| 1744 | SmallVector<NamedAttribute> elems; |
| 1745 | DictionaryAttr oldDict = getAttributionAttrs(op, index, attrName: attrsName); |
| 1746 | if (oldDict) |
| 1747 | elems.append(in_start: oldDict.getValue().begin(), in_end: oldDict.getValue().end()); |
| 1748 | |
| 1749 | bool found = false; |
| 1750 | bool mustSort = true; |
| 1751 | for (unsigned i = 0, e = elems.size(); i < e; ++i) { |
| 1752 | if (elems[i].getName() == name) { |
| 1753 | found = true; |
| 1754 | if (!value) { |
| 1755 | std::swap(a&: elems[i], b&: elems[elems.size() - 1]); |
| 1756 | elems.pop_back(); |
| 1757 | } else { |
| 1758 | mustSort = false; |
| 1759 | elems[i] = NamedAttribute(elems[i].getName(), value); |
| 1760 | } |
| 1761 | break; |
| 1762 | } |
| 1763 | } |
| 1764 | if (!found) { |
| 1765 | if (!value) |
| 1766 | return; |
| 1767 | elems.emplace_back(Args&: name, Args&: value); |
| 1768 | } |
| 1769 | if (mustSort) { |
| 1770 | DictionaryAttr::sortInPlace(array&: elems); |
| 1771 | } |
| 1772 | auto newDict = DictionaryAttr::getWithSorted(context: ctx, value: elems); |
| 1773 | setAttributionAttrs(op, index, value: newDict, attrName: attrsName); |
| 1774 | } |
| 1775 | |
| 1776 | void GPUFuncOp::setWorkgroupAttributionAttr(unsigned index, StringAttr name, |
| 1777 | Attribute value) { |
| 1778 | assert(index < getNumWorkgroupAttributions() && |
| 1779 | "index must map to a workgroup attribution" ); |
| 1780 | setAttributionAttr(op: *this, index, name, value, |
| 1781 | attrsName: getWorkgroupAttribAttrsAttrName()); |
| 1782 | } |
| 1783 | |
| 1784 | void GPUFuncOp::setPrivateAttributionAttr(unsigned index, StringAttr name, |
| 1785 | Attribute value) { |
| 1786 | assert(index < getNumPrivateAttributions() && |
| 1787 | "index must map to a private attribution" ); |
| 1788 | setAttributionAttr(op: *this, index, name, value, |
| 1789 | attrsName: getPrivateAttribAttrsAttrName()); |
| 1790 | } |
| 1791 | |
| 1792 | LogicalResult GPUFuncOp::verifyType() { |
| 1793 | if (isKernel() && getFunctionType().getNumResults() != 0) |
| 1794 | return emitOpError() << "expected void return type for kernel function" ; |
| 1795 | |
| 1796 | return success(); |
| 1797 | } |
| 1798 | |
| 1799 | /// Verifies the body of the function. |
| 1800 | LogicalResult GPUFuncOp::verifyBody() { |
| 1801 | if (empty()) |
| 1802 | return emitOpError() << "expected body with at least one block" ; |
| 1803 | unsigned numFuncArguments = getNumArguments(); |
| 1804 | unsigned numWorkgroupAttributions = getNumWorkgroupAttributions(); |
| 1805 | unsigned numBlockArguments = front().getNumArguments(); |
| 1806 | if (numBlockArguments < numFuncArguments + numWorkgroupAttributions) |
| 1807 | return emitOpError() << "expected at least " |
| 1808 | << numFuncArguments + numWorkgroupAttributions |
| 1809 | << " arguments to body region" ; |
| 1810 | |
| 1811 | ArrayRef<Type> funcArgTypes = getFunctionType().getInputs(); |
| 1812 | for (unsigned i = 0; i < numFuncArguments; ++i) { |
| 1813 | Type blockArgType = front().getArgument(i).getType(); |
| 1814 | if (funcArgTypes[i] != blockArgType) |
| 1815 | return emitOpError() << "expected body region argument #" << i |
| 1816 | << " to be of type " << funcArgTypes[i] << ", got " |
| 1817 | << blockArgType; |
| 1818 | } |
| 1819 | |
| 1820 | if (failed(Result: verifyAttributions(op: getOperation(), attributions: getWorkgroupAttributionBBArgs(), |
| 1821 | memorySpace: GPUDialect::getWorkgroupAddressSpace())) || |
| 1822 | failed(Result: verifyAttributions(op: getOperation(), attributions: getPrivateAttributions(), |
| 1823 | memorySpace: GPUDialect::getPrivateAddressSpace()))) |
| 1824 | return failure(); |
| 1825 | |
| 1826 | return success(); |
| 1827 | } |
| 1828 | |
| 1829 | //===----------------------------------------------------------------------===// |
| 1830 | // ReturnOp |
| 1831 | //===----------------------------------------------------------------------===// |
| 1832 | |
| 1833 | LogicalResult gpu::ReturnOp::verify() { |
| 1834 | GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>(); |
| 1835 | |
| 1836 | FunctionType funType = function.getFunctionType(); |
| 1837 | |
| 1838 | if (funType.getNumResults() != getOperands().size()) |
| 1839 | return emitOpError() |
| 1840 | .append(args: "expected " , args: funType.getNumResults(), args: " result operands" ) |
| 1841 | .attachNote(noteLoc: function.getLoc()) |
| 1842 | .append(arg: "return type declared here" ); |
| 1843 | |
| 1844 | for (const auto &pair : llvm::enumerate( |
| 1845 | First: llvm::zip(t: function.getFunctionType().getResults(), u: getOperands()))) { |
| 1846 | auto [type, operand] = pair.value(); |
| 1847 | if (type != operand.getType()) |
| 1848 | return emitOpError() << "unexpected type `" << operand.getType() |
| 1849 | << "' for operand #" << pair.index(); |
| 1850 | } |
| 1851 | return success(); |
| 1852 | } |
| 1853 | |
| 1854 | //===----------------------------------------------------------------------===// |
| 1855 | // GPUModuleOp |
| 1856 | //===----------------------------------------------------------------------===// |
| 1857 | |
| 1858 | LogicalResult GPUModuleOp::readProperties(DialectBytecodeReader &reader, |
| 1859 | OperationState &state) { |
| 1860 | auto &properties = state.getOrAddProperties<Properties>(); |
| 1861 | // Preserve the pre-DLTI field order for unversioned bytecode. |
| 1862 | if (failed(Result: reader.readOptionalAttribute(attr&: properties.offloadingHandler)) || |
| 1863 | failed(Result: reader.readAttribute(result&: properties.sym_name)) || |
| 1864 | failed(Result: reader.readOptionalAttribute(result&: properties.sym_visibility)) || |
| 1865 | failed(Result: reader.readOptionalAttribute(result&: properties.targets))) |
| 1866 | return failure(); |
| 1867 | |
| 1868 | if (failed(Result: reader.getDialectVersion<GPUDialect>())) |
| 1869 | return success(); |
| 1870 | return reader.readOptionalAttribute(attr&: properties.dlti); |
| 1871 | } |
| 1872 | |
| 1873 | void GPUModuleOp::writeProperties(DialectBytecodeWriter &writer) { |
| 1874 | Properties &properties = getProperties(); |
| 1875 | writer.writeOptionalAttribute(attr: properties.offloadingHandler); |
| 1876 | writer.writeAttribute(attr: properties.sym_name); |
| 1877 | writer.writeOptionalAttribute(attr: properties.sym_visibility); |
| 1878 | writer.writeOptionalAttribute(attr: properties.targets); |
| 1879 | if (writer.getBytecodeVersion() >= bytecode::kDialectVersioning) |
| 1880 | writer.writeOptionalAttribute(attr: properties.dlti); |
| 1881 | } |
| 1882 | |
| 1883 | void GPUModuleOp::build(OpBuilder &builder, OperationState &result, |
| 1884 | StringRef name, ArrayAttr targets, |
| 1885 | Attribute offloadingHandler) { |
| 1886 | result.addRegion()->emplaceBlock(); |
| 1887 | Properties &props = result.getOrAddProperties<Properties>(); |
| 1888 | if (targets) |
| 1889 | props.targets = targets; |
| 1890 | props.setSymName(builder.getStringAttr(bytes: name)); |
| 1891 | props.offloadingHandler = offloadingHandler; |
| 1892 | } |
| 1893 | |
| 1894 | void GPUModuleOp::build(OpBuilder &builder, OperationState &result, |
| 1895 | StringRef name, ArrayRef<Attribute> targets, |
| 1896 | Attribute offloadingHandler) { |
| 1897 | build(builder, result, name, |
| 1898 | targets: targets.empty() ? ArrayAttr() : builder.getArrayAttr(value: targets), |
| 1899 | offloadingHandler); |
| 1900 | } |
| 1901 | |
| 1902 | bool GPUModuleOp::hasTarget(Attribute target) { |
| 1903 | if (ArrayAttr targets = getTargetsAttr()) |
| 1904 | return llvm::count(Range: targets.getValue(), Element: target); |
| 1905 | return false; |
| 1906 | } |
| 1907 | |
| 1908 | void GPUModuleOp::setTargets(ArrayRef<TargetAttrInterface> targets) { |
| 1909 | ArrayAttr &targetsAttr = getProperties().targets; |
| 1910 | SmallVector<Attribute> targetsVector(targets); |
| 1911 | targetsAttr = ArrayAttr::get(context: getContext(), value: targetsVector); |
| 1912 | } |
| 1913 | |
| 1914 | LogicalResult GPUModuleOp::verify() { |
| 1915 | auto targets = getTargetsAttr(); |
| 1916 | |
| 1917 | if (!targets) |
| 1918 | return success(); |
| 1919 | |
| 1920 | for (auto target : targets) { |
| 1921 | if (auto verifyTargetAttr = |
| 1922 | llvm::dyn_cast<TargetAttrVerifyInterface>(Val&: target)) { |
| 1923 | if (verifyTargetAttr.verifyTarget(module: getOperation()).failed()) |
| 1924 | return failure(); |
| 1925 | } |
| 1926 | } |
| 1927 | return success(); |
| 1928 | } |
| 1929 | |
| 1930 | //===----------------------------------------------------------------------===// |
| 1931 | // GPUBinaryOp |
| 1932 | //===----------------------------------------------------------------------===// |
| 1933 | void BinaryOp::build(OpBuilder &builder, OperationState &result, StringRef name, |
| 1934 | Attribute offloadingHandler, ArrayAttr objects) { |
| 1935 | auto &properties = result.getOrAddProperties<Properties>(); |
| 1936 | result.attributes.push_back(newAttribute: builder.getNamedAttr( |
| 1937 | name: getSymNameAttrName(name: result.name), val: builder.getStringAttr(bytes: name))); |
| 1938 | properties.objects = objects; |
| 1939 | if (offloadingHandler) |
| 1940 | properties.offloadingHandler = offloadingHandler; |
| 1941 | else |
| 1942 | properties.offloadingHandler = builder.getAttr<SelectObjectAttr>(args: nullptr); |
| 1943 | } |
| 1944 | |
| 1945 | void BinaryOp::build(OpBuilder &builder, OperationState &result, StringRef name, |
| 1946 | Attribute offloadingHandler, ArrayRef<Attribute> objects) { |
| 1947 | build(builder, result, name, offloadingHandler, |
| 1948 | objects: objects.empty() ? ArrayAttr() : builder.getArrayAttr(value: objects)); |
| 1949 | } |
| 1950 | |
| 1951 | static ParseResult parseOffloadingHandler(OpAsmParser &parser, |
| 1952 | Attribute &offloadingHandler) { |
| 1953 | if (succeeded(Result: parser.parseOptionalLess())) { |
| 1954 | if (parser.parseAttribute(result&: offloadingHandler)) |
| 1955 | return failure(); |
| 1956 | if (parser.parseGreater()) |
| 1957 | return failure(); |
| 1958 | } |
| 1959 | if (!offloadingHandler) |
| 1960 | offloadingHandler = parser.getBuilder().getAttr<SelectObjectAttr>(args: nullptr); |
| 1961 | return success(); |
| 1962 | } |
| 1963 | |
| 1964 | static void printOffloadingHandler(OpAsmPrinter &printer, Operation *op, |
| 1965 | Attribute offloadingHandler) { |
| 1966 | if (offloadingHandler != SelectObjectAttr::get(context: op->getContext(), target: nullptr)) |
| 1967 | printer << '<' << offloadingHandler << '>'; |
| 1968 | } |
| 1969 | |
| 1970 | //===----------------------------------------------------------------------===// |
| 1971 | // GPUMemcpyOp |
| 1972 | //===----------------------------------------------------------------------===// |
| 1973 | |
| 1974 | LogicalResult MemcpyOp::verify() { |
| 1975 | auto srcType = getSrc().getType(); |
| 1976 | auto dstType = getDst().getType(); |
| 1977 | |
| 1978 | if (getElementTypeOrSelf(type: srcType) != getElementTypeOrSelf(type: dstType)) |
| 1979 | return emitOpError(message: "arguments have incompatible element type" ); |
| 1980 | |
| 1981 | if (failed(Result: verifyCompatibleShape(type1: srcType, type2: dstType))) |
| 1982 | return emitOpError(message: "arguments have incompatible shape" ); |
| 1983 | |
| 1984 | return success(); |
| 1985 | } |
| 1986 | |
| 1987 | namespace { |
| 1988 | /// Erases a common case of copy ops where a destination value is used only by |
| 1989 | /// the copy op, alloc and dealloc ops. |
| 1990 | struct EraseTrivialCopyOp : public OpRewritePattern<MemcpyOp> { |
| 1991 | using OpRewritePattern<MemcpyOp>::OpRewritePattern; |
| 1992 | |
| 1993 | LogicalResult matchAndRewrite(MemcpyOp op, |
| 1994 | PatternRewriter &rewriter) const override { |
| 1995 | Value dest = op.getDst(); |
| 1996 | Operation *destDefOp = dest.getDefiningOp(); |
| 1997 | // `dest` must be defined by an op having Allocate memory effect in order to |
| 1998 | // perform the folding. |
| 1999 | if (!destDefOp || |
| 2000 | !hasSingleEffect<MemoryEffects::Allocate>(op: destDefOp, value: dest)) |
| 2001 | return failure(); |
| 2002 | // We can erase `op` iff `dest` has no other use apart from its |
| 2003 | // use by `op` and dealloc ops. |
| 2004 | if (llvm::any_of(Range: dest.getUsers(), P: [op, dest](Operation *user) { |
| 2005 | return user != op && |
| 2006 | !hasSingleEffect<MemoryEffects::Free>(op: user, value: dest); |
| 2007 | })) |
| 2008 | return failure(); |
| 2009 | // We can perform the folding if and only if op has a single async |
| 2010 | // dependency and produces an async token as result, or if it does not have |
| 2011 | // any async dependency and does not produce any async token result. |
| 2012 | if (op.getAsyncDependencies().size() > 1 || |
| 2013 | ((op.getAsyncDependencies().empty() && op.getAsyncToken()) || |
| 2014 | (!op.getAsyncDependencies().empty() && !op.getAsyncToken()))) |
| 2015 | return failure(); |
| 2016 | rewriter.replaceOp(op, newValues: op.getAsyncDependencies()); |
| 2017 | return success(); |
| 2018 | } |
| 2019 | }; |
| 2020 | } // end anonymous namespace |
| 2021 | |
| 2022 | void MemcpyOp::getCanonicalizationPatterns(RewritePatternSet &results, |
| 2023 | MLIRContext *context) { |
| 2024 | results.add<EraseTrivialCopyOp>(arg&: context); |
| 2025 | } |
| 2026 | |
| 2027 | //===----------------------------------------------------------------------===// |
| 2028 | // GPU_SubgroupMmaLoadMatrixOp |
| 2029 | //===----------------------------------------------------------------------===// |
| 2030 | |
| 2031 | LogicalResult SubgroupMmaLoadMatrixOp::verify() { |
| 2032 | auto srcType = getSrcMemref().getType(); |
| 2033 | auto resType = getRes().getType(); |
| 2034 | auto resMatrixType = llvm::cast<gpu::MMAMatrixType>(Val&: resType); |
| 2035 | auto operand = resMatrixType.getOperand(); |
| 2036 | auto srcMemrefType = llvm::cast<MemRefType>(Val&: srcType); |
| 2037 | |
| 2038 | if (!srcMemrefType.isLastDimUnitStride()) |
| 2039 | return emitError( |
| 2040 | message: "expected source memref most minor dim must have unit stride" ); |
| 2041 | |
| 2042 | if (operand != "AOp" && operand != "BOp" && operand != "COp" ) |
| 2043 | return emitError(message: "only AOp, BOp and COp can be loaded" ); |
| 2044 | |
| 2045 | return success(); |
| 2046 | } |
| 2047 | |
| 2048 | //===----------------------------------------------------------------------===// |
| 2049 | // GPU_SubgroupMmaStoreMatrixOp |
| 2050 | //===----------------------------------------------------------------------===// |
| 2051 | |
| 2052 | LogicalResult SubgroupMmaStoreMatrixOp::verify() { |
| 2053 | auto srcType = getSrc().getType(); |
| 2054 | auto dstType = getDstMemref().getType(); |
| 2055 | auto srcMatrixType = llvm::cast<gpu::MMAMatrixType>(Val&: srcType); |
| 2056 | auto dstMemrefType = llvm::cast<MemRefType>(Val&: dstType); |
| 2057 | |
| 2058 | if (!dstMemrefType.isLastDimUnitStride()) |
| 2059 | return emitError( |
| 2060 | message: "expected destination memref most minor dim must have unit stride" ); |
| 2061 | |
| 2062 | if (srcMatrixType.getOperand() != "COp" ) |
| 2063 | return emitError( |
| 2064 | message: "expected the operand matrix being stored to have 'COp' operand type" ); |
| 2065 | |
| 2066 | return success(); |
| 2067 | } |
| 2068 | |
| 2069 | //===----------------------------------------------------------------------===// |
| 2070 | // GPU_SubgroupMmaComputeOp |
| 2071 | //===----------------------------------------------------------------------===// |
| 2072 | |
| 2073 | LogicalResult SubgroupMmaComputeOp::verify() { |
| 2074 | enum OperandMap { A, B, C }; |
| 2075 | SmallVector<MMAMatrixType, 3> opTypes; |
| 2076 | opTypes.push_back(Elt: llvm::cast<MMAMatrixType>(Val: getOpA().getType())); |
| 2077 | opTypes.push_back(Elt: llvm::cast<MMAMatrixType>(Val: getOpB().getType())); |
| 2078 | opTypes.push_back(Elt: llvm::cast<MMAMatrixType>(Val: getOpC().getType())); |
| 2079 | |
| 2080 | if (opTypes[A].getOperand() != "AOp" || opTypes[B].getOperand() != "BOp" || |
| 2081 | opTypes[C].getOperand() != "COp" ) |
| 2082 | return emitError(message: "operands must be in the order AOp, BOp, COp" ); |
| 2083 | |
| 2084 | ArrayRef<int64_t> aShape, bShape, cShape; |
| 2085 | aShape = opTypes[A].getShape(); |
| 2086 | bShape = opTypes[B].getShape(); |
| 2087 | cShape = opTypes[C].getShape(); |
| 2088 | |
| 2089 | if (aShape[1] != bShape[0] || aShape[0] != cShape[0] || |
| 2090 | bShape[1] != cShape[1]) |
| 2091 | return emitError(message: "operand shapes do not satisfy matmul constraints" ); |
| 2092 | |
| 2093 | return success(); |
| 2094 | } |
| 2095 | |
| 2096 | LogicalResult MemcpyOp::fold(FoldAdaptor adaptor, |
| 2097 | SmallVectorImpl<::mlir::OpFoldResult> &results) { |
| 2098 | return memref::foldMemRefCast(op: *this); |
| 2099 | } |
| 2100 | |
| 2101 | LogicalResult MemsetOp::fold(FoldAdaptor adaptor, |
| 2102 | SmallVectorImpl<::mlir::OpFoldResult> &results) { |
| 2103 | return memref::foldMemRefCast(op: *this); |
| 2104 | } |
| 2105 | |
| 2106 | //===----------------------------------------------------------------------===// |
| 2107 | // GPU_WaitOp |
| 2108 | //===----------------------------------------------------------------------===// |
| 2109 | |
| 2110 | namespace { |
| 2111 | /// Remove gpu.wait op use of gpu.wait op def without async dependencies. |
| 2112 | /// %t = gpu.wait async [] // No async dependencies. |
| 2113 | /// ... gpu.wait ... [%t, ...] // %t can be removed. |
| 2114 | struct EraseRedundantGpuWaitOpPairs : public OpRewritePattern<WaitOp> { |
| 2115 | public: |
| 2116 | using Base::Base; |
| 2117 | |
| 2118 | LogicalResult matchAndRewrite(WaitOp op, |
| 2119 | PatternRewriter &rewriter) const final { |
| 2120 | auto predicate = [](Value value) { |
| 2121 | auto waitOp = value.getDefiningOp<WaitOp>(); |
| 2122 | return waitOp && waitOp->getNumOperands() == 0; |
| 2123 | }; |
| 2124 | if (llvm::none_of(Range: op.getAsyncDependencies(), P: predicate)) |
| 2125 | return failure(); |
| 2126 | SmallVector<Value> validOperands; |
| 2127 | for (Value operand : op->getOperands()) { |
| 2128 | if (predicate(operand)) |
| 2129 | continue; |
| 2130 | validOperands.push_back(Elt: operand); |
| 2131 | } |
| 2132 | rewriter.modifyOpInPlace(root: op, callable: [&]() { op->setOperands(validOperands); }); |
| 2133 | return success(); |
| 2134 | } |
| 2135 | }; |
| 2136 | |
| 2137 | /// Simplify trivial gpu.wait ops for the following patterns. |
| 2138 | /// 1. %t = gpu.wait async ... ops, where %t has no uses (regardless of async |
| 2139 | /// dependencies). |
| 2140 | /// 2. %t1 = gpu.wait async [%t0], in this case, we can replace uses of %t1 with |
| 2141 | /// %t0. |
| 2142 | /// 3. gpu.wait [] ops, i.e gpu.wait ops that neither have any async |
| 2143 | /// dependencies nor return any token. |
| 2144 | struct SimplifyGpuWaitOp : public OpRewritePattern<WaitOp> { |
| 2145 | public: |
| 2146 | using Base::Base; |
| 2147 | |
| 2148 | LogicalResult matchAndRewrite(WaitOp op, |
| 2149 | PatternRewriter &rewriter) const final { |
| 2150 | // Erase gpu.wait ops that neither have any async dependencies nor return |
| 2151 | // any async token. |
| 2152 | if (op.getAsyncDependencies().empty() && !op.getAsyncToken()) { |
| 2153 | rewriter.eraseOp(op); |
| 2154 | return success(); |
| 2155 | } |
| 2156 | // Replace uses of %t1 = gpu.wait async [%t0] ops with %t0 and erase the op. |
| 2157 | if (llvm::hasSingleElement(C: op.getAsyncDependencies()) && |
| 2158 | op.getAsyncToken()) { |
| 2159 | rewriter.replaceOp(op, newValues: op.getAsyncDependencies()); |
| 2160 | return success(); |
| 2161 | } |
| 2162 | // Erase %t = gpu.wait async ... ops, where %t has no uses. |
| 2163 | if (op.getAsyncToken() && op.getAsyncToken().use_empty()) { |
| 2164 | rewriter.eraseOp(op); |
| 2165 | return success(); |
| 2166 | } |
| 2167 | return failure(); |
| 2168 | } |
| 2169 | }; |
| 2170 | } // end anonymous namespace |
| 2171 | |
| 2172 | void WaitOp::getCanonicalizationPatterns(RewritePatternSet &results, |
| 2173 | MLIRContext *context) { |
| 2174 | results.add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(arg&: context); |
| 2175 | } |
| 2176 | |
| 2177 | //===----------------------------------------------------------------------===// |
| 2178 | // GPU_AllocOp |
| 2179 | //===----------------------------------------------------------------------===// |
| 2180 | |
| 2181 | LogicalResult AllocOp::verify() { |
| 2182 | auto memRefType = llvm::cast<MemRefType>(Val: getMemref().getType()); |
| 2183 | |
| 2184 | if (failed(Result: verifyDynamicDimensionCount(op: getOperation(), type: memRefType, |
| 2185 | dynamicSizes: getDynamicSizes()))) |
| 2186 | return failure(); |
| 2187 | |
| 2188 | unsigned numSymbols = 0; |
| 2189 | if (!memRefType.getLayout().isIdentity()) |
| 2190 | numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols(); |
| 2191 | if (getSymbolOperands().size() != numSymbols) { |
| 2192 | return emitOpError( |
| 2193 | message: "symbol operand count does not equal memref symbol count" ); |
| 2194 | } |
| 2195 | |
| 2196 | return success(); |
| 2197 | } |
| 2198 | |
| 2199 | namespace { |
| 2200 | /// Folding of memref.dim(gpu.alloc(%size), %idx) -> %size similar to |
| 2201 | /// `memref::AllocOp`. |
| 2202 | struct SimplifyDimOfAllocOp : public OpRewritePattern<memref::DimOp> { |
| 2203 | using OpRewritePattern<memref::DimOp>::OpRewritePattern; |
| 2204 | |
| 2205 | LogicalResult matchAndRewrite(memref::DimOp dimOp, |
| 2206 | PatternRewriter &rewriter) const override { |
| 2207 | std::optional<int64_t> index = dimOp.getConstantIndex(); |
| 2208 | if (!index) |
| 2209 | return failure(); |
| 2210 | |
| 2211 | int64_t indexVal = index.value(); |
| 2212 | auto memrefType = llvm::dyn_cast<MemRefType>(Val: dimOp.getSource().getType()); |
| 2213 | if (!memrefType || indexVal < 0 || indexVal >= memrefType.getRank() || |
| 2214 | !memrefType.isDynamicDim(idx: indexVal)) |
| 2215 | return failure(); |
| 2216 | |
| 2217 | auto alloc = dimOp.getSource().getDefiningOp<AllocOp>(); |
| 2218 | if (!alloc) |
| 2219 | return failure(); |
| 2220 | |
| 2221 | Value substituteOp = *(alloc.getDynamicSizes().begin() + |
| 2222 | memrefType.getDynamicDimIndex(index: indexVal)); |
| 2223 | rewriter.replaceOp(op: dimOp, newValues: substituteOp); |
| 2224 | return success(); |
| 2225 | } |
| 2226 | }; |
| 2227 | } // namespace |
| 2228 | |
| 2229 | void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results, |
| 2230 | MLIRContext *context) { |
| 2231 | results.add<SimplifyDimOfAllocOp>(arg&: context); |
| 2232 | } |
| 2233 | |
| 2234 | //===----------------------------------------------------------------------===// |
| 2235 | // DynamicSharedMemoryOp |
| 2236 | //===----------------------------------------------------------------------===// |
| 2237 | |
| 2238 | LogicalResult gpu::DynamicSharedMemoryOp::verify() { |
| 2239 | if (!getOperation()->getParentWithTrait<OpTrait::SymbolTable>()) |
| 2240 | return emitOpError() << "must be inside an op with symbol table" ; |
| 2241 | |
| 2242 | MemRefType memrefType = getResultMemref().getType(); |
| 2243 | // Check address space |
| 2244 | if (!GPUDialect::hasWorkgroupMemoryAddressSpace(type: memrefType)) { |
| 2245 | return emitOpError() << "address space must be " |
| 2246 | << gpu::AddressSpaceAttr::getMnemonic() << "<" |
| 2247 | << stringifyEnum(enumValue: gpu::AddressSpace::Workgroup) << ">" ; |
| 2248 | } |
| 2249 | if (memrefType.hasStaticShape()) { |
| 2250 | return emitOpError() << "result memref type must be memref<?xi8, " |
| 2251 | "#gpu.address_space<workgroup>>" ; |
| 2252 | } |
| 2253 | return success(); |
| 2254 | } |
| 2255 | |
| 2256 | //===----------------------------------------------------------------------===// |
| 2257 | // GPU WarpExecuteOnLane0Op |
| 2258 | //===----------------------------------------------------------------------===// |
| 2259 | |
| 2260 | void WarpExecuteOnLane0Op::print(OpAsmPrinter &p) { |
| 2261 | p << "(" << getLaneid() << ")" ; |
| 2262 | |
| 2263 | SmallVector<StringRef> coreAttr = {getWarpSizeAttrName()}; |
| 2264 | p << "[" << getWarpSize() << "]" ; |
| 2265 | |
| 2266 | if (!getArgs().empty()) |
| 2267 | p << " args(" << getArgs() << " : " << getArgs().getTypes() << ")" ; |
| 2268 | if (!getResults().empty()) |
| 2269 | p << " -> (" << getResults().getTypes() << ')'; |
| 2270 | p << " " ; |
| 2271 | p.printRegion(blocks&: getRegion(), |
| 2272 | /*printEntryBlockArgs=*/true, |
| 2273 | /*printBlockTerminators=*/!getResults().empty()); |
| 2274 | p.printOptionalAttrDict( |
| 2275 | attrs: getOperation()->getDiscardableAttrDictionary().getValue(), elidedAttrs: coreAttr); |
| 2276 | } |
| 2277 | |
| 2278 | ParseResult WarpExecuteOnLane0Op::parse(OpAsmParser &parser, |
| 2279 | OperationState &result) { |
| 2280 | // Create the region. |
| 2281 | result.regions.reserve(N: 1); |
| 2282 | Region *warpRegion = result.addRegion(); |
| 2283 | |
| 2284 | auto &builder = parser.getBuilder(); |
| 2285 | OpAsmParser::UnresolvedOperand laneId; |
| 2286 | |
| 2287 | // Parse predicate operand. |
| 2288 | if (parser.parseLParen() || |
| 2289 | parser.parseOperand(result&: laneId, /*allowResultNumber=*/false) || |
| 2290 | parser.parseRParen()) |
| 2291 | return failure(); |
| 2292 | |
| 2293 | int64_t warpSize; |
| 2294 | if (parser.parseLSquare() || parser.parseInteger(result&: warpSize) || |
| 2295 | parser.parseRSquare()) |
| 2296 | return failure(); |
| 2297 | result.addAttribute(name: getWarpSizeAttrName(name: OperationName(getOperationName(), |
| 2298 | builder.getContext())), |
| 2299 | attr: builder.getI64IntegerAttr(value: warpSize)); |
| 2300 | |
| 2301 | if (parser.resolveOperand(operand: laneId, type: builder.getIndexType(), result&: result.operands)) |
| 2302 | return failure(); |
| 2303 | |
| 2304 | llvm::SMLoc inputsOperandsLoc; |
| 2305 | SmallVector<OpAsmParser::UnresolvedOperand> inputsOperands; |
| 2306 | SmallVector<Type> inputTypes; |
| 2307 | if (succeeded(Result: parser.parseOptionalKeyword(keyword: "args" ))) { |
| 2308 | if (parser.parseLParen()) |
| 2309 | return failure(); |
| 2310 | |
| 2311 | inputsOperandsLoc = parser.getCurrentLocation(); |
| 2312 | if (parser.parseOperandList(result&: inputsOperands) || |
| 2313 | parser.parseColonTypeList(result&: inputTypes) || parser.parseRParen()) |
| 2314 | return failure(); |
| 2315 | } |
| 2316 | if (parser.resolveOperands(operands&: inputsOperands, types&: inputTypes, loc: inputsOperandsLoc, |
| 2317 | result&: result.operands)) |
| 2318 | return failure(); |
| 2319 | |
| 2320 | // Parse optional results type list. |
| 2321 | if (parser.parseOptionalArrowTypeList(result&: result.types)) |
| 2322 | return failure(); |
| 2323 | // Parse the region. |
| 2324 | if (parser.parseRegion(region&: *warpRegion, /*arguments=*/{}, |
| 2325 | /*argTypes=*/enableNameShadowing: {})) |
| 2326 | return failure(); |
| 2327 | WarpExecuteOnLane0Op::ensureTerminator(region&: *warpRegion, builder, loc: result.location); |
| 2328 | |
| 2329 | // Parse the optional attribute list. |
| 2330 | if (parser.parseOptionalAttrDict(result&: result.attributes)) |
| 2331 | return failure(); |
| 2332 | return success(); |
| 2333 | } |
| 2334 | |
| 2335 | void WarpExecuteOnLane0Op::getSuccessorRegions( |
| 2336 | RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) { |
| 2337 | if (!point.isParent()) { |
| 2338 | regions.push_back(Elt: RegionSuccessor(getOperation())); |
| 2339 | return; |
| 2340 | } |
| 2341 | |
| 2342 | // The warp region is always executed |
| 2343 | regions.push_back(Elt: RegionSuccessor(&getWarpRegion())); |
| 2344 | } |
| 2345 | |
| 2346 | ValueRange WarpExecuteOnLane0Op::getSuccessorInputs(RegionSuccessor successor) { |
| 2347 | return successor.isOperation() ? ValueRange(getResults()) : ValueRange(); |
| 2348 | } |
| 2349 | void WarpExecuteOnLane0Op::build(OpBuilder &builder, OperationState &result, |
| 2350 | TypeRange resultTypes, Value laneId, |
| 2351 | int64_t warpSize) { |
| 2352 | build(odsBuilder&: builder, odsState&: result, resultTypes, laneid: laneId, warpSize, |
| 2353 | /*operands=*/args: {}, /*argTypes=*/blockArgTypes: {}); |
| 2354 | } |
| 2355 | |
| 2356 | void WarpExecuteOnLane0Op::build(OpBuilder &builder, OperationState &result, |
| 2357 | TypeRange resultTypes, Value laneId, |
| 2358 | int64_t warpSize, ValueRange args, |
| 2359 | TypeRange blockArgTypes) { |
| 2360 | result.addOperands(newOperands: laneId); |
| 2361 | result.addAttribute(name: getAttributeNames()[0], |
| 2362 | attr: builder.getI64IntegerAttr(value: warpSize)); |
| 2363 | result.addTypes(newTypes&: resultTypes); |
| 2364 | result.addOperands(newOperands: args); |
| 2365 | assert(args.size() == blockArgTypes.size()); |
| 2366 | OpBuilder::InsertionGuard guard(builder); |
| 2367 | Region *warpRegion = result.addRegion(); |
| 2368 | Block *block = builder.createBlock(parent: warpRegion); |
| 2369 | for (auto [type, arg] : llvm::zip_equal(t&: blockArgTypes, u&: args)) |
| 2370 | block->addArgument(type, loc: arg.getLoc()); |
| 2371 | } |
| 2372 | |
| 2373 | /// Helper check if the distributed vector type is consistent with the expanded |
| 2374 | /// type and distributed size. |
| 2375 | static LogicalResult verifyDistributedType(Type expanded, Type distributed, |
| 2376 | int64_t warpSize, Operation *op) { |
| 2377 | // If the types matches there is no distribution. |
| 2378 | if (expanded == distributed) |
| 2379 | return success(); |
| 2380 | auto expandedVecType = llvm::dyn_cast<VectorType>(Val&: expanded); |
| 2381 | auto distributedVecType = llvm::dyn_cast<VectorType>(Val&: distributed); |
| 2382 | if (!expandedVecType || !distributedVecType) |
| 2383 | return op->emitOpError(message: "expected vector type for distributed operands." ); |
| 2384 | if (expandedVecType.getRank() != distributedVecType.getRank() || |
| 2385 | expandedVecType.getElementType() != distributedVecType.getElementType()) |
| 2386 | return op->emitOpError( |
| 2387 | message: "expected distributed vectors to have same rank and element type." ); |
| 2388 | |
| 2389 | SmallVector<int64_t> scales(expandedVecType.getRank(), 1); |
| 2390 | for (int64_t i = 0, e = expandedVecType.getRank(); i < e; i++) { |
| 2391 | int64_t eDim = expandedVecType.getDimSize(idx: i); |
| 2392 | int64_t dDim = distributedVecType.getDimSize(idx: i); |
| 2393 | if (eDim == dDim) |
| 2394 | continue; |
| 2395 | if (eDim % dDim != 0) |
| 2396 | return op->emitOpError() |
| 2397 | << "expected expanded vector dimension #" << i << " (" << eDim |
| 2398 | << ") to be a multipler of the distributed vector dimension (" |
| 2399 | << dDim << ")" ; |
| 2400 | scales[i] = eDim / dDim; |
| 2401 | } |
| 2402 | if (llvm::product_of(Range&: scales) != warpSize) |
| 2403 | return op->emitOpError() |
| 2404 | << "incompatible distribution dimensions from " << expandedVecType |
| 2405 | << " to " << distributedVecType << " with warp size = " << warpSize; |
| 2406 | |
| 2407 | return success(); |
| 2408 | } |
| 2409 | |
| 2410 | LogicalResult WarpExecuteOnLane0Op::verify() { |
| 2411 | if (getArgs().size() != getWarpRegion().getNumArguments()) |
| 2412 | return emitOpError( |
| 2413 | message: "expected same number op arguments and block arguments." ); |
| 2414 | auto yield = dyn_cast<gpu::YieldOp>(Val: getBody()->getTerminator()); |
| 2415 | if (!yield) |
| 2416 | return emitOpError(message: "expected body to be terminated with 'gpu.yield'" ); |
| 2417 | if (yield.getNumOperands() != getNumResults()) |
| 2418 | return emitOpError( |
| 2419 | message: "expected same number of yield operands and return values." ); |
| 2420 | int64_t warpSize = getWarpSize(); |
| 2421 | for (auto [regionArg, arg] : |
| 2422 | llvm::zip_equal(t: getWarpRegion().getArguments(), u: getArgs())) { |
| 2423 | if (failed(Result: verifyDistributedType(expanded: regionArg.getType(), distributed: arg.getType(), |
| 2424 | warpSize, op: getOperation()))) |
| 2425 | return failure(); |
| 2426 | } |
| 2427 | for (auto [yieldOperand, result] : |
| 2428 | llvm::zip_equal(t: yield.getOperands(), u: getResults())) { |
| 2429 | if (failed(Result: verifyDistributedType(expanded: yieldOperand.getType(), distributed: result.getType(), |
| 2430 | warpSize, op: getOperation()))) |
| 2431 | return failure(); |
| 2432 | } |
| 2433 | return success(); |
| 2434 | } |
| 2435 | bool WarpExecuteOnLane0Op::areTypesCompatible(Type lhs, Type rhs) { |
| 2436 | return succeeded( |
| 2437 | Result: verifyDistributedType(expanded: lhs, distributed: rhs, warpSize: getWarpSize(), op: getOperation())); |
| 2438 | } |
| 2439 | |
| 2440 | gpu::YieldOp WarpExecuteOnLane0Op::getTerminator() { |
| 2441 | return cast<gpu::YieldOp>(Val: getBody()->getTerminator()); |
| 2442 | } |
| 2443 | |
| 2444 | //===----------------------------------------------------------------------===// |
| 2445 | // GPU_SubgroupBroadcastOp |
| 2446 | //===----------------------------------------------------------------------===// |
| 2447 | |
| 2448 | void gpu::SubgroupBroadcastOp::inferResultRanges( |
| 2449 | ArrayRef<ConstantIntRanges> argRanges, SetIntRangeFn setResultRange) { |
| 2450 | setResultRange(getResult(), argRanges.front()); |
| 2451 | } |
| 2452 | |
| 2453 | Speculation::Speculatability gpu::SubgroupBroadcastOp::getSpeculatability() { |
| 2454 | switch (getBroadcastType()) { |
| 2455 | case BroadcastType::first_active_lane: |
| 2456 | // Cannot speculate first_lane broadcast, because speculating it across |
| 2457 | // control flow can change the active lanes. |
| 2458 | return Speculation::NotSpeculatable; |
| 2459 | case BroadcastType::specific_lane: |
| 2460 | // Speculation should be safe as long as we inside structured control flow. |
| 2461 | return Speculation::Speculatable; |
| 2462 | } |
| 2463 | llvm_unreachable("Unknown BroadcastType" ); |
| 2464 | } |
| 2465 | |
| 2466 | LogicalResult gpu::SubgroupBroadcastOp::verify() { |
| 2467 | switch (getBroadcastType()) { |
| 2468 | case BroadcastType::first_active_lane: |
| 2469 | if (getLane()) |
| 2470 | return emitOpError() |
| 2471 | << "lane can only be specified for `specific_lane` broadcast" ; |
| 2472 | return success(); |
| 2473 | case BroadcastType::specific_lane: |
| 2474 | if (!getLane()) |
| 2475 | return emitOpError() |
| 2476 | << "lane must be specified for `specific_lane` broadcast" ; |
| 2477 | return success(); |
| 2478 | } |
| 2479 | llvm_unreachable("Unknown BroadcastType" ); |
| 2480 | } |
| 2481 | |
| 2482 | OpFoldResult gpu::SubgroupBroadcastOp::fold(FoldAdaptor /*adaptor*/) { |
| 2483 | // Broadcast result is always uniform. |
| 2484 | if (auto prev = getSrc().getDefiningOp<SubgroupBroadcastOp>()) |
| 2485 | return prev.getResult(); |
| 2486 | |
| 2487 | return nullptr; |
| 2488 | } |
| 2489 | |
| 2490 | //===----------------------------------------------------------------------===// |
| 2491 | // GPU_BallotOp |
| 2492 | //===----------------------------------------------------------------------===// |
| 2493 | |
| 2494 | // No custom implementations needed; ballot uses default behavior from ODS. |
| 2495 | |
| 2496 | #include "mlir/Dialect/GPU/IR/GPUOpInterfaces.cpp.inc" |
| 2497 | |
| 2498 | #define GET_OP_CLASSES |
| 2499 | #include "mlir/Dialect/GPU/IR/GPUOps.cpp.inc" |
| 2500 | |