MLIR 24.0.0git
ControlFlowOps.cpp
Go to the documentation of this file.
1//===- ControlFlowOps.cpp - MLIR SPIR-V Control Flow Ops -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Defines the control flow operations in the SPIR-V dialect.
10//
11//===----------------------------------------------------------------------===//
12
17
18#include "llvm/ADT/TypeSwitch.h"
19#include "llvm/Support/InterleavedRange.h"
20
21#include "SPIRVOpUtils.h"
22#include "SPIRVParsingUtils.h"
23
24using namespace mlir::spirv::AttrNames;
25
26namespace mlir::spirv {
27
28/// Parses Function, Selection and Loop control attributes. If no control is
29/// specified, "None" is used as a default.
30template <typename EnumAttrClass, typename EnumClass>
31static ParseResult
33 StringRef attrName = spirv::attributeName<EnumClass>()) {
34 if (succeeded(parser.parseOptionalKeyword(kControl))) {
35 EnumClass control;
36 if (parser.parseLParen() ||
37 spirv::parseEnumKeywordAttr<EnumAttrClass>(control, parser, state) ||
38 parser.parseRParen())
39 return failure();
40 return success();
41 }
42 // Set control to "None" otherwise.
43 Builder builder = parser.getBuilder();
44 state.addAttribute(attrName,
45 builder.getAttr<EnumAttrClass>(static_cast<EnumClass>(0)));
46 return success();
47}
48
49//===----------------------------------------------------------------------===//
50// spirv.BranchOp
51//===----------------------------------------------------------------------===//
52
53SuccessorOperands BranchOp::getSuccessorOperands(unsigned index) {
54 assert(index == 0 && "invalid successor index");
55 return SuccessorOperands(0, getTargetOperandsMutable());
56}
57
58//===----------------------------------------------------------------------===//
59// spirv.BranchConditionalOp
60//===----------------------------------------------------------------------===//
61
62SuccessorOperands BranchConditionalOp::getSuccessorOperands(unsigned index) {
63 assert(index < 2 && "invalid successor index");
64 return SuccessorOperands(index == kTrueIndex
65 ? getTrueTargetOperandsMutable()
66 : getFalseTargetOperandsMutable());
67}
68
69ParseResult BranchConditionalOp::parse(OpAsmParser &parser,
70 OperationState &result) {
71 auto &builder = parser.getBuilder();
72 OpAsmParser::UnresolvedOperand condInfo;
73 Block *dest;
74
75 // Parse the condition.
76 Type boolTy = builder.getI1Type();
77 if (parser.parseOperand(condInfo) ||
78 parser.resolveOperand(condInfo, boolTy, result.operands))
79 return failure();
80
81 // Parse the optional branch weights.
82 if (succeeded(parser.parseOptionalLSquare())) {
83 IntegerAttr trueWeight, falseWeight;
84 NamedAttrList weights;
85
86 auto i32Type = builder.getIntegerType(32);
87 if (parser.parseAttribute(trueWeight, i32Type, "weight", weights) ||
88 parser.parseComma() ||
89 parser.parseAttribute(falseWeight, i32Type, "weight", weights) ||
90 parser.parseRSquare())
91 return failure();
92
93 StringAttr branchWeightsAttrName =
94 BranchConditionalOp::getBranchWeightsAttrName(result.name);
95 result.addAttribute(branchWeightsAttrName,
96 builder.getArrayAttr({trueWeight, falseWeight}));
97 }
98
99 // Parse the true branch.
100 SmallVector<Value, 4> trueOperands;
101 if (parser.parseComma() ||
102 parser.parseSuccessorAndUseList(dest, trueOperands))
103 return failure();
104 result.addSuccessors(dest);
105 result.addOperands(trueOperands);
106
107 // Parse the false branch.
108 SmallVector<Value, 4> falseOperands;
109 if (parser.parseComma() ||
110 parser.parseSuccessorAndUseList(dest, falseOperands))
111 return failure();
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())}));
118
119 return success();
120}
121
122void BranchConditionalOp::print(OpAsmPrinter &printer) {
123 printer << ' ' << getCondition();
124
125 if (std::optional<ArrayAttr> weights = getBranchWeights()) {
126 printer << ' '
127 << llvm::interleaved_array(weights->getAsValueRange<IntegerAttr>());
128 }
129
130 printer << ", ";
131 printer.printSuccessorAndUseList(getTrueBlock(), getTrueBlockArguments());
132 printer << ", ";
133 printer.printSuccessorAndUseList(getFalseBlock(), getFalseBlockArguments());
134}
135
136LogicalResult BranchConditionalOp::verify() {
137 if (auto weights = getBranchWeights()) {
138 if (weights->getValue().size() != 2) {
139 return emitOpError("must have exactly two branch weights");
140 }
141 if (llvm::all_of(*weights, [](Attribute attr) {
142 return cast<IntegerAttr>(attr).getValue().isZero();
143 }))
144 return emitOpError("branch weights cannot both be zero");
145 }
146
147 return success();
148}
149
150//===----------------------------------------------------------------------===//
151// spirv.FunctionCall
152//===----------------------------------------------------------------------===//
153
154LogicalResult FunctionCallOp::verify() {
155 if (getNumResults() > 1) {
156 return emitOpError(
157 "expected callee function to have 0 or 1 result, but provided ")
158 << getNumResults();
159 }
160 return success();
161}
162
163LogicalResult
164FunctionCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
165 auto fnName = getCalleeAttr();
166
167 auto funcOp =
168 symbolTable.lookupNearestSymbolFrom<spirv::FuncOp>(*this, fnName);
169 if (!funcOp) {
170 return emitOpError("callee function '")
171 << fnName.getValue() << "' not found in nearest symbol table";
172 }
173
174 auto functionType = funcOp.getFunctionType();
175
176 if (functionType.getNumInputs() != getNumOperands()) {
177 return emitOpError("has incorrect number of operands for callee: expected ")
178 << functionType.getNumInputs() << ", but provided "
179 << getNumOperands();
180 }
181
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;
187 }
188 }
189
190 if (functionType.getNumResults() != getNumResults()) {
191 return emitOpError(
192 "has incorrect number of results has for callee: expected ")
193 << functionType.getNumResults() << ", but provided "
194 << getNumResults();
195 }
196
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();
202 }
203
204 return success();
205}
206
207CallInterfaceCallable FunctionCallOp::getCallableForCallee() {
208 return getCalleeAttr();
209}
210
211void FunctionCallOp::setCalleeFromCallable(CallInterfaceCallable callee) {
212 setCalleeAttr(cast<FlatSymbolRefAttr>(cast<SymbolRefAttr>(callee)));
213}
214
215Operation::operand_range FunctionCallOp::getArgOperands() {
216 return getArguments();
217}
218
219MutableOperandRange FunctionCallOp::getArgOperandsMutable() {
220 return getArgumentsMutable();
221}
222
223//===----------------------------------------------------------------------===//
224// spirv.Switch
225//===----------------------------------------------------------------------===//
226
227void SwitchOp::build(OpBuilder &builder, OperationState &result, Value selector,
228 Block *defaultTarget, ValueRange defaultOperands,
229 DenseIntElementsAttr literals, BlockRange targets,
230 ArrayRef<ValueRange> targetOperands) {
231 build(builder, result, selector, defaultOperands, targetOperands, literals,
232 defaultTarget, targets);
233}
234
235void SwitchOp::build(OpBuilder &builder, OperationState &result, Value selector,
236 Block *defaultTarget, ValueRange defaultOperands,
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());
243 literalsAttr = DenseIntElementsAttr::get(literalType, literals);
244 }
245 build(builder, result, selector, defaultTarget, defaultOperands, literalsAttr,
246 targets, targetOperands);
247}
248
249void SwitchOp::build(OpBuilder &builder, OperationState &result, Value selector,
250 Block *defaultTarget, ValueRange defaultOperands,
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());
257 literalsAttr = DenseIntElementsAttr::get(literalType, literals);
258 }
259 build(builder, result, selector, defaultTarget, defaultOperands, literalsAttr,
260 targets, targetOperands);
261}
262
263LogicalResult SwitchOp::verify() {
264 std::optional<DenseIntElementsAttr> literals = getLiterals();
265 BlockRange targets = getTargets();
266
267 if (!literals && targets.empty())
268 return success();
269
270 if (literals) {
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
276 << ")";
277 }
278
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() << ")";
283 return success();
284}
285
286SuccessorOperands SwitchOp::getSuccessorOperands(unsigned index) {
287 assert(index < getNumSuccessors() && "invalid successor index");
288 return SuccessorOperands(index == 0 ? getDefaultOperandsMutable()
289 : getTargetOperandsMutable(index - 1));
290}
291
292Block *SwitchOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
293 std::optional<DenseIntElementsAttr> literals = getLiterals();
294
295 if (!literals)
296 return getDefaultTarget();
297
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();
304 }
305 return nullptr;
306}
307
308//===----------------------------------------------------------------------===//
309// spirv.KHR.Abort
310//===----------------------------------------------------------------------===//
311
312/// Returns true if `type` is a numerical scalar, physical pointer, vector,
313/// matrix, or an aggregate recursively containing only such types. Without an
314/// enclosing `moduleOp` any pointer is accepted.
315static bool isConcreteType(Type type, spirv::ModuleOp moduleOp) {
316 return TypeSwitch<Type, bool>(type)
317 .Case([&](spirv::PointerType pointerType) {
318 if (!moduleOp)
319 return true;
320 spirv::AddressingModel addressingModel = moduleOp.getAddressingModel();
321 if (addressingModel == spirv::AddressingModel::Logical)
322 return false;
323 return addressingModel !=
324 spirv::AddressingModel::PhysicalStorageBuffer64 ||
325 pointerType.getStorageClass() ==
326 spirv::StorageClass::PhysicalStorageBuffer;
327 })
328 .Case(
329 [](spirv::ScalarType scalarType) { return !scalarType.isInteger(1); })
330 .Case<VectorType, spirv::ArrayType, spirv::MatrixType>(
331 [&](auto compositeType) {
332 return isConcreteType(compositeType.getElementType(), moduleOp);
333 })
334 .Case([&](spirv::StructType structType) {
335 return llvm::all_of(structType.getElementTypes(),
336 [&](Type elementType) {
337 return isConcreteType(elementType, moduleOp);
338 });
339 })
340 .Default(false);
341}
342
343LogicalResult KHRAbortOp::verify() {
344 if (!isConcreteType(getMessage().getType(),
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 "
348 "types)");
349 return success();
350}
351
352//===----------------------------------------------------------------------===//
353// spirv.LifetimeStart / spirv.LifetimeStop
354//===----------------------------------------------------------------------===//
355
356template <typename LifetimeOpTy>
357static LogicalResult verifyLifetimeOp(LifetimeOpTy op) {
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");
361
362 if (op.getSize() == 0)
363 return success();
364 auto moduleOp = op->template getParentOfType<spirv::ModuleOp>();
365 if (!moduleOp)
366 return success();
367 // A non-zero size needs the Addresses capability, which Physical32/64 imply.
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");
372 return success();
373}
374
375LogicalResult LifetimeStartOp::verify() { return verifyLifetimeOp(*this); }
376
377LogicalResult LifetimeStopOp::verify() { return verifyLifetimeOp(*this); }
378
379//===----------------------------------------------------------------------===//
380// spirv.mlir.loop
381//===----------------------------------------------------------------------===//
382
383void LoopOp::build(OpBuilder &builder, OperationState &state) {
384 state.addAttribute("loop_control", builder.getAttr<spirv::LoopControlAttr>(
385 spirv::LoopControl::None));
386 state.addRegion();
387}
388
389ParseResult LoopOp::parse(OpAsmParser &parser, OperationState &result) {
391 result))
392 return failure();
393
394 if (succeeded(parser.parseOptionalArrow()))
395 if (parser.parseTypeList(result.types))
396 return failure();
397
398 return parser.parseRegion(*result.addRegion(), /*arguments=*/{});
399}
400
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) {
406 printer << " -> ";
407 printer << getResultTypes();
408 }
409 printer << ' ';
410 printer.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
411 /*printBlockTerminators=*/true);
412}
413
414/// Returns true if the given `srcBlock` contains only one `spirv.Branch` to the
415/// given `dstBlock`.
416static bool hasOneBranchOpTo(Block &srcBlock, Block &dstBlock) {
417 // Check that there is only one op in the `srcBlock`.
418 if (!llvm::hasSingleElement(srcBlock))
419 return false;
420
421 auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.back());
422 return branchOp && branchOp.getSuccessor() == &dstBlock;
423}
424
425/// Returns true if the given `block` only contains one `spirv.mlir.merge` op.
426static bool isMergeBlock(Block &block) {
427 return llvm::hasSingleElement(block) && isa<spirv::MergeOp>(block.front());
428}
429
430/// Returns true if a `spirv.mlir.merge` op outside the merge block.
431static bool hasOtherMerge(Region &region) {
432 return !region.empty() && llvm::any_of(region.getOps(), [&](Operation &op) {
433 return isa<spirv::MergeOp>(op) && op.getBlock() != &region.back();
434 });
435}
436
437/// Returns true if types yielded by `spirv.mlir.merge` in the region match
438/// those returned by the `op`.
439static bool returnTypesMatch(Region &region, Operation *op) {
440 auto mergeOps = region.getOps<spirv::MergeOp>();
441 Operation *mergeOp = llvm::getSingleElement(mergeOps);
442 return llvm::equal(mergeOp->getOperandTypes(), op->getResultTypes());
443}
444
445LogicalResult LoopOp::verifyRegions() {
446 auto *op = getOperation();
447
448 // We need to verify that the blocks follow the following layout:
449 //
450 // +-------------+
451 // | entry block |
452 // +-------------+
453 // |
454 // v
455 // +-------------+
456 // | loop header | <-----+
457 // +-------------+ |
458 // |
459 // ... |
460 // \ | / |
461 // v |
462 // +---------------+ |
463 // | loop continue | -----+
464 // +---------------+
465 //
466 // ...
467 // \ | /
468 // v
469 // +-------------+
470 // | merge block |
471 // +-------------+
472
473 auto &region = op->getRegion(0);
474 // Allow empty region as a degenerated case, which can come from
475 // optimizations.
476 if (region.empty())
477 return success();
478
479 // The last block is the merge block.
480 Block &merge = region.back();
481 if (!isMergeBlock(merge))
482 return emitOpError("last block must be the merge block with only one "
483 "'spirv.mlir.merge' op");
484 if (hasOtherMerge(region))
485 return emitOpError(
486 "should not have 'spirv.mlir.merge' op outside the merge block");
487
488 if (region.hasOneBlock())
489 return emitOpError(
490 "must have an entry block branching to the loop header block");
491 // The first block is the entry block.
492 Block &entry = region.front();
493
494 if (std::next(region.begin(), 2) == region.end())
495 return emitOpError(
496 "must have a loop header block branched from the entry block");
497 // The second block is the loop header block.
498 Block &header = *std::next(region.begin(), 1);
499
500 if (!hasOneBranchOpTo(entry, header))
501 return emitOpError(
502 "entry block must only have one 'spirv.Branch' op to the second block");
503
504 if (std::next(region.begin(), 3) == region.end())
505 return emitOpError(
506 "requires a loop continue block branching to the loop header block");
507 // The second to last block is the loop continue block.
508 Block &cont = *std::prev(region.end(), 2);
509
510 // Make sure that we have a branch from the loop continue block to the loop
511 // header block.
512 if (llvm::none_of(
513 llvm::seq<unsigned>(0, cont.getNumSuccessors()),
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");
517
518 // Make sure that no other blocks (except the entry and loop continue block)
519 // 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");
526 }
527 }
528 }
529
530 if (!returnTypesMatch(region, op))
531 return emitOpError(
532 "result types do not match types yielded with `spirv.mlir.merge`");
533
534 return success();
535}
536
537Block *LoopOp::getEntryBlock() {
538 assert(!getBody().empty() && "op region should not be empty!");
539 return &getBody().front();
540}
541
542Block *LoopOp::getHeaderBlock() {
543 assert(!getBody().empty() && "op region should not be empty!");
544 // The second block is the loop header block.
545 return &*std::next(getBody().begin());
546}
547
548Block *LoopOp::getContinueBlock() {
549 assert(!getBody().empty() && "op region should not be empty!");
550 // The second to last block is the loop continue block.
551 return &*std::prev(getBody().end(), 2);
552}
553
554Block *LoopOp::getMergeBlock() {
555 assert(!getBody().empty() && "op region should not be empty!");
556 // The last block is the loop merge block.
557 return &getBody().back();
558}
559
560void LoopOp::addEntryAndMergeBlock(OpBuilder &builder) {
561 assert(getBody().empty() && "entry and merge block already exist");
562 OpBuilder::InsertionGuard g(builder);
563 builder.createBlock(&getBody());
564 builder.createBlock(&getBody());
565
566 // Add a spirv.mlir.merge op into the merge block.
567 spirv::MergeOp::create(builder, getLoc());
568}
569
570//===----------------------------------------------------------------------===//
571// spirv.Return
572//===----------------------------------------------------------------------===//
573
574LogicalResult ReturnOp::verify() {
575 // Verification is performed in spirv.func op.
576 return success();
577}
578
579//===----------------------------------------------------------------------===//
580// spirv.ReturnValue
581//===----------------------------------------------------------------------===//
582
583LogicalResult ReturnValueOp::verify() {
584 // Verification is performed in spirv.func op.
585 return success();
586}
587
588//===----------------------------------------------------------------------===//
589// spirv.Select
590//===----------------------------------------------------------------------===//
591
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");
598 }
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");
602 }
603 }
604 return success();
605}
606
607// Custom availability implementation is needed for spirv.Select given the
608// syntax changes starting v1.4.
609SmallVector<ArrayRef<spirv::Extension>, 1> SelectOp::getExtensions() {
610 return {};
611}
612SmallVector<ArrayRef<spirv::Capability>, 1> SelectOp::getCapabilities() {
613 return {};
614}
615std::optional<spirv::Version> SelectOp::getMinVersion() {
616 // Per the spec, "Before version 1.4, results are only computed per
617 // component."
618 if (isa<spirv::ScalarType>(getCondition().getType()) &&
619 isa<spirv::CompositeType>(getType()))
620 return Version::V_1_4;
621
622 return Version::V_1_0;
623}
624std::optional<spirv::Version> SelectOp::getMaxVersion() {
625 return Version::V_1_6;
626}
627
628//===----------------------------------------------------------------------===//
629// spirv.mlir.selection
630//===----------------------------------------------------------------------===//
631
632ParseResult SelectionOp::parse(OpAsmParser &parser, OperationState &result) {
633 if (parseControlAttribute<spirv::SelectionControlAttr,
634 spirv::SelectionControl>(parser, result))
635 return failure();
636
637 if (succeeded(parser.parseOptionalArrow()))
638 if (parser.parseTypeList(result.types))
639 return failure();
640
641 return parser.parseRegion(*result.addRegion(), /*arguments=*/{});
642}
643
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) {
649 printer << " -> ";
650 printer << getResultTypes();
651 }
652 printer << ' ';
653 printer.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
654 /*printBlockTerminators=*/true);
655}
656
657LogicalResult SelectionOp::verifyRegions() {
658 auto *op = getOperation();
659
660 // We need to verify that the blocks follow the following layout:
661 //
662 // +--------------+
663 // | header block |
664 // +--------------+
665 // / | \
666 // ...
667 //
668 //
669 // +---------+ +---------+ +---------+
670 // | case #0 | | case #1 | | case #2 | ...
671 // +---------+ +---------+ +---------+
672 //
673 //
674 // ...
675 // \ | /
676 // v
677 // +-------------+
678 // | merge block |
679 // +-------------+
680
681 auto &region = op->getRegion(0);
682 // Allow empty region as a degenerated case, which can come from
683 // optimizations.
684 if (region.empty())
685 return success();
686
687 // The last block is the merge block.
688 if (!isMergeBlock(region.back()))
689 return emitOpError("last block must be the merge block with only one "
690 "'spirv.mlir.merge' op");
691 if (hasOtherMerge(region))
692 return emitOpError(
693 "should not have 'spirv.mlir.merge' op outside the merge block");
694
695 if (region.hasOneBlock())
696 return emitOpError("must have a selection header block");
697
698 if (!returnTypesMatch(region, op))
699 return emitOpError(
700 "result types do not match types yielded with `spirv.mlir.merge`");
701
702 return success();
703}
704
705Block *SelectionOp::getHeaderBlock() {
706 assert(!getBody().empty() && "op region should not be empty!");
707 // The first block is the loop header block.
708 return &getBody().front();
709}
710
711Block *SelectionOp::getMergeBlock() {
712 assert(!getBody().empty() && "op region should not be empty!");
713 // The last block is the loop merge block.
714 return &getBody().back();
715}
716
717void SelectionOp::addMergeBlock(OpBuilder &builder) {
718 assert(getBody().empty() && "entry and merge block already exist");
719 OpBuilder::InsertionGuard guard(builder);
720 builder.createBlock(&getBody());
721
722 // Add a spirv.mlir.merge op into the merge block.
723 spirv::MergeOp::create(builder, getLoc());
724}
725
726SelectionOp
727SelectionOp::createIfThen(Location loc, Value condition,
728 function_ref<void(OpBuilder &builder)> thenBody,
729 OpBuilder &builder) {
730 auto selectionOp =
731 spirv::SelectionOp::create(builder, loc, spirv::SelectionControl::None);
732
733 selectionOp.addMergeBlock(builder);
734 Block *mergeBlock = selectionOp.getMergeBlock();
735 Block *thenBlock = nullptr;
736
737 // Build the "then" block.
738 {
739 OpBuilder::InsertionGuard guard(builder);
740 thenBlock = builder.createBlock(mergeBlock);
741 thenBody(builder);
742 spirv::BranchOp::create(builder, loc, mergeBlock);
743 }
744
745 // Build the header block.
746 {
747 OpBuilder::InsertionGuard guard(builder);
748 builder.createBlock(thenBlock);
749 spirv::BranchConditionalOp::create(builder, loc, condition, thenBlock,
750 /*trueArguments=*/ArrayRef<Value>(),
751 mergeBlock,
752 /*falseArguments=*/ArrayRef<Value>());
753 }
754
755 return selectionOp;
756}
757
758//===----------------------------------------------------------------------===//
759// spirv.Unreachable
760//===----------------------------------------------------------------------===//
761
762LogicalResult spirv::UnreachableOp::verify() {
763 auto *block = (*this)->getBlock();
764 // Fast track: if this is in entry block, its invalid. Otherwise, if no
765 // predecessors, it's valid.
766 if (block->isEntryBlock())
767 return emitOpError("cannot be used in reachable block");
768 if (block->hasNoPredecessors())
769 return success();
770
771 // TODO: further verification needs to analyze reachability from
772 // the entry block.
773
774 return success();
775}
776
777} // namespace mlir::spirv
return success()
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.
Definition Block.h:34
unsigned getNumSuccessors()
Definition Block.cpp:270
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerType getI1Type()
Definition Builders.cpp:61
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
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 &region, 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.
Definition Builders.cpp:439
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OperandRange operand_range
Definition Operation.h:398
result_type_range getResultTypes()
Definition Operation.h:455
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
iterator_range< OpIterator > getOps()
Definition Region.h:180
bool empty()
Definition Region.h:60
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...
Definition Types.h:74
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
Type getType() const
Return the type of this value.
Definition Value.h:105
StorageClass getStorageClass() const
SPIR-V struct type.
Definition SPIRVTypes.h:314
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 &region)
Returns true if a spirv.mlir.merge op outside the merge block.
static bool returnTypesMatch(Region &region, 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.
Definition Utils.cpp:311
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
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.