21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/Casting.h"
34template <
typename MemoryOpTy>
43 spirv::MemoryAccess memoryAccessAttr;
44 StringAttr memoryAccessAttrName =
45 MemoryOpTy::getMemoryAccessAttrName(state.
name);
47 memoryAccessAttr, parser, state, memoryAccessAttrName))
50 if (spirv::bitEnumContainsAll(memoryAccessAttr,
51 spirv::MemoryAccess::Aligned)) {
54 StringAttr alignmentAttrName = MemoryOpTy::getAlignmentAttrName(state.
name);
69template <
typename MemoryOpTy>
78 spirv::MemoryAccess memoryAccessAttr;
79 StringRef memoryAccessAttrName =
80 MemoryOpTy::getSourceMemoryAccessAttrName(state.
name);
82 memoryAccessAttr, parser, state, memoryAccessAttrName))
85 if (spirv::bitEnumContainsAll(memoryAccessAttr,
86 spirv::MemoryAccess::Aligned)) {
89 StringAttr alignmentAttrName =
90 MemoryOpTy::getSourceAlignmentAttrName(state.
name);
105template <
typename MemoryOpTy>
109 std::optional<spirv::MemoryAccess> memoryAccessAtrrValue = std::nullopt,
110 std::optional<uint32_t> alignmentAttrValue = std::nullopt) {
114 (memoryAccessAtrrValue ? memoryAccessAtrrValue
115 : memoryOp.getSourceMemoryAccess())) {
116 elidedAttrs.push_back(memoryOp.getSourceMemoryAccessAttrName());
118 printer <<
", [\"" << stringifyMemoryAccess(*memAccess) <<
"\"";
120 if (spirv::bitEnumContainsAll(*memAccess, spirv::MemoryAccess::Aligned)) {
123 (alignmentAttrValue ? alignmentAttrValue
124 : memoryOp.getSourceAlignment())) {
125 elidedAttrs.push_back(memoryOp.getSourceAlignmentAttrName());
126 printer <<
", " << *alignment;
134template <
typename MemoryOpTy>
138 std::optional<spirv::MemoryAccess> memoryAccessAtrrValue = std::nullopt,
139 std::optional<uint32_t> alignmentAttrValue = std::nullopt) {
141 if (
auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
142 : memoryOp.getMemoryAccess())) {
143 elidedAttrs.push_back(memoryOp.getMemoryAccessAttrName());
145 printer <<
" [\"" << stringifyMemoryAccess(*memAccess) <<
"\"";
147 if (spirv::bitEnumContainsAll(*memAccess, spirv::MemoryAccess::Aligned)) {
149 if (
auto alignment = (alignmentAttrValue ? alignmentAttrValue
150 : memoryOp.getAlignment())) {
151 elidedAttrs.push_back(memoryOp.getAlignmentAttrName());
152 printer <<
", " << *alignment;
160template <
typename LoadStoreOpTy>
168 if (
auto ptrType = dyn_cast<spirv::PointerType>(
ptr.getType())) {
169 if (val.
getType() != ptrType.getPointeeType())
170 return op.emitOpError(
"mismatch in result type and pointer type");
175 if (!isa<spirv::SPIRVType>(val.
getType()))
176 return op.emitOpError(
"cannot access a value of type ")
177 << val.
getType() <<
" through an untyped pointer";
184enum class MemoryAccessKind { Read, Write, ReadWrite };
192 spirv::MemoryAccessAttr memAccessAttr,
193 Attribute alignmentAttr, MemoryAccessKind kind) {
197 if (!memAccessAttr) {
202 "invalid alignment specification without aligned memory access "
208 spirv::MemoryAccess memAccess = memAccessAttr.getValue();
211 if (kind == MemoryAccessKind::Read &&
212 spirv::bitEnumContainsAll(memAccess,
213 spirv::MemoryAccess::MakePointerAvailable)) {
215 "not compatible with memory operand 'MakePointerAvailable'");
219 if (kind == MemoryAccessKind::Write &&
220 spirv::bitEnumContainsAll(memAccess,
221 spirv::MemoryAccess::MakePointerVisible)) {
223 "not compatible with memory operand 'MakePointerVisible'");
226 if (spirv::bitEnumContainsAny(memAccess,
227 spirv::MemoryAccess::MakePointerAvailable |
228 spirv::MemoryAccess::MakePointerVisible) &&
229 !spirv::bitEnumContainsAll(memAccess,
230 spirv::MemoryAccess::NonPrivatePointer)) {
232 "memory operand 'MakePointerAvailable' or 'MakePointerVisible' "
233 "requires 'NonPrivatePointer' to also be specified");
236 if (spirv::bitEnumContainsAll(memAccess, spirv::MemoryAccess::Aligned)) {
237 if (!alignmentAttr) {
243 "invalid alignment specification with non-aligned memory access "
251template <
typename MemoryOpTy>
253 MemoryAccessKind kind) {
255 memoryOp.getMemoryAccessAttr(),
256 memoryOp.getAlignmentAttr(), kind);
264 auto ptrType = dyn_cast<spirv::PointerType>(type);
266 emitError(baseLoc,
"'spirv.AccessChain' op expected a pointer "
267 "to composite type, but provided ")
272 auto resultType = ptrType.getPointeeType();
273 auto resultStorageClass = ptrType.getStorageClass();
276 for (
auto indexSSA :
indices) {
277 auto cType = dyn_cast<spirv::CompositeType>(resultType);
281 "'spirv.AccessChain' op cannot extract from non-composite type ")
282 << resultType <<
" with index " <<
index;
286 if (isa<spirv::StructType>(resultType)) {
287 Operation *op = indexSSA.getDefiningOp();
289 emitError(baseLoc,
"'spirv.AccessChain' op index must be an "
290 "integer spirv.Constant to access "
291 "element of spirv.struct");
300 "'spirv.AccessChain' index must be an integer spirv.Constant to "
301 "access element of spirv.struct, but provided ")
305 if (
index < 0 ||
static_cast<uint64_t
>(
index) >= cType.getNumElements()) {
306 emitError(baseLoc,
"'spirv.AccessChain' op index ")
307 <<
index <<
" out of bounds for " << resultType;
311 resultType = cType.getElementType(
index);
319 assert(type &&
"Unable to deduce return type based on basePtr and indices");
320 build(builder, state, type, basePtr,
indices);
323template <
typename Op>
330 auto providedResultType =
331 dyn_cast<spirv::PointerType>(accessChainOp.getType());
332 if (!providedResultType)
334 "result type must be a pointer, but provided")
335 << providedResultType;
337 if (resultType != providedResultType)
338 return accessChainOp.
emitOpError(
"invalid result type: expected ")
339 << resultType <<
", but provided " << providedResultType;
344LogicalResult AccessChainOp::verify() {
355 assert(type &&
"Unable to deduce return type based on basePtr and indices");
356 build(builder, state, type, basePtr,
indices);
359LogicalResult InBoundsAccessChainOp::verify() {
367void LoadOp::build(OpBuilder &builder, OperationState &state, Value basePtr,
368 MemoryAccessAttr memoryAccess, IntegerAttr alignment) {
369 auto ptrType = cast<spirv::PointerType>(basePtr.
getType());
370 build(builder, state, ptrType.getPointeeType(), basePtr, memoryAccess,
374ParseResult LoadOp::parse(OpAsmParser &parser, OperationState &
result) {
375 OpAsmParser::UnresolvedOperand ptrInfo;
382 spirv::UntypedPointerType ptrType;
383 if (
failed(*untypedPtr) ||
390 result.addTypes(elementType);
395 spirv::StorageClass storageClass;
408 result.addTypes(elementType);
412void LoadOp::print(OpAsmPrinter &printer) {
413 SmallVector<StringRef, 4> elidedAttrs;
414 auto ptrType = dyn_cast<spirv::PointerType>(getPtr().
getType());
418 printer <<
" " << getPtr();
423 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
426 printer << getPtr().getType() <<
" -> ";
430LogicalResult LoadOp::verify() {
444ParseResult StoreOp::parse(OpAsmParser &parser, OperationState &
result) {
445 SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
451 OpAsmParser::UnresolvedOperand ptrInfo;
454 OpAsmParser::UnresolvedOperand valueInfo;
455 spirv::UntypedPointerType ptrType;
469 spirv::StorageClass storageClass;
485void StoreOp::print(OpAsmPrinter &printer) {
486 SmallVector<StringRef, 4> elidedAttrs;
487 auto ptrType = dyn_cast<spirv::PointerType>(getPtr().
getType());
491 printer <<
" " << getPtr() <<
", " << getValue();
497 printer << getPtr().getType() <<
", ";
498 printer << getValue().getType();
500 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
503LogicalResult StoreOp::verify() {
516void CopyMemoryOp::print(OpAsmPrinter &printer) {
519 StringRef targetStorageClass = stringifyStorageClass(
520 cast<spirv::PointerType>(getTarget().
getType()).getStorageClass());
521 printer <<
" \"" << targetStorageClass <<
"\" " << getTarget() <<
", ";
523 StringRef sourceStorageClass = stringifyStorageClass(
524 cast<spirv::PointerType>(getSource().
getType()).getStorageClass());
525 printer <<
" \"" << sourceStorageClass <<
"\" " << getSource();
527 SmallVector<StringRef, 4> elidedAttrs;
530 getSourceMemoryAccess(),
531 getSourceAlignment());
534 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
537 cast<spirv::PointerType>(getTarget().
getType()).getPointeeType();
538 printer <<
" : " << pointeeType;
541ParseResult CopyMemoryOp::parse(OpAsmParser &parser, OperationState &
result) {
542 spirv::StorageClass targetStorageClass;
543 OpAsmParser::UnresolvedOperand targetPtrInfo;
545 spirv::StorageClass sourceStorageClass;
546 OpAsmParser::UnresolvedOperand sourcePtrInfo;
582LogicalResult CopyMemoryOp::verify() {
584 cast<spirv::PointerType>(getTarget().
getType()).getPointeeType();
587 cast<spirv::PointerType>(getSource().
getType()).getPointeeType();
589 if (targetType != sourceType)
590 return emitOpError(
"both operands must be pointers to the same type");
594 MemoryAccessKind targetKind = getSourceMemoryAccess()
595 ? MemoryAccessKind::Write
596 : MemoryAccessKind::ReadWrite;
601 getOperation(), getSourceMemoryAccessAttr(), getSourceAlignmentAttr(),
602 MemoryAccessKind::Read);
609void InBoundsPtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
610 Value basePtr, Value element,
613 assert(type &&
"Unable to deduce return type based on basePtr and indices");
614 build(builder, state, type, basePtr, element,
indices);
617LogicalResult InBoundsPtrAccessChainOp::verify() {
625void PtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
628 assert(type &&
"Unable to deduce return type based on basePtr and indices");
629 build(builder, state, type, basePtr, element,
indices);
632LogicalResult PtrAccessChainOp::verify() {
640ParseResult VariableOp::parse(OpAsmParser &parser, OperationState &
result) {
642 std::optional<OpAsmParser::UnresolvedOperand> initInfo;
644 initInfo = OpAsmParser::UnresolvedOperand();
662 auto ptrType = dyn_cast<spirv::PointerType>(type);
664 return parser.
emitError(loc,
"expected spirv.ptr type");
681void VariableOp::print(OpAsmPrinter &printer) {
682 SmallVector<StringRef, 4> elidedAttrs{
685 if (getNumOperands() != 0)
686 printer <<
" init(" << getInitializer() <<
")";
692LogicalResult VariableOp::verify() {
696 if (getStorageClass() != spirv::StorageClass::Function) {
698 "can only be used to model function-level variables. Use "
699 "spirv.GlobalVariable for module-level variables.");
703 if (getStorageClass() != pointerType.getStorageClass())
705 "storage class must match result pointer's storage class");
707 if (getNumOperands() != 0) {
710 auto *initOp = getOperand(0).getDefiningOp();
711 if (!initOp || !isa<spirv::ConstantOp,
712 spirv::ReferenceOfOp,
713 spirv::AddressOfOp>(initOp))
714 return emitOpError(
"initializer must be the result of a "
715 "constant or spirv.GlobalVariable op");
718 auto getDecorationAttr = [op = getOperation()](spirv::Decoration decoration) {
723 for (
auto decoration :
724 {spirv::Decoration::DescriptorSet, spirv::Decoration::Binding,
725 spirv::Decoration::BuiltIn}) {
726 if (
auto attr = getDecorationAttr(decoration))
727 return emitOpError(
"cannot have '")
729 <<
"' attribute (only allowed in spirv.GlobalVariable)";
743LogicalResult ArrayLengthOp::verify() {
744 auto ptrType = cast<spirv::PointerType>(getStructure().
getType());
745 auto structType = cast<spirv::StructType>(ptrType.getPointeeType());
746 size_t numElements = structType.getNumElements();
747 if (numElements == 0 ||
748 !isa<spirv::RuntimeArrayType>(structType.getElementType(numElements - 1)))
749 return emitOpError(
"expected struct whose last member is a runtime array");
750 if (getArrayMember() != numElements - 1)
751 return emitOpError(
"array member index must be the last struct member (")
752 << (numElements - 1) <<
"), got " << getArrayMember();
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
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.
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 parseRSquare()=0
Parse a ] token.
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.
virtual ParseResult parseArrow()=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 parseOptionalLSquare()=0
Parse a [ token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
Attributes are known-constant values of operations.
IntegerType getIntegerType(unsigned width)
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
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 parseOptionalOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single operand if present.
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.
This class helps build Operations.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Location getLoc()
The source location the operation was defined or derived from.
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
OperationName getName()
The name of an operation is the key identifier for it.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
bool has_value() const
Returns true if we contain a valid ParseResult value.
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.
static PointerType get(Type pointeeType, StorageClass storageClass)
StorageClass getStorageClass() const
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
static ParseResult parseSourceMemoryAccessAttributes(OpAsmParser &parser, OperationState &state)
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.
static LogicalResult verifyMemoryAccessAttribute(Operation *op, spirv::MemoryAccessAttr memAccessAttr, Attribute alignmentAttr, MemoryAccessKind kind)
Verifies the memory operands mask memAccessAttr of op and its companion alignment attribute alignment...
static void printSourceMemoryAccessAttribute(MemoryOpTy memoryOp, OpAsmPrinter &printer, SmallVectorImpl< StringRef > &elidedAttrs, std::optional< spirv::MemoryAccess > memoryAccessAtrrValue=std::nullopt, std::optional< uint32_t > alignmentAttrValue=std::nullopt)
ParseResult parseMemoryAccessAttributes(OpAsmParser &parser, OperationState &state)
Parses optional memory access (a.k.a.
static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc)
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...
static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr, Value val)
constexpr StringRef attributeName()
static void printMemoryAccessAttribute(MemoryOpTy memoryOp, OpAsmPrinter &printer, SmallVectorImpl< StringRef > &elidedAttrs, std::optional< spirv::MemoryAccess > memoryAccessAtrrValue=std::nullopt, std::optional< uint32_t > alignmentAttrValue=std::nullopt)
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)
static LogicalResult verifyAccessChain(Op accessChainOp, ValueRange indices)
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.
This represents an operation in an abstracted form, suitable for use with the builder APIs.