31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/ADT/TypeSwitch.h"
38#include "llvm/Support/InterleavedRange.h"
51 auto constOp = dyn_cast_or_null<spirv::ConstantOp>(op);
55 auto valueAttr = constOp.getValue();
56 auto integerValueAttr = dyn_cast<IntegerAttr>(valueAttr);
57 if (!integerValueAttr) {
61 if (integerValueAttr.getType().isSignlessInteger())
62 value = integerValueAttr.getInt();
64 value = integerValueAttr.getSInt();
71 spirv::MemorySemantics memorySemantics) {
78 auto atMostOneInSet = spirv::MemorySemantics::Acquire |
79 spirv::MemorySemantics::Release |
80 spirv::MemorySemantics::AcquireRelease |
81 spirv::MemorySemantics::SequentiallyConsistent;
84 llvm::popcount(
static_cast<uint32_t
>(memorySemantics & atMostOneInSet));
87 "expected at most one of these four memory constraints "
88 "to be set: `Acquire`, `Release`,"
89 "`AcquireRelease` or `SequentiallyConsistent`");
100 auto pointeePtrType = dyn_cast<spirv::PointerType>(pointeeType);
101 if (!pointeePtrType) {
102 if (
auto pointeeArrayType = dyn_cast<spirv::ArrayType>(pointeeType)) {
104 dyn_cast<spirv::PointerType>(pointeeArrayType.getElementType());
108 if (!pointeePtrType || pointeePtrType.getStorageClass() !=
109 spirv::StorageClass::PhysicalStorageBuffer)
112 auto getDecorationAttr = [op](spirv::Decoration decoration) {
117 getDecorationAttr(spirv::Decoration::AliasedPointer) !=
nullptr;
118 bool hasRestrictPtr =
119 getDecorationAttr(spirv::Decoration::RestrictPointer) !=
nullptr;
121 if (!hasAliasedPtr && !hasRestrictPtr)
123 <<
" with physical buffer pointer must be decorated "
124 "either 'AliasedPointer' or 'RestrictPointer'";
126 if (hasAliasedPtr && hasRestrictPtr)
128 <<
" with physical buffer pointer must have exactly one "
129 "aliasing decoration";
140 auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
141 stringifyDecoration(spirv::Decoration::DescriptorSet));
142 auto bindingName = llvm::convertToSnakeFromCamelCase(
143 stringifyDecoration(spirv::Decoration::Binding));
145 dyn_cast_or_null<IntegerAttr>(attrs.
get(descriptorSetName));
146 auto binding = dyn_cast_or_null<IntegerAttr>(attrs.
get(bindingName));
147 if (descriptorSet && binding) {
148 elidedAttrs.push_back(descriptorSetName);
149 elidedAttrs.push_back(bindingName);
150 printer <<
" bind(" << descriptorSet.getInt() <<
", " << binding.getInt()
155 auto builtInName = llvm::convertToSnakeFromCamelCase(
156 stringifyDecoration(spirv::Decoration::BuiltIn));
157 if (
auto builtin = dyn_cast_or_null<StringAttr>(attrs.
get(builtInName))) {
158 printer <<
" " << builtInName <<
"(\"" <<
builtin.getValue() <<
"\")";
159 elidedAttrs.push_back(builtInName);
177 auto fnType = dyn_cast<FunctionType>(type);
179 parser.
emitError(loc,
"expected function type");
184 result.addTypes(fnType.getResults());
195 assert(op->
getNumResults() == 1 &&
"op should have one result");
201 [&](
Type type) { return type != resultType; })) {
210 p <<
" : " << resultType;
213template <
typename BlockReadWriteOpTy>
217 if (
auto valVecTy = dyn_cast<VectorType>(valType))
218 valType = valVecTy.getElementType();
220 if (valType != cast<spirv::PointerType>(
ptr.getType()).getPointeeType()) {
221 return op.emitOpError(
"mismatch in result type and pointer type");
233 emitErrorFn(
"expected at least one index for spirv.CompositeExtract");
238 if (
auto cType = dyn_cast<spirv::CompositeType>(type)) {
239 if (cType.hasCompileTimeKnownNumElements() &&
241 static_cast<uint64_t
>(
index) >= cType.getNumElements())) {
242 emitErrorFn(
"index ") <<
index <<
" out of bounds for " << type;
245 type = cType.getElementType(
index);
247 emitErrorFn(
"cannot extract from non-composite type ")
248 << type <<
" with index " <<
index;
258 auto indicesArrayAttr = dyn_cast<ArrayAttr>(
indices);
259 if (!indicesArrayAttr) {
260 emitErrorFn(
"expected a 32-bit integer array attribute for 'indices'");
263 if (indicesArrayAttr.empty()) {
264 emitErrorFn(
"expected at least one index for spirv.CompositeExtract");
269 for (
auto indexAttr : indicesArrayAttr) {
270 auto indexIntAttr = dyn_cast<IntegerAttr>(indexAttr);
272 emitErrorFn(
"expected an 32-bit integer for index, but found '")
276 indexVals.push_back(indexIntAttr.getInt());
283 return ::mlir::emitError(loc, err);
296template <
typename ExtendedBinaryOp>
298 auto resultType = cast<spirv::StructType>(op.getType());
299 if (resultType.getNumElements() != 2)
300 return op.emitOpError(
"expected result struct type containing two members");
302 if (!llvm::all_equal({op.getOperand1().getType(), op.getOperand2().getType(),
303 resultType.getElementType(0),
304 resultType.getElementType(1)}))
305 return op.emitOpError(
306 "expected all operand types and struct member types are the same");
323 auto structType = dyn_cast<spirv::StructType>(resultType);
324 if (!structType || structType.getNumElements() != 2)
325 return parser.
emitError(loc,
"expected spirv.struct type with two members");
331 result.addTypes(resultType);
345 return op->
emitError(
"expected the same type for the first operand and "
346 "result, but provided ")
358 spirv::GlobalVariableOp var) {
359 build(builder, state, var.getType(), SymbolRefAttr::get(var));
365 *
this, getVariableAttr());
367 return emitOpError(
"expected spirv.GlobalVariable symbol");
371 "result type mismatch with the referenced global variable's type");
380LogicalResult spirv::CompositeConstructOp::verify() {
381 operand_range constituents = this->getConstituents();
396 if (coopElementType) {
397 if (constituents.size() != 1)
398 return emitOpError(
"has incorrect number of operands: expected ")
399 <<
"1, but provided " << constituents.size();
400 if (coopElementType != constituents.front().getType())
401 return emitOpError(
"operand type mismatch: expected operand type ")
402 << coopElementType <<
", but provided "
403 << constituents.front().getType();
408 auto cType = cast<spirv::CompositeType>(
getType());
409 if (constituents.size() == cType.getNumElements()) {
410 for (
auto index : llvm::seq<uint32_t>(0, constituents.size())) {
412 return emitOpError(
"operand type mismatch: expected operand type ")
413 << cType.getElementType(
index) <<
", but provided "
414 << constituents[
index].getType();
421 auto resultType = dyn_cast<VectorType>(cType);
424 "expected to return a vector or cooperative matrix when the number of "
425 "constituents is less than what the result needs");
427 if (constituents.size() < 2)
428 return emitOpError(
"has incorrect number of operands: expected at least "
429 "2 for a vector result, but provided ")
430 << constituents.size();
433 for (
Value component : constituents) {
434 if (!isa<VectorType>(component.getType()) &&
435 !component.getType().isIntOrFloat())
436 return emitOpError(
"operand type mismatch: expected operand to have "
437 "a scalar or vector type, but provided ")
438 << component.getType();
440 Type elementType = component.getType();
441 if (
auto vectorType = dyn_cast<VectorType>(component.getType())) {
442 sizes.push_back(vectorType.getNumElements());
443 elementType = vectorType.getElementType();
448 if (elementType != resultType.getElementType())
449 return emitOpError(
"operand element type mismatch: expected to be ")
450 << resultType.getElementType() <<
", but provided " << elementType;
452 unsigned totalCount = llvm::sum_of(sizes);
453 if (totalCount != cType.getNumElements())
454 return emitOpError(
"has incorrect number of operands: expected ")
455 << cType.getNumElements() <<
", but provided " << totalCount;
472 build(builder, state, elementType, composite, indexAttr);
475ParseResult spirv::CompositeExtractOp::parse(
OpAsmParser &parser,
479 StringRef indicesAttrName =
480 spirv::CompositeExtractOp::getIndicesAttrName(
result.name);
497 result.addTypes(resultType);
501void spirv::CompositeExtractOp::print(
OpAsmPrinter &printer) {
502 printer <<
' ' << getComposite() <<
getIndices() <<
" : "
506LogicalResult spirv::CompositeExtractOp::verify() {
507 auto indicesArrayAttr = dyn_cast<ArrayAttr>(
getIndices());
514 return emitOpError(
"invalid result type: expected ")
515 << resultType <<
" but provided " <<
getType();
529 build(builder, state, composite.
getType(),
object, composite, indexAttr);
532ParseResult spirv::CompositeInsertOp::parse(
OpAsmParser &parser,
535 Type objectType, compositeType;
537 StringRef indicesAttrName =
538 spirv::CompositeInsertOp::getIndicesAttrName(
result.name);
551LogicalResult spirv::CompositeInsertOp::verify() {
552 auto indicesArrayAttr = dyn_cast<ArrayAttr>(
getIndices());
558 if (objectType != getObject().
getType()) {
559 return emitOpError(
"object operand type should be ")
560 << objectType <<
", but found " << getObject().getType();
564 return emitOpError(
"result type should be the same as "
565 "the composite type, but found ")
566 << getComposite().getType() <<
" vs " <<
getType();
572void spirv::CompositeInsertOp::print(
OpAsmPrinter &printer) {
573 printer <<
" " << getObject() <<
", " << getComposite() <<
getIndices()
574 <<
" : " << getObject().
getType() <<
" into "
575 << getComposite().getType();
582ParseResult spirv::ConstantOp::parse(
OpAsmParser &parser,
585 StringRef valueAttrName = spirv::ConstantOp::getValueAttrName(
result.name);
590 if (
auto typedAttr = dyn_cast<TypedAttr>(value))
591 type = typedAttr.getType();
592 if (isa<NoneType, TensorType>(type)) {
597 if (isa<TensorArmType>(type)) {
607 printer <<
' ' << getValue();
608 if (isa<spirv::ArrayType, spirv::StructType>(
getType()) &&
609 !isa<spirv::NullAttr>(getValue()))
615 if (isa<spirv::CooperativeMatrixType>(opType)) {
616 auto denseAttr = dyn_cast<DenseElementsAttr>(value);
617 if (!denseAttr || !denseAttr.isSplat())
618 return op.emitOpError(
"expected a splat dense attribute for cooperative "
619 "matrix constant, but found ")
622 if (isa<spirv::NullAttr>(value) &&
623 !isa<spirv::ArrayType, spirv::PointerType, spirv::StructType>(opType))
624 return op.emitOpError(
"must have spirv.ptr, spirv.array or spirv.struct "
625 "result type for null value");
626 if (isa<IntegerAttr, FloatAttr, spirv::NullAttr>(value)) {
627 auto valueType = cast<TypedAttr>(value).getType();
628 if (valueType != opType)
629 return op.emitOpError(
"result type (")
630 << opType <<
") does not match value type (" << valueType <<
")";
633 if (isa<DenseTypedElementsAttr, SparseElementsAttr>(value)) {
634 auto valueType = cast<TypedAttr>(value).getType();
635 if (valueType == opType)
637 auto arrayType = dyn_cast<spirv::ArrayType>(opType);
638 auto shapedType = dyn_cast<ShapedType>(valueType);
640 return op.emitOpError(
"result or element type (")
641 << opType <<
") does not match value type (" << valueType
642 <<
"), must be the same or spirv.array";
644 int numElements = arrayType.getNumElements();
645 auto opElemType = arrayType.getElementType();
646 while (
auto t = dyn_cast<spirv::ArrayType>(opElemType)) {
647 numElements *= t.getNumElements();
648 opElemType = t.getElementType();
650 if (!opElemType.isIntOrFloat())
651 return op.emitOpError(
"only support nested array result type");
653 auto valueElemType = shapedType.getElementType();
654 if (valueElemType != opElemType) {
655 return op.emitOpError(
"result element type (")
656 << opElemType <<
") does not match value element type ("
657 << valueElemType <<
")";
660 if (numElements != shapedType.getNumElements()) {
661 return op.emitOpError(
"result number of elements (")
662 << numElements <<
") does not match value number of elements ("
663 << shapedType.getNumElements() <<
")";
667 if (
auto arrayAttr = dyn_cast<ArrayAttr>(value)) {
668 if (
auto structType = dyn_cast<spirv::StructType>(opType)) {
670 if (structType.isIdentified())
671 return op.emitOpError(
672 "cannot have an identified struct as a constant type");
673 if (arrayAttr.size() != structType.getNumElements())
674 return op.emitOpError(
"number of constituents (")
676 <<
") does not match number of struct members ("
677 << structType.getNumElements() <<
")";
678 for (
auto [idx, element] : llvm::enumerate(arrayAttr.getValue())) {
680 structType.getElementType(idx))))
685 auto arrayType = dyn_cast<spirv::ArrayType>(opType);
687 return op.emitOpError(
688 "must have spirv.array or spirv.struct result type for array value");
689 Type elemType = arrayType.getElementType();
690 for (
Attribute element : arrayAttr.getValue()) {
697 return op.emitOpError(
"cannot have attribute: ") << value;
700LogicalResult spirv::ConstantOp::verify() {
707bool spirv::ConstantOp::isBuildableWith(
Type type) {
709 if (!isa<spirv::SPIRVType>(type))
713 if (
auto structType = dyn_cast<spirv::StructType>(type))
714 return !structType.isIdentified();
715 return isa<spirv::ArrayType>(type);
721spirv::ConstantOp spirv::ConstantOp::getZero(
Type type,
Location loc,
723 if (
auto intType = dyn_cast<IntegerType>(type)) {
724 unsigned width = intType.getWidth();
726 return spirv::ConstantOp::create(builder, loc, type,
728 return spirv::ConstantOp::create(
729 builder, loc, type, builder.
getIntegerAttr(type, APInt(width, 0)));
731 if (
auto floatType = dyn_cast<FloatType>(type)) {
732 return spirv::ConstantOp::create(builder, loc, type,
735 if (
auto vectorType = dyn_cast<VectorType>(type)) {
736 Type elemType = vectorType.getElementType();
737 if (isa<IntegerType>(elemType)) {
738 return spirv::ConstantOp::create(
741 IntegerAttr::get(elemType, 0).getValue()));
743 if (isa<FloatType>(elemType)) {
744 return spirv::ConstantOp::create(
747 FloatAttr::get(elemType, 0.0).getValue()));
751 llvm_unreachable(
"unimplemented types for ConstantOp::getZero()");
754spirv::ConstantOp spirv::ConstantOp::getOne(
Type type,
Location loc,
756 if (
auto intType = dyn_cast<IntegerType>(type)) {
757 unsigned width = intType.getWidth();
759 return spirv::ConstantOp::create(builder, loc, type,
761 return spirv::ConstantOp::create(
762 builder, loc, type, builder.
getIntegerAttr(type, APInt(width, 1)));
764 if (
auto floatType = dyn_cast<FloatType>(type)) {
765 return spirv::ConstantOp::create(builder, loc, type,
768 if (
auto vectorType = dyn_cast<VectorType>(type)) {
769 Type elemType = vectorType.getElementType();
770 if (isa<IntegerType>(elemType)) {
771 return spirv::ConstantOp::create(
774 IntegerAttr::get(elemType, 1).getValue()));
776 if (isa<FloatType>(elemType)) {
777 return spirv::ConstantOp::create(
780 FloatAttr::get(elemType, 1.0).getValue()));
784 llvm_unreachable(
"unimplemented types for ConstantOp::getOne()");
787void mlir::spirv::ConstantOp::getAsmResultNames(
792 llvm::raw_svector_ostream specialName(specialNameBuffer);
793 specialName <<
"cst";
795 IntegerType intTy = dyn_cast<IntegerType>(type);
797 if (IntegerAttr intCst = dyn_cast<IntegerAttr>(getValue())) {
800 if (intTy.getWidth() == 1) {
801 return setNameFn(getResult(), (intCst.getInt() ?
"true" :
"false"));
804 if (intTy.isSignless()) {
805 specialName << intCst.getInt();
806 }
else if (intTy.isUnsigned()) {
807 specialName << intCst.getUInt();
809 specialName << intCst.getSInt();
813 if (intTy || isa<FloatType>(type)) {
814 specialName <<
'_' << type;
817 if (
auto vecType = dyn_cast<VectorType>(type)) {
818 specialName <<
"_vec_";
819 specialName << vecType.getDimSize(0);
821 Type elementType = vecType.getElementType();
823 if (isa<IntegerType>(elementType) || isa<FloatType>(elementType)) {
824 specialName <<
"x" << elementType;
828 setNameFn(getResult(), specialName.str());
831void mlir::spirv::AddressOfOp::getAsmResultNames(
834 llvm::raw_svector_ostream specialName(specialNameBuffer);
835 specialName << getVariable() <<
"_addr";
836 setNameFn(getResult(), specialName.str());
847 if (
auto typedAttr = dyn_cast<TypedAttr>(attr)) {
848 return typedAttr.getType();
851 if (
auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
858LogicalResult spirv::EXTConstantCompositeReplicateOp::verify() {
861 return emitError(
"unknown value attribute type");
863 auto compositeType = dyn_cast<spirv::CompositeType>(
getType());
865 return emitError(
"result type is not a composite type");
867 Type compositeElementType = compositeType.getElementType(0);
870 while (
auto type = dyn_cast<spirv::CompositeType>(compositeElementType)) {
871 compositeElementType = type.getElementType(0);
872 possibleTypes.push_back(compositeElementType);
875 if (!is_contained(possibleTypes, valueType)) {
876 return emitError(
"expected value attribute type ")
877 << interleaved(possibleTypes,
" or ") <<
", but got: " << valueType;
887LogicalResult spirv::ControlBarrierOp::verify() {
896 spirv::ExecutionModel executionModel,
897 spirv::FuncOp function,
899 build(builder, state,
900 spirv::ExecutionModelAttr::get(builder.
getContext(), executionModel),
901 SymbolRefAttr::get(function), builder.
getArrayAttr(interfaceVars));
904ParseResult spirv::EntryPointOp::parse(
OpAsmParser &parser,
906 spirv::ExecutionModel execModel;
919 FlatSymbolRefAttr var;
921 if (parser.parseAttribute(var, Type(),
"var_symbol", attrs))
923 interfaceVars.push_back(var);
928 result.addAttribute(spirv::EntryPointOp::getInterfaceAttrName(
result.name),
936 auto interfaceVars = getInterface().getValue();
937 if (!interfaceVars.empty())
938 printer <<
", " << llvm::interleaved(interfaceVars);
941LogicalResult spirv::EntryPointOp::verify() {
955struct ExecutionModeOperandSchema {
957 unsigned numOperands;
960ExecutionModeOperandSchema
961getExecutionModeOperandSchema(spirv::ExecutionMode mode) {
963 case spirv::ExecutionMode::Invocations:
964 case spirv::ExecutionMode::OutputVertices:
965 case spirv::ExecutionMode::VecTypeHint:
966 case spirv::ExecutionMode::SubgroupSize:
967 case spirv::ExecutionMode::SubgroupsPerWorkgroup:
968 case spirv::ExecutionMode::DenormPreserve:
969 case spirv::ExecutionMode::DenormFlushToZero:
970 case spirv::ExecutionMode::SignedZeroInfNanPreserve:
971 case spirv::ExecutionMode::RoundingModeRTE:
972 case spirv::ExecutionMode::RoundingModeRTZ:
973 case spirv::ExecutionMode::OutputPrimitivesEXT:
974 case spirv::ExecutionMode::SharedLocalMemorySizeINTEL:
975 case spirv::ExecutionMode::RoundingModeRTPINTEL:
976 case spirv::ExecutionMode::RoundingModeRTNINTEL:
977 case spirv::ExecutionMode::FloatingPointModeALTINTEL:
978 case spirv::ExecutionMode::FloatingPointModeIEEEINTEL:
979 case spirv::ExecutionMode::MaxWorkDimINTEL:
980 case spirv::ExecutionMode::NumSIMDWorkitemsINTEL:
981 case spirv::ExecutionMode::SchedulerTargetFmaxMhzINTEL:
982 case spirv::ExecutionMode::StreamingInterfaceINTEL:
983 case spirv::ExecutionMode::NamedBarrierCountINTEL:
985 case spirv::ExecutionMode::LocalSize:
986 case spirv::ExecutionMode::LocalSizeHint:
987 case spirv::ExecutionMode::MaxWorkgroupSizeINTEL:
989 case spirv::ExecutionMode::SubgroupsPerWorkgroupId:
991 case spirv::ExecutionMode::FPFastMathDefault:
993 case spirv::ExecutionMode::LocalSizeId:
994 case spirv::ExecutionMode::LocalSizeHintId:
1007 spirv::FuncOp function,
1008 spirv::ExecutionMode executionMode,
1010 build(builder, state, SymbolRefAttr::get(function),
1011 spirv::ExecutionModeAttr::get(builder.
getContext(), executionMode),
1015ParseResult spirv::ExecutionModeOp::parse(
OpAsmParser &parser,
1017 spirv::ExecutionMode execMode;
1032 values.push_back(cast<IntegerAttr>(value).getInt());
1034 StringRef valuesAttrName =
1035 spirv::ExecutionModeOp::getValuesAttrName(
result.name);
1036 result.addAttribute(valuesAttrName,
1041void spirv::ExecutionModeOp::print(
OpAsmPrinter &printer) {
1044 printer <<
" \"" << stringifyExecutionMode(getExecutionMode()) <<
"\"";
1046 if (!values.empty())
1047 printer <<
", " << llvm::interleaved(values.getAsValueRange<IntegerAttr>());
1050LogicalResult spirv::ExecutionModeOp::verify() {
1051 ExecutionModeOperandSchema schema =
1052 getExecutionModeOperandSchema(getExecutionMode());
1054 if (schema.isIdOperand)
1055 return emitOpError(
"expected ExecutionMode that takes extra operands "
1056 "that are not <id> operands, got: ")
1057 << stringifyExecutionMode(getExecutionMode());
1059 if (getValues().size() != schema.numOperands)
1060 return emitOpError(
"expected ")
1061 << schema.numOperands <<
" value operand(s), got "
1062 << getValues().size();
1071ParseResult spirv::ExecutionModeIdOp::parse(
OpAsmParser &parser,
1073 ExecutionMode execMode;
1083 if (parser.parseAttribute(attr))
1085 values.push_back(attr);
1091 StringRef valuesAttrName = getValuesAttrName(
result.name);
1093 result.addAttribute(valuesAttrName, valuesAttr);
1097void spirv::ExecutionModeIdOp::print(
OpAsmPrinter &printer) {
1100 printer <<
" \"" << stringifyExecutionMode(getExecutionMode()) <<
"\" ";
1102 llvm::interleaveComma(getValues(), printer);
1105LogicalResult spirv::ExecutionModeIdOp::verify() {
1106 ExecutionModeOperandSchema schema =
1107 getExecutionModeOperandSchema(getExecutionMode());
1109 if (!schema.isIdOperand)
1110 return emitOpError(
"expected ExecutionMode that takes extra operands that "
1111 "are <id> operands, got: ")
1112 << stringifyExecutionMode(getExecutionMode());
1114 if (getValues().size() != schema.numOperands)
1115 return emitOpError(
"expected ")
1116 << schema.numOperands <<
" value operand(s), got "
1117 << getValues().size();
1119 if (getExecutionMode() == ExecutionMode::FPFastMathDefault) {
1120 auto targetType = dyn_cast<TypeAttr>(getValues()[0]);
1121 if (!targetType || !isa<FloatType>(targetType.getValue()) ||
1122 !isa<ScalarType>(targetType.getValue()))
1123 return emitOpError(
"expected Target Type to be a scalar float type");
1124 auto fastMathMode = dyn_cast<IntegerAttr>(getValues()[1]);
1125 if (!fastMathMode || !fastMathMode.getType().isInteger(32))
1126 return emitOpError(
"expected Fast-Math Mode to be an i32 constant");
1127 std::optional<FPFastMathMode> mode =
1128 symbolizeFPFastMathMode(fastMathMode.getValue().getZExtValue());
1130 return emitOpError(
"expected Fast-Math Mode to be a valid bitmask");
1131 if (bitEnumContainsAny(*mode, FPFastMathMode::Fast))
1132 return emitOpError(
"expected Fast-Math Mode to not include Fast");
1133 if (bitEnumContainsAny(*mode, FPFastMathMode::AllowTransform) &&
1134 !bitEnumContainsAll(*mode, FPFastMathMode::AllowContract |
1135 FPFastMathMode::AllowReassoc))
1136 return emitOpError(
"expected Fast-Math Mode with AllowTransform to "
1137 "include AllowContract and AllowReassoc");
1141 if (!llvm::all_of(getValues(), llvm::IsaPred<FlatSymbolRefAttr>))
1142 return emitOpError(
"expected value operands to be symbol reference");
1150 auto valueSymbol = dyn_cast<FlatSymbolRefAttr>(value);
1154 return emitOpError(
"cannot find symbol referenced by value operand: ")
1155 << valueSymbol.getValue();
1173 StringAttr nameAttr;
1179 bool isVariadic =
false;
1181 parser,
false, entryArgs, isVariadic, resultTypes,
1186 for (
auto &arg : entryArgs)
1187 argTypes.push_back(arg.type);
1189 result.addAttribute(getFunctionTypeAttrName(
result.name),
1190 TypeAttr::get(fnType));
1193 spirv::FunctionControl fnControl;
1202 assert(resultAttrs.size() == resultTypes.size());
1204 builder,
result, entryArgs, resultAttrs, getArgAttrsAttrName(
result.name),
1205 getResAttrsAttrName(
result.name));
1208 auto *body =
result.addRegion();
1217 if (StringAttr visibility = getSymVisibilityAttr())
1218 printer << visibility.getValue() <<
' ';
1220 auto fnType = getFunctionType();
1222 printer, *
this, fnType.getInputs(),
1223 false, fnType.getResults());
1224 printer <<
" \"" << spirv::stringifyFunctionControl(getFunctionControl())
1229 getFunctionTypeAttrName(), getArgAttrsAttrName(), getResAttrsAttrName(),
1230 getFunctionControlAttrName(), getSymVisibilityAttrName()});
1233 Region &body = this->getBody();
1234 if (!body.empty()) {
1241LogicalResult spirv::FuncOp::verifyType() {
1242 FunctionType fnType = getFunctionType();
1243 if (fnType.getNumResults() > 1)
1244 return emitOpError(
"cannot have more than one result");
1246 auto hasDecorationAttr = [&](spirv::Decoration decoration,
1247 unsigned argIndex) {
1248 auto func = cast<FunctionOpInterface>(getOperation());
1249 for (
auto argAttr : cast<FunctionOpInterface>(
func).
getArgAttrs(argIndex)) {
1250 if (argAttr.getName() != spirv::DecorationAttr::name)
1252 if (
auto decAttr = dyn_cast<spirv::DecorationAttr>(argAttr.getValue()))
1253 return decAttr.getValue() == decoration;
1258 for (
unsigned i = 0, e = this->getNumArguments(); i != e; ++i) {
1259 Type param = fnType.getInputs()[i];
1260 auto inputPtrType = dyn_cast<spirv::PointerType>(param);
1264 auto pointeePtrType =
1265 dyn_cast<spirv::PointerType>(inputPtrType.getPointeeType());
1266 if (pointeePtrType) {
1272 if (pointeePtrType.getStorageClass() !=
1273 spirv::StorageClass::PhysicalStorageBuffer)
1276 bool hasAliasedPtr =
1277 hasDecorationAttr(spirv::Decoration::AliasedPointer, i);
1278 bool hasRestrictPtr =
1279 hasDecorationAttr(spirv::Decoration::RestrictPointer, i);
1280 if (!hasAliasedPtr && !hasRestrictPtr)
1281 return emitOpError()
1282 <<
"with a pointer points to a physical buffer pointer must "
1283 "be decorated either 'AliasedPointer' or 'RestrictPointer'";
1290 if (
auto pointeeArrayType =
1291 dyn_cast<spirv::ArrayType>(inputPtrType.getPointeeType())) {
1293 dyn_cast<spirv::PointerType>(pointeeArrayType.getElementType());
1295 pointeePtrType = inputPtrType;
1298 if (!pointeePtrType || pointeePtrType.getStorageClass() !=
1299 spirv::StorageClass::PhysicalStorageBuffer)
1302 bool hasAliased = hasDecorationAttr(spirv::Decoration::Aliased, i);
1303 bool hasRestrict = hasDecorationAttr(spirv::Decoration::Restrict, i);
1304 if (!hasAliased && !hasRestrict)
1305 return emitOpError() <<
"with physical buffer pointer must be decorated "
1306 "either 'Aliased' or 'Restrict'";
1312LogicalResult spirv::FuncOp::verifyBody() {
1313 FunctionType fnType = getFunctionType();
1314 if (!isExternal()) {
1315 Block &entryBlock = front();
1317 unsigned numArguments = this->getNumArguments();
1319 return emitOpError(
"entry block must have ")
1320 << numArguments <<
" arguments to match function signature";
1322 for (
auto [
index, fnArgType, blockArgType] :
1324 if (blockArgType != fnArgType) {
1325 return emitOpError(
"type of entry block argument #")
1326 <<
index <<
'(' << blockArgType
1327 <<
") must match the type of the corresponding argument in "
1328 <<
"function signature(" << fnArgType <<
')';
1334 if (
auto retOp = dyn_cast<spirv::ReturnOp>(op)) {
1335 if (fnType.getNumResults() != 0)
1336 return retOp.emitOpError(
"cannot be used in functions returning value");
1337 }
else if (
auto retOp = dyn_cast<spirv::ReturnValueOp>(op)) {
1338 if (fnType.getNumResults() != 1)
1339 return retOp.emitOpError(
1340 "returns 1 value but enclosing function requires ")
1341 << fnType.getNumResults() <<
" results";
1343 auto retOperandType = retOp.getValue().getType();
1344 auto fnResultType = fnType.getResult(0);
1345 if (retOperandType != fnResultType)
1346 return retOp.emitOpError(
" return value's type (")
1347 << retOperandType <<
") mismatch with function's result type ("
1348 << fnResultType <<
")";
1355 return failure(walkResult.wasInterrupted());
1359 StringRef name, FunctionType type,
1360 spirv::FunctionControl control,
1364 state.
addAttribute(getFunctionTypeAttrName(state.
name), TypeAttr::get(type));
1366 builder.
getAttr<spirv::FunctionControlAttr>(control));
1375ParseResult spirv::GLFClampOp::parse(
OpAsmParser &parser,
1385ParseResult spirv::GLUClampOp::parse(
OpAsmParser &parser,
1395ParseResult spirv::GLSClampOp::parse(
OpAsmParser &parser,
1405ParseResult spirv::GLNClampOp::parse(
OpAsmParser &parser,
1415ParseResult spirv::GLSmoothStepOp::parse(
OpAsmParser &parser,
1437 Type type, StringRef name,
1438 unsigned descriptorSet,
unsigned binding) {
1439 build(builder, state, TypeAttr::get(type), builder.
getStringAttr(name));
1441 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::DescriptorSet),
1444 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::Binding),
1449 Type type, StringRef name,
1451 build(builder, state, TypeAttr::get(type), builder.
getStringAttr(name));
1453 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::BuiltIn),
1457ParseResult spirv::GlobalVariableOp::parse(
OpAsmParser &parser,
1462 StringAttr nameAttr;
1463 StringRef initializerAttrName =
1464 spirv::GlobalVariableOp::getInitializerAttrName(
result.name);
1471 StringRef dataTypeAttrName =
1472 spirv::GlobalVariableOp::getDataTypeAttrName(
result.name);
1478 result.addAttribute(dataTypeAttrName, TypeAttr::get(dataType));
1496 StringRef typeAttrName =
1497 spirv::GlobalVariableOp::getTypeAttrName(
result.name);
1502 if (!isa<spirv::PointerType, spirv::UntypedPointerType>(type)) {
1504 "expected spirv.ptr or spirv.untyped_ptr type");
1506 result.addAttribute(typeAttrName, TypeAttr::get(type));
1511void spirv::GlobalVariableOp::print(
OpAsmPrinter &printer) {
1517 if (StringAttr visibility = getSymVisibilityAttr())
1518 printer << visibility.getValue() <<
' ';
1520 elidedAttrs.push_back(getSymNameAttrName());
1521 elidedAttrs.push_back(getSymVisibilityAttrName());
1524 if (std::optional<Type> dataType = getDataType()) {
1525 StringRef dataTypeAttrName = getDataTypeAttrName();
1526 printer <<
" " << dataTypeAttrName <<
'(' << *dataType <<
')';
1527 elidedAttrs.push_back(dataTypeAttrName);
1530 StringRef initializerAttrName = this->getInitializerAttrName();
1532 if (
auto initializer = this->getInitializer()) {
1533 printer <<
" " << initializerAttrName <<
'(';
1536 elidedAttrs.push_back(initializerAttrName);
1539 StringRef typeAttrName = this->getTypeAttrName();
1540 elidedAttrs.push_back(typeAttrName);
1542 printer <<
" : " <<
getType();
1545LogicalResult spirv::GlobalVariableOp::verify() {
1546 if (!isa<spirv::PointerType, spirv::UntypedPointerType>(
getType()))
1547 return emitOpError(
"result must be of a !spv.ptr or !spv.untyped_ptr type");
1553 auto storageClass = this->storageClass();
1554 if (storageClass == spirv::StorageClass::Generic ||
1555 storageClass == spirv::StorageClass::Function) {
1556 return emitOpError(
"storage class cannot be '")
1557 << stringifyStorageClass(storageClass) <<
"'";
1560 std::optional<Type> dataType = getDataType();
1561 if (dataType && isa<NoneType>(*dataType))
1562 return emitOpError(
"data type cannot be void");
1563 if (
auto ptrType = dyn_cast<spirv::PointerType>(
getType())) {
1565 return emitOpError(
"data type requires an untyped pointer type");
1566 dataType = ptrType.getPointeeType();
1567 }
else if (!dataType) {
1570 if (storageClass == spirv::StorageClass::Private ||
1571 storageClass == spirv::StorageClass::Workgroup)
1572 return emitOpError(
"with '") << stringifyStorageClass(storageClass)
1573 <<
"' storage class requires a data type";
1575 if (getInitializer())
1576 return emitOpError(
"with an initializer requires a data type");
1579 if (dataType && storageClass != spirv::StorageClass::Private &&
1581 return emitOpError(
"FP4 and FP6 types require Function or Private storage");
1585 if (std::optional<spirv::LinkageAttributesAttr> linkage =
1586 getLinkageAttributes()) {
1587 if (linkage->getLinkageType().getValue() == spirv::LinkageType::Import &&
1590 "with Import linkage type must not have an initializer");
1614 !isa<spirv::SpecConstantOp, spirv::SpecConstantCompositeOp>(initOp)) {
1615 return emitOpError(
"initializer must be result of a "
1616 "spirv.SpecConstant or "
1617 "spirv.SpecConstantCompositeOp op");
1628LogicalResult spirv::INTELConstantFunctionPointerOp::verifySymbolUses(
1631 *
this, getFunctionAttr());
1633 return emitOpError(
"function '")
1634 << getFunction() <<
"' not found in nearest symbol table";
1636 Type pointeeType = cast<spirv::PointerType>(
getType()).getPointeeType();
1637 if (pointeeType != funcOp.getFunctionType()) {
1638 return emitOpError(
"result pointee type mismatch: expected ")
1639 << funcOp.getFunctionType() <<
", but provided " << pointeeType;
1648LogicalResult spirv::INTELFunctionPointerCallOp::verify() {
1649 auto functionType = cast<FunctionType>(
1650 cast<spirv::PointerType>(getFunctionPointer().
getType())
1654 if (functionType.getNumInputs() != arguments.size()) {
1655 return emitOpError(
"has incorrect number of operands for callee: expected ")
1656 << functionType.getNumInputs() <<
", but provided "
1657 << arguments.size();
1660 for (
auto [i, expected, argument] :
1661 llvm::enumerate(functionType.getInputs(), arguments)) {
1662 if (argument.getType() != expected) {
1663 return emitOpError(
"operand type mismatch: expected operand type ")
1664 << expected <<
", but provided " << argument.getType()
1665 <<
" for operand number " << i;
1669 if (functionType.getNumResults() != getNumResults()) {
1670 return emitOpError(
"has incorrect number of results for callee: expected ")
1671 << functionType.getNumResults() <<
", but provided "
1675 if (getReturnValue() &&
1676 getReturnValue().
getType() != functionType.getResult(0)) {
1677 return emitOpError(
"result type mismatch: expected ")
1678 << functionType.getResult(0) <<
", but provided "
1679 << getReturnValue().getType();
1689LogicalResult spirv::INTELSubgroupBlockReadOp::verify() {
1700ParseResult spirv::INTELSubgroupBlockWriteOp::parse(
OpAsmParser &parser,
1703 spirv::StorageClass storageClass;
1714 if (
auto valVecTy = dyn_cast<VectorType>(elementType))
1724void spirv::INTELSubgroupBlockWriteOp::print(
OpAsmPrinter &printer) {
1725 StringRef sc = stringifyStorageClass(
1726 cast<spirv::PointerType>(getPtr().
getType()).getStorageClass());
1727 printer <<
" \"" << sc <<
"\" " << getPtr() <<
", " << getValue() <<
" : "
1728 << getValue().getType();
1731LogicalResult spirv::INTELSubgroupBlockWriteOp::verify() {
1742LogicalResult spirv::IAddCarryOp::verify() {
1743 return ::verifyArithmeticExtendedBinaryOp(*
this);
1746ParseResult spirv::IAddCarryOp::parse(
OpAsmParser &parser,
1748 return ::parseArithmeticExtendedBinaryOp(parser,
result);
1759LogicalResult spirv::ISubBorrowOp::verify() {
1760 return ::verifyArithmeticExtendedBinaryOp(*
this);
1763ParseResult spirv::ISubBorrowOp::parse(
OpAsmParser &parser,
1765 return ::parseArithmeticExtendedBinaryOp(parser,
result);
1768void spirv::ISubBorrowOp::print(
OpAsmPrinter &printer) {
1776LogicalResult spirv::SMulExtendedOp::verify() {
1777 return ::verifyArithmeticExtendedBinaryOp(*
this);
1780ParseResult spirv::SMulExtendedOp::parse(
OpAsmParser &parser,
1782 return ::parseArithmeticExtendedBinaryOp(parser,
result);
1785void spirv::SMulExtendedOp::print(
OpAsmPrinter &printer) {
1793LogicalResult spirv::UMulExtendedOp::verify() {
1794 return ::verifyArithmeticExtendedBinaryOp(*
this);
1797ParseResult spirv::UMulExtendedOp::parse(
OpAsmParser &parser,
1799 return ::parseArithmeticExtendedBinaryOp(parser,
result);
1802void spirv::UMulExtendedOp::print(
OpAsmPrinter &printer) {
1810LogicalResult spirv::MemoryBarrierOp::verify() {
1818LogicalResult spirv::MemoryNamedBarrierOp::verify() {
1827 std::optional<StringRef> name) {
1837 spirv::AddressingModel addressingModel,
1838 spirv::MemoryModel memoryModel,
1839 std::optional<VerCapExtAttr> vceTriple,
1840 std::optional<StringRef> name) {
1843 builder.
getAttr<spirv::AddressingModelAttr>(addressingModel));
1845 builder.
getAttr<spirv::MemoryModelAttr>(memoryModel));
1849 state.
addAttribute(getVCETripleAttrName(), *vceTriple);
1855ParseResult spirv::ModuleOp::parse(
OpAsmParser &parser,
1862 StringAttr nameAttr;
1864 nameAttr, getSymNameAttrName(
result.name),
result.attributes);
1867 spirv::AddressingModel addrModel;
1868 spirv::MemoryModel memoryModel;
1878 spirv::ModuleOp::getVCETripleAttrName(),
1895 if (StringAttr visibility = getSymVisibilityAttr())
1896 printer <<
' ' << visibility.getValue();
1897 if (std::optional<StringRef> name = getName()) {
1908 elidedAttrs.assign({addressingModelAttrName, memoryModelAttrName,
1909 getSymNameAttrName(), getSymVisibilityAttrName()});
1911 if (std::optional<spirv::VerCapExtAttr> triple = getVceTriple()) {
1912 printer <<
" requires " << *triple;
1913 elidedAttrs.push_back(spirv::ModuleOp::getVCETripleAttrName());
1917 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
1922LogicalResult spirv::ModuleOp::verifyRegions() {
1923 Dialect *dialect = (*this)->getDialect();
1928 for (
auto &op : *getBody()) {
1930 return op.
emitError(
"'spirv.module' can only contain spirv.* ops");
1935 if (
auto entryPointOp = dyn_cast<spirv::EntryPointOp>(op)) {
1936 auto funcOp = table.lookup<spirv::FuncOp>(entryPointOp.getFn());
1938 return entryPointOp.emitError(
"function '")
1939 << entryPointOp.getFn() <<
"' not found in 'spirv.module'";
1941 if (
auto interface = entryPointOp.getInterface()) {
1943 auto varSymRef = dyn_cast<FlatSymbolRefAttr>(varRef);
1945 return entryPointOp.emitError(
1946 "expected symbol reference for interface "
1947 "specification instead of '")
1951 table.lookup<spirv::GlobalVariableOp>(varSymRef.getValue());
1953 return entryPointOp.emitError(
"expected spirv.GlobalVariable "
1954 "symbol reference instead of'")
1955 << varSymRef <<
"'";
1960 auto key = std::pair<spirv::FuncOp, spirv::ExecutionModel>(
1961 funcOp, entryPointOp.getExecutionModel());
1962 if (!entryPoints.try_emplace(key, entryPointOp).second)
1963 return entryPointOp.emitError(
"duplicate of a previous EntryPointOp");
1964 }
else if (
auto funcOp = dyn_cast<spirv::FuncOp>(op)) {
1968 auto linkageAttr = funcOp.getLinkageAttributes();
1969 auto hasImportLinkage =
1970 linkageAttr && (linkageAttr.value().getLinkageType().getValue() ==
1971 spirv::LinkageType::Import);
1972 if (funcOp.isExternal() && !hasImportLinkage)
1974 "'spirv.module' cannot contain external functions "
1975 "without 'Import' linkage_attributes (LinkageAttributes)");
1978 for (
auto &block : funcOp)
1979 for (
auto &op : block) {
1982 "functions in 'spirv.module' can only contain spirv.* ops");
2000 auto specConstOp = dyn_cast_or_null<spirv::SpecConstantOp>(specConstSym);
2002 constType = specConstOp.getDefaultValue().getType();
2004 auto specConstCompositeOp =
2005 dyn_cast_or_null<spirv::SpecConstantCompositeOp>(specConstSym);
2006 if (specConstCompositeOp)
2007 constType = specConstCompositeOp.getType();
2009 if (!specConstOp && !specConstCompositeOp)
2011 "expected spirv.SpecConstant or spirv.SpecConstantComposite symbol");
2013 if (getReference().
getType() != constType)
2014 return emitOpError(
"result type mismatch with the referenced "
2015 "specialization constant's type");
2024ParseResult spirv::SpecConstantOp::parse(
OpAsmParser &parser,
2028 StringAttr nameAttr;
2030 StringRef defaultValueAttrName =
2031 spirv::SpecConstantOp::getDefaultValueAttrName(
result.name);
2039 IntegerAttr specIdAttr;
2053void spirv::SpecConstantOp::print(
OpAsmPrinter &printer) {
2055 if (StringAttr visibility = getSymVisibilityAttr())
2056 printer << visibility.getValue() <<
' ';
2061 printer <<
" = " << getDefaultValue();
2064LogicalResult spirv::SpecConstantOp::verify() {
2067 if (specID.getValue().isNegative())
2068 return emitOpError(
"SpecId cannot be negative");
2070 auto value = getDefaultValue();
2071 if (isa<IntegerAttr, FloatAttr>(value)) {
2073 if (!isa<spirv::SPIRVType>(value.getType()))
2074 return emitOpError(
"default value bitwidth disallowed");
2078 "default value can only be a bool, integer, or float scalar");
2085LogicalResult spirv::VectorShuffleOp::verify() {
2086 VectorType resultType = cast<VectorType>(
getType());
2088 size_t numResultElements = resultType.getNumElements();
2089 if (numResultElements != getComponents().size())
2090 return emitOpError(
"result type element count (")
2091 << numResultElements
2092 <<
") mismatch with the number of component selectors ("
2093 << getComponents().size() <<
")";
2095 size_t totalSrcElements =
2096 cast<VectorType>(getVector1().
getType()).getNumElements() +
2097 cast<VectorType>(getVector2().
getType()).getNumElements();
2099 for (
const auto &selector : getComponents().getAsValueRange<IntegerAttr>()) {
2100 uint32_t
index = selector.getZExtValue();
2101 if (
index >= totalSrcElements &&
2102 index != std::numeric_limits<uint32_t>().
max())
2103 return emitOpError(
"component selector ")
2104 <<
index <<
" out of range: expected to be in [0, "
2105 << totalSrcElements <<
") or 0xffffffff";
2114ParseResult spirv::SpecConstantCompositeOp::parse(
OpAsmParser &parser,
2119 StringAttr compositeName;
2131 const char *attrName =
"spec_const";
2138 constituents.push_back(specConstRef);
2144 StringAttr compositeSpecConstituentsName =
2145 spirv::SpecConstantCompositeOp::getConstituentsAttrName(
result.name);
2146 result.addAttribute(compositeSpecConstituentsName,
2153 StringAttr typeAttrName =
2154 spirv::SpecConstantCompositeOp::getTypeAttrName(
result.name);
2155 result.addAttribute(typeAttrName, TypeAttr::get(type));
2160void spirv::SpecConstantCompositeOp::print(
OpAsmPrinter &printer) {
2162 if (StringAttr visibility = getSymVisibilityAttr())
2163 printer << visibility.getValue() <<
' ';
2165 printer <<
" (" << llvm::interleaved(this->getConstituents().getValue())
2169LogicalResult spirv::SpecConstantCompositeOp::verify() {
2170 auto cType = dyn_cast<spirv::CompositeType>(
getType());
2171 auto constituents = this->getConstituents().getValue();
2174 return emitError(
"result type must be a composite type, but provided ")
2177 if (isa<spirv::CooperativeMatrixType>(cType))
2178 return emitError(
"unsupported composite type ") << cType;
2179 if (constituents.size() != cType.getNumElements())
2180 return emitError(
"has incorrect number of operands: expected ")
2181 << cType.getNumElements() <<
", but provided "
2182 << constituents.size();
2187LogicalResult spirv::SpecConstantCompositeOp::verifySymbolUses(
2189 auto cType = cast<spirv::CompositeType>(
getType());
2192 for (
auto index : llvm::seq<uint32_t>(0, constituents.size())) {
2193 auto constituent = cast<FlatSymbolRefAttr>(constituents[
index]);
2199 return emitError(
"unknown constituent symbol ") << constituent.getAttr();
2201 Type constituentType;
2202 if (
auto specConstOp = dyn_cast<spirv::SpecConstantOp>(constituentOp)) {
2203 constituentType = specConstOp.getDefaultValue().getType();
2204 }
else if (
auto specConstCompositeOp =
2205 dyn_cast<spirv::SpecConstantCompositeOp>(constituentOp)) {
2206 constituentType = specConstCompositeOp.getType();
2208 return emitError(
"unsupported constituent ")
2209 << constituent.getAttr()
2210 <<
": must reference a spirv.SpecConstant or "
2211 "spirv.SpecConstantComposite";
2214 if (constituentType != cType.getElementType(
index))
2215 return emitError(
"has incorrect types of operands: expected ")
2216 << cType.getElementType(
index) <<
", but provided "
2228spirv::EXTSpecConstantCompositeReplicateOp::parse(
OpAsmParser &parser,
2232 StringAttr compositeName;
2234 const char *attrName =
"spec_const";
2245 StringAttr compositeSpecConstituentName =
2246 spirv::EXTSpecConstantCompositeReplicateOp::getConstituentAttrName(
2248 result.addAttribute(compositeSpecConstituentName, specConstRef);
2250 StringAttr typeAttrName =
2251 spirv::EXTSpecConstantCompositeReplicateOp::getTypeAttrName(
result.name);
2252 result.addAttribute(typeAttrName, TypeAttr::get(type));
2257void spirv::EXTSpecConstantCompositeReplicateOp::print(
OpAsmPrinter &printer) {
2259 if (StringAttr visibility = getSymVisibilityAttr())
2260 printer << visibility.getValue() <<
' ';
2262 printer <<
" (" << this->getConstituent() <<
") : " <<
getType();
2265LogicalResult spirv::EXTSpecConstantCompositeReplicateOp::verify() {
2266 if (!isa<spirv::CompositeType>(
getType()))
2267 return emitError(
"result type must be a composite type, but provided ")
2273LogicalResult spirv::EXTSpecConstantCompositeReplicateOp::verifySymbolUses(
2275 auto compositeType = cast<spirv::CompositeType>(
getType());
2280 "splat spec constant reference defining constituent not found");
2282 auto constituentSpecConstOp = dyn_cast<spirv::SpecConstantOp>(constituentOp);
2283 if (!constituentSpecConstOp)
2284 return emitError(
"constituent is not a spec constant");
2286 Type constituentType = constituentSpecConstOp.getDefaultValue().getType();
2287 Type compositeElementType = compositeType.getElementType(0);
2288 if (constituentType != compositeElementType)
2289 return emitError(
"constituent has incorrect type: expected ")
2290 << compositeElementType <<
", but provided " << constituentType;
2299ParseResult spirv::SpecConstantOperationOp::parse(
OpAsmParser &parser,
2315 spirv::YieldOp::create(builder, wrappedOp->
getLoc(), wrappedOp->
getResult(0));
2326void spirv::SpecConstantOperationOp::print(
OpAsmPrinter &printer) {
2327 printer <<
" wraps ";
2331LogicalResult spirv::SpecConstantOperationOp::verifyRegions() {
2332 Block &block = getRegion().getBlocks().
front();
2335 return emitOpError(
"expected exactly 2 nested ops");
2340 return emitOpError(
"invalid enclosed op");
2343 if (!isa_and_present<spirv::ConstantOp, spirv::ReferenceOfOp,
2344 spirv::SpecConstantOperationOp>(
2345 operand.getDefiningOp()))
2347 "invalid operand, must be defined by a constant operation");
2356LogicalResult spirv::GLFrexpStructOp::verify() {
2358 dyn_cast<spirv::StructType>(getResult().
getType());
2361 return emitError(
"result type must be a struct type with two memebers");
2365 VectorType exponentVecTy = dyn_cast<VectorType>(exponentTy);
2366 IntegerType exponentIntTy = dyn_cast<IntegerType>(exponentTy);
2368 Type operandTy = getOperand().getType();
2369 VectorType operandVecTy = dyn_cast<VectorType>(operandTy);
2370 FloatType operandFTy = dyn_cast<FloatType>(operandTy);
2372 if (significandTy != operandTy)
2373 return emitError(
"member zero of the resulting struct type must be the "
2374 "same type as the operand");
2376 if (exponentVecTy) {
2377 IntegerType componentIntTy =
2378 dyn_cast<IntegerType>(exponentVecTy.getElementType());
2379 if (!componentIntTy || componentIntTy.getWidth() != 32)
2380 return emitError(
"member one of the resulting struct type must"
2381 "be a scalar or vector of 32 bit integer type");
2382 }
else if (!exponentIntTy || exponentIntTy.getWidth() != 32) {
2383 return emitError(
"member one of the resulting struct type "
2384 "must be a scalar or vector of 32 bit integer type");
2388 if (operandVecTy && exponentVecTy &&
2389 (exponentVecTy.getNumElements() == operandVecTy.getNumElements()))
2392 if (operandFTy && exponentIntTy)
2395 return emitError(
"member one of the resulting struct type must have the same "
2396 "number of components as the operand type");
2405 if (isa<FloatType>(floatType) != isa<IntegerType>(integerType))
2406 return op->
emitOpError(
"operands must both be scalars or vectors");
2409 if (
auto vectorType = dyn_cast<VectorType>(type))
2410 return vectorType.getNumElements();
2415 return op->
emitOpError(
"operands must have the same number of elements");
2420LogicalResult spirv::GLLdexpOp::verify() {
2429LogicalResult spirv::CLLdexpOp::verify() {
2438LogicalResult spirv::CLPownOp::verify() {
2447LogicalResult spirv::CLRootnOp::verify() {
2456LogicalResult spirv::CLSincosOp::verify() {
2458 cast<spirv::PointerType>(getCosval().
getType()).getStorageClass();
2459 if (!llvm::is_contained(
2460 {spirv::StorageClass::CrossWorkgroup, spirv::StorageClass::Workgroup,
2461 spirv::StorageClass::Function, spirv::StorageClass::Generic},
2463 return emitOpError(
"cosval must point to CrossWorkgroup, Workgroup, "
2464 "Function, or Generic storage");
2472LogicalResult spirv::ShiftLeftLogicalOp::verify() {
2480LogicalResult spirv::ShiftRightArithmeticOp::verify() {
2488LogicalResult spirv::ShiftRightLogicalOp::verify() {
2496LogicalResult spirv::VectorTimesScalarOp::verify() {
2498 return emitOpError(
"vector operand and result type mismatch");
2499 auto scalarType = cast<VectorType>(
getType()).getElementType();
2500 if (getScalar().
getType() != scalarType)
2501 return emitOpError(
"scalar operand and result element type match");
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
static int64_t getNumElements(Type t)
Compute the total number of elements in the given type, also taking into account nested types.
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static ParseResult parseArithmeticExtendedBinaryOp(OpAsmParser &parser, OperationState &result)
static Type getValueType(Attribute attr)
static LogicalResult verifyConstantType(spirv::ConstantOp op, Attribute value, Type opType)
static ParseResult parseOneResultSameOperandTypeOp(OpAsmParser &parser, OperationState &result)
static LogicalResult verifyArithmeticExtendedBinaryOp(ExtendedBinaryOp op)
static LogicalResult verifyFloatIntegerBuiltin(Operation *op, Type floatType, Type integerType)
static LogicalResult verifyShiftOp(Operation *op)
static LogicalResult verifyBlockReadWritePtrAndValTypes(BlockReadWriteOpTy op, Value ptr, Value val)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static void printOneResultOp(Operation *op, OpAsmPrinter &p)
static void printArithmeticExtendedBinaryOp(Operation *op, OpAsmPrinter &printer)
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
virtual ParseResult parseOptionalSymbolName(StringAttr &result)=0
Parse an optional -identifier and store it (without the '@' symbol) in a string attribute.
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 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.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
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 parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
ParseResult addTypesToList(ArrayRef< Type > types, SmallVectorImpl< Type > &result)
Add the specified types to the end of the specified type list and return success.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeywordType(const char *keyword, Type &result)
Parse a keyword followed by a type.
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.
Block represents an ordered list of Operations.
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
unsigned getNumArguments()
OpListType & getOperations()
IntegerAttr getI32IntegerAttr(int32_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
FloatAttr getFloatAttr(Type type, double value)
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
IntegerType getIntegerType(unsigned width)
BoolAttr getBoolAttr(bool value)
StringAttr getStringAttr(const Twine &bytes)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
MLIRContext * getContext() const
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
static DenseFPElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseFPElementsAttr with the given arguments.
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...
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
Attribute get(StringAttr name) const
Return the specified attribute if present, null otherwise.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
virtual OptionalParseResult parseOptionalRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual Operation * parseGenericOperation(Block *insertBlock, Block::iterator insertPt)=0
Parse an operation in its generic form.
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 printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
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 printGenericOp(Operation *op, bool printOpName=true)=0
Print the entire operation with the default generic assembly form.
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 setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
A trait to mark ops that can be enclosed/wrapped in a SpecConstantOperation op.
This class implements the operand iterators for the Operation class.
type_range getType() const
void populateInherentAttrs(Operation *op, NamedAttrList &attrs) const
Append the inherent attributes stored in the properties of op to attrs.
Operation is the basic unit of execution within MLIR.
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Value getOperand(unsigned idx)
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
operand_type_range getOperandTypes()
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
void push_back(Block *block)
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,...
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Dialect & getDialect() const
Get the dialect this type is registered to.
Type front()
Return first type in the range.
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.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
static ArrayType get(Type elementType, unsigned elementCount)
Type getElementType() const
static PointerType get(Type pointeeType, StorageClass storageClass)
unsigned getNumElements() const
Type getElementType(unsigned) const
An attribute that specifies the SPIR-V (version, capabilities, extensions) triple.
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,...
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
ArrayRef< NamedAttribute > getArgAttrs(FunctionOpInterface op, unsigned index)
Return all of the attributes for the argument at 'index'.
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.
ParseResult parseOptionalVisibilityKeyword(OpAsmParser &parser, NamedAttrList &attrs)
Parse an optional visibility attribute keyword (i.e., public, private, or nested) without quotes in a...
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
uint64_t getN(LevelType lt)
constexpr char kFnNameAttrName[]
constexpr char kSpecIdAttrName[]
LogicalResult verifyMemorySemantics(Operation *op, spirv::MemorySemantics memorySemantics)
ParseResult parseEnumStrAttr(EnumClass &value, OpAsmParser &parser, StringRef attrName=spirv::attributeName< EnumClass >())
Parses the next string attribute in parser as an enumerant of the given EnumClass.
ParseResult parseEnumKeywordAttr(EnumClass &value, ParserType &parser, StringRef attrName=spirv::attributeName< EnumClass >())
Parses the next keyword in parser as an enumerant of the given EnumClass.
void printVariableDecorations(Operation *op, OpAsmPrinter &printer, SmallVectorImpl< StringRef > &elidedAttrs)
LogicalResult verifyPhysicalStorageBufferDecorations(Operation *op, Type pointeeType)
Verifies the SPV_KHR_physical_storage_buffer rule that a variable whose pointee is a pointer (or arra...
bool containsMicroscalingType(Type type, bool subByteOnly=false)
Returns whether a type contains a microscaling element, including through composite types and pointer...
constexpr StringRef attributeName()
AddressingModel getAddressingModel(TargetEnvAttr targetAttr, bool use64bitAddress)
Returns addressing model selected based on target environment.
FailureOr< ExecutionModel > getExecutionModel(TargetEnvAttr targetAttr)
Returns execution model selected based on target environment.
FailureOr< MemoryModel > getMemoryModel(TargetEnvAttr targetAttr)
Returns memory model selected based on target environment.
LogicalResult extractValueFromConstOp(Operation *op, int32_t &value)
std::string getDecorationString(Decoration decoration)
Converts a SPIR-V Decoration enum value to its snake_case string representation for use in MLIR attri...
ParseResult parseVariableDecorations(OpAsmParser &parser, OperationState &state)
Include the generated interface declarations.
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.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
llvm::function_ref< Fn > function_ref
This is the representation of an operand reference.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.