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"
49#include "mlir/Dialect/GPU/IR/GPUOpsDialect.cpp.inc"
55template <
typename... Attrs>
56void registerAttributeMetadata(
63struct GPUDialectBytecodeInterface : BytecodeDialectInterface {
64 using BytecodeDialectInterface::BytecodeDialectInterface;
66 void writeVersion(DialectBytecodeWriter &writer)
const override {
70 std::unique_ptr<DialectVersion>
71 readVersion(DialectBytecodeReader &reader)
const override {
76 reader.
emitError(
"unsupported gpu dialect bytecode version");
79 return std::make_unique<DialectVersion>();
84int64_t GPUMappingMaskAttr::getMaxNumPhysicalIds()
const {
return 64; }
96Value GPUMappingMaskAttr::createLogicalLinearMappingId(
100 arith::ConstantOp::create(
b, loc,
b.getI64IntegerAttr(getMask()));
101 Value one = arith::ConstantOp::create(
b, loc,
b.getI64IntegerAttr(1));
102 Value filter = arith::ShLIOp::create(
b, loc, one, physicalLinearMappingId);
103 filter = arith::SubIOp::create(
b, loc, filter, one);
104 Value filteredId = arith::AndIOp::create(
b, loc, mask, filter);
105 return math::CtPopOp::create(
b, loc, filteredId);
118Value GPUMappingMaskAttr::createIsActiveIdPredicate(
122 arith::ConstantOp::create(
b, loc,
b.getI64IntegerAttr(getMask()));
123 Value one = arith::ConstantOp::create(
b, loc,
b.getI64IntegerAttr(1));
124 Value filter = arith::ShLIOp::create(
b, loc, one, physicalLinearMappingId);
125 Value filtered = arith::AndIOp::create(
b, loc, mask, filter);
126 Value zero = arith::ConstantOp::create(
b, loc,
b.getI64IntegerAttr(0));
127 return arith::CmpIOp::create(
b, loc, arith::CmpIPredicate::ne, filtered,
131bool GPUDialect::isKernel(
Operation *op) {
132 if (
auto gpuFunc = dyn_cast<GPUFuncOp>(op))
133 return gpuFunc.isKernel();
134 return static_cast<bool>(
141struct GPUInlinerInterface :
public DialectInlinerInterface {
142 using DialectInlinerInterface::DialectInlinerInterface;
145 bool isLegalToInline(Operation *, Region *,
bool, IRMapping &)
const final {
151void GPUDialect::initialize() {
152 addInterfaces<GPUDialectBytecodeInterface>();
153 addTypes<AsyncTokenType>();
154 addTypes<MMAMatrixType>();
155 addTypes<NamedBarrierType>();
156 addTypes<SparseDnTensorHandleType>();
157 addTypes<SparseSpMatHandleType>();
158 addTypes<SparseSpGEMMOpHandleType>();
161 registerAttributeMetadata<
162#define GET_ATTRDEF_LIST
163#include "mlir/Dialect/GPU/IR/GPUOpsAttributes.cpp.inc"
165 addAttribute(
id, std::move(attribute));
168 addInterfaces<GPUInlinerInterface>();
169 declarePromisedInterface<bufferization::BufferDeallocationOpInterface,
171 declarePromisedInterfaces<ValueBoundsOpInterface, ClusterDimOp,
172 ClusterDimBlocksOp, ClusterIdOp, ClusterBlockIdOp,
173 BlockDimOp, BlockIdOp, GridDimOp, ThreadIdOp,
174 LaneIdOp, SubgroupIdOp, GlobalIdOp, NumSubgroupsOp,
175 SubgroupSizeOp, LaunchOp, SubgroupBroadcastOp>();
176 declarePromisedInterfaces<memref::IndexedAccessOpInterface,
177 SubgroupMmaLoadMatrixOp,
178 SubgroupMmaStoreMatrixOp>();
184 return "sparse.dntensor_handle";
186 return "sparse.spmat_handle";
188 return "sparse.spgemmop_handle";
190 llvm_unreachable(
"unknown sparse handle kind");
202 if (keyword ==
"async.token")
205 if (keyword ==
"mma_matrix") {
234 shape, elementType, operand);
237 if (keyword ==
"named_barrier")
255 .Case<NamedBarrierType>([&](
Type) { os <<
"named_barrier"; })
256 .Case<SparseDnTensorHandleType>([&](
Type) {
259 .Case<SparseSpMatHandleType>(
261 .Case<SparseSpGEMMOpHandleType>([&](
Type) {
267 for (
auto dim =
shape.begin(), e =
shape.end() - 1; dim != e; ++dim)
270 os <<
", \"" << fragTy.
getOperand() <<
"\"" <<
'>';
272 .DefaultUnreachable(
"unexpected 'gpu' type kind");
277 auto array = dyn_cast<DenseI32ArrayAttr>(attr.
getValue());
280 " must be a dense i32 array");
281 if (array.size() != 3)
283 " must contain exactly 3 elements");
287LogicalResult GPUDialect::verifyOperationAttribute(
Operation *op,
289 if (attr.
getName() == getKnownBlockSizeAttrHelper().getName())
291 if (attr.
getName() == getKnownGridSizeAttrHelper().getName())
293 if (attr.
getName() == getKnownClusterSizeAttrHelper().getName())
295 if (!llvm::isa<UnitAttr>(attr.
getValue()) ||
296 attr.
getName() != getContainerModuleAttrName())
299 auto module = dyn_cast<ModuleOp>(op);
302 << getContainerModuleAttrName() <<
"' attribute to be attached to '"
303 << ModuleOp::getOperationName() <<
'\'';
317 return parser.
emitError(loc,
"needs to be named when marked 'async'");
332 if (asyncDependencies.empty())
336 printer << llvm::interleaved_array(asyncDependencies);
364 p <<
' ' << keyword <<
'(';
365 llvm::interleaveComma(
366 llvm::enumerate(values), p, [&p, attributes](
auto pair) {
368 p << v <<
" : " << v.
getType();
370 size_t attributionIndex = pair.index();
371 DictionaryAttr attrs;
372 if (attributes && attributionIndex < attributes.size())
373 attrs = llvm::cast<DictionaryAttr>(attributes[attributionIndex]);
383 gpu::AddressSpace memorySpace) {
384 for (
Value v : attributions) {
385 auto type = llvm::dyn_cast<MemRefType>(v.
getType());
387 return op->
emitOpError() <<
"expected memref type in attribution";
392 llvm::dyn_cast_or_null<gpu::AddressSpaceAttr>(type.getMemorySpace());
395 if (addressSpace.getValue() != memorySpace)
397 <<
"expected memory space " << stringifyAddressSpace(memorySpace)
398 <<
" in attribution";
409 using Kind = gpu::AllReduceOperation;
410 if (llvm::is_contained({Kind::MINNUMF, Kind::MAXNUMF, Kind::MINIMUMF,
411 Kind::MAXIMUMF, Kind::MINIMUMNUMF, Kind::MAXIMUMNUMF},
413 if (!isa<FloatType>(resType))
417 if (llvm::is_contained({Kind::MINSI, Kind::MINUI, Kind::MAXSI, Kind::MAXUI,
418 Kind::AND, Kind::OR, Kind::XOR},
420 if (!isa<IntegerType>(resType))
427LogicalResult gpu::AllReduceOp::verifyRegions() {
428 if (getBody().empty() != getOp().has_value())
429 return emitError(
"expected either an op attribute or a non-empty body");
430 if (!getBody().empty()) {
431 if (getBody().getNumArguments() != 2)
432 return emitError(
"expected two region arguments");
433 for (
auto argument : getBody().getArguments()) {
434 if (argument.getType() !=
getType())
435 return emitError(
"incorrect region argument type");
437 unsigned yieldCount = 0;
438 for (
Block &block : getBody()) {
439 if (
auto yield = dyn_cast<gpu::YieldOp>(block.getTerminator())) {
440 if (yield.getNumOperands() != 1)
441 return emitError(
"expected one gpu.yield operand");
442 if (yield.getOperand(0).getType() !=
getType())
443 return emitError(
"incorrect gpu.yield type");
448 return emitError(
"expected gpu.yield op in region");
450 gpu::AllReduceOperation opName = *getOp();
452 return emitError() <<
'`' << gpu::stringifyAllReduceOperation(opName)
453 <<
"` reduction operation is not compatible with type "
462 auto launchOp = dyn_cast<gpu::LaunchOp>(op->
getParentOp());
466 Region &body = launchOp.getBody();
467 assert(!body.
empty() &&
"Invalid region");
486LogicalResult gpu::SubgroupReduceOp::verify() {
488 if (
auto vecTy = dyn_cast<VectorType>(elemType)) {
489 if (vecTy.isScalable())
490 return emitOpError() <<
"is not compatible with scalable vector types";
492 elemType = vecTy.getElementType();
495 gpu::AllReduceOperation opName = getOp();
497 return emitError() <<
'`' << gpu::stringifyAllReduceOperation(opName)
498 <<
"` reduction operation is not compatible with type "
502 auto clusterSize = getClusterSize();
504 uint32_t size = *clusterSize;
505 if (!llvm::isPowerOf2_32(size)) {
506 return emitOpError() <<
"cluster size " << size
507 <<
" is not a power of two";
511 uint32_t stride = getClusterStride();
512 if (stride != 1 && !clusterSize) {
513 return emitOpError() <<
"cluster stride can only be specified if cluster "
516 if (!llvm::isPowerOf2_32(stride)) {
517 return emitOpError() <<
"cluster stride " << stride
518 <<
" is not a power of two";
525 if (getClusterSize() == 1)
542 if (!op->template hasTrait<OpTrait::AttrSizedOperandSegments>())
546 auto sizeAttr = dyn_cast_or_null<DenseI32ArrayAttr>(
566 Value getBlockSizeZ,
Value dynamicSharedMemorySize,
574 if (!workgroupAttributions.empty())
576 getWorkgroupAttributionsAttrName(
result.name),
580 result.addOperands(asyncDependencies);
585 result.addOperands({gridSizeX, gridSizeY, gridSizeZ, getBlockSizeX,
586 getBlockSizeY, getBlockSizeZ});
588 result.addOperands(clusterSizeX);
590 result.addOperands(clusterSizeY);
592 result.addOperands(clusterSizeZ);
593 if (dynamicSharedMemorySize)
594 result.addOperands(dynamicSharedMemorySize);
596 result.addOperands(asyncObject);
600 result.addAttribute(getModuleAttrName(
result.name), module);
602 result.addAttribute(getFunctionAttrName(
result.name), function);
610 for (
unsigned i = 0; i < kNumConfigRegionAttributes; ++i)
613 for (
Type argTy : workgroupAttributions)
615 for (
Type argTy : privateAttributions)
619 segmentSizes.front() = asyncDependencies.size();
620 segmentSizes[7] = clusterSizeX ? 1 : 0;
621 segmentSizes[8] = clusterSizeY ? 1 : 0;
622 segmentSizes[9] = clusterSizeZ ? 1 : 0;
623 segmentSizes[10] = dynamicSharedMemorySize ? 1 : 0;
624 segmentSizes[11] = asyncObject ? 1 : 0;
625 result.addAttribute(getOperandSegmentSizeAttr(),
630 assert(!getBody().empty() &&
"LaunchOp body must not be empty.");
631 auto args = getBody().getArguments();
636 assert(!getBody().empty() &&
"LaunchOp body must not be empty.");
637 auto args = getBody().getArguments();
642 assert(!getBody().empty() &&
"LaunchOp body must not be empty.");
643 auto args = getBody().getArguments();
648 assert(!getBody().empty() &&
"LaunchOp body must not be empty.");
649 auto args = getBody().getArguments();
650 return KernelDim3{args[9], args[10], args[11]};
653std::optional<KernelDim3> LaunchOp::getClusterIds() {
654 assert(!getBody().empty() &&
"LaunchOp body must not be empty.");
655 if (!hasClusterSize())
657 auto args = getBody().getArguments();
658 return KernelDim3{args[12], args[13], args[14]};
661std::optional<KernelDim3> LaunchOp::getClusterSize() {
662 assert(!getBody().empty() &&
"LaunchOp body must not be empty.");
663 if (!hasClusterSize())
665 auto args = getBody().getArguments();
666 return KernelDim3{args[15], args[16], args[17]};
669KernelDim3 LaunchOp::getGridSizeOperandValues() {
670 auto operands = getOperands().drop_front(getAsyncDependencies().size());
671 return KernelDim3{operands[0], operands[1], operands[2]};
674KernelDim3 LaunchOp::getBlockSizeOperandValues() {
675 auto operands = getOperands().drop_front(getAsyncDependencies().size());
676 return KernelDim3{operands[3], operands[4], operands[5]};
679std::optional<KernelDim3> LaunchOp::getClusterSizeOperandValues() {
680 auto operands = getOperands().drop_front(getAsyncDependencies().size());
681 if (!hasClusterSize())
683 return KernelDim3{operands[6], operands[7], operands[8]};
686template <
typename OpTy>
688 if (!op.getAsyncDependencies().empty() && !op.getAsyncToken())
689 return op.emitOpError(
"dependency operands require the dependency-based "
690 "async model i.e. returning a token");
691 if (op.getAsyncToken() && op.getAsyncObject())
692 return op.emitOpError(
"stream-based and dependency-based async models are "
693 "mutually exclusive");
694 if (op.getNumResults() == 0 && op.getAsyncToken())
695 return op.emitOpError(
"needs to be named when async keyword is specified");
699LogicalResult LaunchOp::verify() {
703 if (!(hasClusterSize()) &&
704 (getClusterSizeX() || getClusterSizeY() || getClusterSizeZ()))
705 return emitOpError() <<
"cluster size must be all present";
709LogicalResult LaunchOp::verifyRegions() {
713 if (getBody().empty()) {
714 return emitOpError(
"body region is empty");
716 unsigned actualNumRegionArgs = getBody().getNumArguments();
717 unsigned expectedNumRegionArgs =
718 getNumConfigRegionAttributes() + getNumWorkgroupAttributions();
719 if (actualNumRegionArgs < expectedNumRegionArgs) {
720 return emitOpError(
"expected at least ")
721 << expectedNumRegionArgs <<
" region arguments, but got "
722 << actualNumRegionArgs;
727 GPUDialect::getWorkgroupAddressSpace())) ||
729 GPUDialect::getPrivateAddressSpace())))
734 for (
Block &block : getBody()) {
737 if (block.back().getNumSuccessors() != 0)
739 if (!isa<gpu::TerminatorOp>(&block.back())) {
742 .append(
"expected '", gpu::TerminatorOp::getOperationName(),
743 "' or a terminator with successors")
744 .attachNote(getLoc())
745 .append(
"in '", LaunchOp::getOperationName(),
"' body region");
758 p <<
'(' << ids.
x <<
", " << ids.
y <<
", " << ids.
z <<
") in (";
759 p << size.
x <<
" = " << operands.
x <<
", ";
760 p << size.
y <<
" = " << operands.
y <<
", ";
761 p << size.
z <<
" = " << operands.
z <<
')';
765 if (
auto asyncObject = getAsyncObject()) {
766 p <<
" <" << asyncObject <<
" : " << asyncObject.
getType() <<
">";
768 if (getAsyncToken()) {
770 if (!getAsyncDependencies().empty())
771 p <<
" [" << getAsyncDependencies() <<
']';
774 if (hasClusterSize()) {
775 p <<
' ' << getClustersKeyword();
777 getClusterSizeOperandValues().value(),
778 getClusterIds().value());
780 p <<
' ' << getBlocksKeyword();
783 p <<
' ' << getThreadsKeyword();
786 if (getDynamicSharedMemorySize())
787 p <<
' ' << getDynamicSharedMemorySizeKeyword() <<
' '
788 << getDynamicSharedMemorySize();
791 StringRef moduleAttrName = getModuleAttrName();
792 if (
auto module = getModule()) {
793 p <<
' ' << moduleAttrName <<
'(';
798 StringRef functionAttrName = getFunctionAttrName();
799 if (
auto function = getFunction()) {
800 p <<
' ' << functionAttrName <<
'(';
805 if (getCooperative())
815 (*this)->getDiscardableAttrDictionary().getValue(), {
816 LaunchOp::getOperandSegmentSizeAttr(),
817 getWorkgroupAttributionsAttrName(), getCooperativeAttrName(),
818 moduleAttrName, functionAttrName});
833 assert(
indices.size() == 3 &&
"space for three indices expected");
840 if (args.size() != 3) {
842 << keyword <<
" expects 3 arguments, but got " << args.size();
844 std::move(args.begin(), args.end(),
indices.begin());
846 for (
int i = 0; i < 3; ++i) {
872 sizes(LaunchOp::kNumConfigOperands);
876 LaunchOp::kNumConfigRegionAttributes);
880 Type asyncObjectType;
881 bool hasAsyncObject =
false;
883 hasAsyncObject =
true;
901 "gpu.launch requires 'async' keyword to return a value");
902 result.types.push_back(asyncTokenType);
905 bool hasCluster =
false;
909 regionArgs.resize(18);
918 parser, sizesRef.drop_front(6), regionArgsRef.slice(15, 3),
919 regionArgsRef.slice(12, 3), LaunchOp::getClustersKeyword()))
927 if (parser.
parseKeyword(LaunchOp::getBlocksKeyword()) ||
929 regionArgsRef.slice(6, 3), regionArgsRef.slice(0, 3),
930 LaunchOp::getBlocksKeyword()) ||
933 regionArgsRef.slice(9, 3), regionArgsRef.slice(3, 3),
934 LaunchOp::getThreadsKeyword()) ||
940 bool hasDynamicSharedMemorySize =
false;
942 LaunchOp::getDynamicSharedMemorySizeKeyword())) {
943 hasDynamicSharedMemorySize =
true;
953 asyncObjectType,
result.operands))
957 StringRef moduleAttrName = getModuleAttrName(
result.name);
967 StringRef functionAttrName = getFunctionAttrName(
result.name);
986 LaunchOp::kNumConfigRegionAttributes + 6,
index);
989 for (
auto ssaValueAndType : llvm::zip(regionArgs, dataTypes)) {
991 arg.
ssaName = std::get<0>(ssaValueAndType);
992 arg.
type = std::get<1>(ssaValueAndType);
993 regionArguments.push_back(arg);
1004 unsigned numWorkgroupAttrs = regionArguments.size() -
1005 LaunchOp::kNumConfigRegionAttributes -
1006 (hasCluster ? 6 : 0);
1007 if (numWorkgroupAttrs != 0)
1008 result.addAttribute(LaunchOp::getWorkgroupAttributionsAttrName(
result.name),
1025 segmentSizes.front() = asyncDependencies.size();
1028 segmentSizes[7] = 0;
1029 segmentSizes[8] = 0;
1030 segmentSizes[9] = 0;
1032 segmentSizes[10] = hasDynamicSharedMemorySize ? 1 : 0;
1033 segmentSizes[11] = hasAsyncObject ? 1 : 0;
1034 result.addAttribute(LaunchOp::getOperandSegmentSizeAttr(),
1048 bool simplified =
false;
1049 auto constPropIdUses = [&](
Value id,
Value size) {
1053 if (
id.getUses().empty())
1065 constPropIdUses(op.getBlockIds().x, op.getGridSizeX());
1066 constPropIdUses(op.getBlockIds().y, op.getGridSizeY());
1067 constPropIdUses(op.getBlockIds().z, op.getGridSizeZ());
1068 constPropIdUses(op.getThreadIds().x, op.getBlockSizeX());
1069 constPropIdUses(op.getThreadIds().y, op.getBlockSizeY());
1070 constPropIdUses(op.getThreadIds().z, op.getBlockSizeZ());
1084 int64_t cur = getWorkgroupAttributions().value_or(0);
1085 setWorkgroupAttributions(std::optional<int64_t>(cur + 1));
1086 return getBody().insertArgument(
1087 getNumConfigRegionAttributes() +
static_cast<unsigned>(cur), type, loc);
1095 return getBody().addArgument(type, loc);
1103 SymbolRefAttr kernelSymbol,
KernelDim3 gridSize,
1107 std::optional<KernelDim3> clusterSize) {
1108 assert(kernelSymbol.getNestedReferences().size() == 1 &&
1109 "expected a symbol reference with a single nested reference");
1110 result.addOperands(asyncDependencies);
1117 if (clusterSize.has_value())
1118 result.addOperands({clusterSize->x, clusterSize->y, clusterSize->z});
1119 if (dynamicSharedMemorySize)
1120 result.addOperands(dynamicSharedMemorySize);
1121 result.addOperands(kernelOperands);
1123 result.addOperands(asyncObject);
1125 Properties &prop =
result.getOrAddProperties<Properties>();
1126 prop.kernel = kernelSymbol;
1127 size_t segmentSizesLen = std::size(prop.operandSegmentSizes);
1129 llvm::fill(prop.operandSegmentSizes, 1);
1130 prop.operandSegmentSizes[0] = asyncDependencies.size();
1131 if (!clusterSize.has_value()) {
1132 prop.operandSegmentSizes[segmentSizesLen - 4] = 0;
1133 prop.operandSegmentSizes[segmentSizesLen - 5] = 0;
1134 prop.operandSegmentSizes[segmentSizesLen - 6] = 0;
1136 prop.operandSegmentSizes[segmentSizesLen - 3] =
1137 dynamicSharedMemorySize ? 1 : 0;
1138 prop.operandSegmentSizes[segmentSizesLen - 2] =
1139 static_cast<int32_t
>(kernelOperands.size());
1140 prop.operandSegmentSizes[segmentSizesLen - 1] = asyncObject ? 1 : 0;
1148 std::optional<KernelDim3> clusterSize) {
1149 auto kernelModule = kernelFunc->getParentOfType<GPUModuleOp>();
1151 SymbolRefAttr::get(kernelModule.getNameAttr(),
1152 {SymbolRefAttr::get(kernelFunc.getNameAttr())});
1153 build(builder,
result, kernelSymbol, gridSize, getBlockSize,
1154 dynamicSharedMemorySize, kernelOperands, asyncTokenType,
1155 asyncDependencies, asyncObject, clusterSize);
1158StringAttr LaunchFuncOp::getKernelModuleName() {
1162StringAttr LaunchFuncOp::getKernelName() {
1166unsigned LaunchFuncOp::getNumKernelOperands() {
1167 return getKernelOperands().size();
1170Value LaunchFuncOp::getKernelOperand(
unsigned i) {
1171 return getKernelOperands()[i];
1174KernelDim3 LaunchFuncOp::getGridSizeOperandValues() {
1175 auto operands = getOperands().drop_front(getAsyncDependencies().size());
1176 return KernelDim3{operands[0], operands[1], operands[2]};
1179KernelDim3 LaunchFuncOp::getBlockSizeOperandValues() {
1180 auto operands = getOperands().drop_front(getAsyncDependencies().size());
1181 return KernelDim3{operands[3], operands[4], operands[5]};
1184KernelDim3 LaunchFuncOp::getClusterSizeOperandValues() {
1185 assert(hasClusterSize() &&
1186 "cluster size is not set, check hasClusterSize() first");
1187 auto operands = getOperands().drop_front(getAsyncDependencies().size());
1188 return KernelDim3{operands[6], operands[7], operands[8]};
1191LogicalResult LaunchFuncOp::verify() {
1195 auto module = (*this)->getParentOfType<ModuleOp>();
1197 return emitOpError(
"expected to belong to a module");
1199 if (!module->getDiscardableAttrOfType<UnitAttr>(
1200 GPUDialect::getContainerModuleAttrName()))
1201 return emitOpError(
"expected the closest surrounding module to have the '" +
1202 GPUDialect::getContainerModuleAttrName() +
1205 if (hasClusterSize()) {
1206 if (getClusterSizeY().
getType() != getClusterSizeX().
getType() ||
1208 return emitOpError()
1209 <<
"expects types of the cluster dimensions must be the same";
1217 LaunchFuncOp launchOp = *
this;
1220 if (isa<GPUModuleOp>(table))
1225 if (!launchOp->getParentOp() ||
1226 launchOp->getParentOp()->getParentOp() != table)
1231 if (!launchOp.getKernelAttr())
1235 StringAttr kernelContainerName = launchOp.getKernelModuleName();
1238 if (!kernelContainer)
1240 <<
"kernel container '" << kernelContainerName.getValue()
1241 <<
"' is undefined";
1244 if (isa<BinaryOp>(kernelContainer))
1247 auto kernelModule = dyn_cast<GPUModuleOp>(kernelContainer);
1249 return launchOp.emitOpError()
1250 <<
"kernel module '" << kernelContainerName.getValue()
1251 <<
"' is undefined";
1255 kernelModule, launchOp.getKernelName());
1258 << launchOp.getKernel() <<
"' is undefined";
1259 auto kernelConvertedFunction = dyn_cast<FunctionOpInterface>(kernelFunc);
1260 if (!kernelConvertedFunction) {
1262 <<
"referenced kernel '" << launchOp.getKernel()
1263 <<
"' is not a function";
1264 diag.attachNote(kernelFunc->
getLoc()) <<
"see the kernel definition here";
1268 if (!GPUDialect::isKernel(kernelFunc))
1269 return launchOp.emitOpError(
"kernel function is missing the '")
1270 << GPUDialect::getKernelFuncAttrName() <<
"' attribute";
1275 auto kernelGPUFunction = dyn_cast<gpu::GPUFuncOp>(kernelFunc);
1276 if (!kernelGPUFunction)
1279 unsigned actualNumArguments = launchOp.getNumKernelOperands();
1280 unsigned expectedNumArguments = kernelGPUFunction.getNumArguments();
1281 if (expectedNumArguments != actualNumArguments)
1282 return launchOp.emitOpError(
"got ")
1283 << actualNumArguments <<
" kernel operands but expected "
1284 << expectedNumArguments;
1286 FunctionType functionType = kernelGPUFunction.getFunctionType();
1287 for (
unsigned i = 0; i < expectedNumArguments; ++i) {
1288 if (launchOp.getKernelOperand(i).getType() != functionType.getInput(i)) {
1289 return launchOp.emitOpError(
"type of function argument ")
1290 << i <<
" does not match";
1299 std::optional<OpAsmParser::UnresolvedOperand> clusterValue,
1300 Type &clusterXTy,
Type &clusterYTy,
Type &clusterZTy) {
1307 if (clusterValue.has_value()) {
1308 clusterXTy = clusterYTy = clusterZTy = dimTy;
1315 Type clusterYTy,
Type clusterZTy) {
1317 printer <<
": " << dimTy;
1327 auto parseElement = [&]() -> ParseResult {
1328 return failure(parser.
parseOperand(argNames.emplace_back()) ||
1333 parseElement,
" in argument list");
1338 if (operands.empty())
1341 llvm::interleaveComma(llvm::zip_equal(operands, types), printer,
1342 [&](
const auto &pair) {
1343 auto [operand, type] = pair;
1344 printer << operand <<
" : " << type;
1354 int32_t offset, int32_t width, ShuffleMode mode) {
1355 build(builder,
result, value,
1356 arith::ConstantOp::create(builder,
result.location,
1358 arith::ConstantOp::create(builder,
result.location,
1367LogicalResult RotateOp::verify() {
1368 uint32_t offset = getOffset();
1369 uint32_t width = getWidth();
1371 if (offset >= width) {
1372 return emitOpError() <<
"offset must be in the range [0, " << width <<
")";
1382LogicalResult BarrierOp::verify() {
1383 BarrierScope scope = getScope();
1385 if (getNamedBarrier() && scope != BarrierScope::Workgroup)
1386 return emitOpError(
"named barriers require workgroup scope");
1394 auto nextOp = dyn_cast_or_null<BarrierOp>(op->getNextNode());
1399 if (op.getScope() != nextOp.getScope())
1403 if (op.getNamedBarrier() != nextOp.getNamedBarrier())
1406 std::optional<ArrayAttr> thisMemfence = op.getAddressSpaces();
1407 std::optional<ArrayAttr> nextMemfence = nextOp.getAddressSpaces();
1411 if (!nextMemfence) {
1412 op.removeAddressSpacesAttr();
1416 if (*thisMemfence == *nextMemfence) {
1420 llvm::SmallSetVector<Attribute, 4> mergedSpaces;
1422 mergedSpaces.insert(attr);
1424 mergedSpaces.insert(attr);
1425 op.setAddressSpacesAttr(rewriter.
getArrayAttr(mergedSpaces.takeVector()));
1440 std::optional<AddressSpace> addressSpace) {
1444 AddressSpaceAttr::get(odsBuilder.
getContext(), addressSpace.value()));
1446 odsBuilder, odsState, addressSpacesAttr,
Value{},
1447 BarrierScopeAttr::get(odsBuilder.
getContext(), BarrierScope::Workgroup));
1455 Value memrefToFence) {
1456 std::optional<AddressSpace> addrSpaceToFence;
1457 if (
auto memrefType = dyn_cast<BaseMemRefType>(memrefToFence.
getType()))
1458 if (
auto addrSpaceAttr = dyn_cast_if_present<gpu::AddressSpaceAttr>(
1459 memrefType.getMemorySpace()))
1460 addrSpaceToFence = addrSpaceAttr.getValue();
1461 return build(builder, odsState, addrSpaceToFence);
1471 int64_t cur = getWorkgroupAttributions().value_or(0);
1472 setWorkgroupAttributions(std::optional<int64_t>(cur + 1));
1473 return getBody().insertArgument(
1474 getFunctionType().getNumInputs() +
static_cast<unsigned>(cur), type, loc);
1482 return getBody().addArgument(type, loc);
1486 StringRef name, FunctionType type,
1492 result.getOrAddProperties<Properties>().sym_name =
1494 result.addAttribute(getFunctionTypeAttrName(
result.name),
1495 TypeAttr::get(type));
1496 result.addAttribute(getWorkgroupAttributionsAttrName(
result.name),
1498 result.addAttributes(attrs);
1503 for (
Type argTy : type.getInputs())
1505 for (
Type argTy : workgroupAttributions)
1507 for (
Type argTy : privateAttributions)
1526 size_t existingArgs = args.size();
1533 bool hadAttrs = llvm::any_of(
ArrayRef(args).drop_front(existingArgs),
1538 attributionAttrs =
nullptr;
1544 for (
const auto &argument :
ArrayRef(args).drop_front(existingArgs)) {
1545 if (!argument.attrs)
1548 attributionAttrsVec.push_back(argument.attrs);
1550 attributionAttrs = builder.
getArrayAttr(attributionAttrsVec);
1566 StringAttr nameAttr;
1573 parser,
false, entryArgs, isVariadic, resultTypes,
1577 if (!entryArgs.empty() && entryArgs[0].ssaName.name.empty())
1578 return parser.
emitError(signatureLocation)
1579 <<
"gpu.func requires named arguments";
1586 for (
auto &arg : entryArgs)
1587 argTypes.push_back(arg.
type);
1589 result.addAttribute(getFunctionTypeAttrName(
result.name),
1590 TypeAttr::get(type));
1593 builder,
result, entryArgs, resultAttrs, getArgAttrsAttrName(
result.name),
1594 getResAttrsAttrName(
result.name));
1599 entryArgs, workgroupAttributionAttrs)))
1604 unsigned numWorkgroupAttrs = entryArgs.size() - type.getNumInputs();
1605 if (numWorkgroupAttrs != 0)
1607 GPUFuncOp::getWorkgroupAttributionsAttrName(
result.name),
1609 if (workgroupAttributionAttrs)
1610 result.addAttribute(GPUFuncOp::getWorkgroupAttribAttrsAttrName(
result.name),
1611 workgroupAttributionAttrs);
1616 entryArgs, privateAttributionAttrs)))
1618 if (privateAttributionAttrs)
1619 result.addAttribute(GPUFuncOp::getPrivateAttribAttrsAttrName(
result.name),
1620 privateAttributionAttrs);
1624 result.addAttribute(GPUFuncOp::getKernelAttrName(
result.name),
1633 auto *body =
result.addRegion();
1641 FunctionType type = getFunctionType();
1647 getWorkgroupAttribAttrs().value_or(
nullptr));
1649 getPrivateAttribAttrs().value_or(
nullptr));
1651 p <<
' ' << getKernelKeyword();
1655 {getWorkgroupAttributionsAttrName(), getKernelAttrName(),
1656 GPUDialect::getKernelFuncAttrName(), getFunctionTypeAttrName(),
1657 getArgAttrsAttrName(), getResAttrsAttrName(),
1658 getWorkgroupAttribAttrsAttrName(), getPrivateAttribAttrsAttrName()});
1664 StringAttr attrName) {
1665 ArrayAttr allAttrs = attrName == op.getWorkgroupAttribAttrsAttrName()
1666 ? op.getWorkgroupAttribAttrsAttr()
1667 : op.getPrivateAttribAttrsAttr();
1668 if (!allAttrs ||
index >= allAttrs.size())
1669 return DictionaryAttr();
1670 return llvm::cast<DictionaryAttr>(allAttrs[
index]);
1673DictionaryAttr GPUFuncOp::getworkgroupAttributionAttrs(
unsigned index) {
1677DictionaryAttr GPUFuncOp::getPrivateAttributionAttrs(
unsigned index) {
1682 DictionaryAttr value, StringAttr attrName) {
1684 ArrayAttr allAttrs = attrName == op.getWorkgroupAttribAttrsAttrName()
1685 ? op.getWorkgroupAttribAttrsAttr()
1686 : op.getPrivateAttribAttrsAttr();
1689 elements.append(allAttrs.begin(), allAttrs.end());
1690 while (elements.size() <=
index)
1691 elements.push_back(DictionaryAttr::get(ctx));
1693 elements[
index] = DictionaryAttr::get(ctx);
1695 elements[
index] = value;
1696 ArrayAttr newValue = ArrayAttr::get(ctx, elements);
1697 if (attrName == op.getWorkgroupAttribAttrsAttrName())
1698 op.setWorkgroupAttribAttrsAttr(newValue);
1700 op.setPrivateAttribAttrsAttr(newValue);
1703void GPUFuncOp::setworkgroupAttributionAttrs(
unsigned index,
1704 DictionaryAttr value) {
1708void GPUFuncOp::setPrivateAttributionAttrs(
unsigned int index,
1709 DictionaryAttr value) {
1714 StringAttr name, StringAttr attrsName) {
1718 return dict.get(name);
1723 assert(
index < getNumWorkgroupAttributions() &&
1724 "index must map to a workgroup attribution");
1726 getWorkgroupAttribAttrsAttrName());
1731 assert(
index < getNumPrivateAttributions() &&
1732 "index must map to a private attribution");
1734 getPrivateAttribAttrsAttrName());
1738 Attribute value, StringAttr attrsName) {
1743 elems.append(oldDict.getValue().begin(), oldDict.getValue().end());
1746 bool mustSort =
true;
1747 for (
unsigned i = 0, e = elems.size(); i < e; ++i) {
1748 if (elems[i].getName() == name) {
1751 std::swap(elems[i], elems[elems.size() - 1]);
1763 elems.emplace_back(name, value);
1766 DictionaryAttr::sortInPlace(elems);
1768 auto newDict = DictionaryAttr::getWithSorted(ctx, elems);
1772void GPUFuncOp::setWorkgroupAttributionAttr(
unsigned index, StringAttr name,
1774 assert(
index < getNumWorkgroupAttributions() &&
1775 "index must map to a workgroup attribution");
1777 getWorkgroupAttribAttrsAttrName());
1780void GPUFuncOp::setPrivateAttributionAttr(
unsigned index, StringAttr name,
1782 assert(
index < getNumPrivateAttributions() &&
1783 "index must map to a private attribution");
1785 getPrivateAttribAttrsAttrName());
1788LogicalResult GPUFuncOp::verifyType() {
1789 if (isKernel() && getFunctionType().getNumResults() != 0)
1790 return emitOpError() <<
"expected void return type for kernel function";
1796LogicalResult GPUFuncOp::verifyBody() {
1798 return emitOpError() <<
"expected body with at least one block";
1799 unsigned numFuncArguments = getNumArguments();
1800 unsigned numWorkgroupAttributions = getNumWorkgroupAttributions();
1801 unsigned numBlockArguments = front().getNumArguments();
1802 if (numBlockArguments < numFuncArguments + numWorkgroupAttributions)
1803 return emitOpError() <<
"expected at least "
1804 << numFuncArguments + numWorkgroupAttributions
1805 <<
" arguments to body region";
1808 for (
unsigned i = 0; i < numFuncArguments; ++i) {
1809 Type blockArgType = front().getArgument(i).getType();
1810 if (funcArgTypes[i] != blockArgType)
1811 return emitOpError() <<
"expected body region argument #" << i
1812 <<
" to be of type " << funcArgTypes[i] <<
", got "
1817 GPUDialect::getWorkgroupAddressSpace())) ||
1819 GPUDialect::getPrivateAddressSpace())))
1829LogicalResult gpu::ReturnOp::verify() {
1830 GPUFuncOp function = (*this)->getParentOfType<GPUFuncOp>();
1832 FunctionType funType = function.getFunctionType();
1834 if (funType.getNumResults() != getOperands().size())
1835 return emitOpError()
1836 .append(
"expected ", funType.getNumResults(),
" result operands")
1837 .attachNote(function.getLoc())
1838 .append(
"return type declared here");
1840 for (
const auto &pair : llvm::enumerate(
1841 llvm::zip(function.getFunctionType().getResults(), getOperands()))) {
1842 auto [type, operand] = pair.value();
1843 if (type != operand.getType())
1844 return emitOpError() <<
"unexpected type `" << operand.getType()
1845 <<
"' for operand #" << pair.index();
1870 Properties &properties = getProperties();
1882 result.addRegion()->emplaceBlock();
1883 Properties &props =
result.getOrAddProperties<Properties>();
1885 props.targets = targets;
1887 props.offloadingHandler = offloadingHandler;
1893 build(builder,
result, name,
1899 if (
ArrayAttr targets = getTargetsAttr())
1900 return llvm::count(targets.getValue(),
target);
1905 ArrayAttr &targetsAttr = getProperties().targets;
1907 targetsAttr = ArrayAttr::get(
getContext(), targetsVector);
1910LogicalResult GPUModuleOp::verify() {
1911 auto targets = getTargetsAttr();
1916 for (
auto target : targets) {
1917 if (
auto verifyTargetAttr =
1918 llvm::dyn_cast<TargetAttrVerifyInterface>(
target)) {
1919 if (verifyTargetAttr.verifyTarget(getOperation()).
failed())
1931 auto &properties =
result.getOrAddProperties<Properties>();
1934 properties.objects = objects;
1935 if (offloadingHandler)
1936 properties.offloadingHandler = offloadingHandler;
1938 properties.offloadingHandler = builder.
getAttr<SelectObjectAttr>(
nullptr);
1943 build(builder,
result, name, offloadingHandler,
1955 if (!offloadingHandler)
1962 if (offloadingHandler != SelectObjectAttr::get(op->
getContext(),
nullptr))
1963 printer <<
'<' << offloadingHandler <<
'>';
1970LogicalResult MemcpyOp::verify() {
1971 auto srcType = getSrc().getType();
1972 auto dstType = getDst().getType();
1975 return emitOpError(
"arguments have incompatible element type");
1978 return emitOpError(
"arguments have incompatible shape");
1987 using OpRewritePattern<MemcpyOp>::OpRewritePattern;
1989 LogicalResult matchAndRewrite(MemcpyOp op,
1990 PatternRewriter &rewriter)
const override {
1991 Value dest = op.getDst();
2000 if (llvm::any_of(dest.
getUsers(), [op, dest](Operation *user) {
2001 return user != op &&
2002 !hasSingleEffect<MemoryEffects::Free>(user, dest);
2008 if (op.getAsyncDependencies().size() > 1 ||
2009 ((op.getAsyncDependencies().empty() && op.getAsyncToken()) ||
2010 (!op.getAsyncDependencies().empty() && !op.getAsyncToken())))
2012 rewriter.
replaceOp(op, op.getAsyncDependencies());
2020 results.
add<EraseTrivialCopyOp>(context);
2027LogicalResult SubgroupMmaLoadMatrixOp::verify() {
2028 auto srcType = getSrcMemref().getType();
2029 auto resType = getRes().getType();
2030 auto resMatrixType = llvm::cast<gpu::MMAMatrixType>(resType);
2031 auto operand = resMatrixType.getOperand();
2032 auto srcMemrefType = llvm::cast<MemRefType>(srcType);
2034 if (!srcMemrefType.isLastDimUnitStride())
2036 "expected source memref most minor dim must have unit stride");
2038 if (operand !=
"AOp" && operand !=
"BOp" && operand !=
"COp")
2039 return emitError(
"only AOp, BOp and COp can be loaded");
2048LogicalResult SubgroupMmaStoreMatrixOp::verify() {
2049 auto srcType = getSrc().getType();
2050 auto dstType = getDstMemref().getType();
2051 auto srcMatrixType = llvm::cast<gpu::MMAMatrixType>(srcType);
2052 auto dstMemrefType = llvm::cast<MemRefType>(dstType);
2054 if (!dstMemrefType.isLastDimUnitStride())
2056 "expected destination memref most minor dim must have unit stride");
2058 if (srcMatrixType.getOperand() !=
"COp")
2060 "expected the operand matrix being stored to have 'COp' operand type");
2069LogicalResult SubgroupMmaComputeOp::verify() {
2070 enum OperandMap {
A,
B,
C };
2072 opTypes.push_back(llvm::cast<MMAMatrixType>(getOpA().
getType()));
2073 opTypes.push_back(llvm::cast<MMAMatrixType>(getOpB().
getType()));
2074 opTypes.push_back(llvm::cast<MMAMatrixType>(getOpC().
getType()));
2076 if (opTypes[A].getOperand() !=
"AOp" || opTypes[B].getOperand() !=
"BOp" ||
2077 opTypes[C].getOperand() !=
"COp")
2078 return emitError(
"operands must be in the order AOp, BOp, COp");
2081 aShape = opTypes[
A].getShape();
2082 bShape = opTypes[
B].getShape();
2083 cShape = opTypes[
C].getShape();
2085 if (aShape[1] != bShape[0] || aShape[0] != cShape[0] ||
2086 bShape[1] != cShape[1])
2087 return emitError(
"operand shapes do not satisfy matmul constraints");
2092LogicalResult MemcpyOp::fold(FoldAdaptor adaptor,
2097LogicalResult MemsetOp::fold(FoldAdaptor adaptor,
2114 LogicalResult matchAndRewrite(WaitOp op,
2115 PatternRewriter &rewriter)
const final {
2116 auto predicate = [](Value value) {
2117 auto waitOp = value.getDefiningOp<WaitOp>();
2118 return waitOp && waitOp->getNumOperands() == 0;
2120 if (llvm::none_of(op.getAsyncDependencies(), predicate))
2122 SmallVector<Value> validOperands;
2123 for (Value operand : op->getOperands()) {
2124 if (predicate(operand))
2126 validOperands.push_back(operand);
2128 rewriter.
modifyOpInPlace(op, [&]() { op->setOperands(validOperands); });
2144 LogicalResult matchAndRewrite(WaitOp op,
2145 PatternRewriter &rewriter)
const final {
2148 if (op.getAsyncDependencies().empty() && !op.getAsyncToken()) {
2153 if (llvm::hasSingleElement(op.getAsyncDependencies()) &&
2154 op.getAsyncToken()) {
2155 rewriter.
replaceOp(op, op.getAsyncDependencies());
2159 if (op.getAsyncToken() && op.getAsyncToken().use_empty()) {
2170 results.
add<EraseRedundantGpuWaitOpPairs, SimplifyGpuWaitOp>(context);
2177LogicalResult AllocOp::verify() {
2178 auto memRefType = llvm::cast<MemRefType>(getMemref().
getType());
2184 unsigned numSymbols = 0;
2185 if (!memRefType.getLayout().isIdentity())
2186 numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols();
2187 if (getSymbolOperands().size() != numSymbols) {
2189 "symbol operand count does not equal memref symbol count");
2199 using OpRewritePattern<memref::DimOp>::OpRewritePattern;
2201 LogicalResult matchAndRewrite(memref::DimOp dimOp,
2202 PatternRewriter &rewriter)
const override {
2203 std::optional<int64_t> index = dimOp.getConstantIndex();
2207 int64_t indexVal = index.value();
2208 auto memrefType = llvm::dyn_cast<MemRefType>(dimOp.getSource().getType());
2209 if (!memrefType || indexVal < 0 || indexVal >= memrefType.getRank() ||
2210 !memrefType.isDynamicDim(indexVal))
2213 auto alloc = dimOp.getSource().getDefiningOp<AllocOp>();
2217 Value substituteOp = *(alloc.getDynamicSizes().begin() +
2218 memrefType.getDynamicDimIndex(indexVal));
2219 rewriter.
replaceOp(dimOp, substituteOp);
2227 results.
add<SimplifyDimOfAllocOp>(context);
2234LogicalResult gpu::DynamicSharedMemoryOp::verify() {
2235 if (!getOperation()->getParentWithTrait<OpTrait::SymbolTable>())
2236 return emitOpError() <<
"must be inside an op with symbol table";
2238 MemRefType memrefType = getResultMemref().getType();
2240 if (!GPUDialect::hasWorkgroupMemoryAddressSpace(memrefType)) {
2241 return emitOpError() <<
"address space must be "
2242 << gpu::AddressSpaceAttr::getMnemonic() <<
"<"
2243 << stringifyEnum(gpu::AddressSpace::Workgroup) <<
">";
2245 if (memrefType.hasStaticShape()) {
2246 return emitOpError() <<
"result memref type must be memref<?xi8, "
2247 "#gpu.address_space<workgroup>>";
2257 p <<
"(" << getLaneid() <<
")";
2260 p <<
"[" << getWarpSize() <<
"]";
2262 if (!getArgs().empty())
2263 p <<
" args(" << getArgs() <<
" : " << getArgs().getTypes() <<
")";
2264 if (!getResults().empty())
2265 p <<
" -> (" << getResults().getTypes() <<
')';
2269 !getResults().empty());
2271 getOperation()->getDiscardableAttrDictionary().getValue(), coreAttr);
2274ParseResult WarpExecuteOnLane0Op::parse(
OpAsmParser &parser,
2277 result.regions.reserve(1);
2300 llvm::SMLoc inputsOperandsLoc;
2312 if (parser.
resolveOperands(inputsOperands, inputTypes, inputsOperandsLoc,
2323 WarpExecuteOnLane0Op::ensureTerminator(*warpRegion, builder,
result.location);
2331void WarpExecuteOnLane0Op::getSuccessorRegions(
2348 build(builder,
result, resultTypes, laneId, warpSize,
2356 result.addOperands(laneId);
2357 result.addAttribute(getAttributeNames()[0],
2359 result.addTypes(resultTypes);
2360 result.addOperands(args);
2361 assert(args.size() == blockArgTypes.size());
2365 for (
auto [type, arg] : llvm::zip_equal(blockArgTypes, args))
2374 if (expanded == distributed)
2376 auto expandedVecType = llvm::dyn_cast<VectorType>(expanded);
2377 auto distributedVecType = llvm::dyn_cast<VectorType>(distributed);
2378 if (!expandedVecType || !distributedVecType)
2379 return op->
emitOpError(
"expected vector type for distributed operands.");
2380 if (expandedVecType.getRank() != distributedVecType.getRank() ||
2381 expandedVecType.getElementType() != distributedVecType.getElementType())
2383 "expected distributed vectors to have same rank and element type.");
2386 for (
int64_t i = 0, e = expandedVecType.getRank(); i < e; i++) {
2387 int64_t eDim = expandedVecType.getDimSize(i);
2388 int64_t dDim = distributedVecType.getDimSize(i);
2391 if (eDim % dDim != 0)
2393 <<
"expected expanded vector dimension #" << i <<
" (" << eDim
2394 <<
") to be a multipler of the distributed vector dimension ("
2396 scales[i] = eDim / dDim;
2398 if (llvm::product_of(scales) != warpSize)
2400 <<
"incompatible distribution dimensions from " << expandedVecType
2401 <<
" to " << distributedVecType <<
" with warp size = " << warpSize;
2406LogicalResult WarpExecuteOnLane0Op::verify() {
2407 if (getArgs().size() != getWarpRegion().getNumArguments())
2409 "expected same number op arguments and block arguments.");
2410 auto yield = dyn_cast<gpu::YieldOp>(getBody()->getTerminator());
2412 return emitOpError(
"expected body to be terminated with 'gpu.yield'");
2413 if (yield.getNumOperands() != getNumResults())
2415 "expected same number of yield operands and return values.");
2416 int64_t warpSize = getWarpSize();
2417 for (
auto [regionArg, arg] :
2418 llvm::zip_equal(getWarpRegion().getArguments(), getArgs())) {
2420 warpSize, getOperation())))
2423 for (
auto [yieldOperand,
result] :
2424 llvm::zip_equal(yield.getOperands(), getResults())) {
2426 warpSize, getOperation())))
2431bool WarpExecuteOnLane0Op::areTypesCompatible(
Type lhs,
Type rhs) {
2436gpu::YieldOp WarpExecuteOnLane0Op::getTerminator() {
2437 return cast<gpu::YieldOp>(getBody()->getTerminator());
2444void gpu::SubgroupBroadcastOp::inferResultRanges(
2446 setResultRange(getResult(), argRanges.front());
2450 switch (getBroadcastType()) {
2451 case BroadcastType::first_active_lane:
2455 case BroadcastType::specific_lane:
2459 llvm_unreachable(
"Unknown BroadcastType");
2462LogicalResult gpu::SubgroupBroadcastOp::verify() {
2463 switch (getBroadcastType()) {
2464 case BroadcastType::first_active_lane:
2466 return emitOpError()
2467 <<
"lane can only be specified for `specific_lane` broadcast";
2469 case BroadcastType::specific_lane:
2471 return emitOpError()
2472 <<
"lane must be specified for `specific_lane` broadcast";
2475 llvm_unreachable(
"Unknown BroadcastType");
2478OpFoldResult gpu::SubgroupBroadcastOp::fold(FoldAdaptor ) {
2480 if (
auto prev = getSrc().getDefiningOp<SubgroupBroadcastOp>())
2481 return prev.getResult();
2492#include "mlir/Dialect/GPU/IR/GPUOpInterfaces.cpp.inc"
2494#define GET_OP_CLASSES
2495#include "mlir/Dialect/GPU/IR/GPUOps.cpp.inc"
static void printLaunchFuncOperands(OpAsmPrinter &printer, Operation *, OperandRange operands, TypeRange types)
static ParseResult parseAsyncDependencies(OpAsmParser &parser, Type &asyncTokenType, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &asyncDependencies)
Parses an optional list of async operands with an optional leading keyword.
static void setAttributionAttrs(GPUFuncOp op, unsigned index, DictionaryAttr value, StringAttr attrName)
static void printAttributions(OpAsmPrinter &p, StringRef keyword, ArrayRef< BlockArgument > values, ArrayAttr attributes={})
static LogicalResult verifyDistributedType(Type expanded, Type distributed, int64_t warpSize, Operation *op)
Helper check if the distributed vector type is consistent with the expanded type and distributed size...
static void printAsyncDependencies(OpAsmPrinter &printer, Operation *op, Type asyncTokenType, OperandRange asyncDependencies)
Prints optional async dependencies with its leading keyword.
static ParseResult parseSizeAssignment(OpAsmParser &parser, MutableArrayRef< OpAsmParser::UnresolvedOperand > sizes, MutableArrayRef< OpAsmParser::UnresolvedOperand > regionSizes, MutableArrayRef< OpAsmParser::UnresolvedOperand > indices, StringRef keyword)
static LogicalResult eraseRedundantGpuBarrierOps(BarrierOp op, PatternRewriter &rewriter)
Remove gpu.barrier after gpu.barrier, the threads are already synchronized!
static ParseResult parseOffloadingHandler(OpAsmParser &parser, Attribute &offloadingHandler)
static DictionaryAttr getAttributionAttrs(GPUFuncOp op, unsigned index, StringAttr attrName)
static void printLaunchDimType(OpAsmPrinter &printer, Operation *op, Type dimTy, Value clusterValue, Type clusterXTy, Type clusterYTy, Type clusterZTy)
static bool canMakeGroupOpUniform(Operation *op)
static std::string getSparseHandleKeyword(SparseHandleKind kind)
static LogicalResult verifyKnownLaunchSizeAttr(Operation *op, NamedAttribute attr)
static LogicalResult verifyLaunchAsyncModel(OpTy op)
static ParseResult parseAttributions(OpAsmParser &parser, StringRef keyword, SmallVectorImpl< OpAsmParser::Argument > &args)
Parses a GPU function memory attribution.
static ParseResult parseLaunchDimType(OpAsmParser &parser, Type &dimTy, std::optional< OpAsmParser::UnresolvedOperand > clusterValue, Type &clusterXTy, Type &clusterYTy, Type &clusterZTy)
static void setAttributionAttr(GPUFuncOp op, unsigned index, StringAttr name, Attribute value, StringAttr attrsName)
static ParseResult parseLaunchFuncOperands(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &argNames, SmallVectorImpl< Type > &argTypes)
static void printOffloadingHandler(OpAsmPrinter &printer, Operation *op, Attribute offloadingHandler)
static LogicalResult verifyReduceOpAndType(gpu::AllReduceOperation opName, Type resType)
static void printSizeAssignment(OpAsmPrinter &p, KernelDim3 size, KernelDim3 operands, KernelDim3 ids)
static Attribute getAttributionAttr(GPUFuncOp op, unsigned index, StringAttr name, StringAttr attrsName)
static LogicalResult verifyAttributions(Operation *op, ArrayRef< BlockArgument > attributions, gpu::AddressSpace memorySpace)
Verifies a GPU function memory attribution.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
template bool mlir::hasSingleEffect< MemoryEffects::Allocate >(Operation *)
static void getDynamicSizes(RankedTensorType tp, ValueRange sizes, SmallVectorImpl< Value > &dynSizes)
Collects the dynamic dimension sizes for tp with the assumption that sizes are the dimension sizes fo...
static sycl::kernel * getKernel(ze_module_handle_t zeModule, const char *name)
This class contains all of the static information common to all instances of a registered Attribute.
static AbstractAttribute get(Dialect &dialect)
This method is used by Dialect objects when they register the list of attributes they contain.
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
@ Paren
Parens surrounding zero or more operands.
@ OptionalSquare
Square brackets supporting zero or more ops, or nothing.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual Location getEncodedSourceLoc(SMLoc loc)=0
Re-encode the given source location as an MLIR location and return it.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseColon()=0
Parse a : token.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseOptionalString(std::string *string)=0
Parse a quoted string token if present.
virtual ParseResult parseOptionalLess()=0
Parse a '<' token if present.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getI32IntegerAttr(int32_t value)
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
IntegerAttr getI64IntegerAttr(int64_t value)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
StringAttr getStringAttr(const Twine &bytes)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
MLIRContext * getContext() const
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
This class defines a virtual interface for reading a bytecode stream, providing hooks into the byteco...
virtual LogicalResult readVarInt(uint64_t &result)=0
Read a variable width integer.
virtual FailureOr< const DialectVersion * > getDialectVersion(StringRef dialectName) const =0
Retrieve the dialect version by name if available.
virtual LogicalResult readOptionalAttribute(Attribute &attr)=0
Read an optional reference to the given attribute.
virtual InFlightDiagnostic emitError(const Twine &msg={}) const =0
Emit an error to the reader.
virtual LogicalResult readAttribute(Attribute &result)=0
Read a reference to the given attribute.
This class defines a virtual interface for writing to a bytecode stream, providing hooks into the byt...
virtual void writeOptionalAttribute(Attribute attr)=0
virtual void writeVarInt(uint64_t value)=0
Write a variable width integer to the output stream.
virtual void writeAttribute(Attribute attr)=0
Write a reference to the given attribute.
virtual int64_t getBytecodeVersion() const =0
Return the bytecode version being emitted for.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual size_t getNumResults() const =0
Return the number of declared SSA results.
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
This class represents a single result from folding an operation.
static StringRef getOperandSegmentSizeAttr()
This class implements the operand iterators for the Operation class.
Operation is the basic unit of execution within MLIR.
void setInherentAttr(StringAttr name, Attribute value)
Set an inherent attribute by name.
void insertOperands(unsigned index, ValueRange operands)
Insert the given operands into the operand list at the given 'index'.
Block * getBlock()
Returns the operation block that contains this operation.
std::optional< Attribute > getInherentAttr(StringRef name)
Access an inherent attribute by name: returns an empty optional if there is no inherent attribute wit...
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
MLIRContext * getContext()
Return the context this operation is associated with.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
This class represents a successor of a region.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
This class provides an efficient unique identifier for a specific C++ type.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
user_range getUsers() const
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
static ConcreteType get(MLIRContext *ctx, Args &&...args)
MMAMatrix represents a matrix held by a subgroup for matrix-matrix multiply accumulate operations.
ArrayRef< int64_t > getShape() const
Get shape of the matrix.
Type getElementType() const
Get elementType of a single element.
StringRef getOperand() const
The general form of operation this type supports is given by the equation C += A*B.
static MMAMatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, ArrayRef< int64_t > shape, Type elementType, StringRef operand)
Get MMAMatrixType at a particular location and verify construction Invariants.
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
@ kDialectVersioning
Dialects versioning was added in version 1.
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
llvm::unique_function< InFlightDiagnostic()> getDefaultDiagnosticEmitFn(MLIRContext *ctx)
Utility method to generate a callback that can be used to generate a diagnostic when checking the con...
ParseResult parseFunctionSignatureWithArguments(OpAsmParser &parser, bool allowVariadic, SmallVectorImpl< OpAsmParser::Argument > &arguments, bool &isVariadic, SmallVectorImpl< Type > &resultTypes, SmallVectorImpl< DictionaryAttr > &resultAttrs)
Parses a function signature using parser.
void printFunctionAttributes(OpAsmPrinter &p, Operation *op, ArrayRef< StringRef > elided={})
Prints the list of function prefixed with the "attributes" keyword.
void printFunctionSignature(OpAsmPrinter &p, FunctionOpInterface op, ArrayRef< Type > argTypes, bool isVariadic, ArrayRef< Type > resultTypes)
Prints the signature of the function-like operation op.
void registerAttributeStorage(MLIRContext *context)
Register storage whose definitions are private to MLIRGPUBase.
void addAsyncDependency(Operation *op, Value token)
LogicalResult foldMemRefCast(Operation *op, Value inner=nullptr)
This is a common utility used for patterns of the form "someop(memref.cast) -> someop".
SmallVector< unsigned > getBlockSize(AffineMap dimToLvl)
Given the dimToLvl map, returns the block sizes in a vector.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
llvm::function_ref< void(Value, const ConstantIntRanges &)> SetIntRangeFn
The type of the setResultRanges callback provided to ops implementing InferIntRangeInterface.
LogicalResult verifyDynamicDimensionCount(Operation *op, ShapedType type, ValueRange dynamicSizes)
Verify that the number of dynamic size operands matches the number of dynamic dimensions in the shape...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
llvm::TypeSwitch< T, ResultT > TypeSwitch
LogicalResult verifyCompatibleShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2)
Returns success if the given two shapes are compatible.
llvm::function_ref< Fn > function_ref
Simplify the gpu.launch when the range of a thread or block ID is trivially known to be one.
LogicalResult matchAndRewrite(LaunchOp op, PatternRewriter &rewriter) const override
UnresolvedOperand ssaName
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
Utility class for the GPU dialect to represent triples of Values accessible through ....