18#include "llvm/ADT/TypeSwitch.h"
19#include "llvm/Support/InterleavedRange.h"
30template <
typename EnumAttrClass,
typename EnumClass>
45 builder.
getAttr<EnumAttrClass>(
static_cast<EnumClass
>(0)));
54 assert(
index == 0 &&
"invalid successor index");
63 assert(
index < 2 &&
"invalid successor index");
65 ? getTrueTargetOperandsMutable()
66 : getFalseTargetOperandsMutable());
69ParseResult BranchConditionalOp::parse(OpAsmParser &parser,
72 OpAsmParser::UnresolvedOperand condInfo;
83 IntegerAttr trueWeight, falseWeight;
84 NamedAttrList weights;
86 auto i32Type = builder.getIntegerType(32);
87 if (parser.
parseAttribute(trueWeight, i32Type,
"weight", weights) ||
93 StringAttr branchWeightsAttrName =
94 BranchConditionalOp::getBranchWeightsAttrName(
result.name);
95 result.addAttribute(branchWeightsAttrName,
96 builder.getArrayAttr({trueWeight, falseWeight}));
100 SmallVector<Value, 4> trueOperands;
104 result.addSuccessors(dest);
105 result.addOperands(trueOperands);
108 SmallVector<Value, 4> falseOperands;
112 result.addSuccessors(dest);
113 result.addOperands(falseOperands);
114 result.addAttribute(spirv::BranchConditionalOp::getOperandSegmentSizeAttr(),
115 builder.getDenseI32ArrayAttr(
116 {1, static_cast<int32_t>(trueOperands.size()),
117 static_cast<int32_t>(falseOperands.size())}));
122void BranchConditionalOp::print(OpAsmPrinter &printer) {
123 printer <<
' ' << getCondition();
125 if (std::optional<ArrayAttr> weights = getBranchWeights()) {
127 << llvm::interleaved_array(weights->getAsValueRange<IntegerAttr>());
136LogicalResult BranchConditionalOp::verify() {
137 if (
auto weights = getBranchWeights()) {
138 if (weights->getValue().size() != 2) {
139 return emitOpError(
"must have exactly two branch weights");
141 if (llvm::all_of(*weights, [](Attribute attr) {
142 return cast<IntegerAttr>(attr).getValue().isZero();
144 return emitOpError(
"branch weights cannot both be zero");
154LogicalResult FunctionCallOp::verify() {
155 if (getNumResults() > 1) {
157 "expected callee function to have 0 or 1 result, but provided ")
164FunctionCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
165 auto fnName = getCalleeAttr();
170 return emitOpError(
"callee function '")
171 << fnName.getValue() <<
"' not found in nearest symbol table";
174 auto functionType = funcOp.getFunctionType();
176 if (functionType.getNumInputs() != getNumOperands()) {
177 return emitOpError(
"has incorrect number of operands for callee: expected ")
178 << functionType.getNumInputs() <<
", but provided "
182 for (uint32_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
183 if (getOperand(i).
getType() != functionType.getInput(i)) {
184 return emitOpError(
"operand type mismatch: expected operand type ")
185 << functionType.getInput(i) <<
", but provided "
186 << getOperand(i).getType() <<
" for operand number " << i;
190 if (functionType.getNumResults() != getNumResults()) {
192 "has incorrect number of results has for callee: expected ")
193 << functionType.getNumResults() <<
", but provided "
197 if (getNumResults() &&
198 (getResult(0).
getType() != functionType.getResult(0))) {
199 return emitOpError(
"result type mismatch: expected ")
200 << functionType.getResult(0) <<
", but provided "
201 << getResult(0).getType();
207CallInterfaceCallable FunctionCallOp::getCallableForCallee() {
208 return getCalleeAttr();
211void FunctionCallOp::setCalleeFromCallable(CallInterfaceCallable callee) {
212 setCalleeAttr(cast<FlatSymbolRefAttr>(cast<SymbolRefAttr>(callee)));
216 return getArguments();
219MutableOperandRange FunctionCallOp::getArgOperandsMutable() {
220 return getArgumentsMutable();
227void SwitchOp::build(OpBuilder &builder, OperationState &
result, Value selector,
229 DenseIntElementsAttr literals, BlockRange targets,
230 ArrayRef<ValueRange> targetOperands) {
231 build(builder,
result, selector, defaultOperands, targetOperands, literals,
232 defaultTarget, targets);
235void SwitchOp::build(OpBuilder &builder, OperationState &
result, Value selector,
237 ArrayRef<APInt> literals, BlockRange targets,
238 ArrayRef<ValueRange> targetOperands) {
239 DenseIntElementsAttr literalsAttr;
240 if (!literals.empty()) {
241 ShapedType literalType = VectorType::get(
242 static_cast<int64_t
>(literals.size()), selector.
getType());
245 build(builder,
result, selector, defaultTarget, defaultOperands, literalsAttr,
246 targets, targetOperands);
249void SwitchOp::build(OpBuilder &builder, OperationState &
result, Value selector,
251 ArrayRef<int32_t> literals, BlockRange targets,
252 ArrayRef<ValueRange> targetOperands) {
253 DenseIntElementsAttr literalsAttr;
254 if (!literals.empty()) {
255 ShapedType literalType = VectorType::get(
256 static_cast<int64_t
>(literals.size()), selector.
getType());
259 build(builder,
result, selector, defaultTarget, defaultOperands, literalsAttr,
260 targets, targetOperands);
263LogicalResult SwitchOp::verify() {
264 std::optional<DenseIntElementsAttr> literals = getLiterals();
265 BlockRange targets = getTargets();
267 if (!literals && targets.empty())
271 Type selectorType = getSelector().getType();
272 Type literalType = literals->getType().getElementType();
273 if (literalType != selectorType)
274 return emitOpError() <<
"'selector' type (" << selectorType
275 <<
") should match literals type (" << literalType
279 if (literals && literals->size() !=
static_cast<int64_t
>(targets.size()))
280 return emitOpError() <<
"number of literals (" << literals->size()
281 <<
") should match number of targets ("
282 << targets.size() <<
")";
286SuccessorOperands SwitchOp::getSuccessorOperands(
unsigned index) {
287 assert(index < getNumSuccessors() &&
"invalid successor index");
288 return SuccessorOperands(index == 0 ? getDefaultOperandsMutable()
289 : getTargetOperandsMutable(index - 1));
292Block *SwitchOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
293 std::optional<DenseIntElementsAttr> literals = getLiterals();
296 return getDefaultTarget();
298 SuccessorRange targets = getTargets();
299 if (
auto value = dyn_cast_or_null<IntegerAttr>(operands.front())) {
300 for (
auto [index, literal] : llvm::enumerate(literals->getValues<APInt>()))
301 if (literal == value.getValue())
302 return targets[index];
303 return getDefaultTarget();
320 spirv::AddressingModel addressingModel = moduleOp.getAddressingModel();
321 if (addressingModel == spirv::AddressingModel::Logical)
323 return addressingModel !=
324 spirv::AddressingModel::PhysicalStorageBuffer64 ||
326 spirv::StorageClass::PhysicalStorageBuffer;
330 .Case<VectorType, spirv::ArrayType, spirv::MatrixType>(
331 [&](
auto compositeType) {
336 [&](
Type elementType) {
337 return isConcreteType(elementType, moduleOp);
343LogicalResult KHRAbortOp::verify() {
345 (*this)->getParentOfType<spirv::ModuleOp>()))
346 return emitOpError(
"message must be of a concrete type (numerical scalar, "
347 "physical pointer, vector, matrix, or aggregate of such "
356template <
typename LifetimeOpTy>
358 auto ptrType = cast<spirv::PointerType>(op.getPointer().getType());
359 if (ptrType.getStorageClass() != spirv::StorageClass::Function)
360 return op.emitOpError(
"pointer must have the Function storage class");
362 if (op.getSize() == 0)
364 auto moduleOp = op->template getParentOfType<spirv::ModuleOp>();
368 spirv::AddressingModel model = moduleOp.getAddressingModel();
369 if (model != spirv::AddressingModel::Physical32 &&
370 model != spirv::AddressingModel::Physical64)
371 return op.emitOpError(
"size must be 0 without a physical addressing model");
383void LoopOp::build(OpBuilder &builder, OperationState &state) {
385 spirv::LoopControl::None));
389ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &
result) {
401void LoopOp::print(OpAsmPrinter &printer) {
402 auto control = getLoopControl();
403 if (control != spirv::LoopControl::None)
404 printer <<
" control(" << spirv::stringifyLoopControl(control) <<
")";
405 if (getNumResults() > 0) {
407 printer << getResultTypes();
418 if (!llvm::hasSingleElement(srcBlock))
421 auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.
back());
422 return branchOp && branchOp.getSuccessor() == &dstBlock;
427 return llvm::hasSingleElement(block) && isa<spirv::MergeOp>(block.
front());
433 return isa<spirv::MergeOp>(op) && op.getBlock() != ®ion.back();
440 auto mergeOps = region.
getOps<spirv::MergeOp>();
441 Operation *mergeOp = llvm::getSingleElement(mergeOps);
442 return llvm::equal(mergeOp->getOperandTypes(), op->
getResultTypes());
445LogicalResult LoopOp::verifyRegions() {
446 auto *op = getOperation();
473 auto ®ion = op->getRegion(0);
482 return emitOpError(
"last block must be the merge block with only one "
483 "'spirv.mlir.merge' op");
486 "should not have 'spirv.mlir.merge' op outside the merge block");
488 if (region.hasOneBlock())
490 "must have an entry block branching to the loop header block");
494 if (std::next(region.begin(), 2) == region.end())
496 "must have a loop header block branched from the entry block");
498 Block &header = *std::next(region.begin(), 1);
502 "entry block must only have one 'spirv.Branch' op to the second block");
504 if (std::next(region.begin(), 3) == region.end())
506 "requires a loop continue block branching to the loop header block");
508 Block &cont = *std::prev(region.end(), 2);
514 [&](
unsigned index) { return cont.getSuccessor(index) == &header; }))
515 return emitOpError(
"second to last block must be the loop continue "
516 "block that branches to the loop header block");
520 for (
auto &block : llvm::make_range(std::next(region.begin(), 2),
521 std::prev(region.end(), 2))) {
522 for (
auto i : llvm::seq<unsigned>(0, block.getNumSuccessors())) {
523 if (block.getSuccessor(i) == &header) {
524 return emitOpError(
"can only have the entry and loop continue "
525 "block branching to the loop header block");
532 "result types do not match types yielded with `spirv.mlir.merge`");
537Block *LoopOp::getEntryBlock() {
538 assert(!getBody().empty() &&
"op region should not be empty!");
539 return &getBody().front();
542Block *LoopOp::getHeaderBlock() {
543 assert(!getBody().empty() &&
"op region should not be empty!");
545 return &*std::next(getBody().begin());
548Block *LoopOp::getContinueBlock() {
549 assert(!getBody().empty() &&
"op region should not be empty!");
551 return &*std::prev(getBody().end(), 2);
554Block *LoopOp::getMergeBlock() {
555 assert(!getBody().empty() &&
"op region should not be empty!");
557 return &getBody().back();
560void LoopOp::addEntryAndMergeBlock(OpBuilder &builder) {
561 assert(getBody().empty() &&
"entry and merge block already exist");
562 OpBuilder::InsertionGuard g(builder);
567 spirv::MergeOp::create(builder, getLoc());
574LogicalResult ReturnOp::verify() {
583LogicalResult ReturnValueOp::verify() {
592LogicalResult SelectOp::verify() {
593 if (
auto conditionTy = dyn_cast<VectorType>(getCondition().
getType())) {
594 auto resultVectorTy = dyn_cast<VectorType>(getResult().
getType());
595 if (!resultVectorTy) {
596 return emitOpError(
"result expected to be of vector type when "
597 "condition is of vector type");
599 if (resultVectorTy.getNumElements() != conditionTy.getNumElements()) {
600 return emitOpError(
"result should have the same number of elements as "
601 "the condition when condition is of vector type");
609SmallVector<ArrayRef<spirv::Extension>, 1> SelectOp::getExtensions() {
612SmallVector<ArrayRef<spirv::Capability>, 1> SelectOp::getCapabilities() {
615std::optional<spirv::Version> SelectOp::getMinVersion() {
618 if (isa<spirv::ScalarType>(getCondition().
getType()) &&
619 isa<spirv::CompositeType>(
getType()))
620 return Version::V_1_4;
622 return Version::V_1_0;
624std::optional<spirv::Version> SelectOp::getMaxVersion() {
625 return Version::V_1_6;
632ParseResult SelectionOp::parse(OpAsmParser &parser, OperationState &
result) {
634 spirv::SelectionControl>(parser,
result))
644void SelectionOp::print(OpAsmPrinter &printer) {
645 auto control = getSelectionControl();
646 if (control != spirv::SelectionControl::None)
647 printer <<
" control(" << spirv::stringifySelectionControl(control) <<
")";
648 if (getNumResults() > 0) {
650 printer << getResultTypes();
657LogicalResult SelectionOp::verifyRegions() {
658 auto *op = getOperation();
681 auto ®ion = op->getRegion(0);
689 return emitOpError(
"last block must be the merge block with only one "
690 "'spirv.mlir.merge' op");
693 "should not have 'spirv.mlir.merge' op outside the merge block");
695 if (region.hasOneBlock())
696 return emitOpError(
"must have a selection header block");
700 "result types do not match types yielded with `spirv.mlir.merge`");
705Block *SelectionOp::getHeaderBlock() {
706 assert(!getBody().empty() &&
"op region should not be empty!");
708 return &getBody().front();
711Block *SelectionOp::getMergeBlock() {
712 assert(!getBody().empty() &&
"op region should not be empty!");
714 return &getBody().back();
717void SelectionOp::addMergeBlock(OpBuilder &builder) {
718 assert(getBody().empty() &&
"entry and merge block already exist");
719 OpBuilder::InsertionGuard guard(builder);
723 spirv::MergeOp::create(builder, getLoc());
727SelectionOp::createIfThen(Location loc, Value condition,
729 OpBuilder &builder) {
731 spirv::SelectionOp::create(builder, loc, spirv::SelectionControl::None);
733 selectionOp.addMergeBlock(builder);
734 Block *mergeBlock = selectionOp.getMergeBlock();
735 Block *thenBlock =
nullptr;
739 OpBuilder::InsertionGuard guard(builder);
742 spirv::BranchOp::create(builder, loc, mergeBlock);
747 OpBuilder::InsertionGuard guard(builder);
749 spirv::BranchConditionalOp::create(builder, loc, condition, thenBlock,
762LogicalResult spirv::UnreachableOp::verify() {
763 auto *block = (*this)->getBlock();
766 if (block->isEntryBlock())
767 return emitOpError(
"cannot be used in reachable block");
768 if (block->hasNoPredecessors())
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
virtual ParseResult parseOptionalArrow()=0
Parse a '->' token if present.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseComma()=0
Parse a , token.
ParseResult parseTypeList(SmallVectorImpl< Type > &result)
Parse a type list.
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.
Block represents an ordered list of Operations.
unsigned getNumSuccessors()
This class is a general helper class for creating context-global objects like types,...
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
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 ParseResult parseSuccessorAndUseList(Block *&dest, SmallVectorImpl< Value > &operands)=0
Parse a single operation successor and its operand list.
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 void printSuccessorAndUseList(Block *successor, ValueRange succOperands)=0
Print the successor and its operands.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
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.
Operation is the basic unit of execution within MLIR.
OperandRange operand_range
result_type_range getResultTypes()
This class contains a list of basic blocks and a link to the parent operation it is attached to.
iterator_range< OpIterator > getOps()
This class models how operands are forwarded to block arguments in control flow.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isInteger() const
Return true if this is an integer type (with the specified width).
Type getType() const
Return the type of this value.
StorageClass getStorageClass() const
TypeRange getElementTypes() const
constexpr char kControl[]
static LogicalResult verifyLifetimeOp(LifetimeOpTy op)
static bool isConcreteType(Type type, spirv::ModuleOp moduleOp)
Returns true if type is a numerical scalar, physical pointer, vector, matrix, or an aggregate recursi...
ParseResult parseEnumKeywordAttr(EnumClass &value, ParserType &parser, StringRef attrName=spirv::attributeName< EnumClass >())
Parses the next keyword in parser as an enumerant of the given EnumClass.
static bool hasOtherMerge(Region ®ion)
Returns true if a spirv.mlir.merge op outside the merge block.
static bool returnTypesMatch(Region ®ion, Operation *op)
Returns true if types yielded by spirv.mlir.merge in the region match those returned by the op.
static bool hasOneBranchOpTo(Block &srcBlock, Block &dstBlock)
Returns true if the given srcBlock contains only one spirv.Branch to the given dstBlock.
constexpr StringRef attributeName()
static ParseResult parseControlAttribute(OpAsmParser &parser, OperationState &state, StringRef attrName=spirv::attributeName< EnumClass >())
Parses Function, Selection and Loop control attributes.
static bool isMergeBlock(Block &block)
Returns true if the given block only contains one spirv.mlir.merge op.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::TypeSwitch< T, ResultT > TypeSwitch
llvm::function_ref< Fn > function_ref
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.