18#include "llvm/Support/InterleavedRange.h"
29template <
typename EnumAttrClass,
typename EnumClass>
44 builder.
getAttr<EnumAttrClass>(
static_cast<EnumClass
>(0)));
53 assert(
index == 0 &&
"invalid successor index");
62 assert(
index < 2 &&
"invalid successor index");
64 ? getTrueTargetOperandsMutable()
65 : getFalseTargetOperandsMutable());
68ParseResult BranchConditionalOp::parse(OpAsmParser &parser,
71 OpAsmParser::UnresolvedOperand condInfo;
82 IntegerAttr trueWeight, falseWeight;
83 NamedAttrList weights;
85 auto i32Type = builder.getIntegerType(32);
86 if (parser.
parseAttribute(trueWeight, i32Type,
"weight", weights) ||
92 StringAttr branchWeightsAttrName =
93 BranchConditionalOp::getBranchWeightsAttrName(
result.name);
94 result.addAttribute(branchWeightsAttrName,
95 builder.getArrayAttr({trueWeight, falseWeight}));
99 SmallVector<Value, 4> trueOperands;
103 result.addSuccessors(dest);
104 result.addOperands(trueOperands);
107 SmallVector<Value, 4> falseOperands;
111 result.addSuccessors(dest);
112 result.addOperands(falseOperands);
113 result.addAttribute(spirv::BranchConditionalOp::getOperandSegmentSizeAttr(),
114 builder.getDenseI32ArrayAttr(
115 {1, static_cast<int32_t>(trueOperands.size()),
116 static_cast<int32_t>(falseOperands.size())}));
121void BranchConditionalOp::print(OpAsmPrinter &printer) {
122 printer <<
' ' << getCondition();
124 if (std::optional<ArrayAttr> weights = getBranchWeights()) {
126 << llvm::interleaved_array(weights->getAsValueRange<IntegerAttr>());
135LogicalResult BranchConditionalOp::verify() {
136 if (
auto weights = getBranchWeights()) {
137 if (weights->getValue().size() != 2) {
138 return emitOpError(
"must have exactly two branch weights");
140 if (llvm::all_of(*weights, [](Attribute attr) {
141 return llvm::cast<IntegerAttr>(attr).getValue().isZero();
143 return emitOpError(
"branch weights cannot both be zero");
153LogicalResult FunctionCallOp::verify() {
154 if (getNumResults() > 1) {
156 "expected callee function to have 0 or 1 result, but provided ")
163FunctionCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
164 auto fnName = getCalleeAttr();
170 << fnName.getValue() <<
"' not found in nearest symbol table";
173 auto functionType = funcOp.getFunctionType();
175 if (functionType.getNumInputs() != getNumOperands()) {
176 return emitOpError(
"has incorrect number of operands for callee: expected ")
177 << functionType.getNumInputs() <<
", but provided "
181 for (uint32_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
182 if (getOperand(i).
getType() != functionType.getInput(i)) {
183 return emitOpError(
"operand type mismatch: expected operand type ")
184 << functionType.getInput(i) <<
", but provided "
185 << getOperand(i).getType() <<
" for operand number " << i;
189 if (functionType.getNumResults() != getNumResults()) {
191 "has incorrect number of results has for callee: expected ")
192 << functionType.getNumResults() <<
", but provided "
196 if (getNumResults() &&
197 (getResult(0).
getType() != functionType.getResult(0))) {
198 return emitOpError(
"result type mismatch: expected ")
199 << functionType.getResult(0) <<
", but provided "
200 << getResult(0).getType();
206CallInterfaceCallable FunctionCallOp::getCallableForCallee() {
207 return (*this)->getAttrOfType<SymbolRefAttr>(getCalleeAttrName());
210void FunctionCallOp::setCalleeFromCallable(CallInterfaceCallable callee) {
211 (*this)->setAttr(getCalleeAttrName(), cast<SymbolRefAttr>(callee));
215 return getArguments();
218MutableOperandRange FunctionCallOp::getArgOperandsMutable() {
219 return getArgumentsMutable();
226void LoopOp::build(OpBuilder &builder, OperationState &state) {
228 spirv::LoopControl::None));
232ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &
result) {
244void LoopOp::print(OpAsmPrinter &printer) {
245 auto control = getLoopControl();
246 if (control != spirv::LoopControl::None)
247 printer <<
" control(" << spirv::stringifyLoopControl(control) <<
")";
248 if (getNumResults() > 0) {
250 printer << getResultTypes();
261 if (!llvm::hasSingleElement(srcBlock))
264 auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.
back());
265 return branchOp && branchOp.getSuccessor() == &dstBlock;
270 return llvm::hasSingleElement(block) && isa<spirv::MergeOp>(block.
front());
276 return isa<spirv::MergeOp>(op) && op.getBlock() != ®ion.back();
280LogicalResult LoopOp::verifyRegions() {
281 auto *op = getOperation();
308 auto ®ion = op->getRegion(0);
317 return emitOpError(
"last block must be the merge block with only one "
318 "'spirv.mlir.merge' op");
321 "should not have 'spirv.mlir.merge' op outside the merge block");
323 if (region.hasOneBlock())
325 "must have an entry block branching to the loop header block");
329 if (std::next(region.begin(), 2) == region.end())
331 "must have a loop header block branched from the entry block");
333 Block &header = *std::next(region.begin(), 1);
337 "entry block must only have one 'spirv.Branch' op to the second block");
339 if (std::next(region.begin(), 3) == region.end())
341 "requires a loop continue block branching to the loop header block");
343 Block &cont = *std::prev(region.end(), 2);
349 [&](
unsigned index) { return cont.getSuccessor(index) == &header; }))
350 return emitOpError(
"second to last block must be the loop continue "
351 "block that branches to the loop header block");
355 for (
auto &block : llvm::make_range(std::next(region.begin(), 2),
356 std::prev(region.end(), 2))) {
357 for (
auto i : llvm::seq<unsigned>(0, block.getNumSuccessors())) {
358 if (block.getSuccessor(i) == &header) {
359 return emitOpError(
"can only have the entry and loop continue "
360 "block branching to the loop header block");
368Block *LoopOp::getEntryBlock() {
369 assert(!getBody().empty() &&
"op region should not be empty!");
370 return &getBody().front();
373Block *LoopOp::getHeaderBlock() {
374 assert(!getBody().empty() &&
"op region should not be empty!");
376 return &*std::next(getBody().begin());
379Block *LoopOp::getContinueBlock() {
380 assert(!getBody().empty() &&
"op region should not be empty!");
382 return &*std::prev(getBody().end(), 2);
385Block *LoopOp::getMergeBlock() {
386 assert(!getBody().empty() &&
"op region should not be empty!");
388 return &getBody().back();
391void LoopOp::addEntryAndMergeBlock(OpBuilder &builder) {
392 assert(getBody().empty() &&
"entry and merge block already exist");
393 OpBuilder::InsertionGuard g(builder);
398 spirv::MergeOp::create(builder, getLoc());
405LogicalResult ReturnOp::verify() {
414LogicalResult ReturnValueOp::verify() {
423LogicalResult SelectOp::verify() {
424 if (
auto conditionTy = llvm::dyn_cast<VectorType>(getCondition().
getType())) {
425 auto resultVectorTy = llvm::dyn_cast<VectorType>(getResult().
getType());
426 if (!resultVectorTy) {
427 return emitOpError(
"result expected to be of vector type when "
428 "condition is of vector type");
430 if (resultVectorTy.getNumElements() != conditionTy.getNumElements()) {
431 return emitOpError(
"result should have the same number of elements as "
432 "the condition when condition is of vector type");
440SmallVector<ArrayRef<spirv::Extension>, 1> SelectOp::getExtensions() {
443SmallVector<ArrayRef<spirv::Capability>, 1> SelectOp::getCapabilities() {
446std::optional<spirv::Version> SelectOp::getMinVersion() {
449 if (isa<spirv::ScalarType>(getCondition().
getType()) &&
450 isa<spirv::CompositeType>(
getType()))
451 return Version::V_1_4;
453 return Version::V_1_0;
455std::optional<spirv::Version> SelectOp::getMaxVersion() {
456 return Version::V_1_6;
463ParseResult SelectionOp::parse(OpAsmParser &parser, OperationState &
result) {
465 spirv::SelectionControl>(parser,
result))
475void SelectionOp::print(OpAsmPrinter &printer) {
476 auto control = getSelectionControl();
477 if (control != spirv::SelectionControl::None)
478 printer <<
" control(" << spirv::stringifySelectionControl(control) <<
")";
479 if (getNumResults() > 0) {
481 printer << getResultTypes();
488LogicalResult SelectionOp::verifyRegions() {
489 auto *op = getOperation();
512 auto ®ion = op->getRegion(0);
520 return emitOpError(
"last block must be the merge block with only one "
521 "'spirv.mlir.merge' op");
524 "should not have 'spirv.mlir.merge' op outside the merge block");
526 if (region.hasOneBlock())
527 return emitOpError(
"must have a selection header block");
532Block *SelectionOp::getHeaderBlock() {
533 assert(!getBody().empty() &&
"op region should not be empty!");
535 return &getBody().front();
538Block *SelectionOp::getMergeBlock() {
539 assert(!getBody().empty() &&
"op region should not be empty!");
541 return &getBody().back();
544void SelectionOp::addMergeBlock(OpBuilder &builder) {
545 assert(getBody().empty() &&
"entry and merge block already exist");
546 OpBuilder::InsertionGuard guard(builder);
550 spirv::MergeOp::create(builder, getLoc());
554SelectionOp::createIfThen(Location loc, Value condition,
556 OpBuilder &builder) {
558 spirv::SelectionOp::create(builder, loc, spirv::SelectionControl::None);
560 selectionOp.addMergeBlock(builder);
561 Block *mergeBlock = selectionOp.getMergeBlock();
562 Block *thenBlock =
nullptr;
566 OpBuilder::InsertionGuard guard(builder);
569 spirv::BranchOp::create(builder, loc, mergeBlock);
574 OpBuilder::InsertionGuard guard(builder);
576 spirv::BranchConditionalOp::create(builder, loc, condition, thenBlock,
589LogicalResult spirv::UnreachableOp::verify() {
590 auto *block = (*this)->getBlock();
593 if (block->isEntryBlock())
594 return emitOpError(
"cannot be used in reachable block");
595 if (block->hasNoPredecessors())
p<< " : "<< getMemRefType()<< ", "<< getType();}static LogicalResult verifyVectorMemoryOp(Operation *op, MemRefType memrefType, VectorType vectorType) { if(memrefType.getElementType() !=vectorType.getElementType()) return op-> emitOpError("requires memref and vector types of the same elemental type")
Given a list of lists of parsed operands, populates uniqueOperands with unique operands.
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.
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
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,...
constexpr char kControl[]
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 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::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.