18 #include "llvm/Support/InterleavedRange.h"
29 template <
typename EnumAttrClass,
typename EnumClass>
32 StringRef attrName = spirv::attributeName<EnumClass>()) {
36 spirv::parseEnumKeywordAttr<EnumAttrClass>(control, parser, state) ||
43 state.addAttribute(attrName,
44 builder.
getAttr<EnumAttrClass>(
static_cast<EnumClass
>(0)));
53 assert(index == 0 &&
"invalid successor index");
62 assert(index < 2 &&
"invalid successor index");
63 return SuccessorOperands(index == kTrueIndex
64 ? getTrueTargetOperandsMutable()
65 : getFalseTargetOperandsMutable());
69 OperationState &result) {
70 auto &builder = parser.getBuilder();
71 OpAsmParser::UnresolvedOperand condInfo;
75 Type boolTy = builder.getI1Type();
76 if (parser.parseOperand(condInfo) ||
77 parser.resolveOperand(condInfo, boolTy, result.operands))
81 if (succeeded(parser.parseOptionalLSquare())) {
82 IntegerAttr trueWeight, falseWeight;
83 NamedAttrList weights;
85 auto i32Type = builder.getIntegerType(32);
86 if (parser.parseAttribute(trueWeight, i32Type,
"weight", weights) ||
87 parser.parseComma() ||
88 parser.parseAttribute(falseWeight, i32Type,
"weight", weights) ||
89 parser.parseRSquare())
92 StringAttr branchWeightsAttrName =
93 BranchConditionalOp::getBranchWeightsAttrName(result.name);
94 result.addAttribute(branchWeightsAttrName,
95 builder.getArrayAttr({trueWeight, falseWeight}));
99 SmallVector<Value, 4> trueOperands;
100 if (parser.parseComma() ||
101 parser.parseSuccessorAndUseList(dest, trueOperands))
103 result.addSuccessors(dest);
104 result.addOperands(trueOperands);
107 SmallVector<Value, 4> falseOperands;
108 if (parser.parseComma() ||
109 parser.parseSuccessorAndUseList(dest, 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())}));
122 printer <<
' ' << getCondition();
124 if (std::optional<ArrayAttr> weights = getBranchWeights()) {
126 << llvm::interleaved_array(weights->getAsValueRange<IntegerAttr>());
130 printer.printSuccessorAndUseList(getTrueBlock(), getTrueBlockArguments());
132 printer.printSuccessorAndUseList(getFalseBlock(), getFalseBlockArguments());
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");
154 auto fnName = getCalleeAttr();
156 auto funcOp = dyn_cast_or_null<spirv::FuncOp>(
159 return emitOpError(
"callee function '")
160 << fnName.getValue() <<
"' not found in nearest symbol table";
163 auto functionType = funcOp.getFunctionType();
165 if (getNumResults() > 1) {
167 "expected callee function to have 0 or 1 result, but provided ")
171 if (functionType.getNumInputs() != getNumOperands()) {
172 return emitOpError(
"has incorrect number of operands for callee: expected ")
173 << functionType.getNumInputs() <<
", but provided "
177 for (uint32_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
178 if (getOperand(i).
getType() != functionType.getInput(i)) {
179 return emitOpError(
"operand type mismatch: expected operand type ")
180 << functionType.getInput(i) <<
", but provided "
181 << getOperand(i).getType() <<
" for operand number " << i;
185 if (functionType.getNumResults() != getNumResults()) {
187 "has incorrect number of results has for callee: expected ")
188 << functionType.getNumResults() <<
", but provided "
192 if (getNumResults() &&
193 (getResult(0).
getType() != functionType.getResult(0))) {
194 return emitOpError(
"result type mismatch: expected ")
195 << functionType.getResult(0) <<
", but provided "
196 << getResult(0).getType();
202 CallInterfaceCallable FunctionCallOp::getCallableForCallee() {
203 return (*this)->getAttrOfType<SymbolRefAttr>(getCalleeAttrName());
206 void FunctionCallOp::setCalleeFromCallable(CallInterfaceCallable callee) {
207 (*this)->setAttr(getCalleeAttrName(), cast<SymbolRefAttr>(callee));
211 return getArguments();
214 MutableOperandRange FunctionCallOp::getArgOperandsMutable() {
215 return getArgumentsMutable();
222 void LoopOp::build(OpBuilder &builder, OperationState &state) {
223 state.addAttribute(
"loop_control", builder.getAttr<spirv::LoopControlAttr>(
228 ParseResult
LoopOp::parse(OpAsmParser &parser, OperationState &result) {
229 if (parseControlAttribute<spirv::LoopControlAttr, spirv::LoopControl>(parser,
232 return parser.parseRegion(*result.addRegion(), {});
236 auto control = getLoopControl();
238 printer <<
" control(" << spirv::stringifyLoopControl(control) <<
")";
240 printer.printRegion(getRegion(),
false,
248 if (!llvm::hasSingleElement(srcBlock))
251 auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.
back());
252 return branchOp && branchOp.getSuccessor() == &dstBlock;
257 return llvm::hasSingleElement(block) && isa<spirv::MergeOp>(block.
front());
263 return isa<spirv::MergeOp>(op) && op.getBlock() != ®ion.back();
267 LogicalResult LoopOp::verifyRegions() {
268 auto *op = getOperation();
295 auto ®ion = op->getRegion(0);
304 return emitOpError(
"last block must be the merge block with only one "
305 "'spirv.mlir.merge' op");
308 "should not have 'spirv.mlir.merge' op outside the merge block");
310 if (region.hasOneBlock())
312 "must have an entry block branching to the loop header block");
316 if (std::next(region.begin(), 2) == region.end())
318 "must have a loop header block branched from the entry block");
320 Block &header = *std::next(region.begin(), 1);
324 "entry block must only have one 'spirv.Branch' op to the second block");
326 if (std::next(region.begin(), 3) == region.end())
328 "requires a loop continue block branching to the loop header block");
330 Block &cont = *std::prev(region.end(), 2);
336 [&](
unsigned index) { return cont.getSuccessor(index) == &header; }))
337 return emitOpError(
"second to last block must be the loop continue "
338 "block that branches to the loop header block");
342 for (
auto &block : llvm::make_range(std::next(region.begin(), 2),
343 std::prev(region.end(), 2))) {
344 for (
auto i : llvm::seq<unsigned>(0, block.getNumSuccessors())) {
345 if (block.getSuccessor(i) == &header) {
346 return emitOpError(
"can only have the entry and loop continue "
347 "block branching to the loop header block");
355 Block *LoopOp::getEntryBlock() {
356 assert(!getBody().empty() &&
"op region should not be empty!");
357 return &getBody().front();
360 Block *LoopOp::getHeaderBlock() {
361 assert(!getBody().empty() &&
"op region should not be empty!");
363 return &*std::next(getBody().begin());
366 Block *LoopOp::getContinueBlock() {
367 assert(!getBody().empty() &&
"op region should not be empty!");
369 return &*std::prev(getBody().end(), 2);
372 Block *LoopOp::getMergeBlock() {
373 assert(!getBody().empty() &&
"op region should not be empty!");
375 return &getBody().back();
378 void LoopOp::addEntryAndMergeBlock(OpBuilder &builder) {
379 assert(getBody().empty() &&
"entry and merge block already exist");
380 OpBuilder::InsertionGuard g(builder);
381 builder.createBlock(&getBody());
382 builder.createBlock(&getBody());
385 builder.create<spirv::MergeOp>(getLoc());
411 if (
auto conditionTy = llvm::dyn_cast<VectorType>(getCondition().
getType())) {
412 auto resultVectorTy = llvm::dyn_cast<VectorType>(getResult().
getType());
413 if (!resultVectorTy) {
414 return emitOpError(
"result expected to be of vector type when "
415 "condition is of vector type");
417 if (resultVectorTy.getNumElements() != conditionTy.getNumElements()) {
418 return emitOpError(
"result should have the same number of elements as "
419 "the condition when condition is of vector type");
427 SmallVector<ArrayRef<spirv::Extension>, 1> SelectOp::getExtensions() {
430 SmallVector<ArrayRef<spirv::Capability>, 1> SelectOp::getCapabilities() {
433 std::optional<spirv::Version> SelectOp::getMinVersion() {
436 if (isa<spirv::ScalarType>(getCondition().
getType()) &&
437 isa<spirv::CompositeType>(
getType()))
438 return Version::V_1_4;
440 return Version::V_1_0;
442 std::optional<spirv::Version> SelectOp::getMaxVersion() {
443 return Version::V_1_6;
452 spirv::SelectionControl>(parser, result))
455 if (succeeded(parser.parseOptionalArrow()))
456 if (parser.parseTypeList(result.types))
459 return parser.parseRegion(*result.addRegion(), {});
463 auto control = getSelectionControl();
465 printer <<
" control(" << spirv::stringifySelectionControl(control) <<
")";
466 if (getNumResults() > 0) {
468 printer << getResultTypes();
471 printer.printRegion(getRegion(),
false,
475 LogicalResult SelectionOp::verifyRegions() {
476 auto *op = getOperation();
499 auto ®ion = op->getRegion(0);
507 return emitOpError(
"last block must be the merge block with only one "
508 "'spirv.mlir.merge' op");
511 "should not have 'spirv.mlir.merge' op outside the merge block");
513 if (region.hasOneBlock())
514 return emitOpError(
"must have a selection header block");
519 Block *SelectionOp::getHeaderBlock() {
520 assert(!getBody().empty() &&
"op region should not be empty!");
522 return &getBody().front();
525 Block *SelectionOp::getMergeBlock() {
526 assert(!getBody().empty() &&
"op region should not be empty!");
528 return &getBody().back();
531 void SelectionOp::addMergeBlock(OpBuilder &builder) {
532 assert(getBody().empty() &&
"entry and merge block already exist");
533 OpBuilder::InsertionGuard guard(builder);
534 builder.createBlock(&getBody());
537 builder.create<spirv::MergeOp>(getLoc());
541 SelectionOp::createIfThen(Location loc, Value condition,
543 OpBuilder &builder) {
547 selectionOp.addMergeBlock(builder);
548 Block *mergeBlock = selectionOp.getMergeBlock();
549 Block *thenBlock =
nullptr;
553 OpBuilder::InsertionGuard guard(builder);
554 thenBlock = builder.createBlock(mergeBlock);
556 builder.create<spirv::BranchOp>(loc, mergeBlock);
561 OpBuilder::InsertionGuard guard(builder);
562 builder.createBlock(thenBlock);
563 builder.create<spirv::BranchConditionalOp>(
564 loc, condition, thenBlock,
565 ArrayRef<Value>(), mergeBlock,
577 auto *block = (*this)->getBlock();
580 if (block->isEntryBlock())
581 return emitOpError(
"cannot be used in reachable block");
582 if (block->hasNoPredecessors())
static OperandRange getSuccessorOperands(Block *block, unsigned successorIndex)
Return the operand range used to transfer operands from block to its successor with the given index.
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
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 parseLParen()=0
Parse a ( token.
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,...
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.
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
@ Type
An inlay hint that for a type annotation.
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
constexpr char kControl[]
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.
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.
llvm::function_ref< Fn > function_ref
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
This represents an operation in an abstracted form, suitable for use with the builder APIs.