19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/DialectImplementation.h"
21#include "mlir/IR/PatternMatch.h"
22#include "mlir/IR/Value.h"
23#include "mlir/Interfaces/ControlFlowInterfaces.h"
24#include "mlir/Interfaces/FunctionImplementation.h"
25#include "mlir/Support/LLVM.h"
27#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
28#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
30#include "llvm/ADT/SetOperations.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/TypeSwitch.h"
33#include "llvm/Support/LogicalResult.h"
42struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
43 using OpAsmDialectInterface::OpAsmDialectInterface;
45 AliasResult getAlias(Type type, raw_ostream &os)
const final {
46 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
49 os <<
"rec_anon_" <<
recordType.getKindAsStr();
51 os <<
"rec_" << nameAttr.getValue();
52 return AliasResult::OverridableAlias;
54 if (
auto intType = dyn_cast<cir::IntType>(type)) {
57 unsigned width = intType.getWidth();
58 if (width < 8 || !llvm::isPowerOf2_32(width))
59 return AliasResult::NoAlias;
60 os << intType.getAlias();
61 return AliasResult::OverridableAlias;
63 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
64 os << voidType.getAlias();
65 return AliasResult::OverridableAlias;
68 return AliasResult::NoAlias;
71 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
72 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
73 os << (boolAttr.getValue() ?
"true" :
"false");
74 return AliasResult::FinalAlias;
76 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
77 os <<
"bfi_" << bitfield.getName().str();
78 return AliasResult::FinalAlias;
80 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
81 os << dynCastInfoAttr.getAlias();
82 return AliasResult::FinalAlias;
84 if (
auto cmpThreeWayInfoAttr =
85 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
86 os << cmpThreeWayInfoAttr.getAlias();
87 return AliasResult::FinalAlias;
89 return AliasResult::NoAlias;
94void cir::CIRDialect::initialize() {
99#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
101 addInterfaces<CIROpAsmDialectInterface>();
104Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
105 mlir::Attribute value,
107 mlir::Location loc) {
108 return cir::ConstantOp::create(builder, loc, type,
109 mlir::cast<mlir::TypedAttr>(value));
121 for (
auto en : llvm::enumerate(keywords)) {
122 if (succeeded(parser.parseOptionalKeyword(en.value())))
129template <
typename Ty>
struct EnumTraits {};
131#define REGISTER_ENUM_TYPE(Ty) \
132 template <> struct EnumTraits<cir::Ty> { \
133 static llvm::StringRef stringify(cir::Ty value) { \
134 return stringify##Ty(value); \
136 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
148template <
typename EnumTy,
typename RetTy = EnumTy>
151 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
152 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
156 return static_cast<RetTy
>(defaultValue);
157 return static_cast<RetTy
>(index);
161template <
typename EnumTy,
typename RetTy = EnumTy>
164 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
165 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
170 result =
static_cast<RetTy
>(index);
178 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
179 OpBuilder builder(parser.getBuilder().getContext());
184 builder.createBlock(®ion);
186 Block &block = region.back();
188 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
192 if (!region.hasOneBlock())
193 return parser.emitError(errLoc,
194 "multi-block region must not omit terminator");
197 builder.setInsertionPointToEnd(&block);
198 cir::YieldOp::create(builder, eLoc);
204 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
205 const auto yieldsNothing = [&r]() {
206 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
207 return y && y.getArgs().empty();
209 return singleNonEmptyBlock && yieldsNothing();
214template <
typename ExpectedProducerOp>
216 StringRef operandName) {
217 Operation *producer = operand.getDefiningOp();
218 if (!producer || !isa<ExpectedProducerOp>(producer))
219 return op->emitOpError()
220 <<
"operand '" << operandName <<
"' must be produced by '"
221 << ExpectedProducerOp::getOperationName() <<
"'";
230 cir::InlineKindAttr &inlineKindAttr) {
232 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
236 llvm::StringRef keyword;
237 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
243 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
244 if (!inlineKindResult) {
245 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
247 <<
"] for inlineKind, got: " << keyword;
251 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
256 if (inlineKindAttr) {
257 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
265 mlir::Region ®ion) {
266 auto regionLoc = parser.getCurrentLocation();
267 if (parser.parseRegion(region))
276 mlir::Region ®ion) {
277 printer.printRegion(region,
282mlir::OptionalParseResult
284 mlir::ptr::MemorySpaceAttrInterface &attr);
287 mlir::ptr::MemorySpaceAttrInterface attr);
293void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
294 mlir::OperationState &odsState, mlir::Type addr,
295 llvm::StringRef name, mlir::IntegerAttr alignment) {
296 odsState.addAttribute(getNameAttrName(odsState.name),
297 odsBuilder.getStringAttr(name));
299 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
301 odsState.addTypes(addr);
309 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
310 mlir::Type pointeeTy = ptrTy.getPointee();
312 mlir::Block &body = op.getBody().front();
313 if (body.getNumArguments() != 1)
314 return op.emitOpError(
"body must have exactly one block argument");
316 auto expectedEltPtrTy =
317 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
318 if (!expectedEltPtrTy)
319 return op.emitOpError(
"block argument must be a !cir.ptr type");
321 if (op.getNumElements()) {
322 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
324 return op.emitOpError(
325 "when 'num_elements' is present, 'addr' must be a pointer to a "
326 "!cir.struct or !cir.union type");
328 if (expectedEltPtrTy != ptrTy)
329 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
330 "match the block argument type");
332 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
334 return op.emitOpError(
335 "when 'num_elements' is absent, 'addr' must be a pointer to a "
338 mlir::Type innerEltTy = arrayTy.getElementType();
339 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
340 innerEltTy = nested.getElementType();
342 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
344 return op.emitOpError(
"the block argument type must be a pointer to a "
345 "!cir.struct or !cir.union type");
347 if (expectedEltPtrTy.getPointee() != innerEltTy)
348 return op.emitOpError(
349 "block argument pointee type must match the innermost array "
356LogicalResult cir::ArrayCtor::verify() {
360 mlir::Region &partialDtor = getPartialDtor();
361 if (!partialDtor.empty()) {
362 mlir::Block &dtorBlock = partialDtor.front();
363 if (dtorBlock.getNumArguments() != 1)
364 return emitOpError(
"partial_dtor must have exactly one block argument");
366 auto bodyArgTy = getBody().front().getArgument(0).getType();
367 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
368 return emitOpError(
"partial_dtor block argument type must match "
369 "the body block argument type");
379LogicalResult cir::DeleteArrayOp::verify() {
380 if (getDtorMayThrow() && !getElementDtorAttr())
382 "'dtor_may_throw' requires an 'element_dtor' to be present");
391 cir::AssumeBundleKindAttr kindAttr,
392 OperandRange bundleArgs,
393 TypeRange bundleArgTypes) {
394 cir::AssumeBundleKind
kind = kindAttr.getValue();
395 if (
kind == cir::AssumeBundleKind::None)
398 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
399 if (bundleArgs.empty())
403 p.printOperands(bundleArgs);
405 llvm::interleaveComma(bundleArgTypes, p);
410 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
414 auto loc = p.getCurrentLocation();
415 if (failed(p.parseOptionalKeyword(&keyword))) {
416 bundleKindAttr = cir::AssumeBundleKindAttr::get(
417 p.getContext(), cir::AssumeBundleKind::None);
421 std::optional<cir::AssumeBundleKind> parsedKind =
422 cir::symbolizeAssumeBundleKind(keyword);
424 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
426 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
428 if (p.parseOptionalLParen())
431 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
432 p.parseTypeList(bundleArgTypes) || p.parseRParen())
438LogicalResult cir::AssumeOp::verify() {
439 cir::AssumeBundleKind
kind = getBundleKind();
440 size_t numArgs = getBundleArgs().size();
442 if (
kind == cir::AssumeBundleKind::None) {
444 return emitOpError(
"unexpected bundle operands for kind 'none'");
449 return emitOpError(
"expected bundle operands for kind '")
450 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
453 case cir::AssumeBundleKind::Align:
454 if (numArgs != 2 && numArgs != 3)
455 return emitOpError(
"align bundle expects 2 or 3 operands");
457 case cir::AssumeBundleKind::SeparateStorage:
459 return emitOpError(
"separate_storage bundle expects 2 operands");
461 case cir::AssumeBundleKind::Dereferenceable:
463 return emitOpError(
"dereferenceable bundle expects 2 operands");
476cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
477 cir::GlobalOp global = getReferencedGlobal(symbolTable);
479 return emitOpError(
"'")
480 << getGlobalName() <<
"' does not reference a valid cir.global";
482 if (getTls() && !global.getTlsModel())
483 return emitOpError(
"access to global not marked thread local");
485 if (!global.getStaticLocalGuard().has_value())
486 return emitOpError(
"static_local attribute mismatch");
499void cir::ConditionOp::getSuccessorRegions(
505 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
506 regions.emplace_back(&loopOp.getBody());
507 regions.emplace_back(getOperation());
512 auto await = cast<AwaitOp>(getOperation()->getParentOp());
513 regions.emplace_back(&await.getResume());
514 regions.emplace_back(&await.getSuspend());
518cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
520 return MutableOperandRange(getOperation(), 0, 0);
524cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
526 return MutableOperandRange(getOperation(), 0, 0);
529LogicalResult cir::ConditionOp::verify() {
530 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
531 return emitOpError(
"condition must be within a conditional region");
540 mlir::Attribute attrType) {
541 if (isa<cir::ConstPtrAttr>(attrType)) {
542 if (!mlir::isa<cir::PointerType>(opType))
543 return op->emitOpError(
544 "pointer constant initializing a non-pointer type");
548 if (isa<cir::DataMemberAttr, cir::MethodAttr>(attrType)) {
554 if (isa<cir::ZeroAttr>(attrType)) {
555 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
558 return op->emitOpError(
559 "zero expects struct, array, vector, or complex type");
562 if (mlir::isa<cir::UndefAttr>(attrType)) {
563 if (!mlir::isa<cir::VoidType>(opType))
565 return op->emitOpError(
"undef expects non-void type");
568 if (mlir::isa<cir::BoolAttr>(attrType)) {
569 if (!mlir::isa<cir::BoolType>(opType))
570 return op->emitOpError(
"result type (")
571 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
575 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
576 auto at = cast<TypedAttr>(attrType);
577 if (at.getType() != opType) {
578 return op->emitOpError(
"result type (")
579 << opType <<
") does not match value type (" << at.getType()
585 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
586 cir::ConstComplexAttr, cir::ConstRecordAttr,
587 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
588 cir::VTableAttr>(attrType))
591 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
592 return op->emitOpError(
"global with type ")
593 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
596LogicalResult cir::ConstantOp::verify() {
603OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
611LogicalResult cir::CastOp::verify() {
612 mlir::Type resType =
getType();
613 mlir::Type srcType = getSrc().getType();
617 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
618 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
619 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
620 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
621 return emitOpError() <<
"result type address space does not match the "
622 "address space of the operand";
626 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
627 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
628 if (srcVTy && resVTy) {
629 if ((
kind == cir::CastKind::int_to_float ||
630 kind == cir::CastKind::float_to_int) &&
631 srcVTy.getSize() != resVTy.getSize()) {
633 <<
"vector float-to-int and int-to-float casts require "
634 "source and destination vectors to have the same number of "
639 srcType = srcVTy.getElementType();
640 resType = resVTy.getElementType();
644 case cir::CastKind::int_to_bool: {
645 if (!mlir::isa<cir::BoolType>(resType))
646 return emitOpError() <<
"requires !cir.bool type for result";
647 if (!mlir::isa<cir::IntType>(srcType))
648 return emitOpError() <<
"requires !cir.int type for source";
651 case cir::CastKind::ptr_to_bool: {
652 if (!mlir::isa<cir::BoolType>(resType))
653 return emitOpError() <<
"requires !cir.bool type for result";
654 if (!mlir::isa<cir::PointerType>(srcType))
655 return emitOpError() <<
"requires !cir.ptr type for source";
658 case cir::CastKind::integral: {
659 if (!mlir::isa<cir::IntType>(resType))
660 return emitOpError() <<
"requires !cir.int type for result";
661 if (!mlir::isa<cir::IntType>(srcType))
662 return emitOpError() <<
"requires !cir.int type for source";
665 case cir::CastKind::array_to_ptrdecay: {
666 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
667 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
668 if (!arrayPtrTy || !flatPtrTy)
669 return emitOpError() <<
"requires !cir.ptr type for source and result";
674 case cir::CastKind::bitcast: {
676 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
677 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
679 if (srcPtrTy && resPtrTy) {
685 case cir::CastKind::floating: {
686 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
687 !mlir::isa<cir::FPTypeInterface>(resType))
688 return emitOpError() <<
"requires !cir.float type for source and result";
691 case cir::CastKind::float_to_int: {
692 if (!mlir::isa<cir::FPTypeInterface>(srcType))
693 return emitOpError() <<
"requires !cir.float type for source";
694 if (!mlir::dyn_cast<cir::IntType>(resType))
695 return emitOpError() <<
"requires !cir.int type for result";
698 case cir::CastKind::int_to_ptr: {
699 if (!mlir::dyn_cast<cir::IntType>(srcType))
700 return emitOpError() <<
"requires !cir.int type for source";
701 if (!mlir::dyn_cast<cir::PointerType>(resType))
702 return emitOpError() <<
"requires !cir.ptr type for result";
705 case cir::CastKind::ptr_to_int: {
706 if (!mlir::dyn_cast<cir::PointerType>(srcType))
707 return emitOpError() <<
"requires !cir.ptr type for source";
708 if (!mlir::dyn_cast<cir::IntType>(resType))
709 return emitOpError() <<
"requires !cir.int type for result";
712 case cir::CastKind::float_to_bool: {
713 if (!mlir::isa<cir::FPTypeInterface>(srcType))
714 return emitOpError() <<
"requires !cir.float type for source";
715 if (!mlir::isa<cir::BoolType>(resType))
716 return emitOpError() <<
"requires !cir.bool type for result";
719 case cir::CastKind::bool_to_int: {
720 if (!mlir::isa<cir::BoolType>(srcType))
721 return emitOpError() <<
"requires !cir.bool type for source";
722 if (!mlir::isa<cir::IntType>(resType))
723 return emitOpError() <<
"requires !cir.int type for result";
726 case cir::CastKind::int_to_float: {
727 if (!mlir::isa<cir::IntType>(srcType))
728 return emitOpError() <<
"requires !cir.int type for source";
729 if (!mlir::isa<cir::FPTypeInterface>(resType))
730 return emitOpError() <<
"requires !cir.float type for result";
733 case cir::CastKind::bool_to_float: {
734 if (!mlir::isa<cir::BoolType>(srcType))
735 return emitOpError() <<
"requires !cir.bool type for source";
736 if (!mlir::isa<cir::FPTypeInterface>(resType))
737 return emitOpError() <<
"requires !cir.float type for result";
740 case cir::CastKind::address_space: {
741 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
742 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
743 if (!srcPtrTy || !resPtrTy)
744 return emitOpError() <<
"requires !cir.ptr type for source and result";
745 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
746 return emitOpError() <<
"requires two types differ in addrspace only";
749 case cir::CastKind::float_to_complex: {
750 if (!mlir::isa<cir::FPTypeInterface>(srcType))
751 return emitOpError() <<
"requires !cir.float type for source";
752 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
754 return emitOpError() <<
"requires !cir.complex type for result";
755 if (srcType != resComplexTy.getElementType())
756 return emitOpError() <<
"requires source type match result element type";
759 case cir::CastKind::int_to_complex: {
760 if (!mlir::isa<cir::IntType>(srcType))
761 return emitOpError() <<
"requires !cir.int type for source";
762 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
764 return emitOpError() <<
"requires !cir.complex type for result";
765 if (srcType != resComplexTy.getElementType())
766 return emitOpError() <<
"requires source type match result element type";
769 case cir::CastKind::float_complex_to_real: {
770 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
772 return emitOpError() <<
"requires !cir.complex type for source";
773 if (!mlir::isa<cir::FPTypeInterface>(resType))
774 return emitOpError() <<
"requires !cir.float type for result";
775 if (srcComplexTy.getElementType() != resType)
776 return emitOpError() <<
"requires source element type match result type";
779 case cir::CastKind::int_complex_to_real: {
780 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
782 return emitOpError() <<
"requires !cir.complex type for source";
783 if (!mlir::isa<cir::IntType>(resType))
784 return emitOpError() <<
"requires !cir.int type for result";
785 if (srcComplexTy.getElementType() != resType)
786 return emitOpError() <<
"requires source element type match result type";
789 case cir::CastKind::float_complex_to_bool: {
790 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
791 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
793 <<
"requires floating point !cir.complex type for source";
794 if (!mlir::isa<cir::BoolType>(resType))
795 return emitOpError() <<
"requires !cir.bool type for result";
798 case cir::CastKind::int_complex_to_bool: {
799 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
800 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
802 <<
"requires floating point !cir.complex type for source";
803 if (!mlir::isa<cir::BoolType>(resType))
804 return emitOpError() <<
"requires !cir.bool type for result";
807 case cir::CastKind::float_complex: {
808 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
809 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
811 <<
"requires floating point !cir.complex type for source";
812 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
813 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
815 <<
"requires floating point !cir.complex type for result";
818 case cir::CastKind::float_complex_to_int_complex: {
819 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
820 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
822 <<
"requires floating point !cir.complex type for source";
823 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
824 if (!resComplexTy || !resComplexTy.isIntegerComplex())
825 return emitOpError() <<
"requires integer !cir.complex type for result";
828 case cir::CastKind::int_complex: {
829 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
830 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
831 return emitOpError() <<
"requires integer !cir.complex type for source";
832 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
833 if (!resComplexTy || !resComplexTy.isIntegerComplex())
834 return emitOpError() <<
"requires integer !cir.complex type for result";
837 case cir::CastKind::int_complex_to_float_complex: {
838 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
839 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
840 return emitOpError() <<
"requires integer !cir.complex type for source";
841 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
842 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
844 <<
"requires floating point !cir.complex type for result";
847 case cir::CastKind::member_ptr_to_bool: {
848 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
850 <<
"requires !cir.data_member or !cir.method type for source";
851 if (!mlir::isa<cir::BoolType>(resType))
852 return emitOpError() <<
"requires !cir.bool type for result";
856 llvm_unreachable(
"Unknown CastOp kind?");
860 auto kind = op.getKind();
861 return kind == cir::CastKind::bool_to_int ||
862 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
866 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
867 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
871 cir::CastOp head = op, tail = op;
877 op = head.getSrc().getDefiningOp<cir::CastOp>();
883 if (head.getKind() == cir::CastKind::bool_to_int &&
884 tail.getKind() == cir::CastKind::int_to_bool)
885 return head.getSrc();
890 if (head.getKind() == cir::CastKind::int_to_bool &&
891 tail.getKind() == cir::CastKind::int_to_bool)
892 return head.getResult();
900 if (tail.getKind() == cir::CastKind::bitcast) {
901 auto *inner = tail.getSrc().getDefiningOp();
903 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
904 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
905 innerCast.getSrc().getType() == tail.getType() &&
906 innerCast.getType() == tail.getSrc().getType()) {
907 return innerCast.getSrc();
915OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
916 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
918 return cir::PoisonAttr::get(getContext(),
getType());
923 case cir::CastKind::integral: {
925 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
926 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
927 return mlir::cast<mlir::Attribute>(foldResults[0]);
930 case cir::CastKind::bitcast:
931 case cir::CastKind::address_space:
932 case cir::CastKind::float_complex:
933 case cir::CastKind::int_complex: {
947 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
949 case cir::CastKind::integral: {
950 mlir::Type srcTy = getSrc().getType();
952 assert(mlir::isa<cir::VectorType>(srcTy) ==
953 mlir::isa<cir::VectorType>(
getType()));
954 if (mlir::isa<cir::VectorType>(srcTy))
957 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
958 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
961 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
962 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
963 return cir::IntAttr::get(dstIntTy, newVal);
976mlir::OperandRange cir::CallOp::getArgOperands() {
978 return getArgs().drop_front(1);
982mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
983 mlir::MutableOperandRange args = getArgsMutable();
985 return args.slice(1, args.size() - 1);
989mlir::Value cir::CallOp::getIndirectCall() {
990 assert(isIndirect());
991 return getOperand(0);
995Value cir::CallOp::getArgOperand(
unsigned i) {
998 return getOperand(i);
1002unsigned cir::CallOp::getNumArgOperands() {
1004 return this->getOperation()->getNumOperands() - 1;
1005 return this->getOperation()->getNumOperands();
1008static mlir::ParseResult
1010 mlir::OperationState &result) {
1011 mlir::Block *normalDestSuccessor;
1012 if (parser.parseSuccessor(normalDestSuccessor))
1013 return mlir::failure();
1015 if (parser.parseComma())
1016 return mlir::failure();
1018 mlir::Block *unwindDestSuccessor;
1019 if (parser.parseSuccessor(unwindDestSuccessor))
1020 return mlir::failure();
1022 result.addSuccessors(normalDestSuccessor);
1023 result.addSuccessors(unwindDestSuccessor);
1024 return mlir::success();
1028 mlir::OperationState &result,
1029 bool hasDestinationBlocks =
false) {
1032 mlir::FlatSymbolRefAttr calleeAttr;
1036 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1039 OpAsmParser::UnresolvedOperand indirectVal;
1041 if (parser.parseOperand(indirectVal).failed())
1043 ops.push_back(indirectVal);
1046 if (parser.parseLParen())
1047 return mlir::failure();
1049 opsLoc = parser.getCurrentLocation();
1050 if (parser.parseOperandList(ops))
1051 return mlir::failure();
1052 if (parser.parseRParen())
1053 return mlir::failure();
1055 if (hasDestinationBlocks &&
1057 return ::mlir::failure();
1060 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1061 result.addAttribute(CIRDialect::getMustTailAttrName(),
1062 mlir::UnitAttr::get(parser.getContext()));
1064 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1065 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1066 mlir::UnitAttr::get(parser.getContext()));
1068 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
1069 if (parser.parseLParen().failed())
1071 cir::SideEffect sideEffect;
1074 if (parser.parseRParen().failed())
1076 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
1077 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
1080 if (parser.parseOptionalAttrDict(result.attributes))
1081 return ::mlir::failure();
1083 if (parser.parseColon())
1084 return ::mlir::failure();
1090 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1091 resultTypes, resultAttrs))
1092 return mlir::failure();
1094 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1095 return parser.emitError(
1096 parser.getCurrentLocation(),
1097 "functions with multiple return types are not supported");
1099 result.addTypes(resultTypes);
1101 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1102 return mlir::failure();
1104 if (!resultAttrs.empty() && resultAttrs[0])
1105 result.addAttribute(
1106 CIRDialect::getResAttrsAttrName(),
1107 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1112 bool argAttrsEmpty =
true;
1114 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1115 [&](DictionaryAttr da) -> mlir::Attribute {
1117 argAttrsEmpty =
false;
1121 if (!argAttrsEmpty) {
1126 argAttrsRef = argAttrsRef.drop_front();
1128 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1129 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1132 return mlir::success();
1137 mlir::Value indirectCallee, mlir::OpAsmPrinter &printer,
1138 bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs,
1139 ArrayAttr resAttrs, mlir::Block *normalDest =
nullptr,
1140 mlir::Block *unwindDest =
nullptr) {
1143 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1144 auto ops = callLikeOp.getArgOperands();
1148 printer.printAttributeWithoutType(calleeSym);
1151 assert(indirectCallee);
1152 printer << indirectCallee;
1155 printer <<
"(" << ops <<
")";
1158 assert(unwindDest &&
"expected two successors");
1159 auto tryCall = cast<cir::TryCallOp>(op);
1160 printer <<
' ' << tryCall.getNormalDest();
1163 printer << tryCall.getUnwindDest();
1166 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1167 printer <<
" musttail";
1170 printer <<
" nothrow";
1172 if (sideEffect != cir::SideEffect::All) {
1173 printer <<
" side_effect(";
1174 printer << stringifySideEffect(sideEffect);
1179 CIRDialect::getCalleeAttrName(),
1180 CIRDialect::getMustTailAttrName(),
1181 CIRDialect::getNoThrowAttrName(),
1182 CIRDialect::getSideEffectAttrName(),
1183 CIRDialect::getOperandSegmentSizesAttrName(),
1184 llvm::StringRef(
"res_attrs"),
1185 llvm::StringRef(
"arg_attrs")};
1186 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
1188 if (calleeSym || !argAttrs) {
1189 call_interface_impl::printFunctionSignature(
1190 printer, op->getOperands().getTypes(), argAttrs,
1191 false, op->getResultTypes(), resAttrs);
1199 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1200 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1201 call_interface_impl::printFunctionSignature(
1202 printer, op->getOperands().getTypes(),
1203 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1204 false, op->getResultTypes(), resAttrs);
1208mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1209 mlir::OperationState &result) {
1213void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1214 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1215 cir::SideEffect sideEffect = getSideEffect();
1216 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1217 sideEffect, getArgAttrsAttr(), getResAttrsAttr());
1222 SymbolTableCollection &symbolTable) {
1224 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1227 return mlir::success();
1230 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1232 return op->emitOpError() <<
"'" << fnAttr.getValue()
1233 <<
"' does not reference a valid function";
1235 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
1236 assert(callIf &&
"expected CIR call interface to be always available");
1240 auto fnType = fn.getFunctionType();
1241 if (!fn.getNoProto()) {
1242 unsigned numCallOperands = callIf.getNumArgOperands();
1243 unsigned numFnOpOperands = fnType.getNumInputs();
1245 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1246 return op->emitOpError(
"incorrect number of operands for callee");
1247 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1248 return op->emitOpError(
"too few operands for callee");
1250 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1251 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1252 return op->emitOpError(
"operand type mismatch: expected operand type ")
1253 << fnType.getInput(i) <<
", but provided "
1254 << op->getOperand(i).getType() <<
" for operand number " << i;
1260 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1261 return op->emitOpError(
"callee returns void but call has results");
1264 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1265 return op->emitOpError(
"incorrect number of results for callee");
1268 if (!fnType.hasVoidReturn() &&
1269 op->getResultTypes().front() != fnType.getReturnType()) {
1270 return op->emitOpError(
"result type mismatch: expected ")
1271 << fnType.getReturnType() <<
", but provided "
1272 << op->getResult(0).getType();
1275 return mlir::success();
1279cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1287mlir::OperandRange cir::TryCallOp::getArgOperands() {
1289 return getArgs().drop_front(1);
1293mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1294 mlir::MutableOperandRange args = getArgsMutable();
1296 return args.slice(1, args.size() - 1);
1300mlir::Value cir::TryCallOp::getIndirectCall() {
1301 assert(isIndirect());
1302 return getOperand(0);
1306Value cir::TryCallOp::getArgOperand(
unsigned i) {
1309 return getOperand(i);
1313unsigned cir::TryCallOp::getNumArgOperands() {
1315 return this->getOperation()->getNumOperands() - 1;
1316 return this->getOperation()->getNumOperands();
1320cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1324mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1325 mlir::OperationState &result) {
1329void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1330 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1331 cir::SideEffect sideEffect = getSideEffect();
1332 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1333 sideEffect, getArgAttrsAttr(), getResAttrsAttr(),
1334 getNormalDest(), getUnwindDest());
1342 cir::FuncOp function) {
1344 if (op.getNumOperands() > 1)
1345 return op.emitOpError() <<
"expects at most 1 return operand";
1348 auto expectedTy = function.getFunctionType().getReturnType();
1350 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1351 : op.getOperand(0).getType());
1352 if (actualTy != expectedTy)
1353 return op.emitOpError() <<
"returns " << actualTy
1354 <<
" but enclosing function returns " << expectedTy;
1356 return mlir::success();
1359mlir::LogicalResult cir::ReturnOp::verify() {
1362 auto *fnOp = getOperation()->getParentOp();
1363 while (!isa<cir::FuncOp>(fnOp))
1364 fnOp = fnOp->getParentOp();
1377ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1379 result.regions.reserve(2);
1380 Region *thenRegion = result.addRegion();
1381 Region *elseRegion = result.addRegion();
1383 mlir::Builder &builder = parser.getBuilder();
1384 OpAsmParser::UnresolvedOperand cond;
1385 Type boolType = cir::BoolType::get(builder.getContext());
1387 if (parser.parseOperand(cond) ||
1388 parser.resolveOperand(cond, boolType, result.operands))
1392 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1393 if (parser.parseRegion(*thenRegion, {}, {}))
1400 if (!parser.parseOptionalKeyword(
"else")) {
1401 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1402 if (parser.parseRegion(*elseRegion, {}, {}))
1409 if (parser.parseOptionalAttrDict(result.attributes))
1414void cir::IfOp::print(OpAsmPrinter &p) {
1415 p <<
" " << getCondition() <<
" ";
1416 mlir::Region &thenRegion = this->getThenRegion();
1417 p.printRegion(thenRegion,
1422 mlir::Region &elseRegion = this->getElseRegion();
1423 if (!elseRegion.empty()) {
1425 p.printRegion(elseRegion,
1430 p.printOptionalAttrDict(getOperation()->getAttrs());
1436 cir::YieldOp::create(builder, loc);
1444void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1445 SmallVectorImpl<RegionSuccessor> ®ions) {
1447 if (!point.isParent()) {
1448 regions.emplace_back(getOperation());
1453 Region *elseRegion = &this->getElseRegion();
1454 if (elseRegion->empty())
1455 elseRegion =
nullptr;
1458 regions.push_back(RegionSuccessor(&getThenRegion()));
1460 regions.push_back(RegionSuccessor(elseRegion));
1462 regions.emplace_back(getOperation());
1465mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1466 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1470void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1473 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1474 result.addOperands(cond);
1476 OpBuilder::InsertionGuard guard(builder);
1477 Region *thenRegion = result.addRegion();
1478 builder.createBlock(thenRegion);
1479 thenBuilder(builder, result.location);
1481 Region *elseRegion = result.addRegion();
1482 if (!withElseRegion)
1485 builder.createBlock(elseRegion);
1486 elseBuilder(builder, result.location);
1498void cir::ScopeOp::getSuccessorRegions(
1499 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1501 if (!point.isParent()) {
1502 regions.emplace_back(getOperation());
1507 regions.push_back(RegionSuccessor(&getScopeRegion()));
1510mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1511 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1515void cir::ScopeOp::build(
1516 OpBuilder &builder, OperationState &result,
1517 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1518 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1520 OpBuilder::InsertionGuard guard(builder);
1521 Region *scopeRegion = result.addRegion();
1522 builder.createBlock(scopeRegion);
1526 scopeBuilder(builder, yieldTy, result.location);
1529 result.addTypes(TypeRange{yieldTy});
1532void cir::ScopeOp::build(
1533 OpBuilder &builder, OperationState &result,
1534 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1535 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1536 OpBuilder::InsertionGuard guard(builder);
1537 Region *scopeRegion = result.addRegion();
1538 builder.createBlock(scopeRegion);
1540 scopeBuilder(builder, result.location);
1543LogicalResult cir::ScopeOp::verify() {
1545 return emitOpError() <<
"cir.scope must not be empty since it should "
1546 "include at least an implicit cir.yield ";
1549 mlir::Block &lastBlock =
getRegion().back();
1550 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1551 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1552 return emitOpError() <<
"last block of cir.scope must be terminated";
1556LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1557 SmallVectorImpl<OpFoldResult> &results) {
1562 if (block.getOperations().size() != 1)
1565 auto yield = dyn_cast<cir::YieldOp>(block.front());
1570 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1573 results.push_back(yield.getOperand(0));
1581void cir::CleanupScopeOp::getSuccessorRegions(
1582 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1583 if (!point.isParent()) {
1584 regions.emplace_back(getOperation());
1589 regions.push_back(RegionSuccessor(&getBodyRegion()));
1590 regions.push_back(RegionSuccessor(&getCleanupRegion()));
1594cir::CleanupScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1595 return ValueRange();
1598LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
1599 PatternRewriter &rewriter) {
1600 auto isRegionTrivial = [](Region ®ion) {
1601 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
1602 if (!region.hasOneBlock())
1604 Block &block = llvm::getSingleElement(region);
1605 return llvm::hasSingleElement(block) &&
1606 isa<cir::YieldOp>(llvm::getSingleElement(block));
1609 Region &body = op.getBodyRegion();
1610 Region &
cleanup = op.getCleanupRegion();
1614 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
1615 rewriter.eraseOp(op);
1621 if (!isRegionTrivial(
cleanup) || !body.hasOneBlock())
1624 Block &bodyBlock = body.front();
1625 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
1628 Operation *yield = bodyBlock.getTerminator();
1629 rewriter.inlineBlockBefore(&bodyBlock, op);
1630 rewriter.eraseOp(yield);
1631 rewriter.eraseOp(op);
1635void cir::CleanupScopeOp::build(
1636 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
1637 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
1638 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
1639 result.addAttribute(getCleanupKindAttrName(result.name),
1640 CleanupKindAttr::get(builder.getContext(), cleanupKind));
1642 OpBuilder::InsertionGuard guard(builder);
1645 Region *bodyRegion = result.addRegion();
1646 builder.createBlock(bodyRegion);
1648 bodyBuilder(builder, result.location);
1651 Region *cleanupRegion = result.addRegion();
1652 builder.createBlock(cleanupRegion);
1654 cleanupBuilder(builder, result.location);
1669LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1670 Block *src = op->getBlock();
1671 Block *dst = op.getDest();
1678 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
1683 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
1686 auto operands = op.getDestOperands();
1687 rewriter.eraseOp(op);
1688 rewriter.mergeBlocks(dst, src, operands);
1692mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1693 assert(index == 0 &&
"invalid successor index");
1694 return mlir::SuccessorOperands(getDestOperandsMutable());
1705mlir::SuccessorOperands
1706cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1707 assert(index < getNumSuccessors() &&
"invalid successor index");
1708 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1712 OpAsmParser &parser, Type &flagType,
1713 SmallVectorImpl<Block *> &succOperandBlocks,
1716 if (failed(parser.parseCommaSeparatedList(
1717 OpAsmParser::Delimiter::Square,
1719 Block *destination = nullptr;
1720 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1721 SmallVector<Type> operandTypes;
1723 if (parser.parseSuccessor(destination).failed())
1726 if (succeeded(parser.parseOptionalLParen())) {
1727 if (failed(parser.parseOperandList(
1728 operands, OpAsmParser::Delimiter::None)) ||
1729 failed(parser.parseColonTypeList(operandTypes)) ||
1730 failed(parser.parseRParen()))
1733 succOperandBlocks.push_back(destination);
1734 succOperands.emplace_back(operands);
1735 succOperandsTypes.emplace_back(operandTypes);
1738 "successor blocks")))
1744 Type flagType, SuccessorRange succs,
1745 OperandRangeRange succOperands,
1746 const TypeRangeRange &succOperandsTypes) {
1749 llvm::zip(succs, succOperands),
1752 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1755 if (!succOperands.empty())
1764mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1765 assert(index < getNumSuccessors() &&
"invalid successor index");
1766 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1767 : getDestOperandsFalseMutable());
1771 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1772 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1780void cir::CaseOp::getSuccessorRegions(
1781 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1782 if (!point.isParent()) {
1783 regions.emplace_back(getOperation());
1786 regions.push_back(RegionSuccessor(&getCaseRegion()));
1789mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1790 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1794void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1795 ArrayAttr value, CaseOpKind
kind,
1796 OpBuilder::InsertPoint &insertPoint) {
1797 OpBuilder::InsertionGuard guardSwitch(builder);
1798 result.addAttribute(
"value", value);
1799 result.getOrAddProperties<Properties>().
kind =
1800 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1801 Region *caseRegion = result.addRegion();
1802 builder.createBlock(caseRegion);
1804 insertPoint = builder.saveInsertionPoint();
1811void cir::SwitchOp::getSuccessorRegions(
1812 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1813 if (!point.isParent()) {
1814 region.emplace_back(getOperation());
1818 region.push_back(RegionSuccessor(&getBody()));
1821mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1822 return successor.isOperation() ? ValueRange(getOperation()->getResults())
1826void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1828 assert(switchBuilder &&
"the builder callback for regions must be present");
1829 OpBuilder::InsertionGuard guardSwitch(builder);
1830 Region *switchRegion = result.addRegion();
1831 builder.createBlock(switchRegion);
1832 result.addOperands({cond});
1833 switchBuilder(builder, result.location, result);
1837 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1839 if (isa<cir::SwitchOp>(op) && op != *
this)
1840 return WalkResult::skip();
1842 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1843 cases.push_back(caseOp);
1845 return WalkResult::advance();
1850 collectCases(cases);
1852 if (getBody().empty())
1855 if (!isa<YieldOp>(getBody().front().back()))
1858 if (!llvm::all_of(getBody().front(),
1859 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1862 return llvm::all_of(cases, [
this](CaseOp op) {
1863 return op->getParentOfType<SwitchOp>() == *
this;
1871void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1872 Value value, Block *defaultDestination,
1873 ValueRange defaultOperands,
1875 BlockRange caseDestinations,
1878 std::vector<mlir::Attribute> caseValuesAttrs;
1879 for (
const APInt &val : caseValues)
1880 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1881 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1883 build(builder, result, value, defaultOperands, caseOperands, attrs,
1884 defaultDestination, caseDestinations);
1890 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1891 SmallVectorImpl<Block *> &caseDestinations,
1895 if (failed(parser.parseLSquare()))
1897 if (succeeded(parser.parseOptionalRSquare()))
1901 auto parseCase = [&]() {
1903 if (failed(parser.parseInteger(value)))
1906 values.push_back(cir::IntAttr::get(flagType, value));
1911 if (parser.parseColon() || parser.parseSuccessor(destination))
1913 if (!parser.parseOptionalLParen()) {
1914 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1916 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1919 caseDestinations.push_back(destination);
1920 caseOperands.emplace_back(operands);
1921 caseOperandTypes.emplace_back(operandTypes);
1924 if (failed(parser.parseCommaSeparatedList(parseCase)))
1927 caseValues = ArrayAttr::get(flagType.getContext(), values);
1929 return parser.parseRSquare();
1933 Type flagType, mlir::ArrayAttr caseValues,
1934 SuccessorRange caseDestinations,
1935 OperandRangeRange caseOperands,
1936 const TypeRangeRange &caseOperandTypes) {
1946 llvm::zip(caseValues, caseDestinations),
1949 mlir::Attribute a = std::get<0>(i);
1950 p << mlir::cast<cir::IntAttr>(a).getValue();
1952 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1967 mlir::Attribute &valueAttr) {
1969 return parser.parseAttribute(valueAttr,
"value", attr);
1973 p.printAttribute(value);
1976mlir::LogicalResult cir::GlobalOp::verify() {
1979 if (getInitialValue().has_value()) {
1985 if ((getStaticLocalGuard().has_value()) &&
1986 (!getCtorRegion().empty() || !getDtorRegion().empty()))
1988 "Cannot have a static-local global-op with a constructor or "
1989 "destructor, they require in-function initialization via LocalInitOp");
1991 if (getDynTlsRefs()) {
1992 if (getStaticLocalGuard().has_value())
1994 "cannot have both static local and dynamic tls references");
1995 if (!getTlsModel() || getTlsModel() != TLS_Model::GeneralDynamic)
1996 return emitOpError(
"'dyn_tls_refs' only valid for dynamic tls");
1999 if (getAliasee().has_value()) {
2000 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2001 !getDtorRegion().empty())
2002 return emitOpError(
"global alias shall not have an initializer or "
2003 "constructor/destructor regions");
2012void cir::GlobalOp::build(
2013 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2014 mlir::Type sym_type,
bool isConstant,
2015 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2016 cir::GlobalLinkageKind linkage,
2017 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2018 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2019 odsState.addAttribute(getSymNameAttrName(odsState.name),
2020 odsBuilder.getStringAttr(sym_name));
2021 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2022 mlir::TypeAttr::get(sym_type));
2023 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2024 properties.setConstant(isConstant);
2028 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2030 cir::GlobalLinkageKindAttr linkageAttr =
2031 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2032 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2034 Region *ctorRegion = odsState.addRegion();
2036 odsBuilder.createBlock(ctorRegion);
2037 ctorBuilder(odsBuilder, odsState.location);
2040 Region *dtorRegion = odsState.addRegion();
2042 odsBuilder.createBlock(dtorRegion);
2043 dtorBuilder(odsBuilder, odsState.location);
2052void cir::GlobalOp::getSuccessorRegions(
2053 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2055 if (!point.isParent()) {
2056 regions.emplace_back(getOperation());
2061 Region *ctorRegion = &this->getCtorRegion();
2062 if (ctorRegion->empty())
2063 ctorRegion =
nullptr;
2066 Region *dtorRegion = &this->getDtorRegion();
2067 if (dtorRegion->empty())
2068 dtorRegion =
nullptr;
2072 regions.push_back(RegionSuccessor(ctorRegion));
2074 regions.push_back(RegionSuccessor(dtorRegion));
2077mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
2078 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2083 TypeAttr type, Attribute initAttr,
2084 mlir::Region &ctorRegion,
2085 mlir::Region &dtorRegion) {
2086 auto printType = [&]() { p <<
": " << type; };
2089 if (op.isDeclaration() || op.getAliasee()) {
2095 if (!ctorRegion.empty()) {
2099 p.printRegion(ctorRegion,
2108 if (!dtorRegion.empty()) {
2110 p.printRegion(dtorRegion,
2118 Attribute &initialValueAttr,
2119 mlir::Region &ctorRegion,
2120 mlir::Region &dtorRegion) {
2122 if (parser.parseOptionalEqual().failed()) {
2125 if (parser.parseColonType(opTy))
2130 if (!parser.parseOptionalKeyword(
"ctor")) {
2131 if (parser.parseColonType(opTy))
2133 auto parseLoc = parser.getCurrentLocation();
2134 if (parser.parseRegion(ctorRegion, {}, {}))
2145 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2146 "Non-typed attrs shouldn't appear here.");
2147 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
2148 opTy = typedAttr.getType();
2153 if (!parser.parseOptionalKeyword(
"dtor")) {
2154 auto parseLoc = parser.getCurrentLocation();
2155 if (parser.parseRegion(dtorRegion, {}, {}))
2162 typeAttr = TypeAttr::get(opTy);
2171cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2174 mlir::Operation *op =
2175 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2176 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2177 return emitOpError(
"'")
2179 <<
"' does not reference a valid cir.global or cir.func";
2182 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2183 if (
auto g = dyn_cast<GlobalOp>(op)) {
2184 symTy = g.getSymType();
2185 symAddrSpaceAttr = g.getAddrSpaceAttr();
2188 if (getTls() && !g.getTlsModel())
2189 return emitOpError(
"access to global not marked thread local");
2194 bool getGlobalIsStaticLocal = getStaticLocal();
2195 bool globalIsStaticLocal = g.getStaticLocalGuard().has_value();
2196 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2197 !getOperation()->getParentOfType<cir::GlobalOp>())
2198 return emitOpError(
"static_local attribute mismatch");
2199 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2200 symTy = f.getFunctionType();
2202 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2205 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2206 if (!resultType || symTy != resultType.getPointee())
2207 return emitOpError(
"result type pointee type '")
2208 << resultType.getPointee() <<
"' does not match type " << symTy
2209 <<
" of the global @" <<
getName();
2211 if (symAddrSpaceAttr != resultType.getAddrSpace()) {
2212 return emitOpError()
2213 <<
"result type address space does not match the address "
2214 "space of the global @"
2226cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2232 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2234 return emitOpError(
"'")
2235 <<
name <<
"' does not reference a valid cir.global";
2236 std::optional<mlir::Attribute> init = op.getInitialValue();
2239 if (!isa<cir::VTableAttr>(*init))
2240 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2250cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2259 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2261 return emitOpError(
"'")
2262 <<
name <<
"' does not reference a valid cir.global";
2263 std::optional<mlir::Attribute> init = op.getInitialValue();
2266 if (!isa<cir::ConstArrayAttr>(*init))
2268 "Expected constant array in initializer for global VTT '")
2273LogicalResult cir::VTTAddrPointOp::verify() {
2275 if (
getName() && getSymAddr())
2276 return emitOpError(
"should use either a symbol or value, but not both");
2282 mlir::Type resultType = getAddr().getType();
2283 mlir::Type resTy = cir::PointerType::get(
2284 cir::PointerType::get(cir::VoidType::get(getContext())));
2286 if (resultType != resTy)
2287 return emitOpError(
"result type must be ")
2288 << resTy <<
", but provided result type is " << resultType;
2300void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
2301 StringRef name, FuncType type,
2302 GlobalLinkageKind linkage, CallingConv callingConv) {
2304 result.addAttribute(SymbolTable::getSymbolAttrName(),
2305 builder.getStringAttr(name));
2306 result.addAttribute(getFunctionTypeAttrName(result.name),
2307 TypeAttr::get(type));
2308 result.addAttribute(
2310 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
2311 result.addAttribute(getCallingConvAttrName(result.name),
2312 CallingConvAttr::get(builder.getContext(), callingConv));
2320cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
2321 mlir::StringAttr name, mlir::ArrayAttr args) {
2324 for (mlir::Attribute arg : args) {
2325 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
2326 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
2332ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2333 llvm::SMLoc loc = parser.getCurrentLocation();
2334 mlir::Builder &builder = parser.getBuilder();
2336 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
2337 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
2338 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
2339 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
2340 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
2341 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
2342 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
2343 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
2344 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
2346 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
2347 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
2348 if (::mlir::succeeded(
2349 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
2350 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
2353 cir::InlineKindAttr inlineKindAttr;
2357 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
2359 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
2360 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
2361 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
2362 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
2364 if (parser.parseOptionalKeyword(comdatNameAttr).succeeded())
2365 state.addAttribute(comdatNameAttr, parser.getBuilder().getUnitAttr());
2369 GlobalLinkageKindAttr::get(
2370 parser.getContext(),
2372 parser, GlobalLinkageKind::ExternalLinkage)));
2374 ::llvm::StringRef visAttrStr;
2375 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
2377 state.addAttribute(visNameAttr,
2378 parser.getBuilder().getStringAttr(visAttrStr));
2381 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
2384 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
2385 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
2387 StringAttr nameAttr;
2388 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2394 bool isVariadic =
false;
2395 if (function_interface_impl::parseFunctionSignatureWithArguments(
2396 parser,
true, arguments, isVariadic, resultTypes,
2401 bool argAttrsEmpty =
true;
2402 for (OpAsmParser::Argument &arg : arguments) {
2403 argTypes.push_back(
arg.type);
2407 argAttrs.push_back(
arg.attrs);
2409 argAttrsEmpty =
false;
2413 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
2414 return parser.emitError(
2415 loc,
"functions with multiple return types are not supported");
2417 mlir::Type returnType =
2418 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2419 : resultTypes.front());
2421 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2425 state.addAttribute(getFunctionTypeAttrName(state.name),
2426 TypeAttr::get(fnType));
2428 if (!resultAttrs.empty() && resultAttrs[0])
2430 getResAttrsAttrName(state.name),
2431 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
2434 state.addAttribute(getArgAttrsAttrName(state.name),
2435 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
2437 bool hasAlias =
false;
2438 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2439 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2440 if (parser.parseLParen().failed())
2442 mlir::StringAttr aliaseeAttr;
2443 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2445 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2446 if (parser.parseRParen().failed())
2451 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2452 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2453 if (parser.parseLParen().failed())
2455 mlir::StringAttr personalityAttr;
2456 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2458 state.addAttribute(personalityNameAttr,
2459 FlatSymbolRefAttr::get(personalityAttr));
2460 if (parser.parseRParen().failed())
2465 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
2466 cir::CallingConv callConv = cir::CallingConv::C;
2467 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
2468 if (parser.parseLParen().failed())
2471 return parser.emitError(loc) <<
"unknown calling convention";
2472 if (parser.parseRParen().failed())
2475 state.addAttribute(callConvNameAttr,
2476 cir::CallingConvAttr::get(parser.getContext(), callConv));
2478 auto parseGlobalDtorCtor =
2479 [&](StringRef keyword,
2480 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2481 -> mlir::LogicalResult {
2482 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2483 std::optional<int> priority;
2484 if (mlir::succeeded(parser.parseOptionalLParen())) {
2485 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2486 if (mlir::failed(parsedPriority))
2487 return parser.emitError(parser.getCurrentLocation(),
2488 "failed to parse 'priority', of type 'int'");
2489 priority = parsedPriority.value_or(
int());
2491 if (parser.parseRParen())
2494 createAttr(priority);
2500 if (parser.parseOptionalKeyword(
"special_member").succeeded()) {
2501 if (parser.parseLess().failed())
2504 mlir::Attribute
attr;
2505 if (parser.parseAttribute(attr).failed())
2507 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr>(
2509 return parser.emitError(parser.getCurrentLocation(),
2510 "expected a C++ special member attribute");
2511 state.addAttribute(specialMemberAttr, attr);
2513 if (parser.parseGreater().failed())
2517 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2518 mlir::IntegerAttr globalCtorPriorityAttr =
2519 builder.getI32IntegerAttr(priority.value_or(65535));
2520 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2521 globalCtorPriorityAttr);
2525 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2526 mlir::IntegerAttr globalDtorPriorityAttr =
2527 builder.getI32IntegerAttr(priority.value_or(65535));
2528 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2529 globalDtorPriorityAttr);
2533 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2534 cir::SideEffect sideEffect;
2536 if (parser.parseLParen().failed() ||
2538 parser.parseRParen().failed())
2541 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2542 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2546 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
2547 mlir::ArrayAttr annotationsAttr;
2548 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
2550 state.addAttribute(annotationsNameAttr, annotationsAttr);
2553 NamedAttrList parsedAttrs;
2554 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2557 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2558 if (parsedAttrs.get(disallowed))
2559 return parser.emitError(loc,
"attribute '")
2561 <<
"' should not be specified in the explicit attribute list";
2564 state.attributes.append(parsedAttrs);
2567 auto *body = state.addRegion();
2568 OptionalParseResult parseResult = parser.parseOptionalRegion(
2569 *body, arguments,
false);
2570 if (parseResult.has_value()) {
2572 return parser.emitError(loc,
"function alias shall not have a body");
2573 if (failed(*parseResult))
2577 return parser.emitError(loc,
"expected non-empty function body");
2586bool cir::FuncOp::isDeclaration() {
2589 std::optional<StringRef> aliasee = getAliasee();
2591 return getFunctionBody().empty();
2597bool cir::FuncOp::isCXXSpecialMemberFunction() {
2598 return getCxxSpecialMemberAttr() !=
nullptr;
2601bool cir::FuncOp::isCxxConstructor() {
2602 auto attr = getCxxSpecialMemberAttr();
2603 return attr && dyn_cast<CXXCtorAttr>(attr);
2606bool cir::FuncOp::isCxxDestructor() {
2607 auto attr = getCxxSpecialMemberAttr();
2608 return attr && dyn_cast<CXXDtorAttr>(attr);
2611bool cir::FuncOp::isCxxSpecialAssignment() {
2612 auto attr = getCxxSpecialMemberAttr();
2613 return attr && dyn_cast<CXXAssignAttr>(attr);
2616std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2617 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2619 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2620 return ctor.getCtorKind();
2622 return std::nullopt;
2625std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2626 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2628 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2629 return assign.getAssignKind();
2631 return std::nullopt;
2634bool cir::FuncOp::isCxxTrivialMemberFunction() {
2635 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2637 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2638 return ctor.getIsTrivial();
2639 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2640 return dtor.getIsTrivial();
2641 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2642 return assign.getIsTrivial();
2647mlir::Region *cir::FuncOp::getCallableRegion() {
2653void cir::FuncOp::print(OpAsmPrinter &p) {
2671 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2672 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2674 mlir::SymbolTable::Visibility vis = getVisibility();
2675 if (vis != mlir::SymbolTable::Visibility::Public)
2678 if (getGlobalVisibility() != cir::VisibilityKind::Default)
2679 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
2685 p.printSymbolName(getSymName());
2686 cir::FuncType fnType = getFunctionType();
2687 function_interface_impl::printFunctionSignature(
2688 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2690 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2692 p.printSymbolName(*aliaseeName);
2696 if (getCallingConv() != cir::CallingConv::C) {
2698 p << stringifyCallingConv(getCallingConv());
2702 if (std::optional<StringRef> personalityName = getPersonality()) {
2703 p <<
" personality(";
2704 p.printSymbolName(*personalityName);
2708 if (
auto specialMemberAttr = getCxxSpecialMember()) {
2709 p <<
" special_member<";
2710 p.printAttribute(*specialMemberAttr);
2714 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2715 p <<
" global_ctor";
2716 if (globalCtorPriority.value() != 65535)
2717 p <<
"(" << globalCtorPriority.value() <<
")";
2720 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2721 p <<
" global_dtor";
2722 if (globalDtorPriority.value() != 65535)
2723 p <<
"(" << globalDtorPriority.value() <<
")";
2726 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2727 sideEffect && *sideEffect != cir::SideEffect::All) {
2728 p <<
" side_effect(";
2729 p << stringifySideEffect(*sideEffect);
2733 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
2735 p.printAttribute(annotations);
2738 function_interface_impl::printFunctionAttributes(
2739 p, *
this, cir::FuncOp::getAttributeNames());
2742 Region &body = getOperation()->getRegion(0);
2743 if (!body.empty()) {
2745 p.printRegion(body,
false,
2750mlir::LogicalResult cir::FuncOp::verify() {
2752 if (!isDeclaration() && getCoroutine()) {
2753 bool foundAwait =
false;
2754 int coroBodyCount = 0;
2755 this->walk([&](Operation *op) {
2756 if (
auto await = dyn_cast<AwaitOp>(op)) {
2758 }
else if (isa<CoroBodyOp>(op)) {
2760 if (coroBodyCount > 1) {
2761 return mlir::WalkResult::interrupt();
2764 return mlir::WalkResult::advance();
2767 return emitOpError()
2768 <<
"coroutine body must use at least one cir.await op";
2769 if (coroBodyCount != 1)
2770 return emitOpError()
2771 <<
"coroutine function must have exactly one cir.body op";
2774 llvm::SmallSet<llvm::StringRef, 16> labels;
2775 llvm::SmallSet<llvm::StringRef, 16> gotos;
2776 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2777 bool invalidBlockAddress =
false;
2778 getOperation()->walk([&](mlir::Operation *op) {
2779 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2780 labels.insert(lab.getLabel());
2781 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2782 gotos.insert(goTo.getLabel());
2783 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2784 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2786 invalidBlockAddress =
true;
2787 return mlir::WalkResult::interrupt();
2789 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2791 return mlir::WalkResult::advance();
2794 if (invalidBlockAddress)
2795 return emitOpError() <<
"blockaddress references a different function";
2797 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2798 if (!labels.empty() || !gotos.empty()) {
2799 mismatched = llvm::set_difference(gotos, labels);
2801 if (!mismatched.empty())
2802 return emitOpError() <<
"goto/label mismatch";
2807 if (!labels.empty() || !blockAddresses.empty()) {
2808 mismatched = llvm::set_difference(blockAddresses, labels);
2810 if (!mismatched.empty())
2811 return emitOpError()
2812 <<
"expects an existing label target in the referenced function";
2826LogicalResult cir::AddOp::verify() {
2827 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2828 return emitOpError()
2829 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2830 return mlir::success();
2833LogicalResult cir::SubOp::verify() {
2834 if (getSaturated() && (getNoSignedWrap() || getNoUnsignedWrap()))
2835 return emitOpError()
2836 <<
"the nsw/nuw flags and the saturated flag are mutually exclusive";
2837 return mlir::success();
2849void cir::TernaryOp::getSuccessorRegions(
2850 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2852 if (!point.isParent()) {
2853 regions.emplace_back(getOperation());
2859 regions.push_back(RegionSuccessor(&getTrueRegion()));
2860 regions.push_back(RegionSuccessor(&getFalseRegion()));
2863mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2864 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2868void cir::TernaryOp::build(
2869 OpBuilder &builder, OperationState &result,
Value cond,
2870 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2871 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2872 result.addOperands(cond);
2873 OpBuilder::InsertionGuard guard(builder);
2874 Region *trueRegion = result.addRegion();
2875 builder.createBlock(trueRegion);
2876 trueBuilder(builder, result.location);
2877 Region *falseRegion = result.addRegion();
2878 builder.createBlock(falseRegion);
2879 falseBuilder(builder, result.location);
2884 if (trueRegion->back().mightHaveTerminator())
2885 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2886 if (!yield && falseRegion->back().mightHaveTerminator())
2887 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2889 assert((!yield || yield.getNumOperands() <= 1) &&
2890 "expected zero or one result type");
2891 if (yield && yield.getNumOperands() == 1)
2892 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2899OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2900 mlir::Attribute
condition = adaptor.getCondition();
2902 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2903 return conditionValue ? getTrueValue() : getFalseValue();
2907 mlir::Attribute trueValue = adaptor.getTrueValue();
2908 mlir::Attribute falseValue = adaptor.getFalseValue();
2909 if (trueValue == falseValue)
2911 if (getTrueValue() == getFalseValue())
2912 return getTrueValue();
2917LogicalResult cir::SelectOp::verify() {
2919 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
2926 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
2927 !isa<cir::VectorType>(getFalseValue().
getType())) {
2928 return emitOpError()
2929 <<
"expected both true and false operands to be vector types "
2930 "when the condition is a vector boolean type";
2939LogicalResult cir::ShiftOp::verify() {
2940 mlir::Operation *op = getOperation();
2941 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2942 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2943 if (!op0VecTy ^ !op1VecTy)
2944 return emitOpError() <<
"input types cannot be one vector and one scalar";
2947 if (op0VecTy.getSize() != op1VecTy.getSize())
2948 return emitOpError() <<
"input vector types must have the same size";
2950 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2952 return emitOpError() <<
"the type of the result must be a vector "
2953 <<
"if it is vector shift";
2955 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2956 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2957 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2958 return emitOpError()
2959 <<
"vector operands do not have the same elements sizes";
2961 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2962 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2963 return emitOpError() <<
"vector operands and result type do not have the "
2964 "same elements sizes";
2967 return mlir::success();
2974LogicalResult cir::LabelOp::verify() {
2975 mlir::Operation *op = getOperation();
2976 mlir::Block *blk = op->getBlock();
2977 if (&blk->front() != op)
2978 return emitError() <<
"must be the first operation in a block";
2980 return mlir::success();
2987OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
2988 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2989 return adaptor.getInput();
2997OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
2998 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
2999 return adaptor.getInput();
3007OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3008 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3009 return adaptor.getInput();
3014 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3015 APInt val = intAttr.getValue();
3017 return cir::IntAttr::get(
getType(), val);
3027OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3028 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3029 return adaptor.getInput();
3033 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3034 APFloat val = fpAttr.getValue();
3036 return cir::FPAttr::get(
getType(), val);
3046OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3047 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3048 return adaptor.getInput();
3053 if (mlir::Attribute attr = adaptor.getInput()) {
3054 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3055 APInt val = intAttr.getValue();
3057 return cir::IntAttr::get(
getType(), val);
3059 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3060 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3071 mlir::Type resultTy) {
3074 mlir::Type inputMemberTy;
3075 mlir::Type resultMemberTy;
3076 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3078 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3079 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3082 if (inputMemberTy != resultMemberTy)
3083 return op->emitOpError()
3084 <<
"member types of the operand and the result do not match";
3086 return mlir::success();
3089LogicalResult cir::BaseDataMemberOp::verify() {
3093LogicalResult cir::DerivedDataMemberOp::verify() {
3101LogicalResult cir::BaseMethodOp::verify() {
3105LogicalResult cir::DerivedMethodOp::verify() {
3113void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3117 result.addAttribute(getKindAttrName(result.name),
3118 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3120 OpBuilder::InsertionGuard guard(builder);
3121 Region *readyRegion = result.addRegion();
3122 builder.createBlock(readyRegion);
3123 readyBuilder(builder, result.location);
3127 OpBuilder::InsertionGuard guard(builder);
3128 Region *suspendRegion = result.addRegion();
3129 builder.createBlock(suspendRegion);
3130 suspendBuilder(builder, result.location);
3134 OpBuilder::InsertionGuard guard(builder);
3135 Region *resumeRegion = result.addRegion();
3136 builder.createBlock(resumeRegion);
3137 resumeBuilder(builder, result.location);
3141void cir::AwaitOp::getSuccessorRegions(
3142 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3145 if (!point.isParent()) {
3146 regions.emplace_back(getOperation());
3153 regions.push_back(RegionSuccessor(&this->getReady()));
3154 regions.push_back(RegionSuccessor(&this->getSuspend()));
3155 regions.push_back(RegionSuccessor(&this->getResume()));
3158mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
3159 if (successor.isOperation())
3160 return getOperation()->getResults();
3161 if (successor == &getReady())
3162 return getReady().getArguments();
3163 if (successor == &getSuspend())
3164 return getSuspend().getArguments();
3165 if (successor == &getResume())
3166 return getResume().getArguments();
3167 llvm_unreachable(
"invalid region successor");
3170LogicalResult cir::AwaitOp::verify() {
3171 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3172 return emitOpError(
"ready region must end with cir.condition");
3180void cir::CoroBodyOp::getSuccessorRegions(
3181 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3182 if (!point.isParent()) {
3183 regions.emplace_back(getOperation());
3187 regions.push_back(RegionSuccessor(&getBody()));
3191cir::CoroBodyOp::getSuccessorInputs(RegionSuccessor successor) {
3192 return ValueRange();
3195LogicalResult cir::CoroBodyOp::verify() {
3196 if (!getOperation()->getParentOfType<FuncOp>().getCoroutine())
3197 return emitOpError(
"enclosing function must be a coroutine");
3201void cir::CoroBodyOp::build(OpBuilder &builder, OperationState &result,
3203 assert(bodyBuilder &&
3204 "the builder callback for 'CoroBodyOp' must be present");
3205 OpBuilder::InsertionGuard guard(builder);
3207 Region *bodyRegion = result.addRegion();
3208 builder.createBlock(bodyRegion);
3209 bodyBuilder(builder, result.location);
3216LogicalResult cir::CopyOp::verify() {
3218 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
3219 return emitError() <<
"missing data layout for pointee type";
3221 if (getSkipTailPadding() &&
3222 !mlir::isa<cir::RecordType>(
getType().getPointee()))
3224 <<
"skip_tail_padding is only valid for record pointee types";
3226 return mlir::success();
3233LogicalResult cir::GetRuntimeMemberOp::verify() {
3234 cir::DataMemberType memberPtrTy = getMember().getType();
3236 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
3237 return emitError() <<
"record type does not match the member pointer type";
3238 if (
getType().getPointee() != memberPtrTy.getMemberTy())
3239 return emitError() <<
"result type does not match the member pointer type";
3240 return mlir::success();
3247LogicalResult cir::GetMethodOp::verify() {
3248 cir::MethodType methodTy = getMethod().getType();
3251 cir::PointerType objectPtrTy = getObject().getType();
3252 mlir::Type objectTy = objectPtrTy.getPointee();
3254 if (methodTy.getClassTy() != objectTy)
3255 return emitError() <<
"method class type and object type do not match";
3258 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
3259 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
3266 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
3268 <<
"method return type and callee return type do not match";
3273 if (calleeArgsTy.empty())
3274 return emitError() <<
"callee parameter list lacks receiver object ptr";
3276 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
3277 if (!calleeThisArgPtrTy ||
3278 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
3280 <<
"the first parameter of callee must be a void pointer";
3283 if (calleeArgsTy.size() != methodFuncArgsTy.size())
3284 return emitError() <<
"callee and method parameter counts do not match";
3286 if (calleeArgsTy.size() > 1 &&
3287 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
3289 <<
"callee parameters and method parameters do not match";
3291 return mlir::success();
3298LogicalResult cir::GetMemberOp::verify() {
3299 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
3301 return emitError() <<
"expected pointer to a record type";
3303 if (recordTy.getMembers().size() <=
getIndex())
3304 return emitError() <<
"member index out of bounds";
3307 return emitError() <<
"member type mismatch";
3309 return mlir::success();
3316LogicalResult cir::ExtractMemberOp::verify() {
3317 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3319 <<
"cir.extract_member currently does not support unions";
3320 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3321 if (structTy.getMembers().size() <=
getIndex())
3322 return emitError() <<
"member index out of bounds";
3324 return emitError() <<
"member type mismatch";
3325 return mlir::success();
3332LogicalResult cir::InsertMemberOp::verify() {
3333 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
3334 return emitError() <<
"cir.insert_member currently does not support unions";
3335 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
3336 if (structTy.getMembers().size() <=
getIndex())
3337 return emitError() <<
"member index out of bounds";
3339 return emitError() <<
"member type mismatch";
3341 return mlir::success();
3348OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
3349 if (llvm::any_of(getElements(), [](mlir::Value value) {
3350 return !value.getDefiningOp<cir::ConstantOp>();
3354 return cir::ConstVectorAttr::get(
3355 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
3358LogicalResult cir::VecCreateOp::verify() {
3362 const cir::VectorType vecTy =
getType();
3363 if (getElements().size() != vecTy.getSize()) {
3364 return emitOpError() <<
"operand count of " << getElements().size()
3365 <<
" doesn't match vector type " << vecTy
3366 <<
" element count of " << vecTy.getSize();
3369 const mlir::Type elementType = vecTy.getElementType();
3370 for (
const mlir::Value element : getElements()) {
3371 if (element.getType() != elementType) {
3372 return emitOpError() <<
"operand type " << element.getType()
3373 <<
" doesn't match vector element type "
3385OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
3386 const auto vectorAttr =
3387 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
3391 const auto indexAttr =
3392 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
3396 const mlir::ArrayAttr elements = vectorAttr.getElts();
3397 const uint64_t index = indexAttr.getUInt();
3398 if (index >= elements.size())
3401 return elements[index];
3408OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
3410 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
3412 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
3413 if (!lhsVecAttr || !rhsVecAttr)
3416 mlir::Type inputElemTy =
3417 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
3418 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
3421 cir::CmpOpKind opKind = adaptor.getKind();
3422 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
3423 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
3424 uint64_t vecSize = lhsVecElhs.size();
3427 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
3428 for (uint64_t i = 0; i < vecSize; i++) {
3429 mlir::Attribute lhsAttr = lhsVecElhs[i];
3430 mlir::Attribute rhsAttr = rhsVecElhs[i];
3433 case cir::CmpOpKind::lt: {
3435 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
3436 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3438 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
3439 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3443 case cir::CmpOpKind::le: {
3445 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
3446 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3448 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
3449 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3453 case cir::CmpOpKind::gt: {
3455 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
3456 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3458 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
3459 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3463 case cir::CmpOpKind::ge: {
3465 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
3466 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3468 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
3469 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3473 case cir::CmpOpKind::eq: {
3475 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3476 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3478 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3479 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3483 case cir::CmpOpKind::ne: {
3485 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3486 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3488 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3489 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3493 case cir::CmpOpKind::one: {
3494 llvm::APFloat::cmpResult cr =
3495 mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3496 mlir::cast<cir::FPAttr>(rhsAttr).getValue());
3498 cr != llvm::APFloat::cmpUnordered && cr != llvm::APFloat::cmpEqual;
3501 case cir::CmpOpKind::uno: {
3502 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue().compare(
3503 mlir::cast<cir::FPAttr>(rhsAttr).getValue()) ==
3504 llvm::APFloat::cmpUnordered;
3509 elements[i] = cir::IntAttr::get(
getType().getElementType(), cmpResult);
3512 return cir::ConstVectorAttr::get(
3513 getType(), mlir::ArrayAttr::get(getContext(), elements));
3520OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3522 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3524 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3525 if (!vec1Attr || !vec2Attr)
3528 mlir::Type vec1ElemTy =
3529 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3531 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3532 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3533 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3536 elements.reserve(indicesElts.size());
3538 uint64_t vec1Size = vec1Elts.size();
3539 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3540 if (idxAttr.getSInt() == -1) {
3541 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3545 uint64_t idxValue = idxAttr.getUInt();
3546 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3547 : vec2Elts[idxValue - vec1Size]);
3550 return cir::ConstVectorAttr::get(
3551 getType(), mlir::ArrayAttr::get(getContext(), elements));
3554LogicalResult cir::VecShuffleOp::verify() {
3557 if (getIndices().size() != getResult().
getType().getSize()) {
3558 return emitOpError() <<
": the number of elements in " << getIndices()
3559 <<
" and " << getResult().getType() <<
" don't match";
3564 if (getVec1().
getType().getElementType() !=
3565 getResult().
getType().getElementType()) {
3566 return emitOpError() <<
": element types of " << getVec1().getType()
3567 <<
" and " << getResult().getType() <<
" don't match";
3570 const uint64_t maxValidIndex =
3571 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3573 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3574 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3576 return emitOpError() <<
": index for __builtin_shufflevector must be "
3577 "less than the total number of vector elements";
3586OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3587 mlir::Attribute vec = adaptor.getVec();
3588 mlir::Attribute indices = adaptor.getIndices();
3589 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3590 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3591 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3592 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3594 mlir::ArrayAttr vecElts = vecAttr.getElts();
3595 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3597 const uint64_t numElements = vecElts.size();
3600 elements.reserve(numElements);
3602 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3603 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3604 uint64_t idxValue = idxAttr.getUInt();
3605 uint64_t newIdx = idxValue & maskBits;
3606 elements.push_back(vecElts[newIdx]);
3609 return cir::ConstVectorAttr::get(
3610 getType(), mlir::ArrayAttr::get(getContext(), elements));
3616LogicalResult cir::VecShuffleDynamicOp::verify() {
3618 if (getVec().
getType().getSize() !=
3619 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3620 return emitOpError() <<
": the number of elements in " << getVec().getType()
3621 <<
" and " << getIndices().getType() <<
" don't match";
3630LogicalResult cir::VecTernaryOp::verify() {
3635 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3636 return emitOpError() <<
": the number of elements in "
3637 << getCond().getType() <<
" and " << getLhs().getType()
3643OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3644 mlir::Attribute cond = adaptor.getCond();
3645 mlir::Attribute lhs = adaptor.getLhs();
3646 mlir::Attribute rhs = adaptor.getRhs();
3648 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3649 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3650 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3652 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3653 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3654 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3656 mlir::ArrayAttr condElts = condVec.getElts();
3659 elements.reserve(condElts.size());
3661 for (
const auto &[idx, condAttr] :
3662 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3663 if (condAttr.getSInt()) {
3664 elements.push_back(lhsVec.getElts()[idx]);
3666 elements.push_back(rhsVec.getElts()[idx]);
3670 cir::VectorType vecTy = getLhs().getType();
3671 return cir::ConstVectorAttr::get(
3672 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3679LogicalResult cir::ComplexCreateOp::verify() {
3682 <<
"operand type of cir.complex.create does not match its result type";
3689OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3690 mlir::Attribute real = adaptor.getReal();
3691 mlir::Attribute imag = adaptor.getImag();
3697 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3698 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3699 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3706LogicalResult cir::ComplexRealOp::verify() {
3707 mlir::Type operandTy = getOperand().getType();
3708 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3709 operandTy = complexOperandTy.getElementType();
3712 emitOpError() <<
": result type does not match operand type";
3719OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3720 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3723 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3724 return complexCreateOp.getOperand(0);
3727 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3728 return complex ? complex.getReal() :
nullptr;
3735LogicalResult cir::ComplexImagOp::verify() {
3736 mlir::Type operandTy = getOperand().getType();
3737 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3738 operandTy = complexOperandTy.getElementType();
3741 emitOpError() <<
": result type does not match operand type";
3748OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3749 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3752 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3753 return complexCreateOp.getOperand(1);
3756 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3757 return complex ? complex.getImag() :
nullptr;
3764LogicalResult cir::ComplexRealPtrOp::verify() {
3765 mlir::Type resultPointeeTy =
getType().getPointee();
3766 cir::PointerType operandPtrTy = getOperand().getType();
3767 auto operandPointeeTy =
3768 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3770 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3771 return emitOpError() <<
": result type does not match operand type";
3781LogicalResult cir::ComplexImagPtrOp::verify() {
3782 mlir::Type resultPointeeTy =
getType().getPointee();
3783 cir::PointerType operandPtrTy = getOperand().getType();
3784 auto operandPointeeTy =
3785 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3787 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3788 return emitOpError()
3789 <<
"cir.complex.imag_ptr result type does not match operand type";
3800 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3801 bool poisonZero =
false) {
3802 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3807 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3811 llvm::APInt inputValue = input.getValue();
3812 if (poisonZero && inputValue.isZero())
3813 return cir::PoisonAttr::get(input.getType());
3815 llvm::APInt resultValue = func(inputValue);
3816 return IntAttr::get(input.getType(), resultValue);
3819OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3820 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3821 unsigned resultValue =
3822 inputValue.getBitWidth() - inputValue.getSignificantBits();
3823 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3827OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3830 [](
const llvm::APInt &inputValue) {
3831 unsigned resultValue = inputValue.countLeadingZeros();
3832 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3837OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3840 [](
const llvm::APInt &inputValue) {
3841 return llvm::APInt(inputValue.getBitWidth(),
3842 inputValue.countTrailingZeros());
3847OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3848 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3849 unsigned trailingZeros = inputValue.countTrailingZeros();
3851 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3852 return llvm::APInt(inputValue.getBitWidth(), result);
3856OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3857 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3858 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3862OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3863 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3864 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3868OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3869 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3870 return inputValue.reverseBits();
3874OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3875 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3876 return inputValue.byteSwap();
3880OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3881 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3882 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3884 return cir::PoisonAttr::get(
getType());
3887 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3888 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3889 if (!input && !amount)
3898 llvm::APInt inputValue;
3900 inputValue = input.getValue();
3901 if (inputValue.isZero() || inputValue.isAllOnes()) {
3907 uint64_t amountValue;
3909 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
3910 if (amountValue == 0) {
3916 if (!input || !amount)
3919 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
3920 "input value must have the same bit width as the input type");
3922 llvm::APInt resultValue;
3924 resultValue = inputValue.rotl(amountValue);
3926 resultValue = inputValue.rotr(amountValue);
3928 return IntAttr::get(input.getContext(), input.getType(), resultValue);
3935void cir::InlineAsmOp::print(OpAsmPrinter &p) {
3936 p <<
'(' << getAsmFlavor() <<
", ";
3941 auto *nameIt = names.begin();
3942 auto *attrIt = getOperandAttrs().begin();
3944 for (mlir::OperandRange ops : getAsmOperands()) {
3945 p << *nameIt <<
" = ";
3948 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
3950 p.printOperand(value);
3951 p <<
" : " << value.getType();
3952 if (mlir::isa<mlir::UnitAttr>(*attrIt))
3953 p <<
" (maybe_memory)";
3962 p.printString(getAsmString());
3964 p.printString(getConstraints());
3968 if (getSideEffects())
3969 p <<
" side_effects";
3971 std::array elidedAttrs{
3972 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
3973 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
3974 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
3975 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
3977 if (
auto v = getRes())
3978 p <<
" -> " << v.getType();
3981void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
3983 StringRef asmString, StringRef constraints,
3984 bool sideEffects, cir::AsmFlavor asmFlavor,
3988 for (
auto operandRange : asmOperands) {
3989 segments.push_back(operandRange.size());
3990 odsState.addOperands(operandRange);
3993 odsState.addAttribute(
3994 "operands_segments",
3995 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
3996 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
3997 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
3998 odsState.addAttribute(
"asm_flavor",
3999 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
4002 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
4004 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
4007ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
4008 OperationState &result) {
4011 std::string asmString, constraints;
4013 MLIRContext *ctxt = parser.getBuilder().getContext();
4015 auto error = [&](
const Twine &msg) -> LogicalResult {
4016 return parser.emitError(parser.getCurrentLocation(), msg);
4019 auto expected = [&](
const std::string &c) {
4020 return error(
"expected '" + c +
"'");
4023 if (parser.parseLParen().failed())
4024 return expected(
"(");
4026 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
4028 return error(
"Unknown AsmFlavor");
4030 if (parser.parseComma().failed())
4031 return expected(
",");
4033 auto parseValue = [&](
Value &v) {
4034 OpAsmParser::UnresolvedOperand op;
4036 if (parser.parseOperand(op) || parser.parseColon())
4037 return error(
"can't parse operand");
4040 if (parser.parseType(typ).failed())
4041 return error(
"can't parse operand type");
4043 if (parser.resolveOperand(op, typ, tmp))
4044 return error(
"can't resolve operand");
4046 return mlir::success();
4049 auto parseOperands = [&](llvm::StringRef
name) {
4050 if (parser.parseKeyword(name).failed())
4051 return error(
"expected " + name +
" operands here");
4052 if (parser.parseEqual().failed())
4053 return expected(
"=");
4054 if (parser.parseLSquare().failed())
4055 return expected(
"[");
4058 if (parser.parseOptionalRSquare().succeeded()) {
4059 operandsGroupSizes.push_back(size);
4060 if (parser.parseComma())
4061 return expected(
",");
4062 return mlir::success();
4065 auto parseOperand = [&]() {
4067 if (parseValue(val).succeeded()) {
4068 result.operands.push_back(val);
4071 if (parser.parseOptionalLParen().failed()) {
4072 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
4073 return mlir::success();
4076 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
4077 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
4078 if (parser.parseRParen())
4079 return expected(
")");
4080 return mlir::success();
4082 return expected(
"maybe_memory");
4085 return mlir::failure();
4088 if (parser.parseCommaSeparatedList(parseOperand).failed())
4089 return mlir::failure();
4091 if (parser.parseRSquare().failed() || parser.parseComma().failed())
4092 return expected(
"]");
4093 operandsGroupSizes.push_back(size);
4094 return mlir::success();
4097 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
4098 parseOperands(
"in_out").failed())
4099 return error(
"failed to parse operands");
4101 if (parser.parseLBrace())
4102 return expected(
"{");
4103 if (parser.parseString(&asmString))
4104 return error(
"asm string parsing failed");
4105 if (parser.parseString(&constraints))
4106 return error(
"constraints string parsing failed");
4107 if (parser.parseRBrace())
4108 return expected(
"}");
4109 if (parser.parseRParen())
4110 return expected(
")");
4112 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
4113 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
4115 if (parser.parseOptionalAttrDict(result.attributes).failed())
4116 return mlir::failure();
4118 if (parser.parseOptionalArrow().succeeded() &&
4119 parser.parseType(resType).failed())
4120 return mlir::failure();
4122 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
4123 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
4124 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
4125 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
4126 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
4127 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
4129 result.addTypes(TypeRange{resType});
4131 return mlir::success();
4138template <
typename ThrowOpTy>
4141 return mlir::success();
4143 if (op.getNumOperands() != 0) {
4144 if (op.getTypeInfo())
4145 return mlir::success();
4146 return op.emitOpError() <<
"'type_info' symbol attribute missing";
4149 return mlir::failure();
4154mlir::LogicalResult cir::TryThrowOp::verify() {
4162LogicalResult cir::AtomicFetchOp::verify() {
4163 if (getBinop() != cir::AtomicFetchKind::Add &&
4164 getBinop() != cir::AtomicFetchKind::Sub &&
4165 getBinop() != cir::AtomicFetchKind::Max &&
4166 getBinop() != cir::AtomicFetchKind::Min &&
4167 !mlir::isa<cir::IntType>(getVal().
getType()))
4168 return emitError(
"only atomic add, sub, max, and min operation could "
4169 "operate on floating-point values");
4177LogicalResult cir::TypeInfoAttr::verify(
4178 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
4179 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
4181 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
4191void cir::TryOp::getSuccessorRegions(
4192 mlir::RegionBranchPoint point,
4195 if (!point.isParent()) {
4196 regions.emplace_back(getOperation());
4200 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
4204 for (mlir::Region &handlerRegion : this->getHandlerRegions())
4205 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
4208mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
4209 return successor.isOperation() ? ValueRange(getOperation()->getResults())
4213LogicalResult cir::TryOp::verify() {
4214 mlir::ArrayAttr handlerTypes = getHandlerTypes();
4215 if (!handlerTypes) {
4216 if (!getHandlerRegions().empty())
4218 "handler regions must be empty when no handler types are present");
4222 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
4226 if (handlerRegions.size() != handlerTypes.size())
4228 "number of handler regions and handler types must match");
4230 for (
const auto &[typeAttr, handlerRegion] :
4231 llvm::zip(handlerTypes, handlerRegions)) {
4233 mlir::Block &entryBlock = handlerRegion.front();
4234 if (entryBlock.getNumArguments() != 1 ||
4235 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
4237 "handler region must have a single '!cir.eh_token' argument");
4240 if (mlir::isa<cir::UnwindAttr>(typeAttr))
4246 if (entryBlock.empty())
4247 return emitOpError(
"catch handler region must not be empty");
4248 mlir::Operation *firstOp = &entryBlock.front();
4249 if (mlir::isa_and_present<cir::ConstructCatchParamOp>(firstOp))
4250 firstOp = firstOp->getNextNode();
4251 if (!firstOp || !mlir::isa<cir::BeginCatchOp>(firstOp))
4253 "catch handler region must start with 'cir.begin_catch'");
4261 mlir::MutableArrayRef<mlir::Region> handlerRegions,
4262 mlir::ArrayAttr handlerTypes) {
4266 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
4270 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
4271 printer <<
"catch all ";
4272 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
4273 printer <<
"unwind ";
4275 printer <<
"catch [type ";
4276 printer.printAttribute(typeAttr);
4281 mlir::Region ®ion = handlerRegions[typeIdx];
4282 if (!region.empty() && region.front().getNumArguments() > 0) {
4284 printer.printRegionArgument(region.front().getArgument(0));
4288 printer.printRegion(region,
4295 mlir::OpAsmParser &parser,
4297 mlir::ArrayAttr &handlerTypes) {
4299 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
4300 handlerRegions.emplace_back(
new mlir::Region);
4302 mlir::Region &currRegion = *handlerRegions.back();
4306 if (parser.parseLParen())
4308 mlir::OpAsmParser::Argument arg;
4309 if (parser.parseArgument(arg,
true))
4311 regionArgs.push_back(arg);
4312 if (parser.parseRParen())
4315 mlir::SMLoc regionLoc = parser.getCurrentLocation();
4316 if (parser.parseRegion(currRegion, regionArgs)) {
4317 handlerRegions.clear();
4321 if (currRegion.empty())
4322 return parser.emitError(regionLoc,
"handler region shall not be empty");
4324 if (!(currRegion.back().mightHaveTerminator() &&
4325 currRegion.back().getTerminator()))
4326 return parser.emitError(
4327 regionLoc,
"blocks are expected to be explicitly terminated");
4332 bool hasCatchAll =
false;
4334 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
4335 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
4337 llvm::StringRef attrStr;
4338 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
4339 return parser.emitError(parser.getCurrentLocation(),
4340 "expected 'all' or 'type' keyword");
4342 bool isCatchAll = attrStr ==
"all";
4345 return parser.emitError(parser.getCurrentLocation(),
4346 "can't have more than one catch all");
4350 mlir::Attribute exceptionRTTIAttr;
4351 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
4352 return parser.emitError(parser.getCurrentLocation(),
4353 "expected valid RTTI info attribute");
4355 catcherAttrs.push_back(isCatchAll
4356 ? cir::CatchAllAttr::get(parser.getContext())
4357 : exceptionRTTIAttr);
4359 if (hasLSquare && isCatchAll)
4360 return parser.emitError(parser.getCurrentLocation(),
4361 "catch all dosen't need RTTI info attribute");
4363 if (hasLSquare && parser.parseRSquare().failed())
4364 return parser.emitError(parser.getCurrentLocation(),
4365 "expected `]` after RTTI info attribute");
4367 if (parseCheckedCatcherRegion().failed())
4368 return mlir::failure();
4371 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
4373 return parser.emitError(parser.getCurrentLocation(),
4374 "unwind can't be used with catch all");
4376 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
4377 if (parseCheckedCatcherRegion().failed())
4378 return mlir::failure();
4381 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
4382 return mlir::success();
4390cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
4391 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
4392 if (!isa_and_nonnull<GlobalOp>(op))
4393 return emitOpError(
"'")
4394 << getTypeSym() <<
"' does not reference a valid cir.global";
4402LogicalResult cir::LifetimeStartOp::verify() {
4406LogicalResult cir::LifetimeEndOp::verify() {
4414LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
4415 SymbolTableCollection &symbolTable) {
4416 auto copyFnAttr = getCopyFnAttr();
4420 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
4422 return emitOpError(
"'")
4423 << *getCopyFn() <<
"' does not reference a valid cir.func";
4425 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
4426 return emitOpError(
"catch-init copy_fn must be tagged with the ")
4427 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
4429 cir::FuncType fnType = fn.getFunctionType();
4430 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
4431 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
4434 if (fnType.getInput(0) != getParamAddr().
getType())
4435 return emitOpError(
"first argument of catch-init copy_fn must match the "
4436 "type of 'param_addr'");
4438 if (fnType.getInput(1) != getParamAddr().
getType())
4440 "second argument of catch-init copy_fn must be a pointer "
4441 "to the catch type");
4452 SmallVectorImpl<Block *> &catchDestinations,
4453 Block *&defaultDestination,
4454 mlir::UnitAttr &defaultIsCatchAll) {
4456 if (parser.parseLSquare())
4460 bool hasCatchAll =
false;
4461 bool hasUnwind =
false;
4464 auto parseHandler = [&]() -> ParseResult {
4466 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
4468 return parser.emitError(parser.getCurrentLocation(),
4469 "duplicate 'catch_all' handler");
4471 return parser.emitError(parser.getCurrentLocation(),
4472 "cannot have both 'catch_all' and 'unwind'");
4475 if (parser.parseColon().failed())
4478 if (parser.parseSuccessor(defaultDestination).failed())
4484 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
4486 return parser.emitError(parser.getCurrentLocation(),
4487 "duplicate 'unwind' handler");
4489 return parser.emitError(parser.getCurrentLocation(),
4490 "cannot have both 'catch_all' and 'unwind'");
4493 if (parser.parseColon().failed())
4496 if (parser.parseSuccessor(defaultDestination).failed())
4504 if (parser.parseKeyword(
"catch").failed())
4507 if (parser.parseLParen().failed())
4510 mlir::Attribute catchTypeAttr;
4511 if (parser.parseAttribute(catchTypeAttr).failed())
4513 handlerTypes.push_back(catchTypeAttr);
4515 if (parser.parseRParen().failed())
4518 if (parser.parseColon().failed())
4522 if (parser.parseSuccessor(dest).failed())
4524 catchDestinations.push_back(dest);
4528 if (parser.parseCommaSeparatedList(parseHandler).failed())
4531 if (parser.parseRSquare().failed())
4535 if (!hasCatchAll && !hasUnwind)
4536 return parser.emitError(parser.getCurrentLocation(),
4537 "must have either 'catch_all' or 'unwind' handler");
4540 if (!handlerTypes.empty())
4541 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
4544 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
4550 mlir::ArrayAttr catchTypes,
4551 SuccessorRange catchDestinations,
4552 Block *defaultDestination,
4553 mlir::UnitAttr defaultIsCatchAll) {
4561 llvm::zip(catchTypes, catchDestinations),
4564 p.printAttribute(std::get<0>(i));
4566 p.printSuccessor(std::get<1>(i));
4578 if (defaultIsCatchAll)
4579 p <<
" catch_all : ";
4582 p.printSuccessor(defaultDestination);
4592#define GET_OP_CLASSES
4593#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static void printEhDispatchDestinations(OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, SuccessorRange catchDestinations, Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static ParseResult parseAssumeBundle(OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
static ParseResult parseEhDispatchDestinations(OpAsmParser &parser, mlir::ArrayAttr &catchTypes, SmallVectorImpl< Block * > &catchDestinations, Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
static void printAssumeBundle(OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, OperandRange bundleArgs, TypeRange bundleArgTypes)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
void printGlobalAddressSpaceValue(mlir::AsmPrinter &printer, cir::GlobalOp op, mlir::ptr::MemorySpaceAttrInterface attr)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op, Type flagType, SuccessorRange succs, OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
mlir::OptionalParseResult parseGlobalAddressSpaceValue(mlir::AsmParser &p, mlir::ptr::MemorySpaceAttrInterface &attr)
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
static void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
ParseResult parseIndirectBrOpSucessors(OpAsmParser &parser, Type &flagType, SmallVectorImpl< Block * > &succOperandBlocks, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &succOperands, SmallVectorImpl< SmallVector< Type > > &succOperandsTypes)
static bool omitRegionTerm(mlir::Region &r)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
const 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()