19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/BuiltinTypes.h"
21#include "mlir/IR/DialectImplementation.h"
22#include "mlir/IR/PatternMatch.h"
23#include "mlir/IR/Value.h"
24#include "mlir/Interfaces/ControlFlowInterfaces.h"
25#include "mlir/Interfaces/FunctionImplementation.h"
26#include "mlir/Support/LLVM.h"
28#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
29#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
31#include "llvm/ADT/SetOperations.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/TypeSwitch.h"
34#include "llvm/Support/LogicalResult.h"
43struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
44 using OpAsmDialectInterface::OpAsmDialectInterface;
46 AliasResult getAlias(Type type, raw_ostream &os)
const final {
47 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
50 os <<
"rec_anon_" <<
recordType.getKindAsStr();
52 os <<
"rec_" << nameAttr.getValue();
53 return AliasResult::OverridableAlias;
55 if (
auto intType = dyn_cast<cir::IntType>(type)) {
58 unsigned width = intType.getWidth();
59 if (width < 8 || !llvm::isPowerOf2_32(width))
60 return AliasResult::NoAlias;
61 os << intType.getAlias();
62 return AliasResult::OverridableAlias;
64 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
65 os << voidType.getAlias();
66 return AliasResult::OverridableAlias;
69 return AliasResult::NoAlias;
72 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
73 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
74 os << (boolAttr.getValue() ?
"true" :
"false");
75 return AliasResult::FinalAlias;
77 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
78 os <<
"bfi_" << bitfield.getName().str();
79 return AliasResult::FinalAlias;
81 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
82 os << dynCastInfoAttr.getAlias();
83 return AliasResult::FinalAlias;
85 if (
auto cmpThreeWayInfoAttr =
86 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
87 os << cmpThreeWayInfoAttr.getAlias();
88 return AliasResult::FinalAlias;
90 return AliasResult::NoAlias;
95void cir::CIRDialect::initialize() {
100#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
102 addInterfaces<CIROpAsmDialectInterface>();
105Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
106 mlir::Attribute value,
108 mlir::Location loc) {
109 return cir::ConstantOp::create(builder, loc, type,
110 mlir::cast<mlir::TypedAttr>(value));
122 for (
auto en : llvm::enumerate(keywords)) {
123 if (succeeded(parser.parseOptionalKeyword(en.value())))
130template <
typename Ty>
struct EnumTraits {};
132#define REGISTER_ENUM_TYPE(Ty) \
133 template <> struct EnumTraits<cir::Ty> { \
134 static llvm::StringRef stringify(cir::Ty value) { \
135 return stringify##Ty(value); \
137 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
149template <
typename EnumTy,
typename RetTy = EnumTy>
152 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
153 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
157 return static_cast<RetTy
>(defaultValue);
158 return static_cast<RetTy
>(index);
162template <
typename EnumTy,
typename RetTy = EnumTy>
165 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
166 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
171 result =
static_cast<RetTy
>(index);
179 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
180 OpBuilder builder(parser.getBuilder().getContext());
185 builder.createBlock(®ion);
187 Block &block = region.back();
189 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
193 if (!region.hasOneBlock())
194 return parser.emitError(errLoc,
195 "multi-block region must not omit terminator");
198 builder.setInsertionPointToEnd(&block);
199 cir::YieldOp::create(builder, eLoc);
205 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
206 const auto yieldsNothing = [&r]() {
207 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
208 return y && y.getArgs().empty();
210 return singleNonEmptyBlock && yieldsNothing();
215template <
typename ExpectedProducerOp>
217 StringRef operandName) {
218 Operation *producer = operand.getDefiningOp();
219 if (!producer || !isa<ExpectedProducerOp>(producer))
220 return op->emitOpError()
221 <<
"operand '" << operandName <<
"' must be produced by '"
222 << ExpectedProducerOp::getOperationName() <<
"'";
231 cir::InlineKindAttr &inlineKindAttr) {
233 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
237 llvm::StringRef keyword;
238 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
244 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
245 if (!inlineKindResult) {
246 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
248 <<
"] for inlineKind, got: " << keyword;
252 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
257 if (inlineKindAttr) {
258 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
266 mlir::Region ®ion) {
267 auto regionLoc = parser.getCurrentLocation();
268 if (parser.parseRegion(region))
277 mlir::Region ®ion) {
278 printer.printRegion(region,
283mlir::OptionalParseResult
285 mlir::ptr::MemorySpaceAttrInterface &attr);
288 mlir::ptr::MemorySpaceAttrInterface attr);
294void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
295 mlir::OperationState &odsState, mlir::Type addr,
296 llvm::StringRef name, mlir::IntegerAttr alignment) {
297 odsState.addAttribute(getNameAttrName(odsState.name),
298 odsBuilder.getStringAttr(name));
300 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
302 odsState.addTypes(addr);
310 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
311 mlir::Type pointeeTy = ptrTy.getPointee();
313 mlir::Block &body = op.getBody().front();
314 if (body.getNumArguments() != 1)
315 return op.emitOpError(
"body must have exactly one block argument");
317 auto expectedEltPtrTy =
318 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
319 if (!expectedEltPtrTy)
320 return op.emitOpError(
"block argument must be a !cir.ptr type");
322 if (op.getNumElements()) {
323 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
325 return op.emitOpError(
326 "when 'num_elements' is present, 'addr' must be a pointer to a "
327 "!cir.struct or !cir.union type");
329 if (expectedEltPtrTy != ptrTy)
330 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
331 "match the block argument type");
333 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
335 return op.emitOpError(
336 "when 'num_elements' is absent, 'addr' must be a pointer to a "
339 mlir::Type innerEltTy = arrayTy.getElementType();
340 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
341 innerEltTy = nested.getElementType();
343 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
345 return op.emitOpError(
"the block argument type must be a pointer to a "
346 "!cir.struct or !cir.union type");
348 if (expectedEltPtrTy.getPointee() != innerEltTy)
349 return op.emitOpError(
350 "block argument pointee type must match the innermost array "
357LogicalResult cir::ArrayCtor::verify() {
361 mlir::Region &partialDtor = getPartialDtor();
362 if (!partialDtor.empty()) {
363 mlir::Block &dtorBlock = partialDtor.front();
364 if (dtorBlock.getNumArguments() != 1)
365 return emitOpError(
"partial_dtor must have exactly one block argument");
367 auto bodyArgTy = getBody().front().getArgument(0).getType();
368 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
369 return emitOpError(
"partial_dtor block argument type must match "
370 "the body block argument type");
380LogicalResult cir::DeleteArrayOp::verify() {
381 if (getDtorMayThrow() && !getElementDtorAttr())
383 "'dtor_may_throw' requires an 'element_dtor' to be present");
392 cir::AssumeBundleKindAttr kindAttr,
393 OperandRange bundleArgs,
394 TypeRange bundleArgTypes) {
395 cir::AssumeBundleKind
kind = kindAttr.getValue();
396 if (
kind == cir::AssumeBundleKind::None)
399 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
400 if (bundleArgs.empty())
404 p.printOperands(bundleArgs);
406 llvm::interleaveComma(bundleArgTypes, p);
411 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
415 auto loc = p.getCurrentLocation();
416 if (failed(p.parseOptionalKeyword(&keyword))) {
417 bundleKindAttr = cir::AssumeBundleKindAttr::get(
418 p.getContext(), cir::AssumeBundleKind::None);
422 std::optional<cir::AssumeBundleKind> parsedKind =
423 cir::symbolizeAssumeBundleKind(keyword);
425 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
427 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
429 if (p.parseOptionalLParen())
432 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
433 p.parseTypeList(bundleArgTypes) || p.parseRParen())
439LogicalResult cir::AssumeOp::verify() {
440 cir::AssumeBundleKind
kind = getBundleKind();
441 size_t numArgs = getBundleArgs().size();
443 if (
kind == cir::AssumeBundleKind::None) {
445 return emitOpError(
"unexpected bundle operands for kind 'none'");
450 return emitOpError(
"expected bundle operands for kind '")
451 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
454 case cir::AssumeBundleKind::Align:
455 if (numArgs != 2 && numArgs != 3)
456 return emitOpError(
"align bundle expects 2 or 3 operands");
458 case cir::AssumeBundleKind::SeparateStorage:
460 return emitOpError(
"separate_storage bundle expects 2 operands");
462 case cir::AssumeBundleKind::Dereferenceable:
464 return emitOpError(
"dereferenceable bundle expects 2 operands");
477cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
478 cir::GlobalOp global = getReferencedGlobal(symbolTable);
480 return emitOpError(
"'")
481 << getGlobalName() <<
"' does not reference a valid cir.global";
483 if (getTls() && !global.getTlsModel())
484 return emitOpError(
"access to global not marked thread local");
486 if (!global.getStaticLocalGuard().has_value())
487 return emitOpError(
"static_local attribute mismatch");
500void cir::ConditionOp::getSuccessorRegions(
507 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
508 regions.emplace_back(&loopOp.getBody());
509 if (mlir::Region *
cleanup = loopOp.maybeGetCleanup())
512 regions.emplace_back(getOperation());
517 auto await = cast<AwaitOp>(getOperation()->getParentOp());
518 regions.emplace_back(&await.getResume());
519 regions.emplace_back(&await.getSuspend());
523cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
525 return MutableOperandRange(getOperation(), 0, 0);
529cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
531 return MutableOperandRange(getOperation(), 0, 0);
534LogicalResult cir::ConditionOp::verify() {
535 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
536 return emitOpError(
"condition must be within a conditional region");
544template <
typename LoopOpTy>
546 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
550 if (cleanupKind.has_value() == op.getCleanup().empty())
551 return op.emitOpError(
"cleanup kind must be present if and only if the "
552 "cleanup region is non-empty");
557 if (cleanupKind == cir::CleanupKind::EH)
558 return op.emitOpError(
"loop cleanup kind must be 'normal' or 'all', "
573 mlir::Attribute attrType) {
574 if (isa<cir::ConstPtrAttr>(attrType)) {
575 if (!mlir::isa<cir::PointerType>(opType))
576 return op->emitOpError(
577 "pointer constant initializing a non-pointer type");
581 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
588 if (isa<cir::ZeroAttr>(attrType)) {
589 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
592 return op->emitOpError(
593 "zero expects struct, array, vector, or complex type");
596 if (mlir::isa<cir::UndefAttr>(attrType)) {
597 if (!mlir::isa<cir::VoidType>(opType))
599 return op->emitOpError(
"undef expects non-void type");
602 if (mlir::isa<cir::BoolAttr>(attrType)) {
603 if (!mlir::isa<cir::BoolType>(opType))
604 return op->emitOpError(
"result type (")
605 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
609 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
610 auto at = cast<TypedAttr>(attrType);
611 if (at.getType() != opType) {
612 return op->emitOpError(
"result type (")
613 << opType <<
") does not match value type (" << at.getType()
619 if (mlir::isa<cir::BlockAddrInfoAttr, cir::ConstArrayAttr,
620 cir::ConstVectorAttr, cir::ConstComplexAttr,
621 cir::ConstRecordAttr, cir::GlobalViewAttr, cir::PoisonAttr,
622 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
625 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
626 return op->emitOpError(
"global with type ")
627 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
630LogicalResult cir::ConstantOp::verify() {
637OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
645LogicalResult cir::CastOp::verify() {
646 mlir::Type resType =
getType();
647 mlir::Type srcType = getSrc().getType();
651 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
652 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
653 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
654 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
655 return emitOpError() <<
"result type address space does not match the "
656 "address space of the operand";
660 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
661 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
662 if (srcVTy && resVTy) {
663 if ((
kind == cir::CastKind::int_to_float ||
664 kind == cir::CastKind::float_to_int) &&
665 srcVTy.getSize() != resVTy.getSize()) {
667 <<
"vector float-to-int and int-to-float casts require "
668 "source and destination vectors to have the same number of "
673 srcType = srcVTy.getElementType();
674 resType = resVTy.getElementType();
678 case cir::CastKind::int_to_bool: {
679 if (!mlir::isa<cir::BoolType>(resType))
680 return emitOpError() <<
"requires !cir.bool type for result";
681 if (!mlir::isa<cir::IntType>(srcType))
682 return emitOpError() <<
"requires !cir.int type for source";
685 case cir::CastKind::ptr_to_bool: {
686 if (!mlir::isa<cir::BoolType>(resType))
687 return emitOpError() <<
"requires !cir.bool type for result";
688 if (!mlir::isa<cir::PointerType>(srcType))
689 return emitOpError() <<
"requires !cir.ptr type for source";
692 case cir::CastKind::integral: {
693 if (!mlir::isa<cir::IntType>(resType))
694 return emitOpError() <<
"requires !cir.int type for result";
695 if (!mlir::isa<cir::IntType>(srcType))
696 return emitOpError() <<
"requires !cir.int type for source";
699 case cir::CastKind::array_to_ptrdecay: {
700 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
701 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
702 if (!arrayPtrTy || !flatPtrTy)
703 return emitOpError() <<
"requires !cir.ptr type for source and result";
708 case cir::CastKind::bitcast: {
710 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
711 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
713 if (srcPtrTy && resPtrTy) {
719 case cir::CastKind::floating: {
720 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
721 !mlir::isa<cir::FPTypeInterface>(resType))
722 return emitOpError() <<
"requires !cir.float type for source and result";
725 case cir::CastKind::float_to_int: {
726 if (!mlir::isa<cir::FPTypeInterface>(srcType))
727 return emitOpError() <<
"requires !cir.float type for source";
728 if (!mlir::dyn_cast<cir::IntType>(resType))
729 return emitOpError() <<
"requires !cir.int type for result";
732 case cir::CastKind::int_to_ptr: {
733 if (!mlir::dyn_cast<cir::IntType>(srcType))
734 return emitOpError() <<
"requires !cir.int type for source";
735 if (!mlir::dyn_cast<cir::PointerType>(resType))
736 return emitOpError() <<
"requires !cir.ptr type for result";
739 case cir::CastKind::ptr_to_int: {
740 if (!mlir::dyn_cast<cir::PointerType>(srcType))
741 return emitOpError() <<
"requires !cir.ptr type for source";
742 if (!mlir::dyn_cast<cir::IntType>(resType))
743 return emitOpError() <<
"requires !cir.int type for result";
746 case cir::CastKind::float_to_bool: {
747 if (!mlir::isa<cir::FPTypeInterface>(srcType))
748 return emitOpError() <<
"requires !cir.float type for source";
749 if (!mlir::isa<cir::BoolType>(resType))
750 return emitOpError() <<
"requires !cir.bool type for result";
753 case cir::CastKind::bool_to_int: {
754 if (!mlir::isa<cir::BoolType>(srcType))
755 return emitOpError() <<
"requires !cir.bool type for source";
756 if (!mlir::isa<cir::IntType>(resType))
757 return emitOpError() <<
"requires !cir.int type for result";
760 case cir::CastKind::int_to_float: {
761 if (!mlir::isa<cir::IntType>(srcType))
762 return emitOpError() <<
"requires !cir.int type for source";
763 if (!mlir::isa<cir::FPTypeInterface>(resType))
764 return emitOpError() <<
"requires !cir.float type for result";
767 case cir::CastKind::bool_to_float: {
768 if (!mlir::isa<cir::BoolType>(srcType))
769 return emitOpError() <<
"requires !cir.bool type for source";
770 if (!mlir::isa<cir::FPTypeInterface>(resType))
771 return emitOpError() <<
"requires !cir.float type for result";
774 case cir::CastKind::address_space: {
775 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
776 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
777 if (!srcPtrTy || !resPtrTy)
778 return emitOpError() <<
"requires !cir.ptr type for source and result";
779 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
780 return emitOpError() <<
"requires two types differ in addrspace only";
783 case cir::CastKind::float_to_complex: {
784 if (!mlir::isa<cir::FPTypeInterface>(srcType))
785 return emitOpError() <<
"requires !cir.float type for source";
786 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
788 return emitOpError() <<
"requires !cir.complex type for result";
789 if (srcType != resComplexTy.getElementType())
790 return emitOpError() <<
"requires source type match result element type";
793 case cir::CastKind::int_to_complex: {
794 if (!mlir::isa<cir::IntType>(srcType))
795 return emitOpError() <<
"requires !cir.int type for source";
796 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
798 return emitOpError() <<
"requires !cir.complex type for result";
799 if (srcType != resComplexTy.getElementType())
800 return emitOpError() <<
"requires source type match result element type";
803 case cir::CastKind::float_complex_to_real: {
804 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
806 return emitOpError() <<
"requires !cir.complex type for source";
807 if (!mlir::isa<cir::FPTypeInterface>(resType))
808 return emitOpError() <<
"requires !cir.float type for result";
809 if (srcComplexTy.getElementType() != resType)
810 return emitOpError() <<
"requires source element type match result type";
813 case cir::CastKind::int_complex_to_real: {
814 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
816 return emitOpError() <<
"requires !cir.complex type for source";
817 if (!mlir::isa<cir::IntType>(resType))
818 return emitOpError() <<
"requires !cir.int type for result";
819 if (srcComplexTy.getElementType() != resType)
820 return emitOpError() <<
"requires source element type match result type";
823 case cir::CastKind::float_complex_to_bool: {
824 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
825 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
827 <<
"requires floating point !cir.complex type for source";
828 if (!mlir::isa<cir::BoolType>(resType))
829 return emitOpError() <<
"requires !cir.bool type for result";
832 case cir::CastKind::int_complex_to_bool: {
833 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
834 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
836 <<
"requires floating point !cir.complex type for source";
837 if (!mlir::isa<cir::BoolType>(resType))
838 return emitOpError() <<
"requires !cir.bool type for result";
841 case cir::CastKind::float_complex: {
842 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
843 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
845 <<
"requires floating point !cir.complex type for source";
846 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
847 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
849 <<
"requires floating point !cir.complex type for result";
852 case cir::CastKind::float_complex_to_int_complex: {
853 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
854 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
856 <<
"requires floating point !cir.complex type for source";
857 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
858 if (!resComplexTy || !resComplexTy.isIntegerComplex())
859 return emitOpError() <<
"requires integer !cir.complex type for result";
862 case cir::CastKind::int_complex: {
863 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
864 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
865 return emitOpError() <<
"requires integer !cir.complex type for source";
866 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
867 if (!resComplexTy || !resComplexTy.isIntegerComplex())
868 return emitOpError() <<
"requires integer !cir.complex type for result";
871 case cir::CastKind::int_complex_to_float_complex: {
872 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
873 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
874 return emitOpError() <<
"requires integer !cir.complex type for source";
875 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
876 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
878 <<
"requires floating point !cir.complex type for result";
881 case cir::CastKind::member_ptr_to_bool: {
882 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
884 <<
"requires !cir.data_member or !cir.method type for source";
885 if (!mlir::isa<cir::BoolType>(resType))
886 return emitOpError() <<
"requires !cir.bool type for result";
890 llvm_unreachable(
"Unknown CastOp kind?");
894 auto kind = op.getKind();
895 return kind == cir::CastKind::bool_to_int ||
896 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
900 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
901 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
905 cir::CastOp head = op, tail = op;
911 op = head.getSrc().getDefiningOp<cir::CastOp>();
917 if (head.getKind() == cir::CastKind::bool_to_int &&
918 tail.getKind() == cir::CastKind::int_to_bool)
919 return head.getSrc();
924 if (head.getKind() == cir::CastKind::int_to_bool &&
925 tail.getKind() == cir::CastKind::int_to_bool)
926 return head.getResult();
934 if (tail.getKind() == cir::CastKind::bitcast) {
935 auto *inner = tail.getSrc().getDefiningOp();
937 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
938 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
939 innerCast.getSrc().getType() == tail.getType() &&
940 innerCast.getType() == tail.getSrc().getType()) {
941 return innerCast.getSrc();
949OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
950 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
952 return cir::PoisonAttr::get(getContext(),
getType());
957 case cir::CastKind::integral: {
959 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
960 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
961 return mlir::cast<mlir::Attribute>(foldResults[0]);
964 case cir::CastKind::bitcast:
965 case cir::CastKind::address_space:
966 case cir::CastKind::float_complex:
967 case cir::CastKind::int_complex: {
981 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
983 case cir::CastKind::integral: {
984 mlir::Type srcTy = getSrc().getType();
986 assert(mlir::isa<cir::VectorType>(srcTy) ==
987 mlir::isa<cir::VectorType>(
getType()));
988 if (mlir::isa<cir::VectorType>(srcTy))
991 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
992 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
995 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
996 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
997 return cir::IntAttr::get(dstIntTy, newVal);
1010LogicalResult cir::BuiltinIntCastOp::verify() {
1011 mlir::Type srcType = getSrc().getType();
1012 mlir::Type resType =
getType();
1014 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1015 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1019 if (
static_cast<bool>(srcCirInt) ==
static_cast<bool>(resCirInt))
1020 return emitOpError()
1021 <<
"requires exactly one '!cir.int' operand or result; the other "
1022 "must be a builtin integer or 'index' type";
1024 mlir::Type
builtinType = srcCirInt ? resType : srcType;
1025 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1026 return emitOpError() <<
"requires a builtin integer or 'index' type on the "
1031 if (
auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1032 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1033 if (cirInt.getWidth() != builtinInt.getWidth())
1034 return emitOpError()
1035 <<
"requires the CIR and builtin integer types to have the same "
1036 "width; use 'cir.cast' for width conversions";
1042OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1045 if (
auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1046 if (inner.getSrc().getType() ==
getType())
1047 return inner.getSrc();
1055mlir::OperandRange cir::CallOp::getArgOperands() {
1057 return getArgs().drop_front(1);
1061mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1062 mlir::MutableOperandRange args = getArgsMutable();
1064 return args.slice(1, args.size() - 1);
1068mlir::Value cir::CallOp::getIndirectCall() {
1069 assert(isIndirect());
1070 return getOperand(0);
1074Value cir::CallOp::getArgOperand(
unsigned i) {
1077 return getOperand(i);
1081unsigned cir::CallOp::getNumArgOperands() {
1083 return this->getOperation()->getNumOperands() - 1;
1084 return this->getOperation()->getNumOperands();
1087static mlir::ParseResult
1089 mlir::OperationState &result) {
1090 mlir::Block *normalDestSuccessor;
1091 if (parser.parseSuccessor(normalDestSuccessor))
1092 return mlir::failure();
1094 if (parser.parseComma())
1095 return mlir::failure();
1097 mlir::Block *unwindDestSuccessor;
1098 if (parser.parseSuccessor(unwindDestSuccessor))
1099 return mlir::failure();
1101 result.addSuccessors(normalDestSuccessor);
1102 result.addSuccessors(unwindDestSuccessor);
1103 return mlir::success();
1107 mlir::OperationState &result,
1108 bool hasDestinationBlocks =
false) {
1111 mlir::FlatSymbolRefAttr calleeAttr;
1115 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1118 OpAsmParser::UnresolvedOperand indirectVal;
1120 if (parser.parseOperand(indirectVal).failed())
1122 ops.push_back(indirectVal);
1125 if (parser.parseLParen())
1126 return mlir::failure();
1128 opsLoc = parser.getCurrentLocation();
1129 if (parser.parseOperandList(ops))
1130 return mlir::failure();
1131 if (parser.parseRParen())
1132 return mlir::failure();
1134 if (hasDestinationBlocks &&
1136 return ::mlir::failure();
1139 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1140 result.addAttribute(CIRDialect::getMustTailAttrName(),
1141 mlir::UnitAttr::get(parser.getContext()));
1143 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1144 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1145 mlir::UnitAttr::get(parser.getContext()));
1147 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
1148 if (parser.parseLParen().failed())
1150 cir::SideEffect sideEffect;
1153 if (parser.parseRParen().failed())
1155 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
1156 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1159 if (parser.parseOptionalAttrDict(result.attributes))
1160 return ::mlir::failure();
1162 if (parser.parseColon())
1163 return ::mlir::failure();
1169 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1170 resultTypes, resultAttrs))
1171 return mlir::failure();
1173 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1174 return parser.emitError(
1175 parser.getCurrentLocation(),
1176 "functions with multiple return types are not supported");
1178 result.addTypes(resultTypes);
1180 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1181 return mlir::failure();
1183 if (!resultAttrs.empty() && resultAttrs[0])
1184 result.addAttribute(
1185 CIRDialect::getResAttrsAttrName(),
1186 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1191 bool argAttrsEmpty =
true;
1193 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1194 [&](DictionaryAttr da) -> mlir::Attribute {
1196 argAttrsEmpty =
false;
1200 if (!argAttrsEmpty) {
1205 argAttrsRef = argAttrsRef.drop_front();
1207 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1208 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1211 return mlir::success();
1216 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1217 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1218 ArrayAttr resAttrs, mlir::Block *normalDest =
nullptr,
1219 mlir::Block *unwindDest =
nullptr) {
1222 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1223 auto ops = callLikeOp.getArgOperands();
1227 printer.printAttributeWithoutType(calleeSym);
1230 assert(indirectCallee);
1231 printer << indirectCallee;
1234 printer <<
"(" << ops <<
")";
1237 assert(unwindDest &&
"expected two successors");
1238 auto tryCall = cast<cir::TryCallOp>(op);
1239 printer <<
' ' << tryCall.getNormalDest();
1242 printer << tryCall.getUnwindDest();
1245 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1246 printer <<
" musttail";
1249 printer <<
" nothrow";
1251 if (sideEffect != cir::SideEffect::All) {
1252 printer <<
" side_effect(";
1253 printer << stringifySideEffect(sideEffect);
1258 CIRDialect::getCalleeAttrName(),
1259 CIRDialect::getMustTailAttrName(),
1260 CIRDialect::getNoThrowAttrName(),
1261 CIRDialect::getSideEffectAttrName(),
1262 CIRDialect::getOperandSegmentSizesAttrName(),
1263 llvm::StringRef(
"res_attrs"),
1264 llvm::StringRef(
"arg_attrs")};
1265 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1267 if (calleeSym || !argAttrs) {
1268 call_interface_impl::printFunctionSignature(
1269 printer, op->getOperands().getTypes(), argAttrs,
1270 false, op->getResultTypes(), resAttrs);
1278 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1279 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1280 call_interface_impl::printFunctionSignature(
1281 printer, op->getOperands().getTypes(),
1282 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1283 false, op->getResultTypes(), resAttrs);
1287mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1288 mlir::OperationState &result) {
1292void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1293 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1294 cir::SideEffect sideEffect = getSideEffect();
1295 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1296 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1301 SymbolTableCollection &symbolTable) {
1303 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1306 return mlir::success();
1309 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1311 return op->emitOpError() <<
"'" << fnAttr.getValue()
1312 <<
"' does not reference a valid function";
1314 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1315 assert(callIf &&
"expected CIR call interface to be always available");
1319 auto fnType = fn.getFunctionType();
1320 if (!fn.getNoProto()) {
1321 unsigned numCallOperands = callIf.getNumArgOperands();
1322 unsigned numFnOpOperands = fnType.getNumInputs();
1324 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1325 return op->emitOpError(
"incorrect number of operands for callee");
1326 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1327 return op->emitOpError(
"too few operands for callee");
1329 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1330 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1331 return op->emitOpError(
"operand type mismatch: expected operand type ")
1332 << fnType.getInput(i) <<
", but provided "
1333 << op->getOperand(i).getType() <<
" for operand number " << i;
1339 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1340 return op->emitOpError(
"callee returns void but call has results");
1343 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1344 return op->emitOpError(
"incorrect number of results for callee");
1347 if (!fnType.hasVoidReturn() &&
1348 op->getResultTypes().front() != fnType.getReturnType()) {
1349 return op->emitOpError(
"result type mismatch: expected ")
1350 << fnType.getReturnType() <<
", but provided "
1351 << op->getResult(0).getType();
1354 return mlir::success();
1358cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1366mlir::OperandRange cir::TryCallOp::getArgOperands() {
1368 return getArgs().drop_front(1);
1372mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1373 mlir::MutableOperandRange args = getArgsMutable();
1375 return args.slice(1, args.size() - 1);
1379mlir::Value cir::TryCallOp::getIndirectCall() {
1380 assert(isIndirect());
1381 return getOperand(0);
1385Value cir::TryCallOp::getArgOperand(
unsigned i) {
1388 return getOperand(i);
1392unsigned cir::TryCallOp::getNumArgOperands() {
1394 return this->getOperation()->getNumOperands() - 1;
1395 return this->getOperation()->getNumOperands();
1399cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1403mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1404 mlir::OperationState &result) {
1408void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1409 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1410 cir::SideEffect sideEffect = getSideEffect();
1411 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1412 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1413 getNormalDest(), getUnwindDest());
1421 cir::FuncOp function) {
1423 if (op.getNumOperands() > 1)
1424 return op.emitOpError() <<
"expects at most 1 return operand";
1427 auto expectedTy = function.getFunctionType().getReturnType();
1429 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1430 : op.getOperand(0).getType());
1431 if (actualTy != expectedTy)
1432 return op.emitOpError() <<
"returns " << actualTy
1433 <<
" but enclosing function returns " << expectedTy;
1435 return mlir::success();
1438mlir::LogicalResult cir::ReturnOp::verify() {
1441 auto *fnOp = getOperation()->getParentOp();
1442 while (!isa<cir::FuncOp>(fnOp))
1443 fnOp = fnOp->getParentOp();
1456ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1458 result.regions.reserve(2);
1459 Region *thenRegion = result.addRegion();
1460 Region *elseRegion = result.addRegion();
1462 mlir::Builder &builder = parser.getBuilder();
1463 OpAsmParser::UnresolvedOperand cond;
1464 Type boolType = cir::BoolType::get(builder.getContext());
1466 if (parser.parseOperand(cond) ||
1467 parser.resolveOperand(cond, boolType, result.operands))
1471 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1472 if (parser.parseRegion(*thenRegion, {}, {}))
1479 if (!parser.parseOptionalKeyword(
"else")) {
1480 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1481 if (parser.parseRegion(*elseRegion, {}, {}))
1488 if (parser.parseOptionalAttrDict(result.attributes))
1493void cir::IfOp::print(OpAsmPrinter &p) {
1494 p <<
" " << getCondition() <<
" ";
1495 mlir::Region &thenRegion = this->getThenRegion();
1496 p.printRegion(thenRegion,
1501 mlir::Region &elseRegion = this->getElseRegion();
1502 if (!elseRegion.empty()) {
1504 p.printRegion(elseRegion,
1509 p.printOptionalAttrDict(getOperation()->getAttrs());
1515 cir::YieldOp::create(builder, loc);
1523void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1524 SmallVectorImpl<RegionSuccessor> ®ions) {
1526 if (!point.isParent()) {
1527 regions.emplace_back(getOperation());
1532 Region *elseRegion = &this->getElseRegion();
1533 if (elseRegion->empty())
1534 elseRegion =
nullptr;
1537 regions.push_back(RegionSuccessor(&getThenRegion()));
1539 regions.push_back(RegionSuccessor(elseRegion));
1541 regions.emplace_back(getOperation());
1544mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1545 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1549void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1552 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1553 result.addOperands(cond);
1555 OpBuilder::InsertionGuard guard(builder);
1556 Region *thenRegion = result.addRegion();
1557 builder.createBlock(thenRegion);
1558 thenBuilder(builder, result.location);
1560 Region *elseRegion = result.addRegion();
1561 if (!withElseRegion)
1564 builder.createBlock(elseRegion);
1565 elseBuilder(builder, result.location);
1577void cir::ScopeOp::getSuccessorRegions(
1578 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1580 if (!point.isParent()) {
1581 regions.emplace_back(getOperation());
1586 regions.push_back(RegionSuccessor(&getScopeRegion()));
1589mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1590 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1594void cir::ScopeOp::build(
1595 OpBuilder &builder, OperationState &result,
1596 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1597 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1599 OpBuilder::InsertionGuard guard(builder);
1600 Region *scopeRegion = result.addRegion();
1601 builder.createBlock(scopeRegion);
1605 scopeBuilder(builder, yieldTy, result.location);
1608 result.addTypes(TypeRange{yieldTy});
1611void cir::ScopeOp::build(
1612 OpBuilder &builder, OperationState &result,
1613 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1614 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1615 OpBuilder::InsertionGuard guard(builder);
1616 Region *scopeRegion = result.addRegion();
1617 builder.createBlock(scopeRegion);
1619 scopeBuilder(builder, result.location);
1622LogicalResult cir::ScopeOp::verify() {
1624 return emitOpError() <<
"cir.scope must not be empty since it should "
1625 "include at least an implicit cir.yield ";
1628 mlir::Block &lastBlock =
getRegion().back();
1629 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1630 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1631 return emitOpError() <<
"last block of cir.scope must be terminated";
1635LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1636 SmallVectorImpl<OpFoldResult> &results) {
1641 if (block.getOperations().size() != 1)
1644 auto yield = dyn_cast<cir::YieldOp>(block.front());
1649 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1652 results.push_back(yield.getOperand(0));
1660void cir::CleanupScopeOp::getSuccessorRegions(
1661 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1662 if (!point.isParent()) {
1663 regions.emplace_back(getOperation());
1668 regions.push_back(RegionSuccessor(&getBodyRegion()));
1669 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1673cir::CleanupScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1674 return ValueRange();
1677LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1678 PatternRewriter &rewriter) {
1679 auto isRegionTrivial = [](Region ®ion) {
1680 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1681 if (!region.hasOneBlock())
1683 Block &block = llvm::getSingleElement(region);
1684 return llvm::hasSingleElement(block) &&
1685 isa<cir::YieldOp>(llvm::getSingleElement(block));
1688 Region &body = op.getBodyRegion();
1689 Region &
cleanup = op.getCleanupRegion();
1693 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1694 rewriter.eraseOp(op);
1700 if (!isRegionTrivial(
cleanup) || !body.hasOneBlock())
1703 Block &bodyBlock = body.front();
1704 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1707 Operation *yield = bodyBlock.getTerminator();
1708 rewriter.inlineBlockBefore(&bodyBlock, op);
1709 rewriter.eraseOp(yield);
1710 rewriter.eraseOp(op);
1714void cir::CleanupScopeOp::build(
1715 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1716 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
1717 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
1718 result.addAttribute(getCleanupKindAttrName(result.name),
1719 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1721 OpBuilder::InsertionGuard guard(builder);
1724 Region *bodyRegion = result.addRegion();
1725 builder.createBlock(bodyRegion);
1727 bodyBuilder(builder, result.location);
1730 Region *cleanupRegion = result.addRegion();
1731 builder.createBlock(cleanupRegion);
1733 cleanupBuilder(builder, result.location);
1748LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1749 Block *src = op->getBlock();
1750 Block *dst = op.getDest();
1757 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1762 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1765 auto operands = op.getDestOperands();
1766 rewriter.eraseOp(op);
1767 rewriter.mergeBlocks(dst, src, operands);
1771mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1772 assert(index == 0 &&
"invalid successor index");
1773 return mlir::SuccessorOperands(getDestOperandsMutable());
1784mlir::SuccessorOperands
1785cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1786 assert(index < getNumSuccessors() &&
"invalid successor index");
1787 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1791 OpAsmParser &parser, Type &flagType,
1792 SmallVectorImpl<Block *> &succOperandBlocks,
1795 if (failed(parser.parseCommaSeparatedList(
1796 OpAsmParser::Delimiter::Square,
1798 Block *destination = nullptr;
1799 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1800 SmallVector<Type> operandTypes;
1802 if (parser.parseSuccessor(destination).failed())
1805 if (succeeded(parser.parseOptionalLParen())) {
1806 if (failed(parser.parseOperandList(
1807 operands, OpAsmParser::Delimiter::None)) ||
1808 failed(parser.parseColonTypeList(operandTypes)) ||
1809 failed(parser.parseRParen()))
1812 succOperandBlocks.push_back(destination);
1813 succOperands.emplace_back(operands);
1814 succOperandsTypes.emplace_back(operandTypes);
1817 "successor blocks")))
1823 Type flagType, SuccessorRange succs,
1824 OperandRangeRange succOperands,
1825 const TypeRangeRange &succOperandsTypes) {
1828 llvm::zip(succs, succOperands),
1831 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1834 if (!succOperands.empty())
1843mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1844 assert(index < getNumSuccessors() &&
"invalid successor index");
1845 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1846 : getDestOperandsFalseMutable());
1850 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1851 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1859void cir::CaseOp::getSuccessorRegions(
1860 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1861 if (!point.isParent()) {
1862 regions.emplace_back(getOperation());
1865 regions.push_back(RegionSuccessor(&getCaseRegion()));
1868mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1869 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1873void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1874 ArrayAttr value, CaseOpKind
kind,
1875 OpBuilder::InsertPoint &insertPoint) {
1876 OpBuilder::InsertionGuard guardSwitch(builder);
1877 result.addAttribute(
"value", value);
1878 result.getOrAddProperties<Properties>().
kind =
1879 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1880 Region *caseRegion = result.addRegion();
1881 builder.createBlock(caseRegion);
1883 insertPoint = builder.saveInsertionPoint();
1890void cir::SwitchOp::getSuccessorRegions(
1891 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1892 if (!point.isParent()) {
1893 region.emplace_back(getOperation());
1897 region.push_back(RegionSuccessor(&getBody()));
1900mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1901 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1905void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1907 assert(switchBuilder &&
"the builder callback for regions must be present");
1908 OpBuilder::InsertionGuard guardSwitch(builder);
1909 Region *switchRegion = result.addRegion();
1910 builder.createBlock(switchRegion);
1911 result.addOperands({cond});
1912 switchBuilder(builder, result.location, result);
1916 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1918 if (isa<cir::SwitchOp>(op) && op != *
this)
1919 return WalkResult::skip();
1921 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1922 cases.push_back(caseOp);
1924 return WalkResult::advance();
1929 collectCases(cases);
1931 if (getBody().empty())
1934 if (!isa<YieldOp>(getBody().front().back()))
1937 if (!llvm::all_of(getBody().front(),
1938 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1941 return llvm::all_of(cases, [
this](CaseOp op) {
1942 return op->getParentOfType<SwitchOp>() == *
this;
1950void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1951 Value value, Block *defaultDestination,
1952 ValueRange defaultOperands,
1954 BlockRange caseDestinations,
1957 std::vector<mlir::Attribute> caseValuesAttrs;
1958 for (
const APInt &val : caseValues)
1959 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1960 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1962 build(builder, result, value, defaultOperands, caseOperands, attrs,
1963 defaultDestination, caseDestinations);
1969 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1970 SmallVectorImpl<Block *> &caseDestinations,
1974 if (failed(parser.parseLSquare()))
1976 if (succeeded(parser.parseOptionalRSquare()))
1980 auto parseCase = [&]() {
1982 if (failed(parser.parseInteger(value)))
1985 values.push_back(cir::IntAttr::get(flagType, value));
1990 if (parser.parseColon() || parser.parseSuccessor(destination))
1992 if (!parser.parseOptionalLParen()) {
1993 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1995 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1998 caseDestinations.push_back(destination);
1999 caseOperands.emplace_back(operands);
2000 caseOperandTypes.emplace_back(operandTypes);
2003 if (failed(parser.parseCommaSeparatedList(parseCase)))
2006 caseValues = ArrayAttr::get(flagType.getContext(), values);
2008 return parser.parseRSquare();
2012 Type flagType, mlir::ArrayAttr caseValues,
2013 SuccessorRange caseDestinations,
2014 OperandRangeRange caseOperands,
2015 const TypeRangeRange &caseOperandTypes) {
2025 llvm::zip(caseValues, caseDestinations),
2028 mlir::Attribute a = std::get<0>(i);
2029 p << mlir::cast<cir::IntAttr>(a).getValue();
2031 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2046 mlir::Attribute &valueAttr) {
2048 return parser.parseAttribute(valueAttr,
"value", attr);
2052 p.printAttribute(value);
2055mlir::LogicalResult cir::GlobalOp::verify() {
2058 if (getInitialValue().has_value()) {
2064 if ((getStaticLocalGuard().has_value()) &&
2065 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2067 "Cannot have a static-local global-op with a constructor or "
2068 "destructor, they require in-function initialization via LocalInitOp");
2070 if (getDynTlsRefs()) {
2071 if (getStaticLocalGuard().has_value())
2073 "cannot have both static local and dynamic tls references");
2074 if (!getTlsModel() || getTlsModel() != TLS_Model::GeneralDynamic)
2075 return emitOpError(
"'dyn_tls_refs' only valid for dynamic tls");
2078 if (getAliasee().has_value()) {
2079 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2080 !getDtorRegion().empty())
2081 return emitOpError(
"global alias shall not have an initializer or "
2082 "constructor/destructor regions");
2091void cir::GlobalOp::build(
2092 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2093 mlir::Type sym_type,
bool isConstant,
2094 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2095 cir::GlobalLinkageKind linkage,
2096 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2097 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2098 odsState.addAttribute(getSymNameAttrName(odsState.name),
2099 odsBuilder.getStringAttr(sym_name));
2100 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2101 mlir::TypeAttr::get(sym_type));
2102 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2103 properties.setConstant(isConstant);
2107 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2109 cir::GlobalLinkageKindAttr linkageAttr =
2110 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2111 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2113 Region *ctorRegion = odsState.addRegion();
2115 odsBuilder.createBlock(ctorRegion);
2116 ctorBuilder(odsBuilder, odsState.location);
2119 Region *dtorRegion = odsState.addRegion();
2121 odsBuilder.createBlock(dtorRegion);
2122 dtorBuilder(odsBuilder, odsState.location);
2131void cir::GlobalOp::getSuccessorRegions(
2132 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2134 if (!point.isParent()) {
2135 regions.emplace_back(getOperation());
2140 Region *ctorRegion = &this->getCtorRegion();
2141 if (ctorRegion->empty())
2142 ctorRegion =
nullptr;
2145 Region *dtorRegion = &this->getDtorRegion();
2146 if (dtorRegion->empty())
2147 dtorRegion =
nullptr;
2151 regions.push_back(RegionSuccessor(ctorRegion));
2153 regions.push_back(RegionSuccessor(dtorRegion));
2156mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
2157 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2162 TypeAttr type, Attribute initAttr,
2163 mlir::Region &ctorRegion,
2164 mlir::Region &dtorRegion) {
2165 auto printType = [&]() { p <<
": " << type; };
2168 if (op.isDeclaration() || op.getAliasee()) {
2174 if (!ctorRegion.empty()) {
2178 p.printRegion(ctorRegion,
2187 if (!dtorRegion.empty()) {
2189 p.printRegion(dtorRegion,
2197 Attribute &initialValueAttr,
2198 mlir::Region &ctorRegion,
2199 mlir::Region &dtorRegion) {
2201 if (parser.parseOptionalEqual().failed()) {
2204 if (parser.parseColonType(opTy))
2209 if (!parser.parseOptionalKeyword(
"ctor")) {
2210 if (parser.parseColonType(opTy))
2212 auto parseLoc = parser.getCurrentLocation();
2213 if (parser.parseRegion(ctorRegion, {}, {}))
2224 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2225 "Non-typed attrs shouldn't appear here.");
2226 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2231 if (!parser.parseOptionalKeyword(
"dtor")) {
2232 auto parseLoc = parser.getCurrentLocation();
2233 if (parser.parseRegion(dtorRegion, {}, {}))
2240 typeAttr = TypeAttr::get(opTy);
2249cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2252 mlir::Operation *op =
2253 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2254 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2255 return emitOpError(
"'")
2257 <<
"' does not reference a valid cir.global or cir.func";
2260 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2261 if (
auto g = dyn_cast<GlobalOp>(op)) {
2262 symTy = g.getSymType();
2263 symAddrSpaceAttr = g.getAddrSpaceAttr();
2266 if (getTls() && !g.getTlsModel())
2267 return emitOpError(
"access to global not marked thread local");
2272 bool getGlobalIsStaticLocal = getStaticLocal();
2273 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2274 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2275 !getOperation()->getParentOfType<cir::GlobalOp>())
2276 return emitOpError(
"static_local attribute mismatch");
2277 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2278 symTy = f.getFunctionType();
2280 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2283 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2284 if (!resultType || symTy != resultType.getPointee())
2285 return emitOpError(
"result type pointee type '")
2286 << resultType.getPointee() <<
"' does not match type " << symTy
2287 <<
" of the global @" <<
getName();
2289 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2290 return emitOpError()
2291 <<
"result type address space does not match the address "
2292 "space of the global @"
2304cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2310 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2312 return emitOpError(
"'")
2313 <<
name <<
"' does not reference a valid cir.global";
2314 std::optional<mlir::Attribute> init = op.getInitialValue();
2317 if (!isa<cir::VTableAttr>(*init))
2318 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2328cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2337 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2339 return emitOpError(
"'")
2340 <<
name <<
"' does not reference a valid cir.global";
2341 std::optional<mlir::Attribute> init = op.getInitialValue();
2344 if (!isa<cir::ConstArrayAttr>(*init))
2346 "Expected constant array in initializer for global VTT '")
2351LogicalResult cir::VTTAddrPointOp::verify() {
2353 if (
getName() && getSymAddr())
2354 return emitOpError(
"should use either a symbol or value, but not both");
2360 mlir::Type resultType = getAddr().getType();
2361 mlir::Type resTy = cir::PointerType::get(
2362 cir::PointerType::get(cir::VoidType::get(getContext())));
2364 if (resultType != resTy)
2365 return emitOpError(
"result type must be ")
2366 << resTy <<
", but provided result type is " << resultType;
2378void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2379 StringRef name, FuncType type,
2380 GlobalLinkageKind linkage, CallingConv callingConv) {
2382 result.addAttribute(SymbolTable::getSymbolAttrName(),
2383 builder.getStringAttr(name));
2384 result.addAttribute(getFunctionTypeAttrName(result.name),
2385 TypeAttr::get(type));
2386 result.addAttribute(
2388 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2389 result.addAttribute(getCallingConvAttrName(result.name),
2390 CallingConvAttr::get(builder.getContext(), callingConv));
2398cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2399 mlir::StringAttr name, mlir::ArrayAttr args) {
2402 for (mlir::Attribute arg : args) {
2403 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2404 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2410ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2411 llvm::SMLoc loc = parser.getCurrentLocation();
2412 mlir::Builder &builder = parser.getBuilder();
2414 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2415 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2416 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2417 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2418 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2419 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2420 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2421 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2422 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
2424 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2425 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2426 if (::mlir::succeeded(
2427 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2428 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2431 cir::InlineKindAttr inlineKindAttr;
2435 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2437 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2438 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2439 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2440 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2442 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2443 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2447 GlobalLinkageKindAttr::get(
2448 parser.getContext(),
2450 parser, GlobalLinkageKind::ExternalLinkage)));
2452 ::llvm::StringRef visAttrStr;
2453 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2455 state.addAttribute(visNameAttr,
2456 parser.getBuilder().getStringAttr(visAttrStr));
2459 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2462 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2463 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2465 StringAttr nameAttr;
2466 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2472 bool isVariadic =
false;
2473 if (function_interface_impl::parseFunctionSignatureWithArguments(
2474 parser,
true, arguments, isVariadic, resultTypes,
2479 bool argAttrsEmpty =
true;
2480 for (OpAsmParser::Argument &arg : arguments) {
2481 argTypes.push_back(
arg.type);
2485 argAttrs.push_back(
arg.attrs);
2487 argAttrsEmpty =
false;
2491 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2492 return parser.emitError(
2493 loc,
"functions with multiple return types are not supported");
2495 mlir::Type returnType =
2496 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2497 : resultTypes.front());
2499 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2503 state.addAttribute(getFunctionTypeAttrName(state.name),
2504 TypeAttr::get(fnType));
2506 if (!resultAttrs.empty() && resultAttrs[0])
2508 getResAttrsAttrName(state.name),
2509 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2512 state.addAttribute(getArgAttrsAttrName(state.name),
2513 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2515 bool hasAlias =
false;
2516 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2517 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2518 if (parser.parseLParen().failed())
2520 mlir::StringAttr aliaseeAttr;
2521 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2523 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2524 if (parser.parseRParen().failed())
2529 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2530 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2531 if (parser.parseLParen().failed())
2533 mlir::StringAttr personalityAttr;
2534 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2536 state.addAttribute(personalityNameAttr,
2537 FlatSymbolRefAttr::get(personalityAttr));
2538 if (parser.parseRParen().failed())
2543 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2544 cir::CallingConv callConv = cir::CallingConv::C;
2545 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2546 if (parser.parseLParen().failed())
2549 return parser.emitError(loc) <<
"unknown calling convention";
2550 if (parser.parseRParen().failed())
2553 state.addAttribute(callConvNameAttr,
2554 cir::CallingConvAttr::get(parser.getContext(), callConv));
2556 auto parseGlobalDtorCtor =
2557 [&](StringRef keyword,
2558 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2559 -> mlir::LogicalResult {
2560 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2561 std::optional<int> priority;
2562 if (mlir::succeeded(parser.parseOptionalLParen())) {
2563 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2564 if (mlir::failed(parsedPriority))
2565 return parser.emitError(parser.getCurrentLocation(),
2566 "failed to parse 'priority', of type 'int'");
2567 priority = parsedPriority.value_or(
int());
2569 if (parser.parseRParen())
2572 createAttr(priority);
2578 if (parser.parseOptionalKeyword(
"func_info").succeeded()) {
2579 if (parser.parseLess().failed())
2582 llvm::SMLoc attrLoc = parser.getCurrentLocation();
2583 mlir::Attribute
attr;
2584 if (parser.parseAttribute(attr).failed())
2586 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
2587 cir::FuncIdentityAttr>(attr))
2588 return parser.emitError(attrLoc,
2589 "expected a function info attribute, got ")
2591 state.addAttribute(funcInfoNameAttr, attr);
2593 if (parser.parseGreater().failed())
2597 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2598 mlir::IntegerAttr globalCtorPriorityAttr =
2599 builder.getI32IntegerAttr(priority.value_or(65535));
2600 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2601 globalCtorPriorityAttr);
2605 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2606 mlir::IntegerAttr globalDtorPriorityAttr =
2607 builder.getI32IntegerAttr(priority.value_or(65535));
2608 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2609 globalDtorPriorityAttr);
2613 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2614 cir::SideEffect sideEffect;
2616 if (parser.parseLParen().failed() ||
2618 parser.parseRParen().failed())
2621 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2622 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2626 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2627 mlir::ArrayAttr annotationsAttr;
2628 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2630 state.addAttribute(annotationsNameAttr, annotationsAttr);
2633 NamedAttrList parsedAttrs;
2634 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2637 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2638 if (parsedAttrs.get(disallowed))
2639 return parser.emitError(loc,
"attribute '")
2641 <<
"' should not be specified in the explicit attribute list";
2644 state.attributes.append(parsedAttrs);
2647 auto *body = state.addRegion();
2648 OptionalParseResult parseResult = parser.parseOptionalRegion(
2649 *body, arguments,
false);
2650 if (parseResult.has_value()) {
2652 return parser.emitError(loc,
"function alias shall not have a body");
2653 if (failed(*parseResult))
2657 return parser.emitError(loc,
"expected non-empty function body");
2666bool cir::FuncOp::isDeclaration() {
2669 std::optional<StringRef> aliasee = getAliasee();
2671 return getFunctionBody().empty();
2677bool cir::FuncOp::isCXXSpecialMemberFunction() {
2680 mlir::Attribute
attr = getFuncInfoAttr();
2681 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
2684bool cir::FuncOp::isCxxConstructor() {
2685 auto attr = getFuncInfoAttr();
2686 return attr && dyn_cast<CXXCtorAttr>(attr);
2689bool cir::FuncOp::isCxxDestructor() {
2690 auto attr = getFuncInfoAttr();
2691 return attr && dyn_cast<CXXDtorAttr>(attr);
2694bool cir::FuncOp::isCxxSpecialAssignment() {
2695 auto attr = getFuncInfoAttr();
2696 return attr && dyn_cast<CXXAssignAttr>(attr);
2699std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2700 mlir::Attribute
attr = getFuncInfoAttr();
2702 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2703 return ctor.getCtorKind();
2705 return std::nullopt;
2708std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2709 mlir::Attribute
attr = getFuncInfoAttr();
2711 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2712 return assign.getAssignKind();
2714 return std::nullopt;
2717bool cir::FuncOp::isCxxTrivialMemberFunction() {
2718 mlir::Attribute
attr = getFuncInfoAttr();
2720 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2721 return ctor.getIsTrivial();
2722 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2723 return dtor.getIsTrivial();
2724 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2725 return assign.getIsTrivial();
2730mlir::Region *cir::FuncOp::getCallableRegion() {
2736void cir::FuncOp::print(OpAsmPrinter &p) {
2754 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2755 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2757 mlir::SymbolTable::Visibility vis = getVisibility();
2758 if (vis != mlir::SymbolTable::Visibility::Public)
2761 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2762 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
2768 p.printSymbolName(getSymName());
2769 cir::FuncType fnType = getFunctionType();
2770 function_interface_impl::printFunctionSignature(
2771 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2773 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2775 p.printSymbolName(*aliaseeName);
2779 if (getCallingConv() != cir::CallingConv::C) {
2781 p << stringifyCallingConv(getCallingConv());
2785 if (std::optional<StringRef> personalityName = getPersonality()) {
2786 p <<
" personality(";
2787 p.printSymbolName(*personalityName);
2791 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
2793 p.printAttribute(funcInfo);
2797 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2798 p <<
" global_ctor";
2799 if (globalCtorPriority.value() != 65535)
2800 p <<
"(" << globalCtorPriority.value() <<
")";
2803 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2804 p <<
" global_dtor";
2805 if (globalDtorPriority.value() != 65535)
2806 p <<
"(" << globalDtorPriority.value() <<
")";
2809 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2810 sideEffect && *sideEffect != cir::SideEffect::All) {
2811 p <<
" side_effect(";
2812 p << stringifySideEffect(*sideEffect);
2816 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2818 p.printAttribute(annotations);
2821 function_interface_impl::printFunctionAttributes(
2822 p, *
this, cir::FuncOp::getAttributeNames());
2825 Region &body = getOperation()->getRegion(0);
2826 if (!body.empty()) {
2828 p.printRegion(body,
false,
2833mlir::LogicalResult cir::FuncOp::verify() {
2835 if (!isDeclaration() && getCoroutine()) {
2836 bool foundAwait =
false;
2837 int coroBodyCount = 0;
2838 this->walk([&](Operation *op) {
2839 if (
auto await = dyn_cast<AwaitOp>(op)) {
2841 }
else if (isa<CoroBodyOp>(op)) {
2843 if (coroBodyCount > 1) {
2844 return mlir::WalkResult::interrupt();
2847 return mlir::WalkResult::advance();
2850 return emitOpError()
2851 <<
"coroutine body must use at least one cir.await op";
2852 if (coroBodyCount != 1)
2853 return emitOpError()
2854 <<
"coroutine function must have exactly one cir.body op";
2857 llvm::SmallSet<llvm::StringRef, 16> labels;
2858 llvm::SmallSet<llvm::StringRef, 16> gotos;
2859 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2860 bool invalidBlockAddress =
false;
2861 getOperation()->walk([&](mlir::Operation *op) {
2862 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2863 labels.insert(lab.getLabel());
2864 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2865 gotos.insert(goTo.getLabel());
2866 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2867 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2869 invalidBlockAddress =
true;
2870 return mlir::WalkResult::interrupt();
2872 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2874 return mlir::WalkResult::advance();
2877 if (invalidBlockAddress)
2878 return emitOpError() <<
"blockaddress references a different function";
2880 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2881 if (!labels.empty() || !gotos.empty()) {
2882 mismatched = llvm::set_difference(gotos, labels);
2884 if (!mismatched.empty())
2885 return emitOpError() <<
"goto/label mismatch";
2890 if (!labels.empty() || !blockAddresses.empty()) {
2891 mismatched = llvm::set_difference(blockAddresses, labels);
2893 if (!mismatched.empty())
2894 return emitOpError()
2895 <<
"expects an existing label target in the referenced function";
2909LogicalResult cir::AddOp::verify() {
2910 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2911 return emitOpError()
2912 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2913 return mlir::success();
2916LogicalResult cir::SubOp::verify() {
2917 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2918 return emitOpError()
2919 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2920 return mlir::success();
2932void cir::TernaryOp::getSuccessorRegions(
2933 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2935 if (!point.isParent()) {
2936 regions.emplace_back(getOperation());
2942 regions.push_back(RegionSuccessor(&getTrueRegion()));
2943 regions.push_back(RegionSuccessor(&getFalseRegion()));
2946mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2947 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2951void cir::TernaryOp::build(
2952 OpBuilder &builder, OperationState &result,
Value cond,
2953 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2954 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2955 result.addOperands(cond);
2956 OpBuilder::InsertionGuard guard(builder);
2957 Region *trueRegion = result.addRegion();
2958 builder.createBlock(trueRegion);
2959 trueBuilder(builder, result.location);
2960 Region *falseRegion = result.addRegion();
2961 builder.createBlock(falseRegion);
2962 falseBuilder(builder, result.location);
2967 if (trueRegion->back().mightHaveTerminator())
2968 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2969 if (!yield && falseRegion->back().mightHaveTerminator())
2970 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2972 assert((!yield || yield.getNumOperands() <= 1) &&
2973 "expected zero or one result type");
2974 if (yield && yield.getNumOperands() == 1)
2975 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2982OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2983 mlir::Attribute
condition = adaptor.getCondition();
2985 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2986 return conditionValue ? getTrueValue() : getFalseValue();
2990 mlir::Attribute trueValue = adaptor.getTrueValue();
2991 mlir::Attribute falseValue = adaptor.getFalseValue();
2992 if (trueValue == falseValue)
2994 if (getTrueValue() == getFalseValue())
2995 return getTrueValue();
3000LogicalResult cir::SelectOp::verify() {
3002 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
3009 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
3010 !isa<cir::VectorType>(getFalseValue().
getType())) {
3011 return emitOpError()
3012 <<
"expected both true and false operands to be vector types "
3013 "when the condition is a vector boolean type";
3022LogicalResult cir::ShiftOp::verify() {
3023 mlir::Operation *op = getOperation();
3024 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3025 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3026 if (!op0VecTy ^ !op1VecTy)
3027 return emitOpError() <<
"input types cannot be one vector and one scalar";
3030 if (op0VecTy.getSize() != op1VecTy.getSize())
3031 return emitOpError() <<
"input vector types must have the same size";
3033 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
3035 return emitOpError() <<
"the type of the result must be a vector "
3036 <<
"if it is vector shift";
3038 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3039 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3040 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3041 return emitOpError()
3042 <<
"vector operands do not have the same elements sizes";
3044 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3045 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3046 return emitOpError() <<
"vector operands and result type do not have the "
3047 "same elements sizes";
3050 return mlir::success();
3057LogicalResult cir::LabelOp::verify() {
3058 mlir::Operation *op = getOperation();
3059 mlir::Block *blk = op->getBlock();
3060 if (&blk->front() != op)
3061 return emitError() <<
"must be the first operation in a block";
3063 return mlir::success();
3070OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3071 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3072 return adaptor.getInput();
3080OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3081 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3082 return adaptor.getInput();
3090OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3091 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3092 return adaptor.getInput();
3097 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3098 APInt val = intAttr.getValue();
3100 return cir::IntAttr::get(
getType(), val);
3110OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3111 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3112 return adaptor.getInput();
3116 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3117 APFloat val = fpAttr.getValue();
3119 return cir::FPAttr::get(
getType(), val);
3129OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3130 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3131 return adaptor.getInput();
3136 if (mlir::Attribute attr = adaptor.getInput()) {
3137 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3138 APInt val = intAttr.getValue();
3140 return cir::IntAttr::get(
getType(), val);
3142 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3143 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3154 mlir::Type resultTy) {
3157 mlir::Type inputMemberTy;
3158 mlir::Type resultMemberTy;
3159 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3161 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3162 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3165 if (inputMemberTy != resultMemberTy)
3166 return op->emitOpError()
3167 <<
"member types of the operand and the result do not match";
3169 return mlir::success();
3172LogicalResult cir::BaseDataMemberOp::verify() {
3176LogicalResult cir::DerivedDataMemberOp::verify() {
3184LogicalResult cir::BaseMethodOp::verify() {
3188LogicalResult cir::DerivedMethodOp::verify() {
3196void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3200 result.addAttribute(getKindAttrName(result.name),
3201 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3203 OpBuilder::InsertionGuard guard(builder);
3204 Region *readyRegion = result.addRegion();
3205 builder.createBlock(readyRegion);
3206 readyBuilder(builder, result.location);
3210 OpBuilder::InsertionGuard guard(builder);
3211 Region *suspendRegion = result.addRegion();
3212 builder.createBlock(suspendRegion);
3213 suspendBuilder(builder, result.location);
3217 OpBuilder::InsertionGuard guard(builder);
3218 Region *resumeRegion = result.addRegion();
3219 builder.createBlock(resumeRegion);
3220 resumeBuilder(builder, result.location);
3224void cir::AwaitOp::getSuccessorRegions(
3225 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3228 if (!point.isParent()) {
3229 regions.emplace_back(getOperation());
3236 regions.push_back(RegionSuccessor(&this->getReady()));
3237 regions.push_back(RegionSuccessor(&this->getSuspend()));
3238 regions.push_back(RegionSuccessor(&this->getResume()));
3241mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
3242 if (successor.isOperation())
3243 return getOperation()->getResults();
3244 if (successor == &getReady())
3245 return getReady().getArguments();
3246 if (successor == &getSuspend())
3247 return getSuspend().getArguments();
3248 if (successor == &getResume())
3249 return getResume().getArguments();
3250 llvm_unreachable(
"invalid region successor");
3253LogicalResult cir::AwaitOp::verify() {
3254 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3255 return emitOpError(
"ready region must end with cir.condition");
3263void cir::CoroBodyOp::getSuccessorRegions(
3264 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3265 if (!point.isParent()) {
3266 regions.emplace_back(getOperation());
3270 regions.push_back(RegionSuccessor(&getBody()));
3274cir::CoroBodyOp::getSuccessorInputs(RegionSuccessor successor) {
3275 return ValueRange();
3278LogicalResult cir::CoroBodyOp::verify() {
3279 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3280 return emitOpError(
"enclosing function must be a coroutine");
3284void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3286 assert(bodyBuilder &&
3287 "the builder callback for 'CoroBodyOp' must be present");
3288 OpBuilder::InsertionGuard guard(builder);
3290 Region *bodyRegion = result.addRegion();
3291 builder.createBlock(bodyRegion);
3292 bodyBuilder(builder, result.location);
3299LogicalResult cir::CopyOp::verify() {
3301 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3302 return emitError() <<
"missing data layout for pointee type";
3304 if (getSkipTailPadding() &&
3305 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3307 <<
"skip_tail_padding is only valid for record pointee types";
3309 return mlir::success();
3316LogicalResult cir::GetRuntimeMemberOp::verify() {
3317 cir::DataMemberType memberPtrTy = getMember().getType();
3319 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
3320 return emitError() <<
"record type does not match the member pointer type";
3321 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3322 return emitError() <<
"result type does not match the member pointer type";
3323 return mlir::success();
3330LogicalResult cir::GetMethodOp::verify() {
3331 cir::MethodType methodTy = getMethod().getType();
3334 cir::PointerType objectPtrTy = getObject().getType();
3335 mlir::Type objectTy = objectPtrTy.getPointee();
3337 if (methodTy.getClassTy() != objectTy)
3338 return emitError() <<
"method class type and object type do not match";
3341 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3342 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3349 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3351 <<
"method return type and callee return type do not match";
3356 if (calleeArgsTy.empty())
3357 return emitError() <<
"callee parameter list lacks receiver object ptr";
3359 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3360 if (!calleeThisArgPtrTy ||
3361 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3363 <<
"the first parameter of callee must be a void pointer";
3366 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3367 return emitError() <<
"callee and method parameter counts do not match";
3369 if (calleeArgsTy.size() > 1 &&
3370 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3372 <<
"callee parameters and method parameters do not match";
3374 return mlir::success();
3381LogicalResult cir::GetMemberOp::verify() {
3382 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3384 return emitError() <<
"expected pointer to a record type";
3386 if (recordTy.getMembers().size() <=
getIndex())
3387 return emitError() <<
"member index out of bounds";
3390 return emitError() <<
"member type mismatch";
3392 return mlir::success();
3399LogicalResult cir::ExtractMemberOp::verify() {
3400 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3402 <<
"cir.extract_member currently does not support unions";
3403 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3404 if (structTy.getMembers().size() <=
getIndex())
3405 return emitError() <<
"member index out of bounds";
3407 return emitError() <<
"member type mismatch";
3408 return mlir::success();
3415LogicalResult cir::InsertMemberOp::verify() {
3416 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3417 return emitError() <<
"cir.insert_member currently does not support unions";
3418 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3419 if (structTy.getMembers().size() <=
getIndex())
3420 return emitError() <<
"member index out of bounds";
3422 return emitError() <<
"member type mismatch";
3424 return mlir::success();
3431OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3432 if (llvm::any_of(getElements(), [](mlir::Value value) {
3433 return !value.getDefiningOp<cir::ConstantOp>();
3437 return cir::ConstVectorAttr::get(
3438 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3441LogicalResult cir::VecCreateOp::verify() {
3445 const cir::VectorType vecTy =
getType();
3446 if (getElements().size() != vecTy.getSize()) {
3447 return emitOpError() <<
"operand count of " << getElements().size()
3448 <<
" doesn't match vector type " << vecTy
3449 <<
" element count of " << vecTy.getSize();
3452 const mlir::Type elementType = vecTy.getElementType();
3453 for (
const mlir::Value element : getElements()) {
3454 if (element.getType() != elementType) {
3455 return emitOpError() <<
"operand type " << element.getType()
3456 <<
" doesn't match vector element type "
3468OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3469 const auto vectorAttr =
3470 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3474 const auto indexAttr =
3475 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3479 const mlir::ArrayAttr elements = vectorAttr.getElts();
3480 const uint64_t index = indexAttr.getUInt();
3481 if (index >= elements.size())
3484 return elements[index];
3491OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3493 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3495 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3496 if (!lhsVecAttr || !rhsVecAttr)
3499 mlir::Type inputElemTy =
3500 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3501 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3504 cir::CmpOpKind opKind = adaptor.getKind();
3505 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3506 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3507 uint64_t vecSize = lhsVecElhs.size();
3510 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3511 bool isUnsignedInt =
3512 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
3513 for (uint64_t i = 0; i < vecSize; i++) {
3514 mlir::Attribute lhsAttr = lhsVecElhs[i];
3515 mlir::Attribute rhsAttr = rhsVecElhs[i];
3516 bool cmpResult =
false;
3518 case cir::CmpOpKind::lt: {
3521 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
3522 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3524 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3525 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3527 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3528 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3532 case cir::CmpOpKind::le: {
3535 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
3536 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3538 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3539 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3541 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3542 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3546 case cir::CmpOpKind::gt: {
3549 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
3550 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3552 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3553 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3555 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3556 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3560 case cir::CmpOpKind::ge: {
3563 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
3564 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3566 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3567 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3569 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3570 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3574 case cir::CmpOpKind::eq: {
3576 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3577 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3579 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3580 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3584 case cir::CmpOpKind::ne: {
3586 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3587 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3589 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3590 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3594 case cir::CmpOpKind::one: {
3595 llvm::APFloat::cmpResult cr =
3596 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3597 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3599 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3602 case cir::CmpOpKind::uno: {
3603 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3604 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3605 llvm::APFloat::cmpUnordered;
3614 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL);
3617 return cir::ConstVectorAttr::get(
3618 getType(), mlir::ArrayAttr::get(getContext(), elements));
3625OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3627 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3629 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3630 if (!vec1Attr || !vec2Attr)
3633 mlir::Type vec1ElemTy =
3634 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3636 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3637 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3638 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3641 elements.reserve(indicesElts.size());
3643 uint64_t vec1Size = vec1Elts.size();
3644 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3645 if (idxAttr.getSInt() == -1) {
3646 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3650 uint64_t idxValue = idxAttr.getUInt();
3651 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3652 : vec2Elts[idxValue - vec1Size]);
3655 return cir::ConstVectorAttr::get(
3656 getType(), mlir::ArrayAttr::get(getContext(), elements));
3659LogicalResult cir::VecShuffleOp::verify() {
3662 if (getIndices().size() != getResult().
getType().getSize()) {
3663 return emitOpError() <<
": the number of elements in " << getIndices()
3664 <<
" and " << getResult().getType() <<
" don't match";
3669 if (getVec1().
getType().getElementType() !=
3670 getResult().
getType().getElementType()) {
3671 return emitOpError() <<
": element types of " << getVec1().getType()
3672 <<
" and " << getResult().getType() <<
" don't match";
3675 const uint64_t maxValidIndex =
3676 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3678 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3679 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3681 return emitOpError() <<
": index for __builtin_shufflevector must be "
3682 "less than the total number of vector elements";
3691OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3692 mlir::Attribute vec = adaptor.getVec();
3693 mlir::Attribute indices = adaptor.getIndices();
3694 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3695 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3696 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3697 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3699 mlir::ArrayAttr vecElts = vecAttr.getElts();
3700 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3702 const uint64_t numElements = vecElts.size();
3705 elements.reserve(numElements);
3707 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3708 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3709 uint64_t idxValue = idxAttr.getUInt();
3710 uint64_t newIdx = idxValue & maskBits;
3711 elements.push_back(vecElts[newIdx]);
3714 return cir::ConstVectorAttr::get(
3715 getType(), mlir::ArrayAttr::get(getContext(), elements));
3721LogicalResult cir::VecShuffleDynamicOp::verify() {
3723 if (getVec().
getType().getSize() !=
3724 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3725 return emitOpError() <<
": the number of elements in " << getVec().getType()
3726 <<
" and " << getIndices().getType() <<
" don't match";
3735LogicalResult cir::VecTernaryOp::verify() {
3740 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3741 return emitOpError() <<
": the number of elements in "
3742 << getCond().getType() <<
" and " << getLhs().getType()
3748OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3749 mlir::Attribute cond = adaptor.getCond();
3750 mlir::Attribute lhs = adaptor.getLhs();
3751 mlir::Attribute rhs = adaptor.getRhs();
3753 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3754 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3755 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3757 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3758 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3759 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3761 mlir::ArrayAttr condElts = condVec.getElts();
3764 elements.reserve(condElts.size());
3766 for (
const auto &[idx, condAttr] :
3767 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3768 if (condAttr.getSInt()) {
3769 elements.push_back(lhsVec.getElts()[idx]);
3771 elements.push_back(rhsVec.getElts()[idx]);
3775 cir::VectorType vecTy = getLhs().getType();
3776 return cir::ConstVectorAttr::get(
3777 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3784LogicalResult cir::ComplexCreateOp::verify() {
3787 <<
"operand type of cir.complex.create does not match its result type";
3794OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3795 mlir::Attribute real = adaptor.getReal();
3796 mlir::Attribute imag = adaptor.getImag();
3802 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3803 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3804 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3811LogicalResult cir::ComplexRealOp::verify() {
3812 mlir::Type operandTy = getOperand().getType();
3813 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3814 operandTy = complexOperandTy.getElementType();
3817 emitOpError() <<
": result type does not match operand type";
3824OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3825 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3828 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3829 return complexCreateOp.getOperand(0);
3832 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3833 return complex ? complex.getReal() :
nullptr;
3840LogicalResult cir::ComplexImagOp::verify() {
3841 mlir::Type operandTy = getOperand().getType();
3842 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3843 operandTy = complexOperandTy.getElementType();
3846 emitOpError() <<
": result type does not match operand type";
3853OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3854 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3857 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3858 return complexCreateOp.getOperand(1);
3861 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3862 return complex ? complex.getImag() :
nullptr;
3869LogicalResult cir::ComplexRealPtrOp::verify() {
3870 mlir::Type resultPointeeTy =
getType().getPointee();
3871 cir::PointerType operandPtrTy = getOperand().getType();
3872 auto operandPointeeTy =
3873 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3875 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3876 return emitOpError() <<
": result type does not match operand type";
3886LogicalResult cir::ComplexImagPtrOp::verify() {
3887 mlir::Type resultPointeeTy =
getType().getPointee();
3888 cir::PointerType operandPtrTy = getOperand().getType();
3889 auto operandPointeeTy =
3890 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3892 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3893 return emitOpError()
3894 <<
"cir.complex.imag_ptr result type does not match operand type";
3905 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3906 bool poisonZero =
false) {
3907 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3912 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3916 llvm::APInt inputValue = input.getValue();
3917 if (poisonZero && inputValue.isZero())
3918 return cir::PoisonAttr::get(input.getType());
3920 llvm::APInt resultValue = func(inputValue);
3921 return IntAttr::get(input.getType(), resultValue);
3924OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3925 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3926 unsigned resultValue =
3927 inputValue.getBitWidth() - inputValue.getSignificantBits();
3928 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3932OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3935 [](
const llvm::APInt &inputValue) {
3936 unsigned resultValue = inputValue.countLeadingZeros();
3937 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3942OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3945 [](
const llvm::APInt &inputValue) {
3946 return llvm::APInt(inputValue.getBitWidth(),
3947 inputValue.countTrailingZeros());
3952OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3953 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3954 unsigned trailingZeros = inputValue.countTrailingZeros();
3956 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3957 return llvm::APInt(inputValue.getBitWidth(), result);
3961OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3962 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3963 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3967OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3968 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3969 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3973OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3974 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3975 return inputValue.reverseBits();
3979OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3980 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3981 return inputValue.byteSwap();
3985OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3986 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3987 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3989 return cir::PoisonAttr::get(
getType());
3992 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3993 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3994 if (!input && !amount)
4003 llvm::APInt inputValue;
4005 inputValue = input.getValue();
4006 if (inputValue.isZero() || inputValue.isAllOnes()) {
4012 uint64_t amountValue;
4014 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
4015 if (amountValue == 0) {
4021 if (!input || !amount)
4024 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
4025 "input value must have the same bit width as the input type");
4027 llvm::APInt resultValue;
4029 resultValue = inputValue.rotl(amountValue);
4031 resultValue = inputValue.rotr(amountValue);
4033 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4040void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4041 p <<
'(' << getAsmFlavor() <<
", ";
4046 auto *nameIt = names.begin();
4047 auto *attrIt = getOperandAttrs().begin();
4049 for (mlir::OperandRange ops : getAsmOperands()) {
4050 p << *nameIt <<
" = ";
4053 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4055 p.printOperand(value);
4056 p <<
" : " << value.getType();
4057 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4058 p <<
" (maybe_memory)";
4067 p.printString(getAsmString());
4069 p.printString(getConstraints());
4073 if (getSideEffects())
4074 p <<
" side_effects";
4076 std::array elidedAttrs{
4077 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
4078 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
4079 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
4080 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
4082 if (
auto v = getRes())
4083 p <<
" -> " << v.getType();
4086void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4088 StringRef asmString, StringRef constraints,
4089 bool sideEffects, cir::AsmFlavor asmFlavor,
4093 for (
auto operandRange : asmOperands) {
4094 segments.push_back(operandRange.size());
4095 odsState.addOperands(operandRange);
4098 odsState.addAttribute(
4099 "operands_segments",
4100 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4101 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
4102 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
4103 odsState.addAttribute(
"asm_flavor",
4104 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4107 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
4109 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4112ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4113 OperationState &result) {
4116 std::string asmString, constraints;
4118 MLIRContext *ctxt = parser.getBuilder().getContext();
4120 auto error = [&](
const Twine &msg) -> LogicalResult {
4121 return parser.emitError(parser.getCurrentLocation(), msg);
4124 auto expected = [&](
const std::string &c) {
4125 return error(
"expected '" + c +
"'");
4128 if (parser.parseLParen().failed())
4129 return expected(
"(");
4131 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4133 return error(
"Unknown AsmFlavor");
4135 if (parser.parseComma().failed())
4136 return expected(
",");
4138 auto parseValue = [&](
Value &v) {
4139 OpAsmParser::UnresolvedOperand op;
4141 if (parser.parseOperand(op) || parser.parseColon())
4142 return error(
"can't parse operand");
4145 if (parser.parseType(typ).failed())
4146 return error(
"can't parse operand type");
4148 if (parser.resolveOperand(op, typ, tmp))
4149 return error(
"can't resolve operand");
4151 return mlir::success();
4154 auto parseOperands = [&](llvm::StringRef
name) {
4155 if (parser.parseKeyword(name).failed())
4156 return error(
"expected " + name +
" operands here");
4157 if (parser.parseEqual().failed())
4158 return expected(
"=");
4159 if (parser.parseLSquare().failed())
4160 return expected(
"[");
4163 if (parser.parseOptionalRSquare().succeeded()) {
4164 operandsGroupSizes.push_back(size);
4165 if (parser.parseComma())
4166 return expected(
",");
4167 return mlir::success();
4170 auto parseOperand = [&]() {
4172 if (parseValue(val).succeeded()) {
4173 result.operands.push_back(val);
4176 if (parser.parseOptionalLParen().failed()) {
4177 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4178 return mlir::success();
4181 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4182 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4183 if (parser.parseRParen())
4184 return expected(
")");
4185 return mlir::success();
4187 return expected(
"maybe_memory");
4190 return mlir::failure();
4193 if (parser.parseCommaSeparatedList(parseOperand).failed())
4194 return mlir::failure();
4196 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4197 return expected(
"]");
4198 operandsGroupSizes.push_back(size);
4199 return mlir::success();
4202 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4203 parseOperands(
"in_out").failed())
4204 return error(
"failed to parse operands");
4206 if (parser.parseLBrace())
4207 return expected(
"{");
4208 if (parser.parseString(&asmString))
4209 return error(
"asm string parsing failed");
4210 if (parser.parseString(&constraints))
4211 return error(
"constraints string parsing failed");
4212 if (parser.parseRBrace())
4213 return expected(
"}");
4214 if (parser.parseRParen())
4215 return expected(
")");
4217 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4218 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4220 if (parser.parseOptionalAttrDict(result.attributes).failed())
4221 return mlir::failure();
4223 if (parser.parseOptionalArrow().succeeded() &&
4224 parser.parseType(resType).failed())
4225 return mlir::failure();
4227 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4228 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4229 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4230 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4231 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4232 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4234 result.addTypes(TypeRange{resType});
4236 return mlir::success();
4243template <
typename ThrowOpTy>
4246 return mlir::success();
4248 if (op.getNumOperands() != 0) {
4249 if (op.getTypeInfo())
4250 return mlir::success();
4251 return op.emitOpError() <<
"'type_info' symbol attribute missing";
4254 return mlir::failure();
4259mlir::LogicalResult cir::TryThrowOp::verify() {
4267LogicalResult cir::AtomicFetchOp::verify() {
4268 if (getBinop() != cir::AtomicFetchKind::Add &&
4269 getBinop() != cir::AtomicFetchKind::Sub &&
4270 getBinop() != cir::AtomicFetchKind::Max &&
4271 getBinop() != cir::AtomicFetchKind::Min &&
4272 getBinop() != cir::AtomicFetchKind::Maximum &&
4273 getBinop() != cir::AtomicFetchKind::Minimum &&
4274 getBinop() != cir::AtomicFetchKind::MaximumNum &&
4275 getBinop() != cir::AtomicFetchKind::MinimumNum &&
4276 !mlir::isa<cir::IntType>(getVal().
getType()))
4277 return emitError(
"only atomic add, sub, max, min, maximum, minimum, "
4278 "maximum_num, and minimum_num operation could operate on "
4279 "floating-point values");
4281 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
4282 getBinop() == cir::AtomicFetchKind::Minimum ||
4283 getBinop() == cir::AtomicFetchKind::MaximumNum ||
4284 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
4285 !mlir::isa<cir::FPTypeInterface>(getVal().
getType()))
4286 return emitError(
"atomic maximum, minimum, maximum_num, and minimum_num "
4287 "operation could only operate on floating-point values");
4296LogicalResult cir::TypeInfoAttr::verify(
4297 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4298 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4300 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4310void cir::TryOp::getSuccessorRegions(
4311 mlir::RegionBranchPoint point,
4314 if (!point.isParent()) {
4315 regions.emplace_back(getOperation());
4319 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4323 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4324 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4327mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
4328 return successor.isOperation() ? ValueRange(getOperation()->getResults())
4332LogicalResult cir::TryOp::verify() {
4333 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4334 if (!handlerTypes) {
4335 if (!getHandlerRegions().empty())
4337 "handler regions must be empty when no handler types are present");
4341 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4345 if (handlerRegions.size() != handlerTypes.size())
4347 "number of handler regions and handler types must match");
4349 for (
const auto &[typeAttr, handlerRegion] :
4350 llvm::zip(handlerTypes, handlerRegions)) {
4352 mlir::Block &entryBlock = handlerRegion.front();
4353 if (entryBlock.getNumArguments() != 1 ||
4354 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4356 "handler region must have a single '!cir.eh_token' argument");
4359 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4365 if (entryBlock.empty())
4366 return emitOpError(
"catch handler region must not be empty");
4367 mlir::Operation *firstOp = &entryBlock.front();
4368 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4369 firstOp = firstOp->getNextNode();
4370 if (!firstOp || !mlir::isa<cir::BeginCatchOp>(firstOp))
4372 "catch handler region must start with 'cir.begin_catch'");
4380 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4381 mlir::ArrayAttr handlerTypes) {
4385 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4389 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4390 printer <<
"catch all ";
4391 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4392 printer <<
"unwind ";
4394 printer <<
"catch [type ";
4395 printer.printAttribute(typeAttr);
4400 mlir::Region ®ion = handlerRegions[typeIdx];
4401 if (!region.empty() && region.front().getNumArguments() > 0) {
4403 printer.printRegionArgument(region.front().getArgument(0));
4407 printer.printRegion(region,
4414 mlir::OpAsmParser &parser,
4416 mlir::ArrayAttr &handlerTypes) {
4418 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4419 handlerRegions.emplace_back(
new mlir::Region);
4421 mlir::Region &currRegion = *handlerRegions.back();
4425 if (parser.parseLParen())
4427 mlir::OpAsmParser::Argument arg;
4428 if (parser.parseArgument(arg,
true))
4430 regionArgs.push_back(arg);
4431 if (parser.parseRParen())
4434 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4435 if (parser.parseRegion(currRegion, regionArgs)) {
4436 handlerRegions.clear();
4440 if (currRegion.empty())
4441 return parser.emitError(regionLoc,
"handler region shall not be empty");
4443 if (!(currRegion.back().mightHaveTerminator() &&
4444 currRegion.back().getTerminator()))
4445 return parser.emitError(
4446 regionLoc,
"blocks are expected to be explicitly terminated");
4451 bool hasCatchAll =
false;
4453 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4454 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4456 llvm::StringRef attrStr;
4457 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4458 return parser.emitError(parser.getCurrentLocation(),
4459 "expected 'all' or 'type' keyword");
4461 bool isCatchAll = attrStr ==
"all";
4464 return parser.emitError(parser.getCurrentLocation(),
4465 "can't have more than one catch all");
4469 mlir::Attribute exceptionRTTIAttr;
4470 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4471 return parser.emitError(parser.getCurrentLocation(),
4472 "expected valid RTTI info attribute");
4474 catcherAttrs.push_back(isCatchAll
4475 ? cir::CatchAllAttr::get(parser.getContext())
4476 : exceptionRTTIAttr);
4478 if (hasLSquare && isCatchAll)
4479 return parser.emitError(parser.getCurrentLocation(),
4480 "catch all dosen't need RTTI info attribute");
4482 if (hasLSquare && parser.parseRSquare().failed())
4483 return parser.emitError(parser.getCurrentLocation(),
4484 "expected `]` after RTTI info attribute");
4486 if (parseCheckedCatcherRegion().failed())
4487 return mlir::failure();
4490 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4492 return parser.emitError(parser.getCurrentLocation(),
4493 "unwind can't be used with catch all");
4495 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4496 if (parseCheckedCatcherRegion().failed())
4497 return mlir::failure();
4500 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4501 return mlir::success();
4509cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4510 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
4511 if (!isa_and_nonnull<GlobalOp>(op))
4512 return emitOpError(
"'")
4513 << getTypeSym() <<
"' does not reference a valid cir.global";
4521LogicalResult cir::LifetimeStartOp::verify() {
4525LogicalResult cir::LifetimeEndOp::verify() {
4533LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4534 SymbolTableCollection &symbolTable) {
4535 auto copyFnAttr = getCopyFnAttr();
4539 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
4541 return emitOpError(
"'")
4542 << *getCopyFn() <<
"' does not reference a valid cir.func";
4544 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4545 return emitOpError(
"catch-init copy_fn must be tagged with the ")
4546 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
4548 cir::FuncType fnType = fn.getFunctionType();
4549 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4550 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
4553 if (fnType.getInput(0) != getParamAddr().
getType())
4554 return emitOpError(
"first argument of catch-init copy_fn must match the "
4555 "type of 'param_addr'");
4557 if (fnType.getInput(1) != getParamAddr().
getType())
4559 "second argument of catch-init copy_fn must be a pointer "
4560 "to the catch type");
4571 SmallVectorImpl<Block *> &catchDestinations,
4572 Block *&defaultDestination,
4573 mlir::UnitAttr &defaultIsCatchAll) {
4575 if (parser.parseLSquare())
4579 bool hasCatchAll =
false;
4580 bool hasUnwind =
false;
4583 auto parseHandler = [&]() -> ParseResult {
4585 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
4587 return parser.emitError(parser.getCurrentLocation(),
4588 "duplicate 'catch_all' handler");
4590 return parser.emitError(parser.getCurrentLocation(),
4591 "cannot have both 'catch_all' and 'unwind'");
4594 if (parser.parseColon().failed())
4597 if (parser.parseSuccessor(defaultDestination).failed())
4603 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
4605 return parser.emitError(parser.getCurrentLocation(),
4606 "duplicate 'unwind' handler");
4608 return parser.emitError(parser.getCurrentLocation(),
4609 "cannot have both 'catch_all' and 'unwind'");
4612 if (parser.parseColon().failed())
4615 if (parser.parseSuccessor(defaultDestination).failed())
4623 if (parser.parseKeyword(
"catch").failed())
4626 if (parser.parseLParen().failed())
4629 mlir::Attribute catchTypeAttr;
4630 if (parser.parseAttribute(catchTypeAttr).failed())
4632 handlerTypes.push_back(catchTypeAttr);
4634 if (parser.parseRParen().failed())
4637 if (parser.parseColon().failed())
4641 if (parser.parseSuccessor(dest).failed())
4643 catchDestinations.push_back(dest);
4647 if (parser.parseCommaSeparatedList(parseHandler).failed())
4650 if (parser.parseRSquare().failed())
4654 if (!hasCatchAll && !hasUnwind)
4655 return parser.emitError(parser.getCurrentLocation(),
4656 "must have either 'catch_all' or 'unwind' handler");
4659 if (!handlerTypes.empty())
4660 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4663 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4669 mlir::ArrayAttr catchTypes,
4670 SuccessorRange catchDestinations,
4671 Block *defaultDestination,
4672 mlir::UnitAttr defaultIsCatchAll) {
4680 llvm::zip(catchTypes, catchDestinations),
4683 p.printAttribute(std::get<0>(i));
4685 p.printSuccessor(std::get<1>(i));
4697 if (defaultIsCatchAll)
4698 p <<
" catch_all : ";
4701 p.printSuccessor(defaultDestination);
4711bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
4712 mlir::TypeRange results) {
4713 if (operands.size() != getNumArgs() || results.size() != 1)
4715 mlir::Type iterTy = operands[0];
4716 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
4723#define GET_OP_CLASSES
4724#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static LogicalResult verifyLoopCleanup(LoopOpTy op)
static void printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, SuccessorRange catchDestinations, Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static ParseResult parseAssumeBundle(OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
static ParseResult parseEhDispatchDestinations(OpAsmParser &parser, mlir::ArrayAttr &catchTypes, SmallVectorImpl< Block * > &catchDestinations, Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, OperandRange bundleArgs, TypeRange bundleArgTypes)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
void printGlobalAddressSpaceValue(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op, Type flagType, SuccessorRange succs, OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
mlir::OptionalParseResult parseGlobalAddressSpaceValue(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
static void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
ParseResult parseIndirectBrOpSucessors(OpAsmParser &parser, Type &flagType, SmallVectorImpl< Block * > &succOperandBlocks, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &succOperands, SmallVectorImpl< SmallVector< Type > > &succOperandsTypes)
static bool omitRegionTerm(mlir::Region &r)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
const AstTypeMatcher< BuiltinType > builtinType
const internal::VariadicAllOfMatcher< Attr > attr
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()