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());
267 mlir::Region ®ion) {
268 auto regionLoc = parser.getCurrentLocation();
269 if (parser.parseRegion(region))
278 mlir::Region ®ion) {
279 printer.printRegion(region,
284mlir::OptionalParseResult
286 mlir::ptr::MemorySpaceAttrInterface &attr);
289 mlir::ptr::MemorySpaceAttrInterface attr);
295void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
296 mlir::OperationState &odsState, mlir::Type addr,
297 llvm::StringRef name, mlir::IntegerAttr alignment) {
298 odsState.addAttribute(getNameAttrName(odsState.name),
299 odsBuilder.getStringAttr(name));
301 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
303 odsState.addTypes(addr);
311 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
312 mlir::Type pointeeTy = ptrTy.getPointee();
314 mlir::Block &body = op.getBody().front();
315 if (body.getNumArguments() != 1)
316 return op.emitOpError(
"body must have exactly one block argument");
318 auto expectedEltPtrTy =
319 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
320 if (!expectedEltPtrTy)
321 return op.emitOpError(
"block argument must be a !cir.ptr type");
323 if (op.getNumElements()) {
324 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
326 return op.emitOpError(
327 "when 'num_elements' is present, 'addr' must be a pointer to a "
328 "!cir.struct or !cir.union type");
330 if (expectedEltPtrTy != ptrTy)
331 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
332 "match the block argument type");
334 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
336 return op.emitOpError(
337 "when 'num_elements' is absent, 'addr' must be a pointer to a "
340 mlir::Type innerEltTy = arrayTy.getElementType();
341 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
342 innerEltTy = nested.getElementType();
344 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
346 return op.emitOpError(
"the block argument type must be a pointer to a "
347 "!cir.struct or !cir.union type");
349 if (expectedEltPtrTy.getPointee() != innerEltTy)
350 return op.emitOpError(
351 "block argument pointee type must match the innermost array "
358LogicalResult cir::ArrayCtor::verify() {
362 mlir::Region &partialDtor = getPartialDtor();
363 if (!partialDtor.empty()) {
364 mlir::Block &dtorBlock = partialDtor.front();
365 if (dtorBlock.getNumArguments() != 1)
366 return emitOpError(
"partial_dtor must have exactly one block argument");
368 auto bodyArgTy = getBody().front().getArgument(0).getType();
369 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
370 return emitOpError(
"partial_dtor block argument type must match "
371 "the body block argument type");
381LogicalResult cir::DeleteArrayOp::verify() {
382 if (getDtorMayThrow() && !getElementDtorAttr())
384 "'dtor_may_throw' requires an 'element_dtor' to be present");
393 cir::AssumeBundleKindAttr kindAttr,
394 OperandRange bundleArgs,
395 TypeRange bundleArgTypes) {
396 cir::AssumeBundleKind
kind = kindAttr.getValue();
397 if (
kind == cir::AssumeBundleKind::None)
400 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
401 if (bundleArgs.empty())
405 p.printOperands(bundleArgs);
407 llvm::interleaveComma(bundleArgTypes, p);
412 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
416 auto loc = p.getCurrentLocation();
417 if (failed(p.parseOptionalKeyword(&keyword))) {
418 bundleKindAttr = cir::AssumeBundleKindAttr::get(
419 p.getContext(), cir::AssumeBundleKind::None);
423 std::optional<cir::AssumeBundleKind> parsedKind =
424 cir::symbolizeAssumeBundleKind(keyword);
426 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
428 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
430 if (p.parseOptionalLParen())
433 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
434 p.parseTypeList(bundleArgTypes) || p.parseRParen())
440LogicalResult cir::AssumeOp::verify() {
441 cir::AssumeBundleKind
kind = getBundleKind();
442 size_t numArgs = getBundleArgs().size();
444 if (
kind == cir::AssumeBundleKind::None) {
446 return emitOpError(
"unexpected bundle operands for kind 'none'");
451 return emitOpError(
"expected bundle operands for kind '")
452 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
455 case cir::AssumeBundleKind::Align:
456 if (numArgs != 2 && numArgs != 3)
457 return emitOpError(
"align bundle expects 2 or 3 operands");
459 case cir::AssumeBundleKind::SeparateStorage:
461 return emitOpError(
"separate_storage bundle expects 2 operands");
463 case cir::AssumeBundleKind::Dereferenceable:
465 return emitOpError(
"dereferenceable bundle expects 2 operands");
478cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
479 cir::GlobalOp global = getReferencedGlobal(symbolTable);
481 return emitOpError(
"'")
482 << getGlobalName() <<
"' does not reference a valid cir.global";
484 if (getTls() && !global.getTlsModel())
485 return emitOpError(
"access to global not marked thread local");
487 if (!global.getStaticLocalGuard().has_value())
488 return emitOpError(
"static_local attribute mismatch");
501void cir::ConditionOp::getSuccessorRegions(
508 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
509 regions.emplace_back(&loopOp.getBody());
510 if (mlir::Region *cleanup = loopOp.maybeGetCleanup())
511 regions.emplace_back(cleanup);
513 regions.emplace_back(getOperation());
518 auto await = cast<AwaitOp>(getOperation()->getParentOp());
519 regions.emplace_back(&await.getResume());
520 regions.emplace_back(&await.getSuspend());
524cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
526 return MutableOperandRange(getOperation(), 0, 0);
530cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
532 return MutableOperandRange(getOperation(), 0, 0);
535LogicalResult cir::ConditionOp::verify() {
536 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
537 return emitOpError(
"condition must be within a conditional region");
545template <
typename LoopOpTy>
547 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
551 if (cleanupKind.has_value() == op.getCleanup().empty())
552 return op.emitOpError(
"cleanup kind must be present if and only if the "
553 "cleanup region is non-empty");
558 if (cleanupKind == cir::CleanupKind::EH)
559 return op.emitOpError(
"loop cleanup kind must be 'normal' or 'all', "
574 mlir::Attribute attrType) {
575 if (isa<cir::ConstPtrAttr>(attrType)) {
576 if (!mlir::isa<cir::PointerType>(opType))
577 return op->emitOpError(
578 "pointer constant initializing a non-pointer type");
582 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
589 if (isa<cir::ZeroAttr>(attrType)) {
590 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
593 return op->emitOpError(
594 "zero expects struct, array, vector, or complex type");
597 if (mlir::isa<cir::UndefAttr>(attrType)) {
598 if (!mlir::isa<cir::VoidType>(opType))
600 return op->emitOpError(
"undef expects non-void type");
603 if (mlir::isa<cir::BoolAttr>(attrType)) {
604 if (!mlir::isa<cir::BoolType>(opType))
605 return op->emitOpError(
"result type (")
606 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
610 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
611 auto at = cast<TypedAttr>(attrType);
612 if (at.getType() != opType) {
613 return op->emitOpError(
"result type (")
614 << opType <<
") does not match value type (" << at.getType()
620 if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
621 cir::ConstArrayAttr, cir::ConstVectorAttr,
622 cir::ConstComplexAttr, cir::ConstRecordAttr,
623 cir::GlobalOffsetAttr, cir::GlobalViewAttr, cir::PoisonAttr,
624 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
627 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
628 return op->emitOpError(
"global with type ")
629 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
632LogicalResult cir::ConstantOp::verify() {
639OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
649 case cir::CastKind::floating:
650 case cir::CastKind::int_to_float:
651 case cir::CastKind::float_to_int:
652 case cir::CastKind::float_to_bool:
653 case cir::CastKind::bool_to_float:
654 case cir::CastKind::float_to_complex:
655 case cir::CastKind::float_complex_to_real:
656 case cir::CastKind::float_complex_to_bool:
657 case cir::CastKind::float_complex:
658 case cir::CastKind::float_complex_to_int_complex:
659 case cir::CastKind::int_complex_to_float_complex:
666LogicalResult cir::CastOp::verify() {
667 mlir::Type resType =
getType();
668 mlir::Type srcType = getSrc().getType();
673 <<
"'fenv' is only valid for floating-point cast kinds";
677 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
678 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
679 if (srcPtrTy && resPtrTy && (
kind != cir::CastKind::address_space))
680 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
681 return emitOpError() <<
"result type address space does not match the "
682 "address space of the operand";
685 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
686 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
687 if (srcVTy && resVTy) {
688 if ((
kind == cir::CastKind::int_to_float ||
689 kind == cir::CastKind::float_to_int) &&
690 srcVTy.getSize() != resVTy.getSize()) {
692 <<
"vector float-to-int and int-to-float casts require "
693 "source and destination vectors to have the same number of "
698 srcType = srcVTy.getElementType();
699 resType = resVTy.getElementType();
703 case cir::CastKind::int_to_bool: {
704 if (!mlir::isa<cir::BoolType>(resType))
705 return emitOpError() <<
"requires !cir.bool type for result";
706 if (!mlir::isa<cir::IntType>(srcType))
707 return emitOpError() <<
"requires !cir.int type for source";
710 case cir::CastKind::ptr_to_bool: {
711 if (!mlir::isa<cir::BoolType>(resType))
712 return emitOpError() <<
"requires !cir.bool type for result";
713 if (!mlir::isa<cir::PointerType>(srcType))
714 return emitOpError() <<
"requires !cir.ptr type for source";
717 case cir::CastKind::integral: {
718 if (!mlir::isa<cir::IntType>(resType))
719 return emitOpError() <<
"requires !cir.int type for result";
720 if (!mlir::isa<cir::IntType>(srcType))
721 return emitOpError() <<
"requires !cir.int type for source";
724 case cir::CastKind::array_to_ptrdecay: {
725 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
726 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
727 if (!arrayPtrTy || !flatPtrTy)
728 return emitOpError() <<
"requires !cir.ptr type for source and result";
733 case cir::CastKind::bitcast: {
735 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
736 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
738 if (srcPtrTy && resPtrTy) {
744 case cir::CastKind::floating: {
745 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
746 !mlir::isa<cir::FPTypeInterface>(resType))
747 return emitOpError() <<
"requires !cir.float type for source and result";
750 case cir::CastKind::float_to_int: {
751 if (!mlir::isa<cir::FPTypeInterface>(srcType))
752 return emitOpError() <<
"requires !cir.float type for source";
753 if (!mlir::dyn_cast<cir::IntType>(resType))
754 return emitOpError() <<
"requires !cir.int type for result";
757 case cir::CastKind::int_to_ptr: {
758 if (!mlir::dyn_cast<cir::IntType>(srcType))
759 return emitOpError() <<
"requires !cir.int type for source";
760 if (!mlir::dyn_cast<cir::PointerType>(resType))
761 return emitOpError() <<
"requires !cir.ptr type for result";
764 case cir::CastKind::ptr_to_int: {
765 if (!mlir::dyn_cast<cir::PointerType>(srcType))
766 return emitOpError() <<
"requires !cir.ptr type for source";
767 if (!mlir::dyn_cast<cir::IntType>(resType))
768 return emitOpError() <<
"requires !cir.int type for result";
771 case cir::CastKind::float_to_bool: {
772 if (!mlir::isa<cir::FPTypeInterface>(srcType))
773 return emitOpError() <<
"requires !cir.float type for source";
774 if (!mlir::isa<cir::BoolType>(resType))
775 return emitOpError() <<
"requires !cir.bool type for result";
778 case cir::CastKind::bool_to_int: {
779 if (!mlir::isa<cir::BoolType>(srcType))
780 return emitOpError() <<
"requires !cir.bool type for source";
781 if (!mlir::isa<cir::IntType>(resType))
782 return emitOpError() <<
"requires !cir.int type for result";
785 case cir::CastKind::int_to_float: {
786 if (!mlir::isa<cir::IntType>(srcType))
787 return emitOpError() <<
"requires !cir.int type for source";
788 if (!mlir::isa<cir::FPTypeInterface>(resType))
789 return emitOpError() <<
"requires !cir.float type for result";
792 case cir::CastKind::bool_to_float: {
793 if (!mlir::isa<cir::BoolType>(srcType))
794 return emitOpError() <<
"requires !cir.bool type for source";
795 if (!mlir::isa<cir::FPTypeInterface>(resType))
796 return emitOpError() <<
"requires !cir.float type for result";
799 case cir::CastKind::address_space: {
800 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
801 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
802 if (!srcPtrTy || !resPtrTy)
803 return emitOpError() <<
"requires !cir.ptr type for source and result";
804 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
805 return emitOpError() <<
"requires two types differ in addrspace only";
808 case cir::CastKind::float_to_complex: {
809 if (!mlir::isa<cir::FPTypeInterface>(srcType))
810 return emitOpError() <<
"requires !cir.float type for source";
811 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
813 return emitOpError() <<
"requires !cir.complex type for result";
814 if (srcType != resComplexTy.getElementType())
815 return emitOpError() <<
"requires source type match result element type";
818 case cir::CastKind::int_to_complex: {
819 if (!mlir::isa<cir::IntType>(srcType))
820 return emitOpError() <<
"requires !cir.int type for source";
821 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
823 return emitOpError() <<
"requires !cir.complex type for result";
824 if (srcType != resComplexTy.getElementType())
825 return emitOpError() <<
"requires source type match result element type";
828 case cir::CastKind::float_complex_to_real: {
829 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
831 return emitOpError() <<
"requires !cir.complex type for source";
832 if (!mlir::isa<cir::FPTypeInterface>(resType))
833 return emitOpError() <<
"requires !cir.float type for result";
834 if (srcComplexTy.getElementType() != resType)
835 return emitOpError() <<
"requires source element type match result type";
838 case cir::CastKind::int_complex_to_real: {
839 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
841 return emitOpError() <<
"requires !cir.complex type for source";
842 if (!mlir::isa<cir::IntType>(resType))
843 return emitOpError() <<
"requires !cir.int type for result";
844 if (srcComplexTy.getElementType() != resType)
845 return emitOpError() <<
"requires source element type match result type";
848 case cir::CastKind::float_complex_to_bool: {
849 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
850 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
852 <<
"requires floating point !cir.complex type for source";
853 if (!mlir::isa<cir::BoolType>(resType))
854 return emitOpError() <<
"requires !cir.bool type for result";
857 case cir::CastKind::int_complex_to_bool: {
858 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
859 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
861 <<
"requires floating point !cir.complex type for source";
862 if (!mlir::isa<cir::BoolType>(resType))
863 return emitOpError() <<
"requires !cir.bool type for result";
866 case cir::CastKind::float_complex: {
867 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
868 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
870 <<
"requires floating point !cir.complex type for source";
871 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
872 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
874 <<
"requires floating point !cir.complex type for result";
877 case cir::CastKind::float_complex_to_int_complex: {
878 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
879 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
881 <<
"requires floating point !cir.complex type for source";
882 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
883 if (!resComplexTy || !resComplexTy.isIntegerComplex())
884 return emitOpError() <<
"requires integer !cir.complex type for result";
887 case cir::CastKind::int_complex: {
888 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
889 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
890 return emitOpError() <<
"requires integer !cir.complex type for source";
891 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
892 if (!resComplexTy || !resComplexTy.isIntegerComplex())
893 return emitOpError() <<
"requires integer !cir.complex type for result";
896 case cir::CastKind::int_complex_to_float_complex: {
897 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
898 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
899 return emitOpError() <<
"requires integer !cir.complex type for source";
900 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
901 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
903 <<
"requires floating point !cir.complex type for result";
906 case cir::CastKind::member_ptr_to_bool: {
907 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
909 <<
"requires !cir.data_member or !cir.method type for source";
910 if (!mlir::isa<cir::BoolType>(resType))
911 return emitOpError() <<
"requires !cir.bool type for result";
915 llvm_unreachable(
"Unknown CastOp kind?");
919 auto kind = op.getKind();
920 return kind == cir::CastKind::bool_to_int ||
921 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
925 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
926 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
930 cir::CastOp head = op, tail = op;
936 op = head.getSrc().getDefiningOp<cir::CastOp>();
942 if (head.getKind() == cir::CastKind::bool_to_int &&
943 tail.getKind() == cir::CastKind::int_to_bool)
944 return head.getSrc();
949 if (head.getKind() == cir::CastKind::int_to_bool &&
950 tail.getKind() == cir::CastKind::int_to_bool)
951 return head.getResult();
959 if (tail.getKind() == cir::CastKind::bitcast) {
960 auto *inner = tail.getSrc().getDefiningOp();
962 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
963 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
964 innerCast.getSrc().getType() == tail.getType() &&
965 innerCast.getType() == tail.getSrc().getType()) {
966 return innerCast.getSrc();
974OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
975 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
977 return cir::PoisonAttr::get(getContext(),
getType());
981 if (mlir::isa_and_present<cir::UndefAttr>(adaptor.getSrc()))
982 return cir::UndefAttr::get(
getType());
986 case cir::CastKind::integral: {
988 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
989 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
990 return mlir::cast<mlir::Attribute>(foldResults[0]);
993 case cir::CastKind::bitcast:
994 case cir::CastKind::address_space:
995 case cir::CastKind::float_complex:
996 case cir::CastKind::int_complex: {
1010 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
1012 case cir::CastKind::integral: {
1013 mlir::Type srcTy = getSrc().getType();
1015 assert(mlir::isa<cir::VectorType>(srcTy) ==
1016 mlir::isa<cir::VectorType>(
getType()));
1017 if (mlir::isa<cir::VectorType>(srcTy))
1020 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
1021 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
1022 auto constIntAttr = srcConst.getValueAttr<cir::IntAttr>();
1026 APInt srcValue = constIntAttr.getValue();
1027 APInt newVal = srcIntTy.isSigned()
1028 ? srcValue.sextOrTrunc(dstIntTy.getWidth())
1029 : srcValue.zextOrTrunc(dstIntTy.getWidth());
1030 return cir::IntAttr::get(dstIntTy, newVal);
1043LogicalResult cir::BuiltinIntCastOp::verify() {
1044 mlir::Type srcType = getSrc().getType();
1045 mlir::Type resType =
getType();
1047 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1048 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1052 if (
static_cast<bool>(srcCirInt) ==
static_cast<bool>(resCirInt))
1053 return emitOpError()
1054 <<
"requires exactly one '!cir.int' operand or result; the other "
1055 "must be a builtin integer or 'index' type";
1057 mlir::Type
builtinType = srcCirInt ? resType : srcType;
1058 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1059 return emitOpError() <<
"requires a builtin integer or 'index' type on the "
1064 if (
auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1065 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1066 if (cirInt.getWidth() != builtinInt.getWidth())
1067 return emitOpError()
1068 <<
"requires the CIR and builtin integer types to have the same "
1069 "width; use 'cir.cast' for width conversions";
1075OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1078 if (
auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1079 if (inner.getSrc().getType() ==
getType())
1080 return inner.getSrc();
1088mlir::OperandRange cir::CallOp::getArgOperands() {
1090 return getArgs().drop_front(1);
1094mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1095 mlir::MutableOperandRange args = getArgsMutable();
1097 return args.slice(1, args.size() - 1);
1101mlir::Value cir::CallOp::getIndirectCall() {
1102 assert(isIndirect());
1103 return getOperand(0);
1107Value cir::CallOp::getArgOperand(
unsigned i) {
1110 return getOperand(i);
1114unsigned cir::CallOp::getNumArgOperands() {
1116 return this->getOperation()->getNumOperands() - 1;
1117 return this->getOperation()->getNumOperands();
1120static mlir::ParseResult
1122 mlir::OperationState &result) {
1123 mlir::Block *normalDestSuccessor;
1124 if (parser.parseSuccessor(normalDestSuccessor))
1125 return mlir::failure();
1127 if (parser.parseComma())
1128 return mlir::failure();
1130 mlir::Block *unwindDestSuccessor;
1131 if (parser.parseSuccessor(unwindDestSuccessor))
1132 return mlir::failure();
1134 result.addSuccessors(normalDestSuccessor);
1135 result.addSuccessors(unwindDestSuccessor);
1136 return mlir::success();
1140 mlir::OperationState &result,
1141 bool hasDestinationBlocks =
false) {
1144 mlir::FlatSymbolRefAttr calleeAttr;
1148 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1151 OpAsmParser::UnresolvedOperand indirectVal;
1153 if (parser.parseOperand(indirectVal).failed())
1155 ops.push_back(indirectVal);
1158 if (parser.parseLParen())
1159 return mlir::failure();
1161 opsLoc = parser.getCurrentLocation();
1162 if (parser.parseOperandList(ops))
1163 return mlir::failure();
1164 if (parser.parseRParen())
1165 return mlir::failure();
1167 if (hasDestinationBlocks &&
1169 return ::mlir::failure();
1172 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1173 result.addAttribute(CIRDialect::getMustTailAttrName(),
1174 mlir::UnitAttr::get(parser.getContext()));
1176 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1177 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1178 mlir::UnitAttr::get(parser.getContext()));
1180 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
1181 if (parser.parseLParen().failed())
1183 cir::SideEffect sideEffect;
1186 if (parser.parseRParen().failed())
1188 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
1189 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1192 if (parser.parseOptionalAttrDict(result.attributes))
1193 return ::mlir::failure();
1195 if (parser.parseColon())
1196 return ::mlir::failure();
1202 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1203 resultTypes, resultAttrs))
1204 return mlir::failure();
1206 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1207 return parser.emitError(
1208 parser.getCurrentLocation(),
1209 "functions with multiple return types are not supported");
1211 result.addTypes(resultTypes);
1213 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1214 return mlir::failure();
1216 if (!resultAttrs.empty() && resultAttrs[0])
1217 result.addAttribute(
1218 CIRDialect::getResAttrsAttrName(),
1219 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1224 bool argAttrsEmpty =
true;
1226 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1227 [&](DictionaryAttr da) -> mlir::Attribute {
1229 argAttrsEmpty =
false;
1233 if (!argAttrsEmpty) {
1238 argAttrsRef = argAttrsRef.drop_front();
1240 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1241 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1244 return mlir::success();
1249 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1250 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1251 ArrayAttr resAttrs, mlir::Block *normalDest =
nullptr,
1252 mlir::Block *unwindDest =
nullptr) {
1255 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1256 auto ops = callLikeOp.getArgOperands();
1260 printer.printAttributeWithoutType(calleeSym);
1263 assert(indirectCallee);
1264 printer << indirectCallee;
1267 printer <<
"(" << ops <<
")";
1270 assert(unwindDest &&
"expected two successors");
1271 auto tryCall = cast<cir::TryCallOp>(op);
1272 printer <<
' ' << tryCall.getNormalDest();
1275 printer << tryCall.getUnwindDest();
1278 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1279 printer <<
" musttail";
1282 printer <<
" nothrow";
1284 if (sideEffect != cir::SideEffect::All) {
1285 printer <<
" side_effect(";
1286 printer << stringifySideEffect(sideEffect);
1291 CIRDialect::getCalleeAttrName(),
1292 CIRDialect::getMustTailAttrName(),
1293 CIRDialect::getNoThrowAttrName(),
1294 CIRDialect::getSideEffectAttrName(),
1295 CIRDialect::getOperandSegmentSizesAttrName(),
1296 llvm::StringRef(
"res_attrs"),
1297 llvm::StringRef(
"arg_attrs")};
1298 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1300 if (calleeSym || !argAttrs) {
1301 call_interface_impl::printFunctionSignature(
1302 printer, op->getOperands().getTypes(), argAttrs,
1303 false, op->getResultTypes(), resAttrs);
1311 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1312 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1313 call_interface_impl::printFunctionSignature(
1314 printer, op->getOperands().getTypes(),
1315 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1316 false, op->getResultTypes(), resAttrs);
1320mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1321 mlir::OperationState &result) {
1325void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1326 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1327 cir::SideEffect sideEffect = getSideEffect();
1328 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1329 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1334 SymbolTableCollection &symbolTable) {
1336 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1339 return mlir::success();
1342 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1344 return op->emitOpError() <<
"'" << fnAttr.getValue()
1345 <<
"' does not reference a valid function";
1347 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1348 assert(callIf &&
"expected CIR call interface to be always available");
1352 auto fnType = fn.getFunctionType();
1353 if (!fn.getNoProto()) {
1354 unsigned numCallOperands = callIf.getNumArgOperands();
1355 unsigned numFnOpOperands = fnType.getNumInputs();
1357 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1358 return op->emitOpError(
"incorrect number of operands for callee");
1359 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1360 return op->emitOpError(
"too few operands for callee");
1362 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1363 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1364 return op->emitOpError(
"operand type mismatch: expected operand type ")
1365 << fnType.getInput(i) <<
", but provided "
1366 << op->getOperand(i).getType() <<
" for operand number " << i;
1372 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1373 return op->emitOpError(
"callee returns void but call has results");
1376 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1377 return op->emitOpError(
"incorrect number of results for callee");
1380 if (!fnType.hasVoidReturn() &&
1381 op->getResultTypes().front() != fnType.getReturnType()) {
1382 return op->emitOpError(
"result type mismatch: expected ")
1383 << fnType.getReturnType() <<
", but provided "
1384 << op->getResult(0).getType();
1387 return mlir::success();
1391cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1399mlir::OperandRange cir::TryCallOp::getArgOperands() {
1401 return getArgs().drop_front(1);
1405mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1406 mlir::MutableOperandRange args = getArgsMutable();
1408 return args.slice(1, args.size() - 1);
1412mlir::Value cir::TryCallOp::getIndirectCall() {
1413 assert(isIndirect());
1414 return getOperand(0);
1418Value cir::TryCallOp::getArgOperand(
unsigned i) {
1421 return getOperand(i);
1425unsigned cir::TryCallOp::getNumArgOperands() {
1427 return this->getOperation()->getNumOperands() - 1;
1428 return this->getOperation()->getNumOperands();
1432cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1436mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1437 mlir::OperationState &result) {
1441void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1442 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1443 cir::SideEffect sideEffect = getSideEffect();
1444 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1445 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1446 getNormalDest(), getUnwindDest());
1454 cir::FuncOp function) {
1456 if (op.getNumOperands() > 1)
1457 return op.emitOpError() <<
"expects at most 1 return operand";
1460 auto expectedTy = function.getFunctionType().getReturnType();
1462 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1463 : op.getOperand(0).getType());
1464 if (actualTy != expectedTy)
1465 return op.emitOpError() <<
"returns " << actualTy
1466 <<
" but enclosing function returns " << expectedTy;
1468 return mlir::success();
1471mlir::LogicalResult cir::ReturnOp::verify() {
1474 auto *fnOp = getOperation()->getParentOp();
1475 while (!isa<cir::FuncOp>(fnOp))
1476 fnOp = fnOp->getParentOp();
1489ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1491 result.regions.reserve(2);
1492 Region *thenRegion = result.addRegion();
1493 Region *elseRegion = result.addRegion();
1495 mlir::Builder &builder = parser.getBuilder();
1496 OpAsmParser::UnresolvedOperand cond;
1497 Type boolType = cir::BoolType::get(builder.getContext());
1499 if (parser.parseOperand(cond) ||
1500 parser.resolveOperand(cond, boolType, result.operands))
1504 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1505 if (parser.parseRegion(*thenRegion, {}, {}))
1512 if (!parser.parseOptionalKeyword(
"else")) {
1513 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1514 if (parser.parseRegion(*elseRegion, {}, {}))
1521 if (parser.parseOptionalAttrDict(result.attributes))
1526void cir::IfOp::print(OpAsmPrinter &p) {
1527 p <<
" " << getCondition() <<
" ";
1528 mlir::Region &thenRegion = this->getThenRegion();
1529 p.printRegion(thenRegion,
1534 mlir::Region &elseRegion = this->getElseRegion();
1535 if (!elseRegion.empty()) {
1537 p.printRegion(elseRegion,
1542 p.printOptionalAttrDict(getOperation()->getAttrs());
1548 cir::YieldOp::create(builder, loc);
1556void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1557 SmallVectorImpl<RegionSuccessor> ®ions) {
1559 if (!point.isParent()) {
1560 regions.emplace_back(getOperation());
1565 Region *elseRegion = &this->getElseRegion();
1566 if (elseRegion->empty())
1567 elseRegion =
nullptr;
1570 regions.push_back(RegionSuccessor(&getThenRegion()));
1572 regions.push_back(RegionSuccessor(elseRegion));
1574 regions.emplace_back(getOperation());
1577void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1580 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1581 result.addOperands(cond);
1583 OpBuilder::InsertionGuard guard(builder);
1584 Region *thenRegion = result.addRegion();
1585 builder.createBlock(thenRegion);
1586 thenBuilder(builder, result.location);
1588 Region *elseRegion = result.addRegion();
1589 if (!withElseRegion)
1592 builder.createBlock(elseRegion);
1593 elseBuilder(builder, result.location);
1605void cir::ScopeOp::getSuccessorRegions(
1606 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1608 if (!point.isParent()) {
1609 regions.emplace_back(getOperation());
1614 regions.push_back(RegionSuccessor(&getScopeRegion()));
1617void cir::ScopeOp::build(
1618 OpBuilder &builder, OperationState &result,
1619 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1620 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1622 OpBuilder::InsertionGuard guard(builder);
1623 Region *scopeRegion = result.addRegion();
1624 builder.createBlock(scopeRegion);
1628 scopeBuilder(builder, yieldTy, result.location);
1631 result.addTypes(TypeRange{yieldTy});
1634void cir::ScopeOp::build(
1635 OpBuilder &builder, OperationState &result,
1636 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1637 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1638 OpBuilder::InsertionGuard guard(builder);
1639 Region *scopeRegion = result.addRegion();
1640 builder.createBlock(scopeRegion);
1642 scopeBuilder(builder, result.location);
1645LogicalResult cir::ScopeOp::verify() {
1647 return emitOpError() <<
"cir.scope must not be empty since it should "
1648 "include at least an implicit cir.yield ";
1651 mlir::Block &lastBlock =
getRegion().back();
1652 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1653 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1654 return emitOpError() <<
"last block of cir.scope must be terminated";
1658LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1659 SmallVectorImpl<OpFoldResult> &results) {
1664 if (block.getOperations().size() != 1)
1667 auto yield = dyn_cast<cir::YieldOp>(block.front());
1672 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1675 results.push_back(yield.getOperand(0));
1683void cir::CleanupScopeOp::getSuccessorRegions(
1684 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1685 if (!point.isParent()) {
1686 regions.emplace_back(getOperation());
1691 regions.push_back(RegionSuccessor(&getBodyRegion()));
1692 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1695LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1696 PatternRewriter &rewriter) {
1697 auto isRegionTrivial = [](Region ®ion) {
1698 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1699 if (!region.hasOneBlock())
1701 Block &block = llvm::getSingleElement(region);
1702 return llvm::hasSingleElement(block) &&
1703 isa<cir::YieldOp>(llvm::getSingleElement(block));
1706 Region &body = op.getBodyRegion();
1707 Region &
cleanup = op.getCleanupRegion();
1711 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1712 rewriter.eraseOp(op);
1718 if (!isRegionTrivial(cleanup) || !body.hasOneBlock())
1721 Block &bodyBlock = body.front();
1722 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1725 Operation *yield = bodyBlock.getTerminator();
1726 rewriter.inlineBlockBefore(&bodyBlock, op);
1727 rewriter.eraseOp(yield);
1728 rewriter.eraseOp(op);
1732void cir::CleanupScopeOp::build(
1733 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1734 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
1735 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
1736 result.addAttribute(getCleanupKindAttrName(result.name),
1737 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1739 OpBuilder::InsertionGuard guard(builder);
1742 Region *bodyRegion = result.addRegion();
1743 builder.createBlock(bodyRegion);
1745 bodyBuilder(builder, result.location);
1748 Region *cleanupRegion = result.addRegion();
1749 builder.createBlock(cleanupRegion);
1751 cleanupBuilder(builder, result.location);
1766LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1767 Block *src = op->getBlock();
1768 Block *dst = op.getDest();
1775 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1780 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1783 auto operands = op.getDestOperands();
1784 rewriter.eraseOp(op);
1785 rewriter.mergeBlocks(dst, src, operands);
1789mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1790 assert(index == 0 &&
"invalid successor index");
1791 return mlir::SuccessorOperands(getDestOperandsMutable());
1802mlir::SuccessorOperands
1803cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1804 assert(index < getNumSuccessors() &&
"invalid successor index");
1805 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1809 OpAsmParser &parser, Type &flagType,
1810 SmallVectorImpl<Block *> &succOperandBlocks,
1813 if (failed(parser.parseCommaSeparatedList(
1814 OpAsmParser::Delimiter::Square,
1816 Block *destination = nullptr;
1817 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1818 SmallVector<Type> operandTypes;
1820 if (parser.parseSuccessor(destination).failed())
1823 if (succeeded(parser.parseOptionalLParen())) {
1824 if (failed(parser.parseOperandList(
1825 operands, OpAsmParser::Delimiter::None)) ||
1826 failed(parser.parseColonTypeList(operandTypes)) ||
1827 failed(parser.parseRParen()))
1830 succOperandBlocks.push_back(destination);
1831 succOperands.emplace_back(operands);
1832 succOperandsTypes.emplace_back(operandTypes);
1835 "successor blocks")))
1841 Type flagType, SuccessorRange succs,
1842 OperandRangeRange succOperands,
1843 const TypeRangeRange &succOperandsTypes) {
1846 llvm::zip(succs, succOperands),
1849 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1852 if (!succOperands.empty())
1861mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1862 assert(index < getNumSuccessors() &&
"invalid successor index");
1863 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1864 : getDestOperandsFalseMutable());
1868 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1869 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1877void cir::CaseOp::getSuccessorRegions(
1878 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1879 if (!point.isParent()) {
1880 regions.emplace_back(getOperation());
1883 regions.push_back(RegionSuccessor(&getCaseRegion()));
1886void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1887 ArrayAttr value, CaseOpKind
kind,
1888 OpBuilder::InsertPoint &insertPoint) {
1889 OpBuilder::InsertionGuard guardSwitch(builder);
1890 result.addAttribute(
"value", value);
1891 result.getOrAddProperties<Properties>().
kind =
1892 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1893 Region *caseRegion = result.addRegion();
1894 builder.createBlock(caseRegion);
1896 insertPoint = builder.saveInsertionPoint();
1903void cir::SwitchOp::getSuccessorRegions(
1904 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1905 if (!point.isParent()) {
1906 region.emplace_back(getOperation());
1910 region.push_back(RegionSuccessor(&getBody()));
1913void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1915 assert(switchBuilder &&
"the builder callback for regions must be present");
1916 OpBuilder::InsertionGuard guardSwitch(builder);
1917 Region *switchRegion = result.addRegion();
1918 builder.createBlock(switchRegion);
1919 result.addOperands({cond});
1920 switchBuilder(builder, result.location, result);
1924 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1926 if (isa<cir::SwitchOp>(op) && op != *
this)
1927 return WalkResult::skip();
1929 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1930 cases.push_back(caseOp);
1932 return WalkResult::advance();
1937 collectCases(cases);
1939 if (getBody().empty())
1942 if (!isa<YieldOp>(getBody().front().back()))
1945 if (!llvm::all_of(getBody().front(),
1946 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1949 return llvm::all_of(cases, [
this](CaseOp op) {
1950 return op->getParentOfType<SwitchOp>() == *
this;
1958void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1959 Value value, Block *defaultDestination,
1960 ValueRange defaultOperands,
1962 BlockRange caseDestinations,
1965 std::vector<mlir::Attribute> caseValuesAttrs;
1966 for (
const APInt &val : caseValues)
1967 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1968 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1970 build(builder, result, value, defaultOperands, caseOperands, attrs,
1971 defaultDestination, caseDestinations);
1977 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1978 SmallVectorImpl<Block *> &caseDestinations,
1982 if (failed(parser.parseLSquare()))
1984 if (succeeded(parser.parseOptionalRSquare()))
1988 auto parseCase = [&]() {
1990 if (failed(parser.parseInteger(value)))
1993 values.push_back(cir::IntAttr::get(flagType, value));
1998 if (parser.parseColon() || parser.parseSuccessor(destination))
2000 if (!parser.parseOptionalLParen()) {
2001 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
2003 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
2006 caseDestinations.push_back(destination);
2007 caseOperands.emplace_back(operands);
2008 caseOperandTypes.emplace_back(operandTypes);
2011 if (failed(parser.parseCommaSeparatedList(parseCase)))
2014 caseValues = ArrayAttr::get(flagType.getContext(), values);
2016 return parser.parseRSquare();
2020 Type flagType, mlir::ArrayAttr caseValues,
2021 SuccessorRange caseDestinations,
2022 OperandRangeRange caseOperands,
2023 const TypeRangeRange &caseOperandTypes) {
2033 llvm::zip(caseValues, caseDestinations),
2036 mlir::Attribute a = std::get<0>(i);
2037 p << mlir::cast<cir::IntAttr>(a).getValue();
2039 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2054 mlir::Attribute &valueAttr) {
2056 return parser.parseAttribute(valueAttr,
"value", attr);
2060 p.printAttribute(value);
2063mlir::LogicalResult cir::GlobalOp::verify() {
2066 if (mlir::isa<cir::FuncType>(getSymType()))
2067 return emitOpError(
"global type cannot be a function type");
2071 if (getInitialValue().has_value()) {
2077 if ((getStaticLocalGuard().has_value()) &&
2078 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2080 "Cannot have a static-local global-op with a constructor or "
2081 "destructor, they require in-function initialization via LocalInitOp");
2084 if (getStaticLocalGuard().has_value())
2085 return emitOpError(
"cannot have both static local and tls references");
2087 return emitOpError(
"'tls_refs' only valid for tls");
2090 if (getAliasee().has_value()) {
2091 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2092 !getDtorRegion().empty())
2093 return emitOpError(
"global alias shall not have an initializer or "
2094 "constructor/destructor regions");
2103void cir::GlobalOp::build(
2104 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2105 mlir::Type sym_type,
bool isConstant,
2106 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2107 cir::GlobalLinkageKind linkage,
2108 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2109 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2110 odsState.addAttribute(getSymNameAttrName(odsState.name),
2111 odsBuilder.getStringAttr(sym_name));
2112 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2113 mlir::TypeAttr::get(sym_type));
2114 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2115 properties.setConstant(isConstant);
2119 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2121 cir::GlobalLinkageKindAttr linkageAttr =
2122 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2123 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2125 Region *ctorRegion = odsState.addRegion();
2127 odsBuilder.createBlock(ctorRegion);
2128 ctorBuilder(odsBuilder, odsState.location);
2131 Region *dtorRegion = odsState.addRegion();
2133 odsBuilder.createBlock(dtorRegion);
2134 dtorBuilder(odsBuilder, odsState.location);
2143void cir::GlobalOp::getSuccessorRegions(
2144 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2146 if (!point.isParent()) {
2147 regions.emplace_back(getOperation());
2152 Region *ctorRegion = &this->getCtorRegion();
2153 if (ctorRegion->empty())
2154 ctorRegion =
nullptr;
2157 Region *dtorRegion = &this->getDtorRegion();
2158 if (dtorRegion->empty())
2159 dtorRegion =
nullptr;
2163 regions.push_back(RegionSuccessor(ctorRegion));
2165 regions.push_back(RegionSuccessor(dtorRegion));
2169 TypeAttr type, Attribute initAttr,
2170 mlir::Region &ctorRegion,
2171 mlir::Region &dtorRegion) {
2172 auto printType = [&]() { p <<
": " << type; };
2175 if (op.isDeclaration() || op.getAliasee()) {
2181 if (!ctorRegion.empty()) {
2185 p.printRegion(ctorRegion,
2194 if (!dtorRegion.empty()) {
2196 p.printRegion(dtorRegion,
2204 Attribute &initialValueAttr,
2205 mlir::Region &ctorRegion,
2206 mlir::Region &dtorRegion) {
2208 if (parser.parseOptionalEqual().failed()) {
2211 if (parser.parseColonType(opTy))
2216 if (!parser.parseOptionalKeyword(
"ctor")) {
2217 if (parser.parseColonType(opTy))
2219 auto parseLoc = parser.getCurrentLocation();
2220 if (parser.parseRegion(ctorRegion, {}, {}))
2231 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2232 "Non-typed attrs shouldn't appear here.");
2233 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2238 if (!parser.parseOptionalKeyword(
"dtor")) {
2239 auto parseLoc = parser.getCurrentLocation();
2240 if (parser.parseRegion(dtorRegion, {}, {}))
2247 typeAttr = TypeAttr::get(opTy);
2256cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2259 mlir::Operation *op =
2260 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2261 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2262 return emitOpError(
"'")
2264 <<
"' does not reference a valid cir.global or cir.func";
2267 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2268 if (
auto g = dyn_cast<GlobalOp>(op)) {
2269 symTy = g.getSymType();
2270 symAddrSpaceAttr = g.getAddrSpaceAttr();
2273 if (getTls() && !g.getTlsModel())
2274 return emitOpError(
"access to global not marked thread local");
2279 bool getGlobalIsStaticLocal = getStaticLocal();
2280 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2281 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2282 !getOperation()->getParentOfType<cir::GlobalOp>())
2283 return emitOpError(
"static_local attribute mismatch");
2284 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2285 symTy = f.getFunctionType();
2287 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2290 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2291 if (!resultType || symTy != resultType.getPointee())
2292 return emitOpError(
"result type pointee type '")
2293 << resultType.getPointee() <<
"' does not match type " << symTy
2294 <<
" of the global @" <<
getName();
2296 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2297 return emitOpError()
2298 <<
"result type address space does not match the address "
2299 "space of the global @"
2311cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2317 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2319 return emitOpError(
"'")
2320 <<
name <<
"' does not reference a valid cir.global";
2321 std::optional<mlir::Attribute> init = op.getInitialValue();
2324 if (!isa<cir::VTableAttr>(*init))
2325 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2335cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2344 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2346 return emitOpError(
"'")
2347 <<
name <<
"' does not reference a valid cir.global";
2348 std::optional<mlir::Attribute> init = op.getInitialValue();
2351 if (!isa<cir::ConstArrayAttr>(*init))
2353 "Expected constant array in initializer for global VTT '")
2358LogicalResult cir::VTTAddrPointOp::verify() {
2360 if (
getName() && getSymAddr())
2361 return emitOpError(
"should use either a symbol or value, but not both");
2367 mlir::Type resultType = getAddr().getType();
2368 mlir::Type resTy = cir::PointerType::get(
2369 cir::PointerType::get(cir::VoidType::get(getContext())));
2371 if (resultType != resTy)
2372 return emitOpError(
"result type must be ")
2373 << resTy <<
", but provided result type is " << resultType;
2385void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2386 StringRef name, FuncType type,
2387 GlobalLinkageKind linkage, CallingConv callingConv) {
2389 result.addAttribute(getSymNameAttrName(result.name),
2390 builder.getStringAttr(name));
2391 result.addAttribute(getFunctionTypeAttrName(result.name),
2392 TypeAttr::get(type));
2393 result.addAttribute(
2395 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2396 result.addAttribute(getCallingConvAttrName(result.name),
2397 CallingConvAttr::get(builder.getContext(), callingConv));
2405cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2406 mlir::StringAttr name, mlir::ArrayAttr args) {
2409 for (mlir::Attribute arg : args) {
2410 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2411 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2417ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2418 llvm::SMLoc loc = parser.getCurrentLocation();
2419 mlir::Builder &builder = parser.getBuilder();
2421 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2422 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2423 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2424 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2425 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2426 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2427 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2428 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2429 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
2431 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2432 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2433 if (::mlir::succeeded(
2434 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2435 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2438 cir::InlineKindAttr inlineKindAttr;
2442 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2444 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2445 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2446 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2447 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2449 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2450 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2454 GlobalLinkageKindAttr::get(
2455 parser.getContext(),
2457 parser, GlobalLinkageKind::ExternalLinkage)));
2459 ::llvm::StringRef visAttrStr;
2460 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2462 state.addAttribute(visNameAttr,
2463 parser.getBuilder().getStringAttr(visAttrStr));
2466 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2469 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2470 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2472 StringAttr nameAttr;
2473 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(state.name),
2479 bool isVariadic =
false;
2480 if (function_interface_impl::parseFunctionSignatureWithArguments(
2481 parser,
true, arguments, isVariadic, resultTypes,
2486 bool argAttrsEmpty =
true;
2487 for (OpAsmParser::Argument &arg : arguments) {
2488 argTypes.push_back(
arg.type);
2492 argAttrs.push_back(
arg.attrs);
2494 argAttrsEmpty =
false;
2498 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2499 return parser.emitError(
2500 loc,
"functions with multiple return types are not supported");
2502 mlir::Type returnType =
2503 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2504 : resultTypes.front());
2506 cir::FuncType fnType =
2507 cir::FuncType::getChecked([&]() {
return parser.emitError(loc); },
2508 argTypes, returnType, isVariadic);
2512 state.addAttribute(getFunctionTypeAttrName(state.name),
2513 TypeAttr::get(fnType));
2515 if (!resultAttrs.empty() && resultAttrs[0])
2517 getResAttrsAttrName(state.name),
2518 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2521 state.addAttribute(getArgAttrsAttrName(state.name),
2522 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2524 bool hasAlias =
false;
2525 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2526 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2527 if (parser.parseLParen().failed())
2529 mlir::StringAttr aliaseeAttr;
2530 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2532 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2533 if (parser.parseRParen().failed())
2538 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2539 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2540 if (parser.parseLParen().failed())
2542 mlir::StringAttr personalityAttr;
2543 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2545 state.addAttribute(personalityNameAttr,
2546 FlatSymbolRefAttr::get(personalityAttr));
2547 if (parser.parseRParen().failed())
2552 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2553 cir::CallingConv callConv = cir::CallingConv::C;
2554 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2555 if (parser.parseLParen().failed())
2558 return parser.emitError(loc) <<
"unknown calling convention";
2559 if (parser.parseRParen().failed())
2562 state.addAttribute(callConvNameAttr,
2563 cir::CallingConvAttr::get(parser.getContext(), callConv));
2565 auto parseGlobalDtorCtor =
2566 [&](StringRef keyword,
2567 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2568 -> mlir::LogicalResult {
2569 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2570 std::optional<int> priority;
2571 if (mlir::succeeded(parser.parseOptionalLParen())) {
2572 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2573 if (mlir::failed(parsedPriority))
2574 return parser.emitError(parser.getCurrentLocation(),
2575 "failed to parse 'priority', of type 'int'");
2576 priority = parsedPriority.value_or(
int());
2578 if (parser.parseRParen())
2581 createAttr(priority);
2587 if (parser.parseOptionalKeyword(
"func_info").succeeded()) {
2588 if (parser.parseLess().failed())
2591 llvm::SMLoc attrLoc = parser.getCurrentLocation();
2592 mlir::Attribute
attr;
2593 if (parser.parseAttribute(attr).failed())
2595 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
2596 cir::FuncIdentityAttr>(attr))
2597 return parser.emitError(attrLoc,
2598 "expected a function info attribute, got ")
2600 state.addAttribute(funcInfoNameAttr, attr);
2602 if (parser.parseGreater().failed())
2606 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2607 mlir::IntegerAttr globalCtorPriorityAttr =
2608 builder.getI32IntegerAttr(priority.value_or(65535));
2609 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2610 globalCtorPriorityAttr);
2614 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2615 mlir::IntegerAttr globalDtorPriorityAttr =
2616 builder.getI32IntegerAttr(priority.value_or(65535));
2617 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2618 globalDtorPriorityAttr);
2622 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2623 cir::SideEffect sideEffect;
2625 if (parser.parseLParen().failed() ||
2627 parser.parseRParen().failed())
2630 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2631 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2635 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2636 mlir::ArrayAttr annotationsAttr;
2637 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2639 state.addAttribute(annotationsNameAttr, annotationsAttr);
2642 NamedAttrList parsedAttrs;
2643 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2646 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2647 if (parsedAttrs.get(disallowed))
2648 return parser.emitError(loc,
"attribute '")
2650 <<
"' should not be specified in the explicit attribute list";
2653 state.attributes.append(parsedAttrs);
2656 auto *body = state.addRegion();
2657 OptionalParseResult parseResult = parser.parseOptionalRegion(
2658 *body, arguments,
false);
2659 if (parseResult.has_value()) {
2661 return parser.emitError(loc,
"function alias shall not have a body");
2662 if (failed(*parseResult))
2666 return parser.emitError(loc,
"expected non-empty function body");
2675bool cir::FuncOp::isDeclaration() {
2678 std::optional<StringRef> aliasee = getAliasee();
2680 return getFunctionBody().empty();
2686bool cir::FuncOp::isCXXSpecialMemberFunction() {
2689 mlir::Attribute
attr = getFuncInfoAttr();
2690 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
2693bool cir::FuncOp::isCxxConstructor() {
2694 auto attr = getFuncInfoAttr();
2695 return attr && dyn_cast<CXXCtorAttr>(attr);
2698bool cir::FuncOp::isCxxDestructor() {
2699 auto attr = getFuncInfoAttr();
2700 return attr && dyn_cast<CXXDtorAttr>(attr);
2703bool cir::FuncOp::isCxxSpecialAssignment() {
2704 auto attr = getFuncInfoAttr();
2705 return attr && dyn_cast<CXXAssignAttr>(attr);
2708std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2709 mlir::Attribute
attr = getFuncInfoAttr();
2711 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2712 return ctor.getCtorKind();
2714 return std::nullopt;
2717std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2718 mlir::Attribute
attr = getFuncInfoAttr();
2720 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2721 return assign.getAssignKind();
2723 return std::nullopt;
2726bool cir::FuncOp::isCxxTrivialMemberFunction() {
2727 mlir::Attribute
attr = getFuncInfoAttr();
2729 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2730 return ctor.getIsTrivial();
2731 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2732 return dtor.getIsTrivial();
2733 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2734 return assign.getIsTrivial();
2739mlir::Region *cir::FuncOp::getCallableRegion() {
2745void cir::FuncOp::print(OpAsmPrinter &p) {
2763 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2764 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2766 mlir::SymbolTable::Visibility vis = getVisibility();
2767 if (vis != mlir::SymbolTable::Visibility::Public)
2770 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2771 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
2777 p.printSymbolName(getSymName());
2778 cir::FuncType fnType = getFunctionType();
2779 function_interface_impl::printFunctionSignature(
2780 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2782 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2784 p.printSymbolName(*aliaseeName);
2788 if (getCallingConv() != cir::CallingConv::C) {
2790 p << stringifyCallingConv(getCallingConv());
2794 if (std::optional<StringRef> personalityName = getPersonality()) {
2795 p <<
" personality(";
2796 p.printSymbolName(*personalityName);
2800 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
2802 p.printAttribute(funcInfo);
2806 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2807 p <<
" global_ctor";
2808 if (globalCtorPriority.value() != 65535)
2809 p <<
"(" << globalCtorPriority.value() <<
")";
2812 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2813 p <<
" global_dtor";
2814 if (globalDtorPriority.value() != 65535)
2815 p <<
"(" << globalDtorPriority.value() <<
")";
2818 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2819 sideEffect && *sideEffect != cir::SideEffect::All) {
2820 p <<
" side_effect(";
2821 p << stringifySideEffect(*sideEffect);
2825 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2827 p.printAttribute(annotations);
2830 function_interface_impl::printFunctionAttributes(
2831 p, *
this, cir::FuncOp::getAttributeNames());
2834 Region &body = getOperation()->getRegion(0);
2835 if (!body.empty()) {
2837 p.printRegion(body,
false,
2842mlir::LogicalResult cir::FuncOp::verify() {
2844 if (!isDeclaration() && getCoroutine()) {
2845 bool foundAwait =
false;
2846 int coroBodyCount = 0;
2847 this->walk([&](Operation *op) {
2848 if (
auto await = dyn_cast<AwaitOp>(op)) {
2850 }
else if (isa<CoroBodyOp>(op)) {
2852 if (coroBodyCount > 1) {
2853 return mlir::WalkResult::interrupt();
2856 return mlir::WalkResult::advance();
2859 return emitOpError()
2860 <<
"coroutine body must use at least one cir.await op";
2861 if (coroBodyCount != 1)
2862 return emitOpError()
2863 <<
"coroutine function must have exactly one cir.body op";
2866 llvm::SmallSet<llvm::StringRef, 16> labels;
2867 llvm::SmallSet<llvm::StringRef, 16> gotos;
2868 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2869 bool invalidBlockAddress =
false;
2870 getOperation()->walk([&](mlir::Operation *op) {
2871 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2872 labels.insert(lab.getLabel());
2873 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2874 gotos.insert(goTo.getLabel());
2875 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2876 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2878 invalidBlockAddress =
true;
2879 return mlir::WalkResult::interrupt();
2881 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2883 return mlir::WalkResult::advance();
2886 if (invalidBlockAddress)
2887 return emitOpError() <<
"blockaddress references a different function";
2889 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2890 if (!labels.empty() || !gotos.empty()) {
2891 mismatched = llvm::set_difference(gotos, labels);
2893 if (!mismatched.empty())
2894 return emitOpError() <<
"goto/label mismatch";
2899 if (!labels.empty() || !blockAddresses.empty()) {
2900 mismatched = llvm::set_difference(blockAddresses, labels);
2902 if (!mismatched.empty())
2903 return emitOpError()
2904 <<
"expects an existing label target in the referenced function";
2918LogicalResult cir::AddOp::verify() {
2919 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2920 return emitOpError()
2921 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2922 return mlir::success();
2925LogicalResult cir::SubOp::verify() {
2926 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2927 return emitOpError()
2928 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2929 return mlir::success();
2941void cir::TernaryOp::getSuccessorRegions(
2942 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2944 if (!point.isParent()) {
2945 regions.emplace_back(getOperation());
2951 regions.push_back(RegionSuccessor(&getTrueRegion()));
2952 regions.push_back(RegionSuccessor(&getFalseRegion()));
2955void cir::TernaryOp::build(
2956 OpBuilder &builder, OperationState &result,
Value cond,
2957 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2958 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2959 result.addOperands(cond);
2960 OpBuilder::InsertionGuard guard(builder);
2961 Region *trueRegion = result.addRegion();
2962 builder.createBlock(trueRegion);
2963 trueBuilder(builder, result.location);
2964 Region *falseRegion = result.addRegion();
2965 builder.createBlock(falseRegion);
2966 falseBuilder(builder, result.location);
2971 if (trueRegion->back().mightHaveTerminator())
2972 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2973 if (!yield && falseRegion->back().mightHaveTerminator())
2974 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2976 assert((!yield || yield.getNumOperands() <= 1) &&
2977 "expected zero or one result type");
2978 if (yield && yield.getNumOperands() == 1)
2979 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2986OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2987 mlir::Attribute
condition = adaptor.getCondition();
2989 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2990 return conditionValue ? getTrueValue() : getFalseValue();
2994 mlir::Attribute trueValue = adaptor.getTrueValue();
2995 mlir::Attribute falseValue = adaptor.getFalseValue();
2996 if (trueValue == falseValue)
2998 if (getTrueValue() == getFalseValue())
2999 return getTrueValue();
3004LogicalResult cir::SelectOp::verify() {
3006 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
3013 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
3014 !isa<cir::VectorType>(getFalseValue().
getType())) {
3015 return emitOpError()
3016 <<
"expected both true and false operands to be vector types "
3017 "when the condition is a vector boolean type";
3026LogicalResult cir::ShiftOp::verify() {
3027 mlir::Operation *op = getOperation();
3028 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3029 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3030 if (!op0VecTy ^ !op1VecTy)
3031 return emitOpError() <<
"input types cannot be one vector and one scalar";
3034 if (op0VecTy.getSize() != op1VecTy.getSize())
3035 return emitOpError() <<
"input vector types must have the same size";
3037 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
3039 return emitOpError() <<
"the type of the result must be a vector "
3040 <<
"if it is vector shift";
3042 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3043 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3044 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3045 return emitOpError()
3046 <<
"vector operands do not have the same elements sizes";
3048 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3049 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3050 return emitOpError() <<
"vector operands and result type do not have the "
3051 "same elements sizes";
3054 return mlir::success();
3061LogicalResult cir::LabelOp::verify() {
3062 mlir::Operation *op = getOperation();
3063 mlir::Block *blk = op->getBlock();
3064 if (&blk->front() != op)
3065 return emitError() <<
"must be the first operation in a block";
3067 return mlir::success();
3074OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3075 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3076 return adaptor.getInput();
3084OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3085 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3086 return adaptor.getInput();
3094OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3095 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3096 return adaptor.getInput();
3101 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3102 APInt val = intAttr.getValue();
3104 return cir::IntAttr::get(
getType(), val);
3114OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3115 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3116 return adaptor.getInput();
3120 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3121 APFloat val = fpAttr.getValue();
3123 return cir::FPAttr::get(
getType(), val);
3133OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3134 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3135 return adaptor.getInput();
3140 if (mlir::Attribute attr = adaptor.getInput()) {
3141 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3142 APInt val = intAttr.getValue();
3144 return cir::IntAttr::get(
getType(), val);
3146 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3147 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3158 mlir::Type resultTy) {
3161 mlir::Type inputMemberTy;
3162 mlir::Type resultMemberTy;
3163 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3165 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3166 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3169 if (inputMemberTy != resultMemberTy)
3170 return op->emitOpError()
3171 <<
"member types of the operand and the result do not match";
3173 return mlir::success();
3176LogicalResult cir::BaseDataMemberOp::verify() {
3180LogicalResult cir::DerivedDataMemberOp::verify() {
3188LogicalResult cir::BaseMethodOp::verify() {
3192LogicalResult cir::DerivedMethodOp::verify() {
3200void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3204 result.addAttribute(getKindAttrName(result.name),
3205 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3207 OpBuilder::InsertionGuard guard(builder);
3208 Region *readyRegion = result.addRegion();
3209 builder.createBlock(readyRegion);
3210 readyBuilder(builder, result.location);
3214 OpBuilder::InsertionGuard guard(builder);
3215 Region *suspendRegion = result.addRegion();
3216 builder.createBlock(suspendRegion);
3217 suspendBuilder(builder, result.location);
3221 OpBuilder::InsertionGuard guard(builder);
3222 Region *resumeRegion = result.addRegion();
3223 builder.createBlock(resumeRegion);
3224 resumeBuilder(builder, result.location);
3228void cir::AwaitOp::getSuccessorRegions(
3229 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3230 assert(point.isParent() || point.getTerminatorPredecessorOrNull());
3233 if (point.isParent()) {
3234 regions.emplace_back(&getReady());
3238 mlir::Region *parentRegion =
3239 point.getTerminatorPredecessorOrNull()->getParentRegion();
3248 if (&getReady() == parentRegion) {
3249 regions.emplace_back(&getResume());
3250 regions.emplace_back(&getSuspend());
3255 regions.emplace_back(getOperation());
3258LogicalResult cir::AwaitOp::verify() {
3259 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3260 return emitOpError(
"ready region must end with cir.condition");
3268void cir::CoroBodyOp::getSuccessorRegions(
3269 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3270 if (!point.isParent()) {
3271 regions.emplace_back(getOperation());
3275 regions.push_back(RegionSuccessor(&getBody()));
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);
3303 mlir::Type srcType, mlir::Type dstType) {
3304 printer.printType(srcType);
3305 if (srcType != dstType) {
3307 printer.printType(dstType);
3312 mlir::Type &srcType,
3313 mlir::Type &dstType) {
3314 if (parser.parseType(srcType))
3315 return mlir::failure();
3316 if (parser.parseOptionalComma().succeeded()) {
3317 if (parser.parseType(dstType))
3318 return mlir::failure();
3322 return mlir::success();
3325LogicalResult cir::CopyOp::verify() {
3330 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3331 return emitError() <<
"missing data layout for pointee type";
3333 if (getSkipTailPadding() &&
3334 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3336 <<
"skip_tail_padding is only valid for record pointee types";
3338 return mlir::success();
3345LogicalResult cir::GetRuntimeMemberOp::verify() {
3346 cir::DataMemberType memberPtrTy = getMember().getType();
3348 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
3349 return emitError() <<
"record type does not match the member pointer type";
3350 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3351 return emitError() <<
"result type does not match the member pointer type";
3352 return mlir::success();
3359LogicalResult cir::GetMethodOp::verify() {
3360 cir::MethodType methodTy = getMethod().getType();
3363 cir::PointerType objectPtrTy = getObject().getType();
3364 mlir::Type objectTy = objectPtrTy.getPointee();
3366 if (methodTy.getClassTy() != objectTy)
3367 return emitError() <<
"method class type and object type do not match";
3370 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3371 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3378 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3380 <<
"method return type and callee return type do not match";
3385 if (calleeArgsTy.empty())
3386 return emitError() <<
"callee parameter list lacks receiver object ptr";
3388 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3389 if (!calleeThisArgPtrTy ||
3390 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3392 <<
"the first parameter of callee must be a void pointer";
3395 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3396 return emitError() <<
"callee and method parameter counts do not match";
3398 if (calleeArgsTy.size() > 1 &&
3399 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3401 <<
"callee parameters and method parameters do not match";
3403 return mlir::success();
3414LogicalResult cir::GetMemberOp::verify() {
3415 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3417 return emitError() <<
"expected pointer to a record type";
3419 if (recordTy.getMembers().size() <=
getIndex())
3420 return emitError() <<
"member index out of bounds";
3424 return emitError() <<
"member owns no storage to point at";
3426 if (pointeeTy !=
getType().getPointee())
3427 return emitError() <<
"member type mismatch";
3429 return mlir::success();
3436LogicalResult cir::ExtractMemberOp::verify() {
3437 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3439 <<
"cir.extract_member currently does not support unions";
3440 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3441 if (structTy.getMembers().size() <=
getIndex())
3442 return emitError() <<
"member index out of bounds";
3443 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
3444 if (mlir::isa<cir::BitFieldType>(memberTy))
3445 return emitError() <<
"cir.extract_member does not support bit-fields";
3447 return emitError() <<
"member type mismatch";
3448 return mlir::success();
3455LogicalResult cir::InsertMemberOp::verify() {
3456 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3457 return emitError() <<
"cir.insert_member currently does not support unions";
3458 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3459 if (structTy.getMembers().size() <=
getIndex())
3460 return emitError() <<
"member index out of bounds";
3461 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
3462 if (mlir::isa<cir::BitFieldType>(memberTy))
3463 return emitError() <<
"cir.insert_member does not support bit-fields";
3464 if (memberTy != getValue().
getType())
3465 return emitError() <<
"member type mismatch";
3467 return mlir::success();
3474OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3475 if (llvm::any_of(getElements(), [](mlir::Value value) {
3476 return !value.getDefiningOp<cir::ConstantOp>();
3480 return cir::ConstVectorAttr::get(
3481 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3484LogicalResult cir::VecCreateOp::verify() {
3488 const cir::VectorType vecTy =
getType();
3489 if (getElements().size() != vecTy.getSize()) {
3490 return emitOpError() <<
"operand count of " << getElements().size()
3491 <<
" doesn't match vector type " << vecTy
3492 <<
" element count of " << vecTy.getSize();
3495 const mlir::Type elementType = vecTy.getElementType();
3496 for (
const mlir::Value element : getElements()) {
3497 if (element.getType() != elementType) {
3498 return emitOpError() <<
"operand type " << element.getType()
3499 <<
" doesn't match vector element type "
3511OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3512 const auto vectorAttr =
3513 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3517 const auto indexAttr =
3518 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3522 const mlir::ArrayAttr elements = vectorAttr.getElts();
3523 const uint64_t index = indexAttr.getUInt();
3524 if (index >= elements.size())
3527 return elements[index];
3534LogicalResult cir::CmpOp::verify() {
3535 if (getFenvAttr() && !cir::isAnyFloatingPointType(getLhs().
getType()))
3536 return emitOpError()
3537 <<
"'fenv' is only valid for floating-point comparisons";
3545LogicalResult cir::VecCmpOp::verify() {
3546 if (getFenvAttr() && !cir::isFPOrVectorOfFPType(getLhs().
getType()))
3547 return emitOpError()
3548 <<
"'fenv' is only valid for floating-point comparisons";
3552OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3562 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3564 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3565 if (!lhsVecAttr || !rhsVecAttr)
3568 mlir::Type inputElemTy =
3569 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3570 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3573 cir::CmpOpKind opKind = adaptor.getKind();
3574 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3575 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3576 uint64_t vecSize = lhsVecElhs.size();
3579 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3580 bool isUnsignedInt =
3581 isIntAttr && mlir::cast<cir::IntType>(inputElemTy).isUnsigned();
3582 for (uint64_t i = 0; i < vecSize; i++) {
3583 mlir::Attribute lhsAttr = lhsVecElhs[i];
3584 mlir::Attribute rhsAttr = rhsVecElhs[i];
3585 bool cmpResult =
false;
3587 case cir::CmpOpKind::lt: {
3590 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
3591 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3593 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3594 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3596 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3597 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3601 case cir::CmpOpKind::le: {
3604 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
3605 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3607 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3608 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3610 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3611 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3615 case cir::CmpOpKind::gt: {
3618 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
3619 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3621 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3622 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3624 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3625 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3629 case cir::CmpOpKind::ge: {
3632 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
3633 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
3635 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3636 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3638 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3639 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3643 case cir::CmpOpKind::eq: {
3645 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3646 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3648 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3649 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3653 case cir::CmpOpKind::ne: {
3655 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3656 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3658 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3659 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3663 case cir::CmpOpKind::one: {
3664 llvm::APFloat::cmpResult cr =
3665 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3666 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3668 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3671 case cir::CmpOpKind::uno: {
3672 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3673 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3674 llvm::APFloat::cmpUnordered;
3683 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL);
3686 return cir::ConstVectorAttr::get(
3687 getType(), mlir::ArrayAttr::get(getContext(), elements));
3694OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3696 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3698 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3699 if (!vec1Attr || !vec2Attr)
3702 mlir::Type vec1ElemTy =
3703 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3705 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3706 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3707 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3710 elements.reserve(indicesElts.size());
3712 uint64_t vec1Size = vec1Elts.size();
3713 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3714 if (idxAttr.getSInt() == -1) {
3715 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3719 uint64_t idxValue = idxAttr.getUInt();
3720 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3721 : vec2Elts[idxValue - vec1Size]);
3724 return cir::ConstVectorAttr::get(
3725 getType(), mlir::ArrayAttr::get(getContext(), elements));
3728LogicalResult cir::VecShuffleOp::verify() {
3731 if (getIndices().size() != getResult().
getType().getSize()) {
3732 return emitOpError() <<
": the number of elements in " << getIndices()
3733 <<
" and " << getResult().getType() <<
" don't match";
3738 if (getVec1().
getType().getElementType() !=
3739 getResult().
getType().getElementType()) {
3740 return emitOpError() <<
": element types of " << getVec1().getType()
3741 <<
" and " << getResult().getType() <<
" don't match";
3744 const uint64_t maxValidIndex =
3745 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3747 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3748 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3750 return emitOpError() <<
": index for __builtin_shufflevector must be "
3751 "less than the total number of vector elements";
3760OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3761 mlir::Attribute vec = adaptor.getVec();
3762 mlir::Attribute indices = adaptor.getIndices();
3763 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3764 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3765 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3766 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3768 mlir::ArrayAttr vecElts = vecAttr.getElts();
3769 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3771 const uint64_t numElements = vecElts.size();
3774 elements.reserve(numElements);
3776 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3777 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3778 uint64_t idxValue = idxAttr.getUInt();
3779 uint64_t newIdx = idxValue & maskBits;
3780 elements.push_back(vecElts[newIdx]);
3783 return cir::ConstVectorAttr::get(
3784 getType(), mlir::ArrayAttr::get(getContext(), elements));
3790LogicalResult cir::VecShuffleDynamicOp::verify() {
3792 if (getVec().
getType().getSize() !=
3793 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3794 return emitOpError() <<
": the number of elements in " << getVec().getType()
3795 <<
" and " << getIndices().getType() <<
" don't match";
3804LogicalResult cir::VecTernaryOp::verify() {
3809 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3810 return emitOpError() <<
": the number of elements in "
3811 << getCond().getType() <<
" and " << getLhs().getType()
3817OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3818 mlir::Attribute cond = adaptor.getCond();
3819 mlir::Attribute lhs = adaptor.getLhs();
3820 mlir::Attribute rhs = adaptor.getRhs();
3822 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3823 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3824 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3826 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3827 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3828 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3830 mlir::ArrayAttr condElts = condVec.getElts();
3833 elements.reserve(condElts.size());
3835 for (
const auto &[idx, condAttr] :
3836 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3837 if (condAttr.getSInt()) {
3838 elements.push_back(lhsVec.getElts()[idx]);
3840 elements.push_back(rhsVec.getElts()[idx]);
3844 cir::VectorType vecTy = getLhs().getType();
3845 return cir::ConstVectorAttr::get(
3846 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3853LogicalResult cir::ComplexCreateOp::verify() {
3856 <<
"operand type of cir.complex.create does not match its result type";
3863OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3864 mlir::Attribute real = adaptor.getReal();
3865 mlir::Attribute imag = adaptor.getImag();
3871 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3872 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3873 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3880LogicalResult cir::ComplexRealOp::verify() {
3881 mlir::Type operandTy = getOperand().getType();
3882 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3883 operandTy = complexOperandTy.getElementType();
3886 emitOpError() <<
": result type does not match operand type";
3893OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3894 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3897 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3898 return complexCreateOp.getOperand(0);
3901 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3902 return complex ? complex.getReal() :
nullptr;
3909LogicalResult cir::ComplexImagOp::verify() {
3910 mlir::Type operandTy = getOperand().getType();
3911 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3912 operandTy = complexOperandTy.getElementType();
3915 emitOpError() <<
": result type does not match operand type";
3922OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3923 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3926 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3927 return complexCreateOp.getOperand(1);
3930 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3931 return complex ? complex.getImag() :
nullptr;
3938LogicalResult cir::ComplexRealPtrOp::verify() {
3939 mlir::Type resultPointeeTy =
getType().getPointee();
3940 cir::PointerType operandPtrTy = getOperand().getType();
3941 auto operandPointeeTy =
3942 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3944 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3945 return emitOpError() <<
": result type does not match operand type";
3955LogicalResult cir::ComplexImagPtrOp::verify() {
3956 mlir::Type resultPointeeTy =
getType().getPointee();
3957 cir::PointerType operandPtrTy = getOperand().getType();
3958 auto operandPointeeTy =
3959 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3961 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3962 return emitOpError()
3963 <<
"cir.complex.imag_ptr result type does not match operand type";
3974 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3975 bool poisonZero =
false) {
3976 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3981 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3985 llvm::APInt inputValue = input.getValue();
3986 if (poisonZero && inputValue.isZero())
3987 return cir::PoisonAttr::get(input.getType());
3989 llvm::APInt resultValue = func(inputValue);
3990 return IntAttr::get(input.getType(), resultValue);
3993OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3994 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3995 unsigned resultValue =
3996 inputValue.getBitWidth() - inputValue.getSignificantBits();
3997 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4001OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
4004 [](
const llvm::APInt &inputValue) {
4005 unsigned resultValue = inputValue.countLeadingZeros();
4006 return llvm::APInt(inputValue.getBitWidth(), resultValue);
4011OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
4014 [](
const llvm::APInt &inputValue) {
4015 return llvm::APInt(inputValue.getBitWidth(),
4016 inputValue.countTrailingZeros());
4021OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
4022 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4023 unsigned trailingZeros = inputValue.countTrailingZeros();
4025 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
4026 return llvm::APInt(inputValue.getBitWidth(), result);
4030OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
4031 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4032 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
4036OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
4037 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4038 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
4042OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
4043 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4044 return inputValue.reverseBits();
4048OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
4049 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
4050 return inputValue.byteSwap();
4054OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
4055 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
4056 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
4058 return cir::PoisonAttr::get(
getType());
4061 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
4062 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
4063 if (!input && !amount)
4072 llvm::APInt inputValue;
4074 inputValue = input.getValue();
4075 if (inputValue.isZero() || inputValue.isAllOnes()) {
4081 uint64_t amountValue;
4083 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
4084 if (amountValue == 0) {
4090 if (!input || !amount)
4093 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
4094 "input value must have the same bit width as the input type");
4096 llvm::APInt resultValue;
4098 resultValue = inputValue.rotl(amountValue);
4100 resultValue = inputValue.rotr(amountValue);
4102 return IntAttr::get(input.getContext(), input.getType(), resultValue);
4109void cir::InlineAsmOp::print(OpAsmPrinter &p) {
4110 p <<
'(' << getAsmFlavor() <<
", ";
4115 auto *nameIt = names.begin();
4116 auto *attrIt = getOperandAttrs().begin();
4118 for (mlir::OperandRange ops : getAsmOperands()) {
4119 p << *nameIt <<
" = ";
4122 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
4124 p.printOperand(value);
4125 p <<
" : " << value.getType();
4126 if (mlir::isa<mlir::UnitAttr>(*attrIt))
4127 p <<
" (maybe_memory)";
4136 p.printString(getAsmString());
4138 p.printString(getConstraints());
4142 if (getSideEffects())
4143 p <<
" side_effects";
4145 std::array elidedAttrs{
4146 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
4147 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
4148 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
4149 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
4151 if (
auto v = getRes())
4152 p <<
" -> " << v.getType();
4155void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
4157 StringRef asmString, StringRef constraints,
4158 bool sideEffects, cir::AsmFlavor asmFlavor,
4162 for (
auto operandRange : asmOperands) {
4163 segments.push_back(operandRange.size());
4164 odsState.addOperands(operandRange);
4167 odsState.addAttribute(
4168 "operands_segments",
4169 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
4170 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
4171 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
4172 odsState.addAttribute(
"asm_flavor",
4173 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4176 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
4178 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4181ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4182 OperationState &result) {
4185 std::string asmString, constraints;
4187 MLIRContext *ctxt = parser.getBuilder().getContext();
4189 auto error = [&](
const Twine &msg) -> LogicalResult {
4190 return parser.emitError(parser.getCurrentLocation(), msg);
4193 auto expected = [&](
const std::string &c) {
4194 return error(
"expected '" + c +
"'");
4197 if (parser.parseLParen().failed())
4198 return expected(
"(");
4200 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4202 return error(
"Unknown AsmFlavor");
4204 if (parser.parseComma().failed())
4205 return expected(
",");
4207 auto parseValue = [&](
Value &v) {
4208 OpAsmParser::UnresolvedOperand op;
4210 if (parser.parseOperand(op) || parser.parseColon())
4211 return error(
"can't parse operand");
4214 if (parser.parseType(typ).failed())
4215 return error(
"can't parse operand type");
4217 if (parser.resolveOperand(op, typ, tmp))
4218 return error(
"can't resolve operand");
4220 return mlir::success();
4223 auto parseOperands = [&](llvm::StringRef
name) {
4224 if (parser.parseKeyword(name).failed())
4225 return error(
"expected " + name +
" operands here");
4226 if (parser.parseEqual().failed())
4227 return expected(
"=");
4228 if (parser.parseLSquare().failed())
4229 return expected(
"[");
4232 if (parser.parseOptionalRSquare().succeeded()) {
4233 operandsGroupSizes.push_back(size);
4234 if (parser.parseComma())
4235 return expected(
",");
4236 return mlir::success();
4239 auto parseOperand = [&]() {
4241 if (parseValue(val).succeeded()) {
4242 result.operands.push_back(val);
4245 if (parser.parseOptionalLParen().failed()) {
4246 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4247 return mlir::success();
4250 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4251 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4252 if (parser.parseRParen())
4253 return expected(
")");
4254 return mlir::success();
4256 return expected(
"maybe_memory");
4259 return mlir::failure();
4262 if (parser.parseCommaSeparatedList(parseOperand).failed())
4263 return mlir::failure();
4265 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4266 return expected(
"]");
4267 operandsGroupSizes.push_back(size);
4268 return mlir::success();
4271 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4272 parseOperands(
"in_out").failed())
4273 return error(
"failed to parse operands");
4275 if (parser.parseLBrace())
4276 return expected(
"{");
4277 if (parser.parseString(&asmString))
4278 return error(
"asm string parsing failed");
4279 if (parser.parseString(&constraints))
4280 return error(
"constraints string parsing failed");
4281 if (parser.parseRBrace())
4282 return expected(
"}");
4283 if (parser.parseRParen())
4284 return expected(
")");
4286 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4287 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4289 if (parser.parseOptionalAttrDict(result.attributes).failed())
4290 return mlir::failure();
4292 if (parser.parseOptionalArrow().succeeded() &&
4293 parser.parseType(resType).failed())
4294 return mlir::failure();
4296 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4297 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4298 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4299 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4300 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4301 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4303 result.addTypes(TypeRange{resType});
4305 return mlir::success();
4312template <
typename ThrowOpTy>
4315 return mlir::success();
4317 if (op.getNumOperands() != 0) {
4318 if (op.getTypeInfo())
4319 return mlir::success();
4320 return op.emitOpError() <<
"'type_info' symbol attribute missing";
4323 return mlir::failure();
4328mlir::LogicalResult cir::TryThrowOp::verify() {
4336LogicalResult cir::AtomicFetchOp::verify() {
4337 if (getBinop() != cir::AtomicFetchKind::Add &&
4338 getBinop() != cir::AtomicFetchKind::Sub &&
4339 getBinop() != cir::AtomicFetchKind::Max &&
4340 getBinop() != cir::AtomicFetchKind::Min &&
4341 getBinop() != cir::AtomicFetchKind::Maximum &&
4342 getBinop() != cir::AtomicFetchKind::Minimum &&
4343 getBinop() != cir::AtomicFetchKind::MaximumNum &&
4344 getBinop() != cir::AtomicFetchKind::MinimumNum &&
4345 !mlir::isa<cir::IntType>(getVal().
getType()))
4346 return emitError(
"only atomic add, sub, max, min, maximum, minimum, "
4347 "maximum_num, and minimum_num operation could operate on "
4348 "floating-point values");
4350 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
4351 getBinop() == cir::AtomicFetchKind::Minimum ||
4352 getBinop() == cir::AtomicFetchKind::MaximumNum ||
4353 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
4354 !mlir::isa<cir::FPTypeInterface>(getVal().
getType()))
4355 return emitError(
"atomic maximum, minimum, maximum_num, and minimum_num "
4356 "operation could only operate on floating-point values");
4365LogicalResult cir::TypeInfoAttr::verify(
4366 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4367 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4369 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4379void cir::TryOp::getSuccessorRegions(
4380 mlir::RegionBranchPoint point,
4383 if (!point.isParent()) {
4384 regions.emplace_back(getOperation());
4388 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4392 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4393 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4396LogicalResult cir::TryOp::verify() {
4397 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4398 if (!handlerTypes) {
4399 if (!getHandlerRegions().empty())
4401 "handler regions must be empty when no handler types are present");
4405 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4409 if (handlerRegions.size() != handlerTypes.size())
4411 "number of handler regions and handler types must match");
4413 for (
const auto &[typeAttr, handlerRegion] :
4414 llvm::zip(handlerTypes, handlerRegions)) {
4416 mlir::Block &entryBlock = handlerRegion.front();
4417 if (entryBlock.getNumArguments() != 1 ||
4418 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4420 "handler region must have a single '!cir.eh_token' argument");
4423 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4440 if (entryBlock.empty())
4441 return emitOpError(
"catch handler region must not be empty");
4443 mlir::Operation *firstOp = &entryBlock.front();
4444 if (mlir::isa<cir::LifetimeStartOp>(firstOp)) {
4445 mlir::Operation *next = firstOp->getNextNode();
4446 auto lifetimeScope = mlir::dyn_cast_if_present<cir::CleanupScopeOp>(next);
4448 return emitOpError(
"'cir.lifetime.start' in a catch handler region "
4449 "must be followed by the 'cir.cleanup.scope' of "
4450 "its lifetime-end cleanup");
4451 if (lifetimeScope.getBodyRegion().empty())
4453 "'cir.lifetime.start' in a catch handler region must be "
4454 "followed by the 'cir.cleanup.scope' of its lifetime-end "
4456 mlir::Block &scopeBody = lifetimeScope.getBodyRegion().front();
4457 firstOp = scopeBody.empty() ?
nullptr : &scopeBody.front();
4460 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4461 firstOp = firstOp->getNextNode();
4462 if (!mlir::isa_and_present<cir::BeginCatchOp>(firstOp))
4464 "catch handler region must start with 'cir.begin_catch'");
4472 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4473 mlir::ArrayAttr handlerTypes) {
4477 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4481 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4482 printer <<
"catch all ";
4483 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4484 printer <<
"unwind ";
4486 printer <<
"catch [type ";
4487 printer.printAttribute(typeAttr);
4492 mlir::Region ®ion = handlerRegions[typeIdx];
4493 if (!region.empty() && region.front().getNumArguments() > 0) {
4495 printer.printRegionArgument(region.front().getArgument(0));
4499 printer.printRegion(region,
4506 mlir::OpAsmParser &parser,
4508 mlir::ArrayAttr &handlerTypes) {
4510 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4511 handlerRegions.emplace_back(
new mlir::Region);
4513 mlir::Region &currRegion = *handlerRegions.back();
4517 if (parser.parseLParen())
4519 mlir::OpAsmParser::Argument arg;
4520 if (parser.parseArgument(arg,
true))
4522 regionArgs.push_back(arg);
4523 if (parser.parseRParen())
4526 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4527 if (parser.parseRegion(currRegion, regionArgs)) {
4528 handlerRegions.clear();
4532 if (currRegion.empty())
4533 return parser.emitError(regionLoc,
"handler region shall not be empty");
4535 if (!(currRegion.back().mightHaveTerminator() &&
4536 currRegion.back().getTerminator()))
4537 return parser.emitError(
4538 regionLoc,
"blocks are expected to be explicitly terminated");
4543 bool hasCatchAll =
false;
4545 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4546 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4548 llvm::StringRef attrStr;
4549 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4550 return parser.emitError(parser.getCurrentLocation(),
4551 "expected 'all' or 'type' keyword");
4553 bool isCatchAll = attrStr ==
"all";
4556 return parser.emitError(parser.getCurrentLocation(),
4557 "can't have more than one catch all");
4561 mlir::Attribute exceptionRTTIAttr;
4562 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4563 return parser.emitError(parser.getCurrentLocation(),
4564 "expected valid RTTI info attribute");
4566 catcherAttrs.push_back(isCatchAll
4567 ? cir::CatchAllAttr::get(parser.getContext())
4568 : exceptionRTTIAttr);
4570 if (hasLSquare && isCatchAll)
4571 return parser.emitError(parser.getCurrentLocation(),
4572 "catch all dosen't need RTTI info attribute");
4574 if (hasLSquare && parser.parseRSquare().failed())
4575 return parser.emitError(parser.getCurrentLocation(),
4576 "expected `]` after RTTI info attribute");
4578 if (parseCheckedCatcherRegion().failed())
4579 return mlir::failure();
4582 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4584 return parser.emitError(parser.getCurrentLocation(),
4585 "unwind can't be used with catch all");
4587 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4588 if (parseCheckedCatcherRegion().failed())
4589 return mlir::failure();
4592 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4593 return mlir::success();
4601cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4602 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
4603 if (!isa_and_nonnull<GlobalOp>(op))
4604 return emitOpError(
"'")
4605 << getTypeSym() <<
"' does not reference a valid cir.global";
4613LogicalResult cir::LifetimeStartOp::verify() {
4617LogicalResult cir::LifetimeEndOp::verify() {
4627 auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr);
4628 if (!intAttr || !intAttr.getType().isSignlessInteger(32))
4629 return std::nullopt;
4630 int64_t width = intAttr.getInt();
4633 return std::nullopt;
4634 return static_cast<unsigned>(width);
4637LogicalResult cir::MemChrOp::verify() {
4638 auto moduleOp = (*this)->getParentOfType<mlir::ModuleOp>();
4640 return emitOpError(
"expects an enclosing module");
4643 if (mlir::cast<cir::PointerType>(getSrc().
getType()).getAddrSpace())
4644 return emitOpError(
"src must be in the default address space");
4646 auto checkWidth = [&](cir::IntType type, llvm::StringRef operandName,
4647 llvm::StringRef attrName) -> LogicalResult {
4648 mlir::Attribute
attr = moduleOp->getAttr(attrName);
4650 return emitOpError(
"expects the module to record ") << attrName;
4653 return emitOpError(
"requires ")
4655 <<
" to be a signless i32 holding a fundamental integer width";
4656 if (type.getWidth() != *width)
4657 return emitOpError() << operandName <<
" must have the width recorded in "
4662 if (failed(checkWidth(getPattern().
getType(),
"pattern",
4663 cir::CIRDialect::getIntTypeWidthAttrName())))
4665 return checkWidth(getLen().
getType(),
"len",
4666 cir::CIRDialect::getSizeTypeWidthAttrName());
4673LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4674 SymbolTableCollection &symbolTable) {
4675 auto copyFnAttr = getCopyFnAttr();
4679 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
4681 return emitOpError(
"'")
4682 << *getCopyFn() <<
"' does not reference a valid cir.func";
4684 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4685 return emitOpError(
"catch-init copy_fn must be tagged with the ")
4686 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
4688 cir::FuncType fnType = fn.getFunctionType();
4689 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4690 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
4693 if (fnType.getInput(0) != getParamAddr().
getType())
4694 return emitOpError(
"first argument of catch-init copy_fn must match the "
4695 "type of 'param_addr'");
4697 if (fnType.getInput(1) != getParamAddr().
getType())
4699 "second argument of catch-init copy_fn must be a pointer "
4700 "to the catch type");
4711 SmallVectorImpl<Block *> &catchDestinations,
4712 Block *&defaultDestination,
4713 mlir::UnitAttr &defaultIsCatchAll) {
4715 if (parser.parseLSquare())
4719 bool hasCatchAll =
false;
4720 bool hasUnwind =
false;
4723 auto parseHandler = [&]() -> ParseResult {
4725 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
4727 return parser.emitError(parser.getCurrentLocation(),
4728 "duplicate 'catch_all' handler");
4730 return parser.emitError(parser.getCurrentLocation(),
4731 "cannot have both 'catch_all' and 'unwind'");
4734 if (parser.parseColon().failed())
4737 if (parser.parseSuccessor(defaultDestination).failed())
4743 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
4745 return parser.emitError(parser.getCurrentLocation(),
4746 "duplicate 'unwind' handler");
4748 return parser.emitError(parser.getCurrentLocation(),
4749 "cannot have both 'catch_all' and 'unwind'");
4752 if (parser.parseColon().failed())
4755 if (parser.parseSuccessor(defaultDestination).failed())
4763 if (parser.parseKeyword(
"catch").failed())
4766 if (parser.parseLParen().failed())
4769 mlir::Attribute catchTypeAttr;
4770 if (parser.parseAttribute(catchTypeAttr).failed())
4772 handlerTypes.push_back(catchTypeAttr);
4774 if (parser.parseRParen().failed())
4777 if (parser.parseColon().failed())
4781 if (parser.parseSuccessor(dest).failed())
4783 catchDestinations.push_back(dest);
4787 if (parser.parseCommaSeparatedList(parseHandler).failed())
4790 if (parser.parseRSquare().failed())
4794 if (!hasCatchAll && !hasUnwind)
4795 return parser.emitError(parser.getCurrentLocation(),
4796 "must have either 'catch_all' or 'unwind' handler");
4799 if (!handlerTypes.empty())
4800 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4803 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4809 mlir::ArrayAttr catchTypes,
4810 SuccessorRange catchDestinations,
4811 Block *defaultDestination,
4812 mlir::UnitAttr defaultIsCatchAll) {
4820 llvm::zip(catchTypes, catchDestinations),
4823 p.printAttribute(std::get<0>(i));
4825 p.printSuccessor(std::get<1>(i));
4837 if (defaultIsCatchAll)
4838 p <<
" catch_all : ";
4841 p.printSuccessor(defaultDestination);
4851bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
4852 mlir::TypeRange results) {
4853 if (operands.size() != getNumArgs() || results.size() != 1)
4855 mlir::Type iterTy = operands[0];
4856 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
4863#define GET_OP_CLASSES
4864#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 void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::Type srcType, mlir::Type dstType)
mlir::OptionalParseResult parseGlobalMemorySpace(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static std::optional< unsigned > getRecordedIntegerWidth(mlir::Attribute attr)
Reads a fundamental integer width from a signless i32 attribute.
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static bool isFloatingPointCastKind(cir::CastKind kind)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static mlir::Type memberPointeeType(cir::RecordType recordTy, unsigned idx)
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 )* )?
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)
void printGlobalMemorySpace(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
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.
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 mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser, mlir::Type &srcType, mlir::Type &dstType)
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
C++ view class that accepts both !cir.struct and !cir.union types.
llvm::ArrayRef< mlir::Type > getMembers() const
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
bool isValidFundamentalIntWidth(unsigned width)
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()