20#include "mlir/IR/Attributes.h"
21#include "mlir/IR/BuiltinOps.h"
22#include "mlir/IR/BuiltinTypes.h"
23#include "mlir/IR/DialectImplementation.h"
24#include "mlir/IR/PatternMatch.h"
25#include "mlir/IR/Value.h"
26#include "mlir/Interfaces/ControlFlowInterfaces.h"
27#include "mlir/Interfaces/FunctionImplementation.h"
28#include "mlir/Support/LLVM.h"
31#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
32#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
34#include "llvm/ADT/SetOperations.h"
35#include "llvm/ADT/SmallSet.h"
36#include "llvm/ADT/TypeSwitch.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/LogicalResult.h"
50struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
51 using OpAsmDialectInterface::OpAsmDialectInterface;
53 AliasResult getAlias(Type type, raw_ostream &os)
const final {
54 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
57 os <<
"rec_anon_" <<
recordType.getKindAsStr();
59 os <<
"rec_" << nameAttr.getValue();
60 return AliasResult::OverridableAlias;
62 if (
auto intType = dyn_cast<cir::IntType>(type)) {
65 unsigned width = intType.getWidth();
66 if (width < 8 || !llvm::isPowerOf2_32(width))
67 return AliasResult::NoAlias;
68 os << intType.getAlias();
69 return AliasResult::OverridableAlias;
71 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
72 os << voidType.getAlias();
73 return AliasResult::OverridableAlias;
76 return AliasResult::NoAlias;
79 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
80 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
81 os << (boolAttr.getValue() ?
"true" :
"false");
82 return AliasResult::FinalAlias;
84 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
85 os <<
"bfi_" << bitfield.getName().str();
86 return AliasResult::FinalAlias;
88 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
89 os << dynCastInfoAttr.getAlias();
90 return AliasResult::FinalAlias;
92 if (
auto cmpThreeWayInfoAttr =
93 mlir::dyn_cast<cir::CmpThreeWayInfoAttr>(attr)) {
94 os << cmpThreeWayInfoAttr.getAlias();
95 return AliasResult::FinalAlias;
97 return AliasResult::NoAlias;
102void cir::CIRDialect::initialize() {
103 addInterfaces<CIROpAsmDialectInterface>();
107Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
108 mlir::Attribute value,
110 mlir::Location loc) {
111 return cir::ConstantOp::create(builder, loc, type,
112 mlir::cast<mlir::TypedAttr>(value));
116 return attrName == CIRDialect::getOpenCLVersionAttrName() ||
117 attrName == CIRDialect::getOpenCLCXXVersionAttrName() ||
118 attrName == CIRDialect::getOpenCLSPIRVersionAttrName();
122 NamedAttribute attr) {
123 StringRef attrName = attr.getName().getValue();
124 if (isa<ModuleOp>(op))
127 return op->emitError() << attrName
128 <<
" attribute must be attached to a module";
132 cir::OpenCLVersionAttr cxxVersion) {
133 return (openCLVersion.getMajorVersion() == 2 &&
134 openCLVersion.getMinorVersion() == 0 &&
135 cxxVersion.getMajorVersion() == 1 &&
136 cxxVersion.getMinorVersion() == 0) ||
137 (openCLVersion.getMajorVersion() == 3 &&
138 openCLVersion.getMinorVersion() == 0 &&
139 cxxVersion.getMajorVersion() == 2021 &&
140 cxxVersion.getMinorVersion() == 0);
144 cir::OpenCLVersionAttr cxxVersion) {
145 Attribute openCLAttr =
146 module->getAttr(CIRDialect::getOpenCLVersionAttrName());
148 return module.emitError()
149 << "module attribute '" << CIRDialect::getOpenCLCXXVersionAttrName()
150 << "' requires the companion attribute '"
151 << CIRDialect::getOpenCLVersionAttrName() << "'";
153 auto openCLVersion = dyn_cast<cir::OpenCLVersionAttr>(openCLAttr);
158 return module.emitError("incompatible OpenCL and C++ for OpenCL versions");
164 NamedAttribute attr) {
168 StringRef attrName = attr.getName().getValue();
169 auto version = dyn_cast<cir::OpenCLVersionAttr>(attr.getValue());
171 return op->emitError() <<
"expected " << attrName
172 <<
" to be #cir.cl.version";
175 if (attrName == CIRDialect::getOpenCLCXXVersionAttrName())
181LogicalResult cir::CIRDialect::verifyRegionArgAttribute(
182 Operation *op,
unsigned ,
unsigned ,
183 NamedAttribute attr) {
190LogicalResult cir::CIRDialect::verifyRegionResultAttribute(
191 Operation *op,
unsigned ,
unsigned ,
192 NamedAttribute attr) {
204 cir::OffloadKind expected) {
205 auto attr =
module->getAttrOfType<cir::OffloadKindAttr>(
206 cir::CIRDialect::getOffloadKindAttrName());
208 return module.emitOpError()
209 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
210 << "' offload kind attribute";
211 if (attr.getValue() != expected)
212 return module.emitOpError()
213 << "expects '" << cir::CIRDialect::getOffloadKindAttrName()
214 << "' value '" << cir::stringifyOffloadKind(expected) << "'";
223 auto container = mlir::dyn_cast<mlir::ModuleOp>(op);
225 return op->emitOpError()
226 <<
"expects '" << cir::CIRDialect::getOffloadContainerAttrName()
227 <<
"' attribute to be attached to '"
228 << mlir::ModuleOp::getOperationName() <<
"'";
230 mlir::Block &body = *container.getBody();
232 return container.emitOpError()
233 <<
"expects host module as the first nested op";
235 auto host = mlir::dyn_cast<mlir::ModuleOp>(body.front());
237 return container.emitOpError()
238 <<
"expects host module as the first nested op";
243 if (std::next(body.begin()) == body.end())
244 return container.emitOpError() <<
"expects at least one device module";
246 for (
auto &op : llvm::drop_begin(body)) {
247 auto module = mlir::dyn_cast<mlir::ModuleOp>(op);
249 return container.emitOpError()
250 <<
"expects only nested builtin.module ops";
258cir::CIRDialect::verifyOperationAttribute(mlir::Operation *op,
259 mlir::NamedAttribute attr) {
260 llvm::StringRef attrName =
attr.getName().getValue();
264 if (attrName == getCXXABIAttrName()) {
265 if (!mlir::isa<mlir::ModuleOp>(op))
266 return op->emitOpError() <<
"expects '" << getCXXABIAttrName()
267 <<
"' attribute to be attached to '"
268 << mlir::ModuleOp::getOperationName() <<
"'";
269 auto abi = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
271 return op->emitOpError()
272 <<
"expects '" << getCXXABIAttrName() <<
"' to be a string";
274 StringRef abival = abi.getValue();
276 return op->emitOpError() <<
"unknown C++ ABI '" << abi.getValue() <<
"'";
279 if (
auto triple = op->getAttrOfType<mlir::StringAttr>(getTripleAttrName()))
281 llvm::Triple(triple.getValue()),
kind))
282 return op->emitOpError()
283 <<
"C++ ABI '" << abi.getValue()
284 <<
"' is not supported on target '" << triple.getValue() <<
"'";
289 if (attrName == getOffloadContainerAttrName()) {
290 if (!mlir::isa<mlir::UnitAttr>(
attr.getValue()))
291 return op->emitOpError() <<
"expects '" << getOffloadContainerAttrName()
292 <<
"' to be a unit attribute";
299 if (attrName == getOffloadKindAttrName() && !mlir::isa<mlir::ModuleOp>(op))
300 return op->emitOpError() <<
"expects '" << getOffloadKindAttrName()
301 <<
"' attribute to be attached to '"
302 << mlir::ModuleOp::getOperationName() <<
"'";
304 if (attrName == getModuleFramePointerAttrName()) {
305 if (!mlir::isa<mlir::ModuleOp>(op))
306 return op->emitOpError() <<
"expects '" << getModuleFramePointerAttrName()
307 <<
"' attribute to be attached to '"
308 << mlir::ModuleOp::getOperationName() <<
"'";
309 if (!mlir::isa<cir::FramePointerKindAttr>(
attr.getValue()))
310 return op->emitOpError() <<
"expects '" << getModuleFramePointerAttrName()
311 <<
"' to be a #cir.frame_pointer attribute";
317 if (attrName == getCUDADeviceBinaryAttrName()) {
318 auto bytes = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
321 if (!arrayTy || arrayTy.getSize() !=
bytes.size())
322 return op->emitOpError()
323 <<
"expects '" << getCUDADeviceBinaryAttrName()
324 <<
"' to be a string typed as an array of its length";
325 return cir::ConstArrayAttr::verify([&] {
return op->emitOpError(); },
330 if (attrName == getCUDAOffloadEntriesAttrName()) {
331 if (!mlir::isa<mlir::ModuleOp>(op))
332 return op->emitOpError() <<
"expects '" << getCUDAOffloadEntriesAttrName()
333 <<
"' attribute to be attached to '"
334 << mlir::ModuleOp::getOperationName() <<
"'";
335 auto entries = mlir::dyn_cast<mlir::ArrayAttr>(
attr.getValue());
337 !llvm::all_of(entries, llvm::IsaPred<cir::CUDAOffloadEntryAttr>))
338 return op->emitOpError() <<
"expects '" << getCUDAOffloadEntriesAttrName()
339 <<
"' to be an array of #cir.cu.offload_entry";
343 if (attrName == getTripleAttrName()) {
344 if (!mlir::isa<mlir::ModuleOp>(op))
345 return op->emitOpError()
346 <<
"expects '" << getTripleAttrName() <<
"' attribute to be "
347 <<
"attached to '" << mlir::ModuleOp::getOperationName() <<
"'";
349 auto tripleStr = mlir::dyn_cast<mlir::StringAttr>(
attr.getValue());
351 return op->emitOpError() <<
"expects '" << getTripleAttrName() <<
"' to "
353 llvm::Triple triple(tripleStr.getValue());
356 if (triple.getArch() == llvm::Triple::UnknownArch)
357 return op->emitOpError()
358 <<
"unknown triple '" << tripleStr.getValue() <<
"' in '"
359 << getTripleAttrName() <<
"' attribute";
362 if (attrName == getOptInfoAttrName()) {
363 if (!mlir::isa<mlir::ModuleOp>(op))
364 return op->emitOpError()
365 <<
"expects '" << getOptInfoAttrName() <<
"' attribute to be "
366 <<
"attached to '" << mlir::ModuleOp::getOperationName() <<
"'";
368 auto optInfo = mlir::dyn_cast<cir::OptInfoAttr>(
attr.getValue());
372 return op->emitOpError()
373 <<
"malformed " << cir::CIRDialect::getOptInfoAttrName()
389 for (
auto en : llvm::enumerate(keywords)) {
390 if (succeeded(parser.parseOptionalKeyword(en.value())))
397template <
typename Ty>
struct EnumTraits {};
399#define REGISTER_ENUM_TYPE(Ty) \
400 template <> struct EnumTraits<cir::Ty> { \
401 static llvm::StringRef stringify(cir::Ty value) { \
402 return stringify##Ty(value); \
404 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
415template <
typename EnumTy,
typename RetTy = EnumTy>
418 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
419 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
423 return static_cast<RetTy
>(defaultValue);
424 return static_cast<RetTy
>(index);
428template <
typename EnumTy,
typename RetTy = EnumTy>
431 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
432 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
437 result =
static_cast<RetTy
>(index);
445 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
446 OpBuilder builder(parser.getBuilder().getContext());
451 builder.createBlock(®ion);
453 Block &block = region.back();
455 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
459 if (!region.hasOneBlock())
460 return parser.emitError(errLoc,
461 "multi-block region must not omit terminator");
464 builder.setInsertionPointToEnd(&block);
465 cir::YieldOp::create(builder, eLoc);
471 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
472 const auto yieldsNothing = [&r]() {
473 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
474 return y && y.getArgs().empty();
476 return singleNonEmptyBlock && yieldsNothing();
481template <
typename ExpectedProducerOp>
483 StringRef operandName) {
484 Operation *producer = operand.getDefiningOp();
485 if (!producer || !isa<ExpectedProducerOp>(producer))
486 return op->emitOpError()
487 <<
"operand '" << operandName <<
"' must be produced by '"
488 << ExpectedProducerOp::getOperationName() <<
"'";
494 mod->getAttrOfType<mlir::StringAttr>(CIRDialect::getTripleAttrName());
501 return llvm::Triple{tripleAttr.getValue()};
509 cir::InlineKindAttr &inlineKindAttr) {
511 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
515 llvm::StringRef keyword;
516 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
522 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
523 if (!inlineKindResult) {
524 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
526 <<
"] for inlineKind, got: " << keyword;
530 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
535 if (inlineKindAttr) {
536 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
545 mlir::Region ®ion) {
546 auto regionLoc = parser.getCurrentLocation();
547 if (parser.parseRegion(region))
555 cir::ScopeOp &op, mlir::Region ®ion) {
556 printer.printRegion(region,
565void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
566 mlir::OperationState &odsState, mlir::Type addr,
567 llvm::StringRef name, mlir::IntegerAttr alignment) {
568 odsState.addAttribute(getNameAttrName(odsState.name),
569 odsBuilder.getStringAttr(name));
571 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
573 odsState.addTypes(addr);
577 auto loweringOpts = mod->getAttrOfType<cir::LoweringOptionsAttr>(
578 cir::CIRDialect::getLoweringOptionsAttrName());
579 return loweringOpts && loweringOpts.getRelativeCxxAbiVtables();
583 const mlir::DataLayout &dataLayout) {
587 return dataLayout.getTypeSize(
588 cir::PointerType::get(cir::VoidType::get(mod.getContext())));
592 mlir::Value ptr = addr;
593 while (cir::CastOp castOp = ptr.getDefiningOp<cir::CastOp>()) {
594 if (!castOp.isAllocaPreservingCast())
596 ptr = castOp.getSrc();
598 return ptr.getDefiningOp<cir::AllocaOp>();
606 auto ptrTy = mlir::cast<cir::PointerType>(op.getAddr().getType());
607 mlir::Type pointeeTy = ptrTy.getPointee();
609 mlir::Block &body = op.getBody().front();
610 if (body.getNumArguments() != 1)
611 return op.emitOpError(
"body must have exactly one block argument");
613 auto expectedEltPtrTy =
614 mlir::dyn_cast<cir::PointerType>(body.getArgument(0).getType());
615 if (!expectedEltPtrTy)
616 return op.emitOpError(
"block argument must be a !cir.ptr type");
618 if (op.getNumElements()) {
619 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
621 return op.emitOpError(
622 "when 'num_elements' is present, 'addr' must be a pointer to a "
623 "!cir.struct or !cir.union type");
625 if (expectedEltPtrTy != ptrTy)
626 return op.emitOpError(
"when 'num_elements' is present, 'addr' type must "
627 "match the block argument type");
629 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(pointeeTy);
631 return op.emitOpError(
632 "when 'num_elements' is absent, 'addr' must be a pointer to a "
635 mlir::Type innerEltTy = arrayTy.getElementType();
636 while (
auto nested = mlir::dyn_cast<cir::ArrayType>(innerEltTy))
637 innerEltTy = nested.getElementType();
639 auto recTy = mlir::dyn_cast<cir::RecordType>(innerEltTy);
641 return op.emitOpError(
"the block argument type must be a pointer to a "
642 "!cir.struct or !cir.union type");
644 if (expectedEltPtrTy.getPointee() != innerEltTy)
645 return op.emitOpError(
646 "block argument pointee type must match the innermost array "
649 if (expectedEltPtrTy.getAddrSpace() != ptrTy.getAddrSpace())
650 return op.emitOpError(
651 "block argument address space must match the 'addr' address space");
657LogicalResult cir::ArrayCtor::verify() {
661 mlir::Region &partialDtor = getPartialDtor();
662 if (!partialDtor.empty()) {
663 mlir::Block &dtorBlock = partialDtor.front();
664 if (dtorBlock.getNumArguments() != 1)
665 return emitOpError(
"partial_dtor must have exactly one block argument");
667 auto bodyArgTy = getBody().front().getArgument(0).getType();
668 if (dtorBlock.getArgument(0).getType() != bodyArgTy)
669 return emitOpError(
"partial_dtor block argument type must match "
670 "the body block argument type");
680LogicalResult cir::DeleteArrayOp::verify() {
681 if (getDtorMayThrow() && !getElementDtorAttr())
683 "'dtor_may_throw' requires an 'element_dtor' to be present");
692 cir::AssumeBundleKindAttr kindAttr,
693 OperandRange bundleArgs, TypeRange bundleArgTypes) {
694 cir::AssumeBundleKind
kind = kindAttr.getValue();
695 if (
kind == cir::AssumeBundleKind::None)
698 p <<
" " << cir::stringifyAssumeBundleKind(
kind);
699 if (bundleArgs.empty())
703 p.printOperands(bundleArgs);
705 llvm::interleaveComma(bundleArgTypes, p);
710 OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr,
714 auto loc = p.getCurrentLocation();
715 if (failed(p.parseOptionalKeyword(&keyword))) {
716 bundleKindAttr = cir::AssumeBundleKindAttr::get(
717 p.getContext(), cir::AssumeBundleKind::None);
721 std::optional<cir::AssumeBundleKind> parsedKind =
722 cir::symbolizeAssumeBundleKind(keyword);
724 return p.emitError(loc,
"unknown assume bundle kind '") << keyword <<
"'";
726 bundleKindAttr = cir::AssumeBundleKindAttr::get(p.getContext(), *parsedKind);
728 if (p.parseOptionalLParen())
731 if (p.parseOperandList(bundleArgs) || p.parseColon() ||
732 p.parseTypeList(bundleArgTypes) || p.parseRParen())
738LogicalResult cir::AssumeOp::verify() {
739 cir::AssumeBundleKind
kind = getBundleKind();
740 size_t numArgs = getBundleArgs().size();
742 if (
kind == cir::AssumeBundleKind::None) {
744 return emitOpError(
"unexpected bundle operands for kind 'none'");
749 return emitOpError(
"expected bundle operands for kind '")
750 << cir::stringifyAssumeBundleKind(
kind) <<
"'";
753 case cir::AssumeBundleKind::Align:
754 if (numArgs != 2 && numArgs != 3)
755 return emitOpError(
"align bundle expects 2 or 3 operands");
757 case cir::AssumeBundleKind::SeparateStorage:
759 return emitOpError(
"separate_storage bundle expects 2 operands");
761 case cir::AssumeBundleKind::Dereferenceable:
763 return emitOpError(
"dereferenceable bundle expects 2 operands");
775LogicalResult cir::AnnotationOp::verify() {
776 if (mlir::ArrayAttr args = getAnnotation().getArgs(); args && !args.empty())
777 return emitOpError(
"annotation must not have arguments");
778 return mlir::success();
786cir::LocalInitOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
787 cir::GlobalOp global = getReferencedGlobal(symbolTable);
789 return emitOpError(
"'")
790 << getGlobalName() <<
"' does not reference a valid cir.global";
792 if (getTls() && !global.getTlsModel())
793 return emitOpError(
"access to global not marked thread local");
795 if (!global.getDynamicInitGuard().has_value())
796 return emitOpError(
"static_local attribute mismatch");
808 for (mlir::Operation *parent = op->getParentOp(); parent;
809 parent = parent->getParentOp()) {
810 mlir::Region *ctorRegion =
nullptr;
811 if (
auto global = mlir::dyn_cast<cir::GlobalOp>(parent))
812 ctorRegion = &global.getCtorRegion();
813 else if (
auto localInit = mlir::dyn_cast<cir::LocalInitOp>(parent))
814 ctorRegion = &localInit.getCtorRegion();
815 else if (mlir::isa<cir::FuncOp, cir::RegisterExitDtorOp>(parent))
818 return ctorRegion->isAncestor(op->getParentRegion());
823LogicalResult cir::RegisterExitDtorOp::verify() {
824 mlir::Block &body = getBody().front();
825 if (body.without_terminator().empty())
826 return emitOpError(
"body must destroy the object");
827 if (body.getTerminator()->getNumOperands())
828 return emitOpError(
"body must not yield a value");
830 return emitOpError(
"must be in the ctor region of a cir.global or "
836cir::RegisterExitDtorOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
837 auto global = symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(
838 *
this, getObjectAttr());
840 return emitOpError(
"'")
841 << getObject() <<
"' does not reference a valid cir.global";
842 if (!global.getCtorRegion().empty() || !global.getDtorRegion().empty())
843 return emitOpError(
"object must not have ctor or dtor regions");
858 mlir::Operation *loopOp = loop.getOperation();
860 ->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
861 if (op != loopOp && isa<cir::LoopOpInterface, cir::SwitchOp>(op))
862 return mlir::WalkResult::skip();
863 if (isa<cir::BreakOp>(op))
864 return mlir::WalkResult::interrupt();
865 return mlir::WalkResult::advance();
870void cir::ConditionOp::getSuccessorRegions(
873 FoldAdaptor adaptor(operands, *
this);
874 auto cond = mlir::dyn_cast_if_present<cir::BoolAttr>(adaptor.getCondition());
875 bool mayBeTrue = !cond || cond.getValue();
876 bool mayBeFalse = !cond || !cond.getValue();
883 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
885 regions.emplace_back(&loopOp.getBody());
887 if (mlir::Region *cleanup = loopOp.maybeGetCleanup())
888 regions.emplace_back(cleanup);
890 regions.emplace_back(loopOp.getOperation());
897 auto await = cast<AwaitOp>(getOperation()->getParentOp());
899 regions.emplace_back(&await.getResume());
901 regions.emplace_back(&await.getSuspend());
905cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
907 return MutableOperandRange(getOperation(), 0, 0);
911cir::ResumeOp::getMutableSuccessorOperands(RegionSuccessor point) {
913 return MutableOperandRange(getOperation(), 0, 0);
917cir::CoroSuspendPoint::getMutableSuccessorOperands(RegionSuccessor point) {
919 return MutableOperandRange(getOperation(), 0, 0);
922LogicalResult cir::ConditionOp::verify() {
923 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
924 return emitOpError(
"condition must be within a conditional region");
932template <
typename LoopOpTy>
934 std::optional<cir::CleanupKind> cleanupKind = op.getCleanupKind();
938 if (cleanupKind.has_value() == op.getCleanup().empty())
939 return op.emitOpError(
"cleanup kind must be present if and only if the "
940 "cleanup region is non-empty");
945 if (cleanupKind == cir::CleanupKind::EH)
946 return op.emitOpError(
"loop cleanup kind must be 'normal' or 'all', "
961 mlir::Attribute attrType) {
962 if (isa<cir::ConstPtrAttr>(attrType)) {
963 if (!mlir::isa<cir::PointerType>(opType))
964 return op->emitOpError(
965 "pointer constant initializing a non-pointer type");
969 if (isa<cir::DataMemberAttr, cir::DataMemberOffsetAttr, cir::MethodAttr>(
976 if (isa<cir::ZeroAttr>(attrType)) {
977 if (isa<
cir::RecordType, cir::ArrayType, cir::MatrixType, cir::VectorType,
978 cir::ComplexType>(opType) ||
979 cir::isAnyOpaqueFloatingPointType(opType))
981 return op->emitOpError(
"zero expects struct, array, vector, complex, or "
982 "opaque floating-point type");
985 if (mlir::isa<cir::UndefAttr>(attrType)) {
986 if (!mlir::isa<cir::VoidType>(opType))
988 return op->emitOpError(
"undef expects non-void type");
991 if (mlir::isa<cir::BoolAttr>(attrType)) {
992 if (!mlir::isa<cir::BoolType>(opType))
993 return op->emitOpError(
"result type (")
994 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
998 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
999 auto at = cast<TypedAttr>(attrType);
1000 if (at.getType() != opType) {
1001 return op->emitOpError(
"result type (")
1002 << opType <<
") does not match value type (" << at.getType()
1008 if (mlir::isa<cir::BlockAddrDiffAttr, cir::BlockAddrInfoAttr,
1009 cir::ConstArrayAttr, cir::ConstVectorAttr,
1010 cir::ConstComplexAttr, cir::ConstRecordAttr,
1011 cir::GlobalOffsetAttr, cir::GlobalViewAttr, cir::PoisonAttr,
1012 cir::TypeInfoAttr, cir::VTableAttr>(attrType))
1015 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
1016 return op->emitOpError(
"global with type ")
1017 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
1020LogicalResult cir::ConstantOp::verify() {
1027OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
1037 case cir::CastKind::floating:
1038 case cir::CastKind::int_to_float:
1039 case cir::CastKind::float_to_int:
1040 case cir::CastKind::float_to_bool:
1041 case cir::CastKind::bool_to_float:
1042 case cir::CastKind::float_to_complex:
1043 case cir::CastKind::float_complex_to_real:
1044 case cir::CastKind::float_complex_to_bool:
1045 case cir::CastKind::float_complex:
1046 case cir::CastKind::float_complex_to_int_complex:
1047 case cir::CastKind::int_complex_to_float_complex:
1054LogicalResult cir::CastOp::verify() {
1055 mlir::Type resType =
getType();
1056 mlir::Type srcType = getSrc().getType();
1059 return emitOpError()
1060 <<
"'fenv' is only valid for floating-point cast kinds";
1064 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1065 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1066 if (srcPtrTy && resPtrTy && (
kind != cir::CastKind::address_space))
1067 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
1068 return emitOpError() <<
"result type address space does not match the "
1069 "address space of the operand";
1072 auto srcVTy = mlir::dyn_cast<cir::VectorType>(srcType);
1073 auto resVTy = mlir::dyn_cast<cir::VectorType>(resType);
1074 if (srcVTy && resVTy) {
1075 if (
kind != cir::CastKind::bitcast &&
1076 srcVTy.getSize() != resVTy.getSize()) {
1077 return emitOpError() <<
"vector " << cir::stringifyCastKind(
kind)
1078 <<
" cast require source and destination vectors to "
1079 "have the same number of "
1084 srcType = srcVTy.getElementType();
1085 resType = resVTy.getElementType();
1088 auto srcMatTy = mlir::dyn_cast<cir::MatrixType>(srcType);
1089 auto resMatTy = mlir::dyn_cast<cir::MatrixType>(resType);
1090 if (srcMatTy && resMatTy) {
1091 if (
kind != cir::CastKind::bitcast &&
1092 (srcMatTy.getNumRows() != resMatTy.getNumRows() ||
1093 srcMatTy.getNumColumns() != resMatTy.getNumColumns())) {
1094 return emitOpError() <<
"matrix " << cir::stringifyCastKind(
kind)
1095 <<
" cast require source and destination matrices "
1096 "to have the same number of "
1100 srcType = srcMatTy.getElementType();
1101 resType = resMatTy.getElementType();
1105 case cir::CastKind::int_to_bool: {
1106 if (!mlir::isa<cir::BoolType>(resType))
1107 return emitOpError() <<
"requires !cir.bool type for result";
1108 if (!mlir::isa<cir::IntType>(srcType))
1109 return emitOpError() <<
"requires !cir.int type for source";
1112 case cir::CastKind::ptr_to_bool: {
1113 if (!mlir::isa<cir::BoolType>(resType))
1114 return emitOpError() <<
"requires !cir.bool type for result";
1115 if (!mlir::isa<cir::PointerType>(srcType))
1116 return emitOpError() <<
"requires !cir.ptr type for source";
1119 case cir::CastKind::integral: {
1120 if (!mlir::isa<cir::IntType>(resType))
1121 return emitOpError() <<
"requires !cir.int type for result";
1122 if (!mlir::isa<cir::IntType>(srcType))
1123 return emitOpError() <<
"requires !cir.int type for source";
1126 case cir::CastKind::array_to_ptrdecay: {
1127 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1128 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1129 if (!arrayPtrTy || !flatPtrTy)
1130 return emitOpError() <<
"requires !cir.ptr type for source and result";
1135 case cir::CastKind::bitcast: {
1137 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1138 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1140 if (srcPtrTy && resPtrTy) {
1146 case cir::CastKind::floating: {
1147 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
1148 !mlir::isa<cir::FPTypeInterface>(resType))
1149 return emitOpError() <<
"requires !cir.float type for source and result";
1152 case cir::CastKind::float_to_int: {
1153 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1154 return emitOpError() <<
"requires !cir.float type for source";
1155 if (!mlir::dyn_cast<cir::IntType>(resType))
1156 return emitOpError() <<
"requires !cir.int type for result";
1159 case cir::CastKind::int_to_ptr: {
1160 if (!mlir::dyn_cast<cir::IntType>(srcType))
1161 return emitOpError() <<
"requires !cir.int type for source";
1162 if (!mlir::dyn_cast<cir::PointerType>(resType))
1163 return emitOpError() <<
"requires !cir.ptr type for result";
1166 case cir::CastKind::ptr_to_int: {
1167 if (!mlir::dyn_cast<cir::PointerType>(srcType))
1168 return emitOpError() <<
"requires !cir.ptr type for source";
1169 if (!mlir::dyn_cast<cir::IntType>(resType))
1170 return emitOpError() <<
"requires !cir.int type for result";
1173 case cir::CastKind::float_to_bool: {
1174 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1175 return emitOpError() <<
"requires !cir.float type for source";
1176 if (!mlir::isa<cir::BoolType>(resType))
1177 return emitOpError() <<
"requires !cir.bool type for result";
1180 case cir::CastKind::bool_to_int: {
1181 if (!mlir::isa<cir::BoolType>(srcType))
1182 return emitOpError() <<
"requires !cir.bool type for source";
1183 if (!mlir::isa<cir::IntType>(resType))
1184 return emitOpError() <<
"requires !cir.int type for result";
1187 case cir::CastKind::int_to_float: {
1188 if (!mlir::isa<cir::IntType>(srcType))
1189 return emitOpError() <<
"requires !cir.int type for source";
1190 if (!mlir::isa<cir::FPTypeInterface>(resType))
1191 return emitOpError() <<
"requires !cir.float type for result";
1194 case cir::CastKind::bool_to_float: {
1195 if (!mlir::isa<cir::BoolType>(srcType))
1196 return emitOpError() <<
"requires !cir.bool type for source";
1197 if (!mlir::isa<cir::FPTypeInterface>(resType))
1198 return emitOpError() <<
"requires !cir.float type for result";
1201 case cir::CastKind::address_space: {
1202 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
1203 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
1204 if (!srcPtrTy || !resPtrTy)
1205 return emitOpError() <<
"requires !cir.ptr type for source and result";
1206 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
1207 return emitOpError() <<
"requires two types differ in addrspace only";
1210 case cir::CastKind::float_to_complex: {
1211 if (!mlir::isa<cir::FPTypeInterface>(srcType))
1212 return emitOpError() <<
"requires !cir.float type for source";
1213 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1215 return emitOpError() <<
"requires !cir.complex type for result";
1216 if (srcType != resComplexTy.getElementType())
1217 return emitOpError() <<
"requires source type match result element type";
1220 case cir::CastKind::int_to_complex: {
1221 if (!mlir::isa<cir::IntType>(srcType))
1222 return emitOpError() <<
"requires !cir.int type for source";
1223 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1225 return emitOpError() <<
"requires !cir.complex type for result";
1226 if (srcType != resComplexTy.getElementType())
1227 return emitOpError() <<
"requires source type match result element type";
1230 case cir::CastKind::float_complex_to_real: {
1231 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1233 return emitOpError() <<
"requires !cir.complex type for source";
1234 if (!mlir::isa<cir::FPTypeInterface>(resType))
1235 return emitOpError() <<
"requires !cir.float type for result";
1236 if (srcComplexTy.getElementType() != resType)
1237 return emitOpError() <<
"requires source element type match result type";
1240 case cir::CastKind::int_complex_to_real: {
1241 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1243 return emitOpError() <<
"requires !cir.complex type for source";
1244 if (!mlir::isa<cir::IntType>(resType))
1245 return emitOpError() <<
"requires !cir.int type for result";
1246 if (srcComplexTy.getElementType() != resType)
1247 return emitOpError() <<
"requires source element type match result type";
1250 case cir::CastKind::float_complex_to_bool: {
1251 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1252 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1253 return emitOpError()
1254 <<
"requires floating point !cir.complex type for source";
1255 if (!mlir::isa<cir::BoolType>(resType))
1256 return emitOpError() <<
"requires !cir.bool type for result";
1259 case cir::CastKind::int_complex_to_bool: {
1260 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1261 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1262 return emitOpError()
1263 <<
"requires floating point !cir.complex type for source";
1264 if (!mlir::isa<cir::BoolType>(resType))
1265 return emitOpError() <<
"requires !cir.bool type for result";
1268 case cir::CastKind::float_complex: {
1269 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1270 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1271 return emitOpError()
1272 <<
"requires floating point !cir.complex type for source";
1273 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1274 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1275 return emitOpError()
1276 <<
"requires floating point !cir.complex type for result";
1279 case cir::CastKind::float_complex_to_int_complex: {
1280 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1281 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
1282 return emitOpError()
1283 <<
"requires floating point !cir.complex type for source";
1284 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1285 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1286 return emitOpError() <<
"requires integer !cir.complex type for result";
1289 case cir::CastKind::int_complex: {
1290 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1291 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1292 return emitOpError() <<
"requires integer !cir.complex type for source";
1293 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1294 if (!resComplexTy || !resComplexTy.isIntegerComplex())
1295 return emitOpError() <<
"requires integer !cir.complex type for result";
1298 case cir::CastKind::int_complex_to_float_complex: {
1299 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
1300 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
1301 return emitOpError() <<
"requires integer !cir.complex type for source";
1302 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
1303 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
1304 return emitOpError()
1305 <<
"requires floating point !cir.complex type for result";
1308 case cir::CastKind::member_ptr_to_bool: {
1309 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
1310 return emitOpError()
1311 <<
"requires !cir.data_member or !cir.method type for source";
1312 if (!mlir::isa<cir::BoolType>(resType))
1313 return emitOpError() <<
"requires !cir.bool type for result";
1317 llvm_unreachable(
"Unknown CastOp kind?");
1321 auto kind = op.getKind();
1322 return kind == cir::CastKind::bool_to_int ||
1323 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
1327 const auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
1328 return ptrTy && mlir::isa<cir::FuncType>(ptrTy.getPointee());
1332 cir::CastOp head = op, tail = op;
1338 op = head.getSrc().getDefiningOp<cir::CastOp>();
1344 if (head.getKind() == cir::CastKind::bool_to_int &&
1345 tail.getKind() == cir::CastKind::int_to_bool)
1346 return head.getSrc();
1351 if (head.getKind() == cir::CastKind::int_to_bool &&
1352 tail.getKind() == cir::CastKind::int_to_bool)
1353 return head.getResult();
1361 if (tail.getKind() == cir::CastKind::bitcast) {
1362 auto *inner = tail.getSrc().getDefiningOp();
1364 auto innerCast = mlir::dyn_cast<cir::CastOp>(inner);
1365 if (innerCast && innerCast.getKind() == cir::CastKind::bitcast &&
1366 innerCast.getSrc().getType() == tail.getType() &&
1367 innerCast.getType() == tail.getSrc().getType()) {
1368 return innerCast.getSrc();
1376OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
1377 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
1379 return cir::PoisonAttr::get(getContext(),
getType());
1383 if (mlir::isa_and_present<cir::UndefAttr>(adaptor.getSrc()))
1384 return cir::UndefAttr::get(
getType());
1388 case cir::CastKind::integral:
1389 case cir::CastKind::bitcast:
1390 case cir::CastKind::address_space:
1391 case cir::CastKind::float_complex:
1392 case cir::CastKind::int_complex: {
1406 if (mlir::Attribute src = adaptor.getSrc()) {
1408 case cir::CastKind::integral: {
1409 mlir::Type srcTy = getSrc().getType();
1411 assert(mlir::isa<cir::VectorType>(srcTy) ==
1412 mlir::isa<cir::VectorType>(
getType()));
1413 if (mlir::isa<cir::VectorType>(srcTy))
1416 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
1417 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
1418 auto constIntAttr = mlir::dyn_cast<cir::IntAttr>(src);
1422 APInt srcValue = constIntAttr.getValue();
1423 APInt newVal = srcIntTy.isSigned()
1424 ? srcValue.sextOrTrunc(dstIntTy.getWidth())
1425 : srcValue.zextOrTrunc(dstIntTy.getWidth());
1426 return cir::IntAttr::get(dstIntTy, newVal);
1428 case cir::CastKind::int_to_bool:
1429 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(src))
1430 return cir::BoolAttr::get(getContext(), !intAttr.getValue().isZero());
1432 case cir::CastKind::bool_to_int:
1434 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(src))
1435 return cir::IntAttr::get(
1437 llvm::APInt(mlir::cast<cir::IntType>(
getType()).getWidth(),
1438 boolAttr.getValue()));
1451LogicalResult cir::BuiltinIntCastOp::verify() {
1452 mlir::Type srcType = getSrc().getType();
1453 mlir::Type resType =
getType();
1455 auto srcCirInt = mlir::dyn_cast<cir::IntType>(srcType);
1456 auto resCirInt = mlir::dyn_cast<cir::IntType>(resType);
1460 if (
static_cast<bool>(srcCirInt) ==
static_cast<bool>(resCirInt))
1461 return emitOpError()
1462 <<
"requires exactly one '!cir.int' operand or result; the other "
1463 "must be a builtin integer or 'index' type";
1465 mlir::Type
builtinType = srcCirInt ? resType : srcType;
1466 if (!mlir::isa<mlir::IntegerType, mlir::IndexType>(builtinType))
1467 return emitOpError() <<
"requires a builtin integer or 'index' type on the "
1472 if (
auto builtinInt = mlir::dyn_cast<mlir::IntegerType>(builtinType)) {
1473 cir::IntType cirInt = srcCirInt ? srcCirInt : resCirInt;
1474 if (cirInt.getWidth() != builtinInt.getWidth())
1475 return emitOpError()
1476 <<
"requires the CIR and builtin integer types to have the same "
1477 "width; use 'cir.cast' for width conversions";
1483OpFoldResult cir::BuiltinIntCastOp::fold(FoldAdaptor adaptor) {
1486 if (
auto inner = getSrc().getDefiningOp<cir::BuiltinIntCastOp>())
1487 if (inner.getSrc().getType() ==
getType())
1488 return inner.getSrc();
1496mlir::OperandRange cir::CallOp::getArgOperands() {
1498 return getArgs().drop_front(1);
1502mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
1503 mlir::MutableOperandRange args = getArgsMutable();
1505 return args.slice(1, args.size() - 1);
1509mlir::Value cir::CallOp::getIndirectCall() {
1510 assert(isIndirect());
1511 return getOperand(0);
1515Value cir::CallOp::getArgOperand(
unsigned i) {
1518 return getOperand(i);
1522unsigned cir::CallOp::getNumArgOperands() {
1524 return this->getOperation()->getNumOperands() - 1;
1525 return this->getOperation()->getNumOperands();
1528static mlir::ParseResult
1530 mlir::OperationState &result) {
1531 mlir::Block *normalDestSuccessor;
1532 if (parser.parseSuccessor(normalDestSuccessor))
1533 return mlir::failure();
1535 if (parser.parseComma())
1536 return mlir::failure();
1538 mlir::Block *unwindDestSuccessor;
1539 if (parser.parseSuccessor(unwindDestSuccessor))
1540 return mlir::failure();
1542 result.addSuccessors(normalDestSuccessor);
1543 result.addSuccessors(unwindDestSuccessor);
1544 return mlir::success();
1553 const mlir::NamedAttrList &attrs) {
1554 if (mlir::Attribute effects =
1555 attrs.get(CIRDialect::getMemoryEffectsAttrName()))
1556 if (!mlir::isa<cir::MemoryEffectsAttr>(effects))
1557 return parser.emitError(loc,
"attribute '")
1558 << CIRDialect::getMemoryEffectsAttrName()
1559 <<
"' must be a #cir.memory_effects attribute";
1561 if (mlir::Attribute uwtable = attrs.get(CIRDialect::getUwtableAttrName()))
1562 if (!mlir::isa<cir::UnwindTableKindAttr>(uwtable))
1563 return parser.emitError(loc,
"attribute '")
1564 << CIRDialect::getUwtableAttrName()
1565 <<
"' must be a #cir.uwtable attribute";
1567 if (mlir::Attribute framePointer =
1568 attrs.get(CIRDialect::getFramePointerAttrName()))
1569 if (!mlir::isa<cir::FramePointerKindAttr>(framePointer))
1570 return parser.emitError(loc,
"attribute '")
1571 << CIRDialect::getFramePointerAttrName()
1572 <<
"' must be a #cir.frame_pointer attribute";
1574 for (llvm::StringRef name :
1575 {CIRDialect::getNoUnwindAttrName(), CIRDialect::getWillReturnAttrName(),
1576 CIRDialect::getMustProgressAttrName()})
1577 if (mlir::Attribute flag = attrs.get(name))
1578 if (!mlir::isa<mlir::UnitAttr>(flag))
1579 return parser.emitError(loc,
"attribute '")
1580 << name <<
"' must be a unit attribute";
1582 return mlir::success();
1586 mlir::OperationState &result,
1587 bool hasDestinationBlocks =
false) {
1590 mlir::FlatSymbolRefAttr calleeAttr;
1594 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
1597 OpAsmParser::UnresolvedOperand indirectVal;
1599 if (parser.parseOperand(indirectVal).failed())
1601 ops.push_back(indirectVal);
1604 if (parser.parseLParen())
1605 return mlir::failure();
1607 opsLoc = parser.getCurrentLocation();
1608 if (parser.parseOperandList(ops))
1609 return mlir::failure();
1610 if (parser.parseRParen())
1611 return mlir::failure();
1613 if (hasDestinationBlocks &&
1615 return ::mlir::failure();
1618 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
1619 cir::CallingConv callingConv;
1620 if (parser.parseLParen().failed())
1623 return parser.emitError(parser.getCurrentLocation(),
1624 "unknown calling convention");
1625 if (parser.parseRParen().failed())
1627 result.addAttribute(
1628 CIRDialect::getCallingConvAttrName(),
1629 cir::CallingConvAttr::get(parser.getContext(), callingConv));
1632 if (parser.parseOptionalKeyword(
"musttail").succeeded())
1633 result.addAttribute(CIRDialect::getMustTailAttrName(),
1634 mlir::UnitAttr::get(parser.getContext()));
1636 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
1637 result.addAttribute(CIRDialect::getNoThrowAttrName(),
1638 mlir::UnitAttr::get(parser.getContext()));
1640 if (parser.parseOptionalKeyword(
"nounwind").succeeded())
1641 result.addAttribute(CIRDialect::getNoUnwindAttrName(),
1642 mlir::UnitAttr::get(parser.getContext()));
1644 if (parser.parseOptionalKeyword(
"willreturn").succeeded())
1645 result.addAttribute(CIRDialect::getWillReturnAttrName(),
1646 mlir::UnitAttr::get(parser.getContext()));
1648 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
1649 if (parser.parseOptionalAttrDict(result.attributes))
1650 return ::mlir::failure();
1653 return ::mlir::failure();
1655 if (parser.parseColon())
1656 return ::mlir::failure();
1662 if (call_interface_impl::parseFunctionSignature(parser, argTypes, argAttrs,
1663 resultTypes, resultAttrs))
1664 return mlir::failure();
1666 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
1667 return parser.emitError(
1668 parser.getCurrentLocation(),
1669 "functions with multiple return types are not supported");
1671 result.addTypes(resultTypes);
1673 if (parser.resolveOperands(ops, argTypes, opsLoc, result.operands))
1674 return mlir::failure();
1676 if (!resultAttrs.empty() && resultAttrs[0])
1677 result.addAttribute(
1678 CIRDialect::getResAttrsAttrName(),
1679 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
1684 bool argAttrsEmpty =
true;
1686 llvm::transform(argAttrs, std::back_inserter(convertedArgAttrs),
1687 [&](DictionaryAttr da) -> mlir::Attribute {
1689 argAttrsEmpty =
false;
1693 if (!argAttrsEmpty) {
1698 argAttrsRef = argAttrsRef.drop_front();
1700 result.addAttribute(CIRDialect::getArgAttrsAttrName(),
1701 mlir::ArrayAttr::get(parser.getContext(), argAttrsRef));
1704 return mlir::success();
1708 mlir::FlatSymbolRefAttr calleeSym,
1709 mlir::Value indirectCallee,
1710 mlir::OpAsmPrinter &printer,
bool isNothrow,
1711 ArrayAttr argAttrs, ArrayAttr resAttrs,
1712 mlir::Block *normalDest =
nullptr,
1713 mlir::Block *unwindDest =
nullptr) {
1716 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
1717 auto ops = callLikeOp.getArgOperands();
1721 printer.printAttributeWithoutType(calleeSym);
1724 assert(indirectCallee);
1725 printer << indirectCallee;
1728 printer <<
"(" << ops <<
")";
1731 assert(unwindDest &&
"expected two successors");
1732 auto tryCall = cast<cir::TryCallOp>(op);
1733 printer <<
' ' << tryCall.getNormalDest();
1736 printer << tryCall.getUnwindDest();
1739 cir::CallingConv callingConv = callLikeOp.getCallingConv();
1740 if (callingConv != cir::CallingConv::C)
1741 printer <<
" cc(" << stringifyCallingConv(callingConv) <<
")";
1743 if (op->hasAttr(CIRDialect::getMustTailAttrName()))
1744 printer <<
" musttail";
1747 printer <<
" nothrow";
1749 if (op->hasAttr(CIRDialect::getNoUnwindAttrName()))
1750 printer <<
" nounwind";
1752 if (op->hasAttr(CIRDialect::getWillReturnAttrName()))
1753 printer <<
" willreturn";
1755 llvm::StringRef elidedAttrs[] = {
1756 CIRDialect::getCalleeAttrName(),
1757 CIRDialect::getCallingConvAttrName(),
1758 CIRDialect::getMustTailAttrName(),
1759 CIRDialect::getNoThrowAttrName(),
1760 CIRDialect::getNoUnwindAttrName(),
1761 CIRDialect::getWillReturnAttrName(),
1762 CIRDialect::getOperandSegmentSizesAttrName(),
1769 for (mlir::NamedAttribute attr : op->getDiscardableAttrs())
1770 if (!llvm::is_contained(elidedAttrs, attr.getName()))
1771 attrs.push_back(attr);
1772 op->getName().walkInherentAttrs(op, [&](llvm::StringRef name,
1773 mlir::Attribute &attr) {
1774 if (!llvm::is_contained(elidedAttrs, name))
1775 attrs.emplace_back(mlir::StringAttr::get(op->getContext(), name), attr);
1777 llvm::sort(attrs, [](mlir::NamedAttribute lhs, mlir::NamedAttribute rhs) {
1778 return lhs.getName().strref() < rhs.getName().strref();
1780 printer.printOptionalAttrDict(attrs);
1782 if (calleeSym || !argAttrs) {
1783 call_interface_impl::printFunctionSignature(
1784 printer, op->getOperands().getTypes(), argAttrs,
1785 false, op->getResultTypes(), resAttrs);
1793 shimmedArgAttrs.push_back(mlir::DictionaryAttr::get(op->getContext(), {}));
1794 shimmedArgAttrs.append(argAttrs.begin(), argAttrs.end());
1795 call_interface_impl::printFunctionSignature(
1796 printer, op->getOperands().getTypes(),
1797 mlir::ArrayAttr::get(op->getContext(), shimmedArgAttrs),
1798 false, op->getResultTypes(), resAttrs);
1802mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
1803 mlir::OperationState &result) {
1807void cir::CallOp::print(mlir::OpAsmPrinter &p) {
1808 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1809 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1810 getArgAttrsAttr(), getResAttrsAttr());
1815 SymbolTableCollection &symbolTable) {
1816 auto callIf = cast<cir::CIRCallOpInterface>(op);
1820 cir::FuncType fnType;
1821 bool hasPrototype =
true;
1823 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
1825 if (op->getNumOperands() == 0)
1826 return op->emitOpError(
"indirect call requires a callee operand");
1827 mlir::Type calleeTy = callIf.getIndirectCall().getType();
1828 if (
auto ptrTy = mlir::dyn_cast<cir::PointerType>(calleeTy))
1829 fnType = mlir::dyn_cast<cir::FuncType>(ptrTy.getPointee());
1831 return op->emitOpError()
1832 <<
"indirect callee must be a pointer to a function, but has type "
1835 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
1837 return op->emitOpError() <<
"'" << fnAttr.getValue()
1838 <<
"' does not reference a valid function";
1839 fnType = fn.getFunctionType();
1840 hasPrototype = !fn.getNoProto();
1846 unsigned numCallOperands = callIf.getNumArgOperands();
1847 unsigned numFnOpOperands = fnType.getNumInputs();
1849 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
1850 return op->emitOpError(
"incorrect number of operands for callee");
1851 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
1852 return op->emitOpError(
"too few operands for callee");
1854 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
1855 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
1856 return op->emitOpError(
"operand type mismatch: expected operand type ")
1857 << fnType.getInput(i) <<
", but provided "
1858 << callIf.getArgOperand(i).getType() <<
" for operand number "
1865 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
1866 return op->emitOpError(
"callee returns void but call has results");
1869 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
1870 return op->emitOpError(
"incorrect number of results for callee");
1873 if (!fnType.hasVoidReturn() &&
1874 op->getResultTypes().front() != fnType.getReturnType()) {
1875 return op->emitOpError(
"result type mismatch: expected ")
1876 << fnType.getReturnType() <<
", but provided "
1877 << op->getResult(0).getType();
1880 return mlir::success();
1884cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1892mlir::OperandRange cir::TryCallOp::getArgOperands() {
1894 return getArgs().drop_front(1);
1898mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1899 mlir::MutableOperandRange args = getArgsMutable();
1901 return args.slice(1, args.size() - 1);
1905mlir::Value cir::TryCallOp::getIndirectCall() {
1906 assert(isIndirect());
1907 return getOperand(0);
1911Value cir::TryCallOp::getArgOperand(
unsigned i) {
1914 return getOperand(i);
1918unsigned cir::TryCallOp::getNumArgOperands() {
1920 return this->getOperation()->getNumOperands() - 1;
1921 return this->getOperation()->getNumOperands();
1925cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1929mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1930 mlir::OperationState &result) {
1934void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1935 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1936 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1937 getArgAttrsAttr(), getResAttrsAttr(), getNormalDest(),
1946 cir::FuncOp function) {
1948 if (op.getNumOperands() > 1)
1949 return op.emitOpError() <<
"expects at most 1 return operand";
1952 auto expectedTy = function.getFunctionType().getReturnType();
1954 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1955 : op.getOperand(0).getType());
1956 if (actualTy != expectedTy)
1957 return op.emitOpError() <<
"returns " << actualTy
1958 <<
" but enclosing function returns " << expectedTy;
1960 return mlir::success();
1963mlir::LogicalResult cir::ReturnOp::verify() {
1966 auto *fnOp = getOperation()->getParentOp();
1967 while (!isa<cir::FuncOp>(fnOp))
1968 fnOp = fnOp->getParentOp();
1981ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1983 result.regions.reserve(2);
1984 Region *thenRegion = result.addRegion();
1985 Region *elseRegion = result.addRegion();
1987 mlir::Builder &builder = parser.getBuilder();
1988 OpAsmParser::UnresolvedOperand cond;
1989 Type boolType = cir::BoolType::get(builder.getContext());
1991 if (parser.parseOperand(cond) ||
1992 parser.resolveOperand(cond, boolType, result.operands))
1996 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1997 if (parser.parseRegion(*thenRegion, {}, {}))
2004 if (!parser.parseOptionalKeyword(
"else")) {
2005 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
2006 if (parser.parseRegion(*elseRegion, {}, {}))
2013 if (parser.parseOptionalAttrDict(result.attributes))
2018void cir::IfOp::print(OpAsmPrinter &p) {
2019 p <<
" " << getCondition() <<
" ";
2020 mlir::Region &thenRegion = this->getThenRegion();
2021 p.printRegion(thenRegion,
2026 mlir::Region &elseRegion = this->getElseRegion();
2027 if (!elseRegion.empty()) {
2029 p.printRegion(elseRegion,
2034 p.printOptionalAttrDict(
2035 getOperation()->getDiscardableAttrDictionary().getValue());
2041 cir::YieldOp::create(builder, loc);
2049void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
2050 SmallVectorImpl<RegionSuccessor> ®ions) {
2052 if (!point.isParent()) {
2053 regions.emplace_back(getOperation());
2058 Region *elseRegion = &this->getElseRegion();
2059 if (elseRegion->empty())
2060 elseRegion =
nullptr;
2063 regions.push_back(RegionSuccessor(&getThenRegion()));
2065 regions.push_back(RegionSuccessor(elseRegion));
2067 regions.emplace_back(getOperation());
2070void cir::IfOp::getEntrySuccessorRegions(
2072 FoldAdaptor adaptor(operands, *
this);
2073 auto cond = mlir::dyn_cast_if_present<cir::BoolAttr>(adaptor.getCondition());
2075 getSuccessorRegions(mlir::RegionBranchPoint::parent(), regions);
2082 if (cond.getValue())
2083 regions.emplace_back(&getThenRegion());
2084 else if (!getElseRegion().empty())
2085 regions.emplace_back(&getElseRegion());
2087 regions.emplace_back(getOperation());
2090void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
2093 assert(thenBuilder &&
"the builder callback for 'then' must be present");
2094 result.addOperands(cond);
2096 OpBuilder::InsertionGuard guard(builder);
2097 Region *thenRegion = result.addRegion();
2098 builder.createBlock(thenRegion);
2099 thenBuilder(builder, result.location);
2101 Region *elseRegion = result.addRegion();
2102 if (!withElseRegion)
2105 builder.createBlock(elseRegion);
2106 elseBuilder(builder, result.location);
2113void cir::ScopeOp::build(
2114 OpBuilder &builder, OperationState &result,
2115 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
2116 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
2118 OpBuilder::InsertionGuard guard(builder);
2119 Region *scopeRegion = result.addRegion();
2120 builder.createBlock(scopeRegion);
2124 scopeBuilder(builder, yieldTy, result.location);
2127 result.addTypes(TypeRange{yieldTy});
2130void cir::ScopeOp::build(
2131 OpBuilder &builder, OperationState &result,
2132 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
2133 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
2134 OpBuilder::InsertionGuard guard(builder);
2135 Region *scopeRegion = result.addRegion();
2136 builder.createBlock(scopeRegion);
2138 scopeBuilder(builder, result.location);
2141LogicalResult cir::ScopeOp::verify() {
2142 if (getRegion().empty()) {
2143 return emitOpError() <<
"cir.scope must not be empty since it should "
2144 "include at least an implicit cir.yield ";
2147 mlir::Block &lastBlock = getRegion().back();
2148 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
2149 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
2150 return emitOpError() <<
"last block of cir.scope must be terminated";
2154LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
2155 SmallVectorImpl<OpFoldResult> &results) {
2157 if (!getRegion().hasOneBlock())
2159 Block &block = getRegion().front();
2160 if (block.getOperations().size() != 1)
2163 auto yield = dyn_cast<cir::YieldOp>(block.front());
2168 if (getNumResults() != 1 || yield.getNumOperands() != 1)
2171 results.push_back(yield.getOperand(0));
2180 for (mlir::Block &block : cleanupRegion) {
2181 for (mlir::Operation &op : block) {
2182 if (isa<cir::YieldOp, cir::LifetimeEndOp, cir::StackRestoreOp>(op))
2185 auto loadOp = dyn_cast<cir::LoadOp>(op);
2186 if (loadOp && loadOp.getResult().hasOneUse() &&
2187 isa<cir::StackRestoreOp>(*loadOp.getResult().getUsers().begin()))
2195LogicalResult cir::CleanupScopeOp::verify() {
2199 cir::CallOp mustTailCall;
2200 getBodyRegion().walk([&](cir::CallOp callOp) {
2201 if (!callOp.getMusttail())
2202 return WalkResult::advance();
2203 mustTailCall = callOp;
2204 return WalkResult::interrupt();
2212 InFlightDiagnostic diag =
2213 emitOpError(
"cleanup is not redundant before a return, so it cannot be "
2214 "skipped by a musttail call");
2215 diag.attachNote(mustTailCall.getLoc()) <<
"musttail call is here";
2219void cir::CleanupScopeOp::getSuccessorRegions(
2220 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2225 if (point.isParent()) {
2226 regions.reserve(regions.size() + 2);
2227 regions.emplace_back(&getBodyRegion());
2228 regions.emplace_back(&getCleanupRegion());
2232 mlir::Operation *term = point.getTerminatorPredecessorOrNull();
2233 if (term->getParentRegion() == &getCleanupRegion()) {
2234 regions.emplace_back(getOperation());
2238 regions.emplace_back(&getCleanupRegion());
2243 cir::CleanupKindAttr
kind = getCleanupKindAttr();
2244 if (isa<cir::ResumeOp>(term) ? !
kind.isEH() : !
kind.isNormal())
2245 regions.emplace_back(getOperation());
2248LogicalResult cir::CleanupScopeOp::canonicalize(CleanupScopeOp op,
2249 PatternRewriter &rewriter) {
2250 auto isRegionTrivial = [](Region ®ion) {
2251 assert(!region.empty() &&
"CleanupScopeOp regions must not be empty");
2252 if (!region.hasOneBlock())
2254 Block &block = llvm::getSingleElement(region);
2255 return llvm::hasSingleElement(block) &&
2256 isa<cir::YieldOp>(llvm::getSingleElement(block));
2259 Region &body = op.getBodyRegion();
2260 Region &
cleanup = op.getCleanupRegion();
2264 if (op.getCleanupKind() == CleanupKind::EH && isRegionTrivial(body)) {
2265 rewriter.eraseOp(op);
2271 if (!isRegionTrivial(cleanup) || !body.hasOneBlock())
2274 Block &bodyBlock = body.front();
2275 if (!isa<cir::YieldOp>(bodyBlock.getTerminator()))
2280 if (isa<cir::LabelOp>(bodyBlock.front()))
2283 Operation *yield = bodyBlock.getTerminator();
2284 rewriter.inlineBlockBefore(&bodyBlock, op);
2285 rewriter.eraseOp(yield);
2286 rewriter.eraseOp(op);
2290void cir::CleanupScopeOp::build(
2291 OpBuilder &builder, OperationState &result, CleanupKind cleanupKind,
2292 function_ref<
void(OpBuilder &, Location)> bodyBuilder,
2293 function_ref<
void(OpBuilder &, Location)> cleanupBuilder) {
2294 result.addAttribute(getCleanupKindAttrName(result.name),
2295 CleanupKindAttr::get(builder.getContext(), cleanupKind));
2297 OpBuilder::InsertionGuard guard(builder);
2300 Region *bodyRegion = result.addRegion();
2301 builder.createBlock(bodyRegion);
2303 bodyBuilder(builder, result.location);
2306 Region *cleanupRegion = result.addRegion();
2307 builder.createBlock(cleanupRegion);
2309 cleanupBuilder(builder, result.location);
2324LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
2325 Block *src = op->getBlock();
2326 Block *dst = op.getDest();
2333 if (src->getNumSuccessors() != 1 || dst->getSinglePredecessor() != src)
2338 if (isa<cir::LabelOp, cir::IndirectBrOp>(dst->front()))
2344 if (src->getNextNode() != dst && dst == &dst->getParent()->back() &&
2345 isa<RegionBranchTerminatorOpInterface>(dst->getTerminator()))
2351 if (llvm::any_of(op.getDestOperands(), [&](
Value operand) {
2352 auto arg = dyn_cast<BlockArgument>(operand);
2353 return arg && arg.getOwner() == dst;
2359 rewriter.eraseOp(op);
2360 rewriter.mergeBlocks(dst, src, operands);
2364mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
2365 assert(index == 0 &&
"invalid successor index");
2366 return mlir::SuccessorOperands(getDestOperandsMutable());
2377mlir::SuccessorOperands
2378cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
2379 assert(index < getNumSuccessors() &&
"invalid successor index");
2380 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
2384 OpAsmParser &parser, Type &flagType,
2385 SmallVectorImpl<Block *> &succOperandBlocks,
2388 if (failed(parser.parseCommaSeparatedList(
2389 OpAsmParser::Delimiter::Square,
2391 Block *destination = nullptr;
2392 SmallVector<OpAsmParser::UnresolvedOperand> operands;
2393 SmallVector<Type> operandTypes;
2395 if (parser.parseSuccessor(destination).failed())
2398 if (succeeded(parser.parseOptionalLParen())) {
2399 if (failed(parser.parseOperandList(
2400 operands, OpAsmParser::Delimiter::None)) ||
2401 failed(parser.parseColonTypeList(operandTypes)) ||
2402 failed(parser.parseRParen()))
2405 succOperandBlocks.push_back(destination);
2406 succOperands.emplace_back(operands);
2407 succOperandsTypes.emplace_back(operandTypes);
2410 "successor blocks")))
2416 Type flagType, SuccessorRange succs,
2417 OperandRangeRange succOperands,
2418 const TypeRangeRange &succOperandsTypes) {
2421 llvm::zip(succs, succOperands),
2424 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
2427 if (!succOperands.empty())
2436mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
2437 assert(index < getNumSuccessors() &&
"invalid successor index");
2438 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
2439 : getDestOperandsFalseMutable());
2443 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
2444 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
2452void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
2453 ArrayAttr value, CaseOpKind
kind,
2454 OpBuilder::InsertPoint &insertPoint) {
2455 OpBuilder::InsertionGuard guardSwitch(builder);
2456 result.addAttribute(
"value", value);
2457 result.getOrAddProperties<Properties>().
kind =
2458 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
2459 Region *caseRegion = result.addRegion();
2460 builder.createBlock(caseRegion);
2462 insertPoint = builder.saveInsertionPoint();
2469void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
2471 assert(switchBuilder &&
"the builder callback for regions must be present");
2472 OpBuilder::InsertionGuard guardSwitch(builder);
2473 Region *switchRegion = result.addRegion();
2474 builder.createBlock(switchRegion);
2475 result.addOperands({cond});
2476 switchBuilder(builder, result.location, result);
2480 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
2482 if (isa<cir::SwitchOp>(op) && op != *
this)
2483 return WalkResult::skip();
2485 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
2486 cases.push_back(caseOp);
2488 return WalkResult::advance();
2493 collectCases(cases);
2495 if (getBody().empty())
2498 if (!isa<YieldOp>(getBody().front().back()))
2501 if (!llvm::all_of(getBody().front(),
2502 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
2505 return llvm::all_of(cases, [
this](CaseOp op) {
2506 return op->getParentOfType<SwitchOp>() == *
this;
2514void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
2515 Value value, Block *defaultDestination,
2516 ValueRange defaultOperands,
2518 BlockRange caseDestinations,
2521 std::vector<mlir::Attribute> caseValuesAttrs;
2522 for (
const APInt &val : caseValues)
2523 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
2524 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
2526 build(builder, result, value, defaultOperands, caseOperands, attrs,
2527 defaultDestination, caseDestinations);
2530SuccessorOperands cir::SwitchFlatOp::getSuccessorOperands(
unsigned index) {
2531 assert(index < getNumSuccessors() &&
"invalid successor index");
2533 return SuccessorOperands(getDefaultOperandsMutable());
2534 return SuccessorOperands(getCaseOperandsMutable()[index - 1]);
2539 auto cond = dyn_cast_if_present<cir::IntAttr>(operands.front());
2542 for (
auto [value, dest] : llvm::zip(getCaseValues(), getCaseDestinations())) {
2543 const APInt &caseValue = cast<cir::IntAttr>(value).getValue();
2544 if (caseValue == cond.getValue())
2547 return getDefaultDestination();
2553 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
2554 SmallVectorImpl<Block *> &caseDestinations,
2558 if (failed(parser.parseLSquare()))
2560 if (succeeded(parser.parseOptionalRSquare()))
2564 auto parseCase = [&]() {
2566 if (failed(parser.parseInteger(value)))
2569 values.push_back(cir::IntAttr::get(flagType, value));
2574 if (parser.parseColon() || parser.parseSuccessor(destination))
2576 if (!parser.parseOptionalLParen()) {
2577 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
2579 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
2582 caseDestinations.push_back(destination);
2583 caseOperands.emplace_back(operands);
2584 caseOperandTypes.emplace_back(operandTypes);
2587 if (failed(parser.parseCommaSeparatedList(parseCase)))
2590 caseValues = ArrayAttr::get(flagType.getContext(), values);
2592 return parser.parseRSquare();
2596 Type flagType, mlir::ArrayAttr caseValues,
2597 SuccessorRange caseDestinations,
2598 OperandRangeRange caseOperands,
2599 const TypeRangeRange &caseOperandTypes) {
2609 llvm::zip(caseValues, caseDestinations),
2612 mlir::Attribute a = std::get<0>(i);
2613 p << mlir::cast<cir::IntAttr>(a).getValue();
2615 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
2630 mlir::Attribute &valueAttr) {
2632 return parser.parseAttribute(valueAttr,
"value", attr);
2636 p.printAttribute(value);
2639mlir::LogicalResult cir::GlobalOp::verify() {
2642 if (mlir::isa<cir::FuncType>(getSymType()))
2643 return emitOpError(
"global type cannot be a function type");
2647 if (getInitialValue().has_value()) {
2655 if (!getCtorRegion().empty() && !getInitialValue().has_value())
2657 "cannot have a constructor region without an initial value");
2659 std::optional<DynamicInitInfoAttr>
info = getDynamicInitInfo();
2661 if ((getDynamicInitGuard().has_value()) && (!info ||
info->getLocal()) &&
2662 (!getCtorRegion().empty() || !getDtorRegion().empty()))
2664 "Cannot have a static-local global-op with a constructor or "
2665 "destructor, they require in-function initialization via LocalInitOp");
2671 if (getDynamicInitGuard().has_value() != getDynamicInitInfo().has_value())
2672 return emitOpError(
"'dynamic_init_guard' and 'dynamic_init_info' must be "
2673 "present together");
2682 if (getDynamicInitGuard().has_value() && !getTlsRefs()->getGuardName())
2683 return emitOpError(
"cannot have a dynamic-init guard combined with "
2684 "ordered tls references");
2686 return emitOpError(
"'tls_refs' only valid for tls");
2689 if (getAliasee().has_value()) {
2690 if (getInitialValue().has_value() || !getCtorRegion().empty() ||
2691 !getDtorRegion().empty())
2692 return emitOpError(
"global alias shall not have an initializer or "
2693 "constructor/destructor regions");
2702void cir::GlobalOp::build(
2703 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
2704 mlir::Type sym_type,
bool isConstant,
2705 mlir::ptr::MemorySpaceAttrInterface addrSpace,
2706 cir::GlobalLinkageKind linkage,
2707 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
2708 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
2709 odsState.addAttribute(getSymNameAttrName(odsState.name),
2710 odsBuilder.getStringAttr(sym_name));
2711 odsState.addAttribute(getSymTypeAttrName(odsState.name),
2712 mlir::TypeAttr::get(sym_type));
2713 auto &properties = odsState.getOrAddProperties<cir::GlobalOp::Properties>();
2714 properties.setConstant(isConstant);
2718 odsState.addAttribute(getAddrSpaceAttrName(odsState.name), addrSpace);
2720 cir::GlobalLinkageKindAttr linkageAttr =
2721 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
2722 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
2724 Region *ctorRegion = odsState.addRegion();
2726 odsBuilder.createBlock(ctorRegion);
2727 ctorBuilder(odsBuilder, odsState.location);
2730 Region *dtorRegion = odsState.addRegion();
2732 odsBuilder.createBlock(dtorRegion);
2733 dtorBuilder(odsBuilder, odsState.location);
2742void cir::GlobalOp::getSuccessorRegions(
2743 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2745 if (!point.isParent()) {
2746 regions.emplace_back(getOperation());
2751 Region *ctorRegion = &this->getCtorRegion();
2752 if (ctorRegion->empty())
2753 ctorRegion =
nullptr;
2756 Region *dtorRegion = &this->getDtorRegion();
2757 if (dtorRegion->empty())
2758 dtorRegion =
nullptr;
2762 regions.push_back(RegionSuccessor(ctorRegion));
2764 regions.push_back(RegionSuccessor(dtorRegion));
2771 if (!comdat.getValue().empty())
2772 p <<
"(\"" << comdat.getValue() <<
"\")";
2776 StringAttr comdat) {
2781 if (parser.parseOptionalKeyword(
"comdat").failed())
2783 std::string comdatKey;
2784 if (succeeded(parser.parseOptionalLParen())) {
2785 if (parser.parseString(&comdatKey).failed() ||
2786 parser.parseRParen().failed())
2789 comdatAttr = parser.getBuilder().getStringAttr(comdatKey);
2794 TypeAttr type, Attribute initAttr,
2795 mlir::Region &ctorRegion,
2796 mlir::Region &dtorRegion) {
2797 auto printType = [&]() { p <<
": " << type; };
2800 if (op.isDeclaration() || op.getAliasee()) {
2809 if (!ctorRegion.empty()) {
2811 p.printRegion(ctorRegion,
2816 if (!dtorRegion.empty()) {
2818 p.printRegion(dtorRegion,
2826 Attribute &initialValueAttr,
2827 mlir::Region &ctorRegion,
2828 mlir::Region &dtorRegion) {
2830 if (parser.parseOptionalEqual().failed()) {
2833 if (parser.parseColonType(opTy))
2842 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
2843 "Non-typed attrs shouldn't appear here.");
2844 opTy = mlir::cast<mlir::TypedAttr>(initialValueAttr).getType();
2848 if (!parser.parseOptionalKeyword(
"ctor")) {
2849 auto parseLoc = parser.getCurrentLocation();
2850 if (parser.parseRegion(ctorRegion, {}, {}))
2858 if (!parser.parseOptionalKeyword(
"dtor")) {
2859 auto parseLoc = parser.getCurrentLocation();
2860 if (parser.parseRegion(dtorRegion, {}, {}))
2867 typeAttr = TypeAttr::get(opTy);
2876cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2879 mlir::Operation *op =
2880 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
2881 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
2882 return emitOpError(
"'")
2884 <<
"' does not reference a valid cir.global or cir.func";
2887 mlir::ptr::MemorySpaceAttrInterface symAddrSpaceAttr{};
2888 if (
auto g = dyn_cast<GlobalOp>(op)) {
2889 symTy = g.getSymType();
2890 symAddrSpaceAttr = g.getAddrSpaceAttr();
2893 if (getTls() && !g.getTlsModel())
2894 return emitOpError(
"access to global not marked thread local");
2899 bool getGlobalIsStaticLocal = getStaticLocal();
2900 bool globalIsStaticLocal =
2901 g.getDynamicInitGuard().has_value() &&
2902 (!g.getDynamicInitInfo() || g.getDynamicInitInfo()->getLocal());
2904 if (getGlobalIsStaticLocal != globalIsStaticLocal &&
2905 !getOperation()->getParentOfType<cir::GlobalOp>())
2906 return emitOpError(
"static_local attribute mismatch");
2907 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
2908 symTy = f.getFunctionType();
2910 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
2913 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
2914 if (!resultType || symTy != resultType.getPointee())
2915 return emitOpError(
"result type pointee type '")
2916 << resultType.getPointee() <<
"' does not match type " << symTy
2917 <<
" of the global @" <<
getName();
2921 dyn_cast_if_present<TargetAddressSpaceAttr>(resultType.getAddrSpace());
2923 isa<FuncOp>(op) && targetAS &&
2924 targetAS.getValue() ==
2927 if (!isProgramAS && symAddrSpaceAttr != resultType.getAddrSpace()) {
2928 return emitOpError()
2929 <<
"result type address space does not match the address "
2930 "space of the global @"
2942cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2948 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2950 return emitOpError(
"'")
2951 <<
name <<
"' does not reference a valid cir.global";
2952 std::optional<mlir::Attribute> init = op.getInitialValue();
2955 auto vtable = dyn_cast<cir::VTableAttr>(*init);
2957 return emitOpError(
"Expected #cir.vtable in initializer for global '")
2962 cir::AddressPointAttr addressPoint = getAddressPoint();
2963 mlir::ArrayAttr addressPoints = vtable.getAddressPoints();
2964 if (addressPoint.getIndex() < 0 ||
2965 static_cast<size_t>(addressPoint.getIndex()) >= addressPoints.size())
2966 return emitOpError(
"address point refers to vtable ")
2967 << addressPoint.getIndex() <<
", but '" <<
name <<
"' has "
2968 << addressPoints.size() <<
" vtables";
2969 if (addressPoint != addressPoints[addressPoint.getIndex()])
2970 return emitOpError(
"address point ")
2971 << addressPoint <<
" does not match the address point "
2972 << addressPoints[addressPoint.getIndex()] <<
" of '" <<
name <<
"'";
2981cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2990 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
2992 return emitOpError(
"'")
2993 <<
name <<
"' does not reference a valid cir.global";
2994 auto resultType = mlir::cast<cir::PointerType>(getAddr().
getType());
2995 if (op.getAddrSpaceAttr() != resultType.getAddrSpace())
2996 return emitOpError()
2997 <<
"result type address space does not match the address "
2998 "space of the global @"
3000 std::optional<mlir::Attribute> init = op.getInitialValue();
3003 if (!isa<cir::ConstArrayAttr>(*init))
3005 "Expected constant array in initializer for global VTT '")
3010LogicalResult cir::VTTAddrPointOp::verify() {
3012 if (
getName() && getSymAddr())
3013 return emitOpError(
"should use either a symbol or value, but not both");
3020 auto resultType = mlir::cast<cir::PointerType>(getAddr().
getType());
3021 auto eltTy = mlir::dyn_cast<cir::PointerType>(resultType.getPointee());
3022 mlir::Type resTy = cir::PointerType::get(
3023 cir::PointerType::get(cir::VoidType::get(getContext()),
3024 eltTy ? eltTy.getAddrSpace() :
nullptr),
3025 resultType.getAddrSpace());
3027 if (resultType != resTy)
3028 return emitOpError(
"result type must be ")
3029 << resTy <<
", but provided result type is " << resultType;
3044 return name == CIRDialect::getMemoryEffectsAttrName() ||
3045 name == CIRDialect::getUwtableAttrName() ||
3046 name == CIRDialect::getFramePointerAttrName();
3049void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
3050 StringRef name, FuncType type,
3051 GlobalLinkageKind linkage, CallingConv callingConv) {
3053 result.addAttribute(getSymNameAttrName(result.name),
3054 builder.getStringAttr(name));
3055 result.addAttribute(getFunctionTypeAttrName(result.name),
3056 TypeAttr::get(type));
3057 result.addAttribute(
3059 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
3060 result.addAttribute(getCallingConvAttrName(result.name),
3061 CallingConvAttr::get(builder.getContext(), callingConv));
3064 result.addAttribute(getRequiresCallConvLoweringAttrName(result.name),
3065 builder.getUnitAttr());
3073cir::AnnotationAttr::verify(function_ref<InFlightDiagnostic()> emitError,
3074 mlir::StringAttr name, mlir::ArrayAttr args) {
3077 for (mlir::Attribute arg : args) {
3078 if (!isa<mlir::StringAttr, mlir::IntegerAttr>(arg))
3079 return emitError() <<
"annotation args must be StringAttr or IntegerAttr,"
3085ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
3086 llvm::SMLoc loc = parser.getCurrentLocation();
3087 mlir::Builder &builder = parser.getBuilder();
3089 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
3090 mlir::StringAttr coroutineKindNameAttr = getCoroutineKindAttrName(state.name);
3091 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
3092 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
3093 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
3094 mlir::StringAttr requiresCallConvLoweringNameAttr =
3095 getRequiresCallConvLoweringAttrName(state.name);
3096 mlir::StringAttr comdatNameAttr = getComdatAttrName(state.name);
3097 mlir::StringAttr alignmentNameAttr = getAlignmentAttrName(state.name);
3098 mlir::StringAttr preferredAlignmentNameAttr =
3099 getPreferredAlignmentAttrName(state.name);
3100 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
3101 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
3102 mlir::StringAttr unnamedAddrNameAttr = getUnnamedAddrAttrName(state.name);
3103 mlir::StringAttr funcInfoNameAttr = getFuncInfoAttrName(state.name);
3105 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
3106 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
3110 static constexpr llvm::StringRef keywords[] = {
"coroutine",
3111 "flattened_coroutine"};
3112 llvm::StringRef keyword;
3113 if (parser.parseOptionalKeyword(&keyword, keywords).succeeded())
3115 coroutineKindNameAttr,
3116 cir::CoroutineKindAttr::get(builder.getContext(),
3117 *cir::symbolizeCoroutineKind(keyword)));
3121 cir::InlineKindAttr inlineKindAttr;
3125 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
3127 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
3128 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
3129 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
3130 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
3133 StringAttr comdatAttr;
3137 state.addAttribute(comdatNameAttr, comdatAttr);
3140 auto parseAlignmentBody = [&](
int64_t &value) {
3141 if (parser.parseLParen().failed() || parser.parseInteger(value).failed() ||
3142 parser.parseRParen().failed())
3146 return static_cast<LogicalResult
>(parser.emitError(
3147 loc,
"function alignment must be a positive integer"));
3152 if (parser.parseOptionalKeyword(alignmentNameAttr).succeeded()) {
3154 if (parseAlignmentBody(value).failed())
3156 state.addAttribute(alignmentNameAttr, builder.getI64IntegerAttr(value));
3159 if (parser.parseOptionalKeyword(preferredAlignmentNameAttr).succeeded()) {
3161 if (parseAlignmentBody(value).failed())
3163 state.addAttribute(preferredAlignmentNameAttr,
3164 builder.getI64IntegerAttr(value));
3169 GlobalLinkageKindAttr::get(
3170 parser.getContext(),
3172 parser, GlobalLinkageKind::ExternalLinkage)));
3174 ::llvm::StringRef visAttrStr;
3175 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
3177 state.addAttribute(visNameAttr,
3178 parser.getBuilder().getStringAttr(visAttrStr));
3181 state.getOrAddProperties<cir::FuncOp::Properties>().global_visibility =
3184 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
3185 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
3187 if (parser.parseOptionalKeyword(unnamedAddrNameAttr).succeeded())
3188 state.addAttribute(unnamedAddrNameAttr, parser.getBuilder().getUnitAttr());
3190 StringAttr nameAttr;
3191 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(state.name),
3197 bool isVariadic =
false;
3198 if (function_interface_impl::parseFunctionSignatureWithArguments(
3199 parser,
true, arguments, isVariadic, resultTypes,
3204 bool argAttrsEmpty =
true;
3205 for (OpAsmParser::Argument &arg : arguments) {
3206 argTypes.push_back(
arg.type);
3210 argAttrs.push_back(
arg.attrs);
3212 argAttrsEmpty =
false;
3216 if (resultTypes.size() > 1 || resultAttrs.size() > 1)
3217 return parser.emitError(
3218 loc,
"functions with multiple return types are not supported");
3220 mlir::Type returnType =
3221 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
3222 : resultTypes.front());
3224 cir::FuncType fnType =
3225 cir::FuncType::getChecked([&]() {
return parser.emitError(loc); },
3226 argTypes, returnType, isVariadic);
3230 state.addAttribute(getFunctionTypeAttrName(state.name),
3231 TypeAttr::get(fnType));
3233 if (!resultAttrs.empty() && resultAttrs[0])
3235 getResAttrsAttrName(state.name),
3236 mlir::ArrayAttr::get(parser.getContext(), {resultAttrs[0]}));
3239 state.addAttribute(getArgAttrsAttrName(state.name),
3240 mlir::ArrayAttr::get(parser.getContext(), argAttrs));
3242 bool hasAlias =
false;
3243 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
3244 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
3245 if (parser.parseLParen().failed())
3247 mlir::StringAttr aliaseeAttr;
3248 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
3250 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
3251 if (parser.parseRParen().failed())
3256 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
3257 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
3258 if (parser.parseLParen().failed())
3260 mlir::StringAttr personalityAttr;
3261 if (parser.parseOptionalSymbolName(personalityAttr).failed())
3263 state.addAttribute(personalityNameAttr,
3264 FlatSymbolRefAttr::get(personalityAttr));
3265 if (parser.parseRParen().failed())
3270 mlir::StringAttr callConvNameAttr = getCallingConvAttrName(state.name);
3271 cir::CallingConv callConv = cir::CallingConv::C;
3272 if (parser.parseOptionalKeyword(
"cc").succeeded()) {
3273 if (parser.parseLParen().failed())
3276 return parser.emitError(loc) <<
"unknown calling convention";
3277 if (parser.parseRParen().failed())
3280 state.addAttribute(callConvNameAttr,
3281 cir::CallingConvAttr::get(parser.getContext(), callConv));
3283 auto parseGlobalDtorCtor =
3284 [&](StringRef keyword,
3285 llvm::function_ref<void(std::optional<int> prio)> createAttr)
3286 -> mlir::LogicalResult {
3287 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
3288 std::optional<int> priority;
3289 if (mlir::succeeded(parser.parseOptionalLParen())) {
3290 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
3291 if (mlir::failed(parsedPriority))
3292 return parser.emitError(parser.getCurrentLocation(),
3293 "failed to parse 'priority', of type 'int'");
3294 priority = parsedPriority.value_or(
int());
3296 if (parser.parseRParen())
3299 createAttr(priority);
3305 if (parser.parseOptionalKeyword(
"func_info").succeeded()) {
3306 if (parser.parseLess().failed())
3309 llvm::SMLoc attrLoc = parser.getCurrentLocation();
3310 mlir::Attribute
attr;
3311 if (parser.parseAttribute(attr).failed())
3313 if (!mlir::isa<cir::CXXCtorAttr, cir::CXXDtorAttr, cir::CXXAssignAttr,
3314 cir::FuncIdentityAttr>(attr))
3315 return parser.emitError(attrLoc,
3316 "expected a function info attribute, got ")
3318 state.addAttribute(funcInfoNameAttr, attr);
3320 if (parser.parseGreater().failed())
3324 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
3325 mlir::IntegerAttr globalCtorPriorityAttr =
3326 builder.getI32IntegerAttr(priority.value_or(65535));
3327 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
3328 globalCtorPriorityAttr);
3332 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
3333 mlir::IntegerAttr globalDtorPriorityAttr =
3334 builder.getI32IntegerAttr(priority.value_or(65535));
3335 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
3336 globalDtorPriorityAttr);
3341 mlir::StringAttr annotationsNameAttr = getAnnotationsAttrName(state.name);
3342 mlir::ArrayAttr annotationsAttr;
3343 if (parser.parseOptionalAttribute(annotationsAttr).has_value() &&
3345 state.addAttribute(annotationsNameAttr, annotationsAttr);
3347 if (parser.parseOptionalKeyword(requiresCallConvLoweringNameAttr).succeeded())
3348 state.addAttribute(requiresCallConvLoweringNameAttr,
3349 parser.getBuilder().getUnitAttr());
3352 NamedAttrList parsedAttrs;
3353 llvm::SMLoc attrsLoc = parser.getCurrentLocation();
3354 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
3358 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
3361 if (parsedAttrs.get(disallowed))
3362 return parser.emitError(loc,
"attribute '")
3364 <<
"' should not be specified in the explicit attribute list";
3370 state.attributes.append(parsedAttrs);
3373 auto *body = state.addRegion();
3374 OptionalParseResult parseResult = parser.parseOptionalRegion(
3375 *body, arguments,
false);
3376 if (parseResult.has_value()) {
3378 return parser.emitError(loc,
"function alias shall not have a body");
3379 if (failed(*parseResult))
3383 return parser.emitError(loc,
"expected non-empty function body");
3392bool cir::FuncOp::isDeclaration() {
3395 std::optional<StringRef> aliasee = getAliasee();
3397 return getFunctionBody().empty();
3403bool cir::FuncOp::isCXXSpecialMemberFunction() {
3406 mlir::Attribute
attr = getFuncInfoAttr();
3407 return attr && mlir::isa<CXXCtorAttr, CXXDtorAttr, CXXAssignAttr>(attr);
3410bool cir::FuncOp::isCxxConstructor() {
3411 auto attr = getFuncInfoAttr();
3412 return attr && dyn_cast<CXXCtorAttr>(attr);
3415bool cir::FuncOp::isCxxDestructor() {
3416 auto attr = getFuncInfoAttr();
3417 return attr && dyn_cast<CXXDtorAttr>(attr);
3420bool cir::FuncOp::isCxxSpecialAssignment() {
3421 auto attr = getFuncInfoAttr();
3422 return attr && dyn_cast<CXXAssignAttr>(attr);
3425std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
3426 mlir::Attribute
attr = getFuncInfoAttr();
3428 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
3429 return ctor.getCtorKind();
3431 return std::nullopt;
3434std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
3435 mlir::Attribute
attr = getFuncInfoAttr();
3437 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
3438 return assign.getAssignKind();
3440 return std::nullopt;
3443bool cir::FuncOp::isCxxTrivialMemberFunction() {
3444 mlir::Attribute
attr = getFuncInfoAttr();
3446 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
3447 return ctor.getIsTrivial();
3448 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
3449 return dtor.getIsTrivial();
3450 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
3451 return assign.getIsTrivial();
3456mlir::Region *cir::FuncOp::getCallableRegion() {
3460 if (getBody().empty())
3465void cir::FuncOp::print(OpAsmPrinter &p) {
3469 if (std::optional<cir::CoroutineKind> coroKind = getCoroutineKind())
3470 p <<
' ' << cir::stringifyCoroutineKind(*coroKind);
3480 if (getComdatAttr()) {
3486 p <<
" alignment(" << *getAlignment() <<
')';
3488 if (getPreferredAlignment())
3489 p <<
" preferred_alignment(" << *getPreferredAlignment() <<
')';
3491 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
3492 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
3494 mlir::SymbolTable::Visibility vis = getVisibility();
3495 if (vis != mlir::SymbolTable::Visibility::Public)
3498 if (getGlobalVisibility() != cir::VisibilityKind::Default)
3499 p <<
' ' << stringifyVisibilityKind(getGlobalVisibility());
3504 if (getUnnamedAddr())
3505 p <<
" unnamed_addr";
3508 p.printSymbolName(getSymName());
3509 cir::FuncType fnType = getFunctionType();
3510 function_interface_impl::printFunctionSignature(
3511 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
3513 if (std::optional<StringRef> aliaseeName = getAliasee()) {
3515 p.printSymbolName(*aliaseeName);
3519 if (getCallingConv() != cir::CallingConv::C) {
3521 p << stringifyCallingConv(getCallingConv());
3525 if (std::optional<StringRef> personalityName = getPersonality()) {
3526 p <<
" personality(";
3527 p.printSymbolName(*personalityName);
3531 if (mlir::Attribute funcInfo = getFuncInfoAttr()) {
3533 p.printAttribute(funcInfo);
3537 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
3538 p <<
" global_ctor";
3539 if (globalCtorPriority.value() != 65535)
3540 p <<
"(" << globalCtorPriority.value() <<
")";
3543 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
3544 p <<
" global_dtor";
3545 if (globalDtorPriority.value() != 65535)
3546 p <<
"(" << globalDtorPriority.value() <<
")";
3549 if (mlir::ArrayAttr annotations = getAnnotationsAttr()) {
3551 p.printAttribute(annotations);
3554 if (getRequiresCallConvLowering())
3555 p <<
' ' << getRequiresCallConvLoweringAttrName().getValue();
3559 for (llvm::StringRef name : cir::FuncOp::getAttributeNames())
3561 elidedAttrs.push_back(name);
3562 function_interface_impl::printFunctionAttributes(p, *
this, elidedAttrs);
3565 Region &body = getOperation()->getRegion(0);
3566 if (!body.empty()) {
3568 p.printRegion(body,
false,
3573mlir::LogicalResult cir::FuncOp::verify() {
3575 if (!isDeclaration() && getCoroutineKind() == cir::CoroutineKind::Coroutine) {
3576 int coroutineOpCount = 0;
3577 this->walk([&](Operation *op) {
3578 if (isa<CoroutineOp>(op)) {
3580 if (coroutineOpCount > 1) {
3581 return mlir::WalkResult::interrupt();
3584 return mlir::WalkResult::advance();
3586 if (coroutineOpCount != 1)
3587 return emitOpError()
3588 <<
"coroutine function must have exactly one cir.coroutine op";
3591 llvm::SmallSet<llvm::StringRef, 16> labels;
3592 llvm::SmallSet<llvm::StringRef, 16> gotos;
3593 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
3594 bool invalidBlockAddress =
false;
3595 getOperation()->walk([&](mlir::Operation *op) {
3596 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
3597 labels.insert(lab.getLabel());
3598 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
3599 gotos.insert(goTo.getLabel());
3600 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
3601 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
3603 invalidBlockAddress =
true;
3604 return mlir::WalkResult::interrupt();
3606 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
3608 return mlir::WalkResult::advance();
3611 if (invalidBlockAddress)
3612 return emitOpError() <<
"blockaddress references a different function";
3614 llvm::SmallSet<llvm::StringRef, 16> mismatched;
3615 if (!labels.empty() || !gotos.empty()) {
3616 mismatched = llvm::set_difference(gotos, labels);
3618 if (!mismatched.empty())
3619 return emitOpError() <<
"goto/label mismatch";
3624 if (!labels.empty() || !blockAddresses.empty()) {
3625 mismatched = llvm::set_difference(blockAddresses, labels);
3627 if (!mismatched.empty())
3628 return emitOpError()
3629 <<
"expects an existing label target in the referenced function";
3639void cir::TernaryOp::build(
3640 OpBuilder &builder, OperationState &result,
Value cond,
3641 function_ref<
void(OpBuilder &, Location)> trueBuilder,
3642 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
3643 result.addOperands(cond);
3644 OpBuilder::InsertionGuard guard(builder);
3645 Region *trueRegion = result.addRegion();
3646 builder.createBlock(trueRegion);
3647 trueBuilder(builder, result.location);
3648 Region *falseRegion = result.addRegion();
3649 builder.createBlock(falseRegion);
3650 falseBuilder(builder, result.location);
3655 if (trueRegion->back().mightHaveTerminator())
3656 yield = dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
3657 if (!yield && falseRegion->back().mightHaveTerminator())
3658 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
3660 assert((!yield || yield.getNumOperands() <= 1) &&
3661 "expected zero or one result type");
3662 if (yield && yield.getNumOperands() == 1)
3663 result.addTypes(TypeRange{yield.getOperandTypes().front()});
3666void cir::TernaryOp::getEntrySuccessorRegions(
3669 FoldAdaptor adaptor(operands, *
this);
3670 auto cond = mlir::dyn_cast_if_present<cir::BoolAttr>(adaptor.getCond());
3671 if (!cond || cond.getValue())
3672 regions.emplace_back(&getTrueRegion());
3673 if (!cond || !cond.getValue())
3674 regions.emplace_back(&getFalseRegion());
3681OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
3683 mlir::dyn_cast_if_present<cir::BoolAttr>(adaptor.getCondition()))
3684 return condition.getValue() ? getTrueValue() : getFalseValue();
3687 mlir::Attribute trueValue = adaptor.getTrueValue();
3688 mlir::Attribute falseValue = adaptor.getFalseValue();
3689 if (trueValue == falseValue)
3691 if (getTrueValue() == getFalseValue())
3692 return getTrueValue();
3697LogicalResult cir::SelectOp::verify() {
3699 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
3706 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
3707 !isa<cir::VectorType>(getFalseValue().
getType())) {
3708 return emitOpError()
3709 <<
"expected both true and false operands to be vector types "
3710 "when the condition is a vector boolean type";
3719LogicalResult cir::ShiftOp::verify() {
3720 mlir::Operation *op = getOperation();
3721 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
3722 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
3723 if (!op0VecTy ^ !op1VecTy)
3724 return emitOpError() <<
"input types cannot be one vector and one scalar";
3727 if (op0VecTy.getSize() != op1VecTy.getSize())
3728 return emitOpError() <<
"input vector types must have the same size";
3730 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
3732 return emitOpError() <<
"the type of the result must be a vector "
3733 <<
"if it is vector shift";
3735 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
3736 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
3737 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
3738 return emitOpError()
3739 <<
"vector operands do not have the same elements sizes";
3741 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
3742 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
3743 return emitOpError() <<
"vector operands and result type do not have the "
3744 "same elements sizes";
3747 return mlir::success();
3754LogicalResult cir::LabelOp::verify() {
3755 mlir::Operation *op = getOperation();
3756 mlir::Block *blk = op->getBlock();
3757 if (&blk->front() != op)
3758 return emitError() <<
"must be the first operation in a block";
3760 return mlir::success();
3767OpFoldResult cir::IncOp::fold(FoldAdaptor adaptor) {
3768 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3769 return adaptor.getInput();
3777OpFoldResult cir::DecOp::fold(FoldAdaptor adaptor) {
3778 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3779 return adaptor.getInput();
3787OpFoldResult cir::MinusOp::fold(FoldAdaptor adaptor) {
3788 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3789 return adaptor.getInput();
3794 mlir::dyn_cast_if_present<cir::IntAttr>(adaptor.getInput())) {
3795 APInt val = intAttr.getValue();
3797 return cir::IntAttr::get(
getType(), val);
3807OpFoldResult cir::FNegOp::fold(FoldAdaptor adaptor) {
3808 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3809 return adaptor.getInput();
3813 mlir::dyn_cast_if_present<cir::FPAttr>(adaptor.getInput())) {
3814 APFloat val = fpAttr.getValue();
3816 return cir::FPAttr::get(
getType(), val);
3826OpFoldResult cir::NotOp::fold(FoldAdaptor adaptor) {
3827 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()))
3828 return adaptor.getInput();
3833 if (mlir::Attribute attr = adaptor.getInput()) {
3834 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(attr)) {
3835 APInt val = intAttr.getValue();
3837 return cir::IntAttr::get(
getType(), val);
3839 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr))
3840 return cir::BoolAttr::get(getContext(), !boolAttr.getValue());
3850LogicalResult cir::BaseClassAddrOp::verify() {
3851 if (getSrcAddr().
getType().getAddrSpace() !=
getType().getAddrSpace())
3852 return emitOpError() <<
"address space mismatch";
3853 return mlir::success();
3856LogicalResult cir::DerivedClassAddrOp::verify() {
3857 if (getSrcAddr().
getType().getAddrSpace() !=
getType().getAddrSpace())
3858 return emitOpError() <<
"address space mismatch";
3859 return mlir::success();
3867 mlir::Type resultTy) {
3870 mlir::Type inputMemberTy;
3871 mlir::Type resultMemberTy;
3872 if (mlir::isa<cir::DataMemberType>(src.getType())) {
3874 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
3875 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
3878 if (inputMemberTy != resultMemberTy)
3879 return op->emitOpError()
3880 <<
"member types of the operand and the result do not match";
3882 return mlir::success();
3885LogicalResult cir::BaseDataMemberOp::verify() {
3889LogicalResult cir::DerivedDataMemberOp::verify() {
3897LogicalResult cir::BaseMethodOp::verify() {
3901LogicalResult cir::DerivedMethodOp::verify() {
3909void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
3913 result.addAttribute(getKindAttrName(result.name),
3914 cir::AwaitKindAttr::get(builder.getContext(),
kind));
3916 OpBuilder::InsertionGuard guard(builder);
3917 Region *readyRegion = result.addRegion();
3918 builder.createBlock(readyRegion);
3919 readyBuilder(builder, result.location);
3923 OpBuilder::InsertionGuard guard(builder);
3924 Region *suspendRegion = result.addRegion();
3925 builder.createBlock(suspendRegion);
3926 suspendBuilder(builder, result.location);
3930 OpBuilder::InsertionGuard guard(builder);
3931 Region *resumeRegion = result.addRegion();
3932 builder.createBlock(resumeRegion);
3933 resumeBuilder(builder, result.location);
3937void cir::AwaitOp::getSuccessorRegions(
3938 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3939 assert(point.isParent() || point.getTerminatorPredecessorOrNull());
3942 if (point.isParent()) {
3943 regions.emplace_back(&getReady());
3947 mlir::Region *parentRegion =
3948 point.getTerminatorPredecessorOrNull()->getParentRegion();
3957 if (&getReady() == parentRegion) {
3958 regions.emplace_back(&getResume());
3959 regions.emplace_back(&getSuspend());
3966 if (&getSuspend() == parentRegion) {
3967 regions.emplace_back(&getResume());
3968 regions.emplace_back(getOperation());
3973 regions.emplace_back(getOperation());
3976LogicalResult cir::AwaitOp::verify() {
3977 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
3978 return emitOpError(
"ready region must end with cir.condition");
3979 if (this->getSuspend().empty())
3980 return emitOpError(
"suspend region must not be empty");
3981 if (!isa<CoroSuspendPoint>(this->getSuspend().back().getTerminator()))
3982 return emitOpError(
"suspend region must end with cir.coro.suspend_point");
3990LogicalResult cir::CoReturnOp::verify() {
3991 mlir::Operation *coRet = getOperation();
3992 auto coroutine = coRet->getParentOfType<CoroutineOp>();
3993 if (!coroutine.getBody().isAncestor(getOperation()->getParentRegion()))
3994 return emitOpError(
"must be inside the cir.coroutine body region");
4002void cir::CoroutineOp::build(OpBuilder &builder, OperationState &result,
4009 OpBuilder::InsertionGuard guard(builder);
4010 Region *initialRegion = result.addRegion();
4011 builder.createBlock(initialRegion);
4012 initialSuspendBuilder(builder, result.location);
4016 OpBuilder::InsertionGuard guard(builder);
4017 Region *bodyRegion = result.addRegion();
4018 builder.createBlock(bodyRegion);
4019 bodyBuilder(builder, result.location);
4023 OpBuilder::InsertionGuard guard(builder);
4024 Region *finalRegion = result.addRegion();
4025 builder.createBlock(finalRegion);
4026 finalSuspendBuilder(builder, result.location);
4030 OpBuilder::InsertionGuard guard(builder);
4031 Region *destroyRegion = result.addRegion();
4032 builder.createBlock(destroyRegion);
4033 destroyBuilder(builder, result.location);
4037 OpBuilder::InsertionGuard guard(builder);
4038 Region *exitRegion = result.addRegion();
4039 builder.createBlock(exitRegion);
4040 exitBuilder(builder, result.location);
4044void cir::CoroutineOp::getSuccessorRegions(
4045 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
4048 if (point.isParent()) {
4049 regions.emplace_back(&getInitialSuspend());
4053 mlir::Region *parent =
4054 point.getTerminatorPredecessorOrNull()->getParentRegion();
4060 if (parent == &getInitialSuspend()) {
4061 regions.emplace_back(&getBody());
4062 regions.emplace_back(&getExit());
4063 regions.emplace_back(&getDestroy());
4072 if (parent == &getBody()) {
4074 regions.emplace_back(&getFinalSuspend());
4075 regions.emplace_back(&getExit());
4076 regions.emplace_back(&getDestroy());
4084 if (parent == &getFinalSuspend()) {
4085 regions.emplace_back(
4087 regions.emplace_back(&getExit());
4092 if (parent == &getDestroy()) {
4093 regions.emplace_back(&getExit());
4097 if (parent == &getExit()) {
4098 regions.emplace_back(getOperation());
4104cir::CoroutineOp::getSuccessorInputs(RegionSuccessor successor) {
4105 return ValueRange();
4108LogicalResult cir::CoroutineOp::verify() {
4109 mlir::Region &initialSuspend = getInitialSuspend();
4110 mlir::Region &body = getBody();
4111 mlir::Region &finalSuspend = getFinalSuspend();
4112 mlir::Region &destroy = getDestroy();
4113 mlir::Region &exit = getExit();
4118 int initAwaitCount = 0;
4119 bool hasInvalidAwait =
false;
4121 initialSuspend.walk([&](Operation *op) {
4122 auto awaitOp = mlir::dyn_cast<AwaitOp>(op);
4124 return mlir::WalkResult::advance();
4126 if (awaitOp.getKind() == cir::AwaitKind::Init)
4129 hasInvalidAwait =
true;
4131 if (initAwaitCount > 1 || hasInvalidAwait)
4132 return mlir::WalkResult::interrupt();
4134 return mlir::WalkResult::advance();
4137 if (hasInvalidAwait)
4138 return emitOpError(
"'initial_suspend' must not contain any cir.await other "
4139 "than the 'init' one");
4140 if (initAwaitCount != 1)
4142 "must have exactly one 'init' cir.await in 'initial_suspend'");
4145 int finalAwaitCount = 0;
4146 hasInvalidAwait =
false;
4148 finalSuspend.walk([&](Operation *op) {
4149 auto awaitOp = mlir::dyn_cast<AwaitOp>(op);
4151 return mlir::WalkResult::advance();
4153 if (awaitOp.getKind() == cir::AwaitKind::Final)
4156 hasInvalidAwait =
true;
4158 if (finalAwaitCount > 1 || hasInvalidAwait)
4159 return mlir::WalkResult::interrupt();
4161 return mlir::WalkResult::advance();
4164 if (hasInvalidAwait)
4165 return emitOpError(
"'final_suspend' must not contain any cir.await other "
4166 "than the 'final' one");
4167 if (finalAwaitCount > 1)
4169 "must have one or zero 'final' cir.await in 'final_suspend'");
4176 if (initialSuspend.empty() || initialSuspend.back().empty())
4177 return emitOpError(
"initial_suspend region must not be empty");
4178 if (!isa<YieldOp>(initialSuspend.back().back()))
4179 return emitOpError(
"'initial_suspend' must end with cir.yield");
4181 if (body.empty() || body.back().empty())
4182 return emitOpError(
"'body' region must not be empty");
4183 if (!isa<YieldOp, CoReturnOp>(body.back().back()))
4184 return emitOpError(
"'body' must end with cir.yield or cir.co_return");
4186 if (finalSuspend.empty() || finalSuspend.back().empty())
4187 return emitOpError(
"'final_suspend' region must not be empty");
4188 if (!isa<YieldOp>(finalSuspend.back().back()))
4189 return emitOpError(
"'final_suspend' must end with cir.yield");
4191 if (destroy.empty() || destroy.back().empty())
4192 return emitOpError(
"'destroy' region must not be empty");
4193 if (!isa<YieldOp>(destroy.back().back()))
4194 return emitOpError(
"'destroy' must end with cir.yield");
4196 if (exit.empty() || exit.back().empty())
4197 return emitOpError(
"'exit' region must not be empty");
4198 if (!isa<ReturnOp>(exit.back().back()))
4199 return emitOpError(
"'exit' must end with cir.return");
4201 return mlir::success();
4212 mlir::Type srcType, mlir::Type dstType) {
4213 printer.printType(srcType);
4214 if (srcType != dstType) {
4216 printer.printType(dstType);
4221 mlir::Type &srcType,
4222 mlir::Type &dstType) {
4223 if (parser.parseType(srcType))
4224 return mlir::failure();
4225 if (parser.parseOptionalComma().succeeded()) {
4226 if (parser.parseType(dstType))
4227 return mlir::failure();
4231 return mlir::success();
4234LogicalResult cir::CopyOp::verify() {
4239 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
4240 return emitError() <<
"missing data layout for pointee type";
4242 if (getSkipTailPadding() &&
4243 !mlir::isa<cir::RecordType>(
getType().getPointee()))
4245 <<
"skip_tail_padding is only valid for record pointee types";
4247 return mlir::success();
4254LogicalResult cir::PtrMaskOp::verify() {
4255 mlir::DataLayout layout = mlir::DataLayout::closest(*
this);
4256 std::optional<uint64_t> indexWidth =
4257 layout.getTypeIndexBitwidth(getPtr().
getType());
4259 return emitOpError() <<
"pointer has no index width";
4261 uint64_t maskWidth = getMask().getType().getWidth();
4262 if (maskWidth != *indexWidth)
4263 return emitOpError() <<
"mask width " << maskWidth
4264 <<
" must equal the pointer index width "
4267 return mlir::success();
4274LogicalResult cir::GetRuntimeMemberOp::verify() {
4275 cir::DataMemberType memberPtrTy = getMember().getType();
4277 if (getAddr().
getType().getPointee() != memberPtrTy.getClassTy())
4278 return emitError() <<
"record type does not match the member pointer type";
4279 if (
getType().getPointee() != memberPtrTy.getMemberTy())
4280 return emitError() <<
"result type does not match the member pointer type";
4281 if (
getType().getAddrSpace() != getAddr().
getType().getAddrSpace())
4283 <<
"result address space does not match the object address space";
4284 return mlir::success();
4291LogicalResult cir::GetMethodOp::verify() {
4292 cir::MethodType methodTy = getMethod().getType();
4295 cir::PointerType objectPtrTy = getObject().getType();
4296 mlir::Type objectTy = objectPtrTy.getPointee();
4298 if (methodTy.getClassTy() != objectTy)
4299 return emitError() <<
"method class type and object type do not match";
4302 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
4303 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
4310 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
4312 <<
"method return type and callee return type do not match";
4317 if (calleeArgsTy.empty())
4318 return emitError() <<
"callee parameter list lacks receiver object ptr";
4320 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
4321 if (!calleeThisArgPtrTy ||
4322 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
4324 <<
"the first parameter of callee must be a void pointer";
4327 if (calleeArgsTy.size() != methodFuncArgsTy.size())
4328 return emitError() <<
"callee and method parameter counts do not match";
4330 if (calleeArgsTy.size() > 1 &&
4331 calleeArgsTy.slice(1) != methodFuncArgsTy.slice(1))
4333 <<
"callee parameters and method parameters do not match";
4335 return mlir::success();
4346LogicalResult cir::GetMemberOp::verify() {
4347 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
4349 return emitError() <<
"expected pointer to a record type";
4351 if (recordTy.getMembers().size() <=
getIndex())
4352 return emitError() <<
"member index out of bounds";
4356 return emitError() <<
"member owns no storage to point at";
4358 if (pointeeTy !=
getType().getPointee())
4359 return emitError() <<
"member type mismatch";
4361 if (getAddrTy().getAddrSpace() !=
getType().getAddrSpace())
4362 return emitError() <<
"address space mismatch";
4364 return mlir::success();
4371LogicalResult cir::ExtractMemberOp::verify() {
4372 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
4374 <<
"cir.extract_member currently does not support unions";
4375 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
4376 if (structTy.getMembers().size() <=
getIndex())
4377 return emitError() <<
"member index out of bounds";
4378 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
4379 if (mlir::isa<cir::BitFieldType>(memberTy))
4380 return emitError() <<
"cir.extract_member does not support bit-fields";
4382 return emitError() <<
"member type mismatch";
4383 return mlir::success();
4390LogicalResult cir::InsertMemberOp::verify() {
4391 if (mlir::isa<cir::UnionType>(getRecord().
getType()))
4392 return emitError() <<
"cir.insert_member currently does not support unions";
4393 auto structTy = mlir::cast<cir::StructType>(getRecord().
getType());
4394 if (structTy.getMembers().size() <=
getIndex())
4395 return emitError() <<
"member index out of bounds";
4396 mlir::Type memberTy = structTy.getMembers()[
getIndex()];
4397 if (mlir::isa<cir::BitFieldType>(memberTy))
4398 return emitError() <<
"cir.insert_member does not support bit-fields";
4399 if (memberTy != getValue().
getType())
4400 return emitError() <<
"member type mismatch";
4402 return mlir::success();
4409OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
4410 if (llvm::any_of(getElements(), [](mlir::Value value) {
4411 return !value.getDefiningOp<cir::ConstantOp>();
4415 return cir::ConstVectorAttr::get(
4416 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
4419LogicalResult cir::VecCreateOp::verify() {
4423 const cir::VectorType vecTy =
getType();
4424 if (vecTy.isScalable())
4425 return emitOpError() <<
"scalable vectors are not supported";
4427 if (getElements().size() != vecTy.getFixedSize()) {
4428 return emitOpError() <<
"operand count of " << getElements().size()
4429 <<
" doesn't match vector type " << vecTy
4430 <<
" element count of " << vecTy.getFixedSize();
4433 const mlir::Type elementType = vecTy.getElementType();
4434 for (
const mlir::Value element : getElements()) {
4435 if (element.getType() != elementType) {
4436 return emitOpError() <<
"operand type " << element.getType()
4437 <<
" doesn't match vector element type "
4449OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
4450 const auto vectorAttr =
4451 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
4455 const auto indexAttr =
4456 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
4460 const mlir::ArrayAttr elements = vectorAttr.getElts();
4461 const uint64_t index = indexAttr.getUInt();
4462 if (index >= elements.size())
4465 return elements[index];
4472LogicalResult cir::CmpOp::verify() {
4473 if (getFenvAttr() && !cir::isAnyFloatingPointType(getLhs().
getType()))
4474 return emitOpError()
4475 <<
"'fenv' is only valid for floating-point comparisons";
4483OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
4485 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
4487 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
4488 if (!lhsVecAttr || !rhsVecAttr)
4491 mlir::Type inputElemTy =
4492 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
4493 auto IntTy = mlir::dyn_cast<cir::IntType>(inputElemTy);
4498 cir::CmpOpKind opKind = adaptor.getKind();
4499 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
4500 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
4501 uint64_t vecSize = lhsVecElhs.size();
4504 bool isUnsignedInt = IntTy.isUnsigned();
4505 for (
uint64_t i = 0; i < vecSize; i++) {
4506 mlir::Attribute lhsAttr = lhsVecElhs[i];
4507 mlir::Attribute rhsAttr = rhsVecElhs[i];
4508 bool cmpResult =
false;
4510 case cir::CmpOpKind::lt: {
4512 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <
4513 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4515 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
4516 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4519 case cir::CmpOpKind::le: {
4521 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() <=
4522 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4524 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
4525 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4528 case cir::CmpOpKind::gt: {
4530 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >
4531 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4533 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
4534 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4537 case cir::CmpOpKind::ge: {
4539 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getUInt() >=
4540 mlir::cast<cir::IntAttr>(rhsAttr).getUInt();
4542 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
4543 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
4546 case cir::CmpOpKind::eq:
4547 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getValue() ==
4548 mlir::cast<cir::IntAttr>(rhsAttr).getValue();
4550 case cir::CmpOpKind::ne:
4551 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getValue() !=
4552 mlir::cast<cir::IntAttr>(rhsAttr).getValue();
4554 case cir::CmpOpKind::one:
4555 case cir::CmpOpKind::uno: {
4556 llvm_unreachable(
"Should not reach fp-only comparison kinds here");
4564 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL);
4567 return cir::ConstVectorAttr::get(
4568 getType(), mlir::ArrayAttr::get(getContext(), elements));
4575OpFoldResult cir::VecFCmpOp::fold(FoldAdaptor adaptor) {
4585 if (
kind == cir::FCmpOpKind::_true ||
kind == cir::FCmpOpKind::_false) {
4586 mlir::Attribute elt =
4587 cir::IntAttr::get(
getType().getElementType(),
4588 (
kind == cir::FCmpOpKind::_true) ? -1LL : 0LL);
4590 return cir::ConstVectorAttr::get(
4591 getType(), mlir::ArrayAttr::get(getContext(), elements));
4595 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
4597 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
4598 if (!lhsVecAttr || !rhsVecAttr)
4601 mlir::ArrayAttr lhsElts = lhsVecAttr.getElts();
4602 mlir::ArrayAttr rhsElts = rhsVecAttr.getElts();
4605 elements.reserve(vecSize);
4606 for (
auto [lhsElt, rhsElt] : llvm::zip_equal(lhsElts, rhsElts)) {
4607 auto lhsFP = mlir::cast<cir::FPAttr>(lhsElt);
4608 auto rhsFP = mlir::cast<cir::FPAttr>(rhsElt);
4610 llvm::APFloat::cmpResult cr = lhsFP.getValue().compare(rhsFP.getValue());
4611 bool unordered = cr == llvm::APFloat::cmpUnordered;
4612 bool eq = cr == llvm::APFloat::cmpEqual;
4613 bool lt = cr == llvm::APFloat::cmpLessThan;
4614 bool gt = cr == llvm::APFloat::cmpGreaterThan;
4615 bool cmpResult =
false;
4617 case cir::FCmpOpKind::oeq:
4620 case cir::FCmpOpKind::ogt:
4623 case cir::FCmpOpKind::oge:
4624 cmpResult = gt || eq;
4626 case cir::FCmpOpKind::olt:
4629 case cir::FCmpOpKind::ole:
4630 cmpResult = lt || eq;
4632 case cir::FCmpOpKind::one:
4633 cmpResult = lt || gt;
4635 case cir::FCmpOpKind::ord:
4636 cmpResult = !unordered;
4638 case cir::FCmpOpKind::ueq:
4639 cmpResult = unordered || eq;
4641 case cir::FCmpOpKind::ugt:
4642 cmpResult = unordered || gt;
4644 case cir::FCmpOpKind::uge:
4645 cmpResult = unordered || gt || eq;
4647 case cir::FCmpOpKind::ult:
4648 cmpResult = unordered || lt;
4650 case cir::FCmpOpKind::ule:
4651 cmpResult = unordered || lt || eq;
4653 case cir::FCmpOpKind::une:
4654 cmpResult = unordered || lt || gt;
4656 case cir::FCmpOpKind::uno:
4657 cmpResult = unordered;
4659 case cir::FCmpOpKind::_true:
4660 case cir::FCmpOpKind::_false:
4661 llvm_unreachable(
"Op kind have been handled already");
4668 cir::IntAttr::get(
getType().getElementType(), cmpResult ? -1LL : 0LL));
4671 return cir::ConstVectorAttr::get(
4672 getType(), mlir::ArrayAttr::get(getContext(), elements));
4679OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
4681 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
4683 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
4684 if (!vec1Attr || !vec2Attr)
4687 mlir::Type vec1ElemTy =
4688 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
4690 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
4691 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
4692 mlir::ArrayAttr indicesElts = adaptor.getIndices();
4695 elements.reserve(indicesElts.size());
4697 uint64_t vec1Size = vec1Elts.size();
4698 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4699 if (idxAttr.getSInt() == -1) {
4700 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
4704 uint64_t idxValue = idxAttr.getUInt();
4705 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
4706 : vec2Elts[idxValue - vec1Size]);
4709 return cir::ConstVectorAttr::get(
4710 mlir::cast<cir::VectorType>(
getType()),
4711 mlir::ArrayAttr::get(getContext(), elements));
4714LogicalResult cir::VecShuffleOp::verify() {
4715 if (!mlir::isa<cir::VectorType>(
getType()))
4718 auto vec1Ty = mlir::cast<cir::VectorType>(getVec1().
getType());
4719 auto vec2Ty = mlir::cast<cir::VectorType>(getVec2().
getType());
4720 auto resultTy = mlir::cast<cir::VectorType>(getResult().
getType());
4721 if (vec1Ty.isScalable() || vec2Ty.isScalable() || resultTy.isScalable())
4722 return emitOpError() <<
"scalable vectors are not supported";
4726 if (getIndices().size() != resultTy.getFixedSize()) {
4727 return emitOpError() <<
": the number of elements in " << getIndices()
4728 <<
" and " << resultTy <<
" don't match";
4733 if (vec1Ty.getElementType() != resultTy.getElementType()) {
4734 return emitOpError() <<
": element types of " << getVec1().getType()
4735 <<
" and " << resultTy <<
" don't match";
4739 vec1Ty.getFixedSize() + vec2Ty.getFixedSize() - 1;
4741 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
4742 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
4744 return emitOpError() <<
": index for __builtin_shufflevector must be "
4745 "less than the total number of vector elements";
4754OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
4755 mlir::Attribute vec = adaptor.getVec();
4756 mlir::Attribute indices = adaptor.getIndices();
4757 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
4758 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
4759 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
4760 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
4762 mlir::ArrayAttr vecElts = vecAttr.getElts();
4763 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
4765 const uint64_t numElements = vecElts.size();
4768 elements.reserve(numElements);
4770 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
4771 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
4772 uint64_t idxValue = idxAttr.getUInt();
4773 uint64_t newIdx = idxValue & maskBits;
4774 elements.push_back(vecElts[newIdx]);
4777 return cir::ConstVectorAttr::get(
4778 getType(), mlir::ArrayAttr::get(getContext(), elements));
4784LogicalResult cir::VecShuffleDynamicOp::verify() {
4786 if (getVec().
getType().getSize() !=
4787 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
4788 return emitOpError() <<
": the number of elements in " << getVec().getType()
4789 <<
" and " << getIndices().getType() <<
" don't match";
4798LogicalResult cir::VecTernaryOp::verify() {
4803 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
4804 return emitOpError() <<
": the number of elements in "
4805 << getCond().getType() <<
" and " << getLhs().getType()
4811OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
4812 mlir::Attribute cond = adaptor.getCond();
4813 mlir::Attribute lhs = adaptor.getLhs();
4814 mlir::Attribute rhs = adaptor.getRhs();
4816 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
4817 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
4818 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
4820 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
4821 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
4822 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
4824 mlir::ArrayAttr condElts = condVec.getElts();
4827 elements.reserve(condElts.size());
4829 for (
const auto &[idx, condAttr] :
4830 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
4831 if (condAttr.getSInt()) {
4832 elements.push_back(lhsVec.getElts()[idx]);
4834 elements.push_back(rhsVec.getElts()[idx]);
4838 cir::VectorType vecTy = getLhs().getType();
4839 return cir::ConstVectorAttr::get(
4840 vecTy, mlir::ArrayAttr::get(getContext(), elements));
4847LogicalResult cir::LdexpOp::verify() {
4848 auto srcVecTy = mlir::dyn_cast<cir::VectorType>(getSrc().
getType());
4849 auto expVecTy = mlir::dyn_cast<cir::VectorType>(getExp().
getType());
4850 if (!srcVecTy != !expVecTy ||
4851 (srcVecTy && srcVecTy.getSize() != expVecTy.getSize()))
4852 return emitOpError()
4853 <<
"exponent must have the same number of elements as the value";
4866 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4867 effects.emplace_back(MemoryEffects::Read::get(), &addr);
4868 if (isVolatileOrAtomic) {
4869 effects.emplace_back(MemoryEffects::Write::get());
4870 effects.emplace_back(MemoryEffects::Read::get());
4874void cir::LoadOp::getEffects(
4875 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4879void cir::GetBitfieldOp::getEffects(
4880 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4884void cir::MatrixColumnMajorLoadOp::getEffects(
4885 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4893LogicalResult cir::MatrixTransposeOp::verify() {
4894 cir::MatrixType valueTy = getValue().getType();
4895 cir::MatrixType resultTy = getResult().getType();
4897 if ((valueTy.getElementType() != resultTy.getElementType()) ||
4898 (valueTy.getNumRows() != resultTy.getNumColumns()) ||
4899 (valueTy.getNumColumns() != resultTy.getNumRows())) {
4901 cir::MatrixType::get(valueTy.getElementType(), valueTy.getNumColumns(),
4902 valueTy.getNumRows());
4903 emitOpError() <<
"operand type " << valueTy <<
" expects result type of "
4904 << expectedTy <<
" but got " << resultTy;
4915LogicalResult cir::ComplexCreateOp::verify() {
4918 <<
"operand type of cir.complex.create does not match its result type";
4925OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
4926 mlir::Attribute real = adaptor.getReal();
4927 mlir::Attribute imag = adaptor.getImag();
4933 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
4934 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
4935 return cir::ConstComplexAttr::get(realAttr, imagAttr);
4942LogicalResult cir::ComplexRealOp::verify() {
4943 mlir::Type operandTy = getOperand().getType();
4944 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4945 operandTy = complexOperandTy.getElementType();
4948 emitOpError() <<
": result type does not match operand type";
4955OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
4956 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
4959 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4960 return complexCreateOp.getOperand(0);
4963 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4964 return complex ? complex.getReal() :
nullptr;
4971LogicalResult cir::ComplexImagOp::verify() {
4972 mlir::Type operandTy = getOperand().getType();
4973 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
4974 operandTy = complexOperandTy.getElementType();
4977 emitOpError() <<
": result type does not match operand type";
4984OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
4985 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
4988 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
4989 return complexCreateOp.getOperand(1);
4992 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
4993 return complex ? complex.getImag() :
nullptr;
5000LogicalResult cir::ComplexRealPtrOp::verify() {
5001 mlir::Type resultPointeeTy =
getType().getPointee();
5002 cir::PointerType operandPtrTy = getOperand().getType();
5003 auto operandPointeeTy =
5004 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
5006 if (resultPointeeTy != operandPointeeTy.getElementType()) {
5007 return emitOpError() <<
": result type does not match operand type";
5017LogicalResult cir::ComplexImagPtrOp::verify() {
5018 mlir::Type resultPointeeTy =
getType().getPointee();
5019 cir::PointerType operandPtrTy = getOperand().getType();
5020 auto operandPointeeTy =
5021 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
5023 if (resultPointeeTy != operandPointeeTy.getElementType()) {
5024 return emitOpError()
5025 <<
"cir.complex.imag_ptr result type does not match operand type";
5036 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
5037 bool poisonZero =
false) {
5038 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
5043 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
5047 llvm::APInt inputValue = input.getValue();
5048 if (poisonZero && inputValue.isZero())
5049 return cir::PoisonAttr::get(input.getType());
5051 llvm::APInt resultValue = func(inputValue);
5052 return IntAttr::get(input.getType(), resultValue);
5055OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
5056 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
5057 unsigned resultValue =
5058 inputValue.getBitWidth() - inputValue.getSignificantBits();
5059 return llvm::APInt(inputValue.getBitWidth(), resultValue);
5063OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
5066 [](
const llvm::APInt &inputValue) {
5067 unsigned resultValue = inputValue.countLeadingZeros();
5068 return llvm::APInt(inputValue.getBitWidth(), resultValue);
5073OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
5076 [](
const llvm::APInt &inputValue) {
5077 return llvm::APInt(inputValue.getBitWidth(),
5078 inputValue.countTrailingZeros());
5083OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
5084 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
5085 unsigned trailingZeros = inputValue.countTrailingZeros();
5087 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
5088 return llvm::APInt(inputValue.getBitWidth(), result);
5092OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
5093 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
5094 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
5098OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
5099 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
5100 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
5104OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
5105 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
5106 return inputValue.reverseBits();
5110OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
5111 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
5112 return inputValue.byteSwap();
5116OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
5117 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
5118 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
5120 return cir::PoisonAttr::get(
getType());
5123 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
5124 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
5125 if (!input && !amount)
5134 llvm::APInt inputValue;
5136 inputValue = input.getValue();
5137 if (inputValue.isZero() || inputValue.isAllOnes()) {
5145 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
5146 if (amountValue == 0) {
5152 if (!input || !amount)
5155 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
5156 "input value must have the same bit width as the input type");
5158 llvm::APInt resultValue;
5160 resultValue = inputValue.rotl(amountValue);
5162 resultValue = inputValue.rotr(amountValue);
5164 return IntAttr::get(input.getContext(), input.getType(), resultValue);
5171void cir::InlineAsmOp::print(OpAsmPrinter &p) {
5172 p <<
'(' << getAsmFlavor() <<
", ";
5177 mlir::MutableOperandRangeRange groups = getAsmOperandsMutable();
5179 for (
auto [index, name] : llvm::enumerate(names)) {
5183 llvm::interleaveComma(groups[index], p, [&](OpOperand &operand) {
5184 p.printOperand(operand.get());
5185 p <<
" : " << operand.get().getType();
5186 if (isMemoryOperand(operand.getOperandNumber()))
5187 p <<
" (maybe_memory)";
5194 p.printString(getAsmString());
5196 p.printString(getConstraints());
5200 if (getSideEffects())
5201 p <<
" side_effects";
5202 if (getConvergent())
5205 p.printOptionalAttrDict(
5206 getOperation()->getDiscardableAttrDictionary().getValue());
5208 if (
auto v = getRes())
5209 p <<
" -> " << v.getType();
5212void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
5214 StringRef asmString, StringRef constraints,
5215 bool sideEffects,
bool convergent,
5216 cir::AsmFlavor asmFlavor,
5220 for (
auto operandRange : asmOperands) {
5221 segments.push_back(operandRange.size());
5222 odsState.addOperands(operandRange);
5225 odsState.addAttribute(
5226 "operands_segments",
5227 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
5228 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
5229 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
5230 odsState.addAttribute(
"asm_flavor",
5231 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
5234 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
5237 odsState.addAttribute(
"convergent", odsBuilder.getUnitAttr());
5239 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
5242ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
5243 OperationState &result) {
5246 std::string asmString, constraints;
5248 MLIRContext *ctxt = parser.getBuilder().getContext();
5250 auto error = [&](
const Twine &msg) -> LogicalResult {
5251 return parser.emitError(parser.getCurrentLocation(), msg);
5254 auto expected = [&](
const std::string &c) {
5255 return error(
"expected '" + c +
"'");
5258 if (parser.parseLParen().failed())
5259 return expected(
"(");
5261 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
5263 return error(
"Unknown AsmFlavor");
5265 if (parser.parseComma().failed())
5266 return expected(
",");
5268 auto parseValue = [&](
Value &v) {
5269 OpAsmParser::UnresolvedOperand op;
5271 if (parser.parseOperand(op) || parser.parseColon())
5272 return error(
"can't parse operand");
5275 if (parser.parseType(typ).failed())
5276 return error(
"can't parse operand type");
5278 if (parser.resolveOperand(op, typ, tmp))
5279 return error(
"can't resolve operand");
5281 return mlir::success();
5284 auto parseOperands = [&](llvm::StringRef
name) {
5285 if (parser.parseKeyword(name).failed())
5286 return error(
"expected " + name +
" operands here");
5287 if (parser.parseEqual().failed())
5288 return expected(
"=");
5289 if (parser.parseLSquare().failed())
5290 return expected(
"[");
5293 if (parser.parseOptionalRSquare().succeeded()) {
5294 operandsGroupSizes.push_back(size);
5295 if (parser.parseComma())
5296 return expected(
",");
5297 return mlir::success();
5300 auto parseOperand = [&]() {
5302 if (parseValue(val).succeeded()) {
5303 result.operands.push_back(val);
5306 if (parser.parseOptionalLParen().failed()) {
5307 operandAttrs.push_back(mlir::DictionaryAttr::get(ctxt));
5308 return mlir::success();
5311 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
5312 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
5313 if (parser.parseRParen())
5314 return expected(
")");
5315 return mlir::success();
5317 return expected(
"maybe_memory");
5320 return mlir::failure();
5323 if (parser.parseCommaSeparatedList(parseOperand).failed())
5324 return mlir::failure();
5326 if (parser.parseRSquare().failed() || parser.parseComma().failed())
5327 return expected(
"]");
5328 operandsGroupSizes.push_back(size);
5329 return mlir::success();
5332 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
5333 parseOperands(
"in_out").failed())
5334 return error(
"failed to parse operands");
5336 if (parser.parseLBrace())
5337 return expected(
"{");
5338 if (parser.parseString(&asmString))
5339 return error(
"asm string parsing failed");
5340 if (parser.parseString(&constraints))
5341 return error(
"constraints string parsing failed");
5342 if (parser.parseRBrace())
5343 return expected(
"}");
5344 if (parser.parseRParen())
5345 return expected(
")");
5347 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
5348 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
5350 if (parser.parseOptionalKeyword(
"convergent").succeeded())
5351 result.attributes.set(
"convergent", UnitAttr::get(ctxt));
5353 if (parser.parseOptionalAttrDict(result.attributes).failed())
5354 return mlir::failure();
5356 if (parser.parseOptionalArrow().succeeded() &&
5357 parser.parseType(resType).failed())
5358 return mlir::failure();
5360 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
5361 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
5362 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
5363 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
5364 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
5365 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
5367 result.addTypes(TypeRange{resType});
5369 return mlir::success();
5372LogicalResult cir::InlineAsmOp::verify() {
5373 if (getOperandAttrs().size() != getNumOperands())
5374 return emitOpError() <<
"expects " << getNumOperands()
5375 <<
" operand attributes, but got "
5376 << getOperandAttrs().size();
5377 for (
auto [index, operand] : llvm::enumerate(getOperands()))
5378 if (isMemoryOperand(index) && !isa<cir::PointerType>(operand.getType()))
5379 return emitOpError() <<
"memory operand #" << index
5380 <<
" must be a pointer, but got "
5381 << operand.getType();
5385void InlineAsmOp::getEffects(
5389 if (getSideEffects()) {
5390 effects.emplace_back(mlir::MemoryEffects::Read::get());
5391 effects.emplace_back(mlir::MemoryEffects::Write::get());
5394 for (OpOperand &operand : getOperation()->getOpOperands()) {
5395 if (!isMemoryOperand(operand.getOperandNumber()))
5397 effects.emplace_back(mlir::MemoryEffects::Read::get(), &operand);
5398 effects.emplace_back(mlir::MemoryEffects::Write::get(), &operand);
5406template <
typename ThrowOpTy>
5409 return mlir::success();
5411 if (op.getNumOperands() != 0) {
5412 if (op.getTypeInfo())
5413 return mlir::success();
5414 return op.emitOpError() <<
"'type_info' symbol attribute missing";
5417 return mlir::failure();
5422mlir::LogicalResult cir::TryThrowOp::verify() {
5430LogicalResult cir::AtomicFetchOp::verify() {
5431 if (getBinop() != cir::AtomicFetchKind::Add &&
5432 getBinop() != cir::AtomicFetchKind::Sub &&
5433 getBinop() != cir::AtomicFetchKind::Max &&
5434 getBinop() != cir::AtomicFetchKind::Min &&
5435 getBinop() != cir::AtomicFetchKind::Maximum &&
5436 getBinop() != cir::AtomicFetchKind::Minimum &&
5437 getBinop() != cir::AtomicFetchKind::MaximumNum &&
5438 getBinop() != cir::AtomicFetchKind::MinimumNum &&
5439 !mlir::isa<cir::IntType>(getVal().
getType()))
5440 return emitError(
"only atomic add, sub, max, min, maximum, minimum, "
5441 "maximum_num, and minimum_num operation could operate on "
5442 "floating-point values");
5444 if ((getBinop() == cir::AtomicFetchKind::Maximum ||
5445 getBinop() == cir::AtomicFetchKind::Minimum ||
5446 getBinop() == cir::AtomicFetchKind::MaximumNum ||
5447 getBinop() == cir::AtomicFetchKind::MinimumNum) &&
5448 !cir::isFPOrVectorOfFPType(getVal().
getType()))
5449 return emitError(
"atomic maximum, minimum, maximum_num, and minimum_num "
5450 "operation could only operate on floating-point values");
5459LogicalResult cir::TypeInfoAttr::verify(
5460 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
5461 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
5463 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
5473void cir::TryOp::getSuccessorRegions(
5474 mlir::RegionBranchPoint point,
5476 if (point.isParent()) {
5477 regions.emplace_back(&getTryRegion());
5480 mlir::Operation *term = point.getTerminatorPredecessorOrNull();
5481 if (term->getParentRegion() != &getTryRegion()) {
5482 regions.emplace_back(getOperation());
5487 if (!isa<cir::ResumeOp>(term) || getHandlerRegions().empty())
5488 regions.emplace_back(getOperation());
5497 regions.reserve(regions.size() + getHandlerRegions().size());
5498 for (mlir::Region &handlerRegion : getHandlerRegions())
5499 regions.emplace_back(&handlerRegion);
5510 cir::ConstructCatchParamOp constructOp) {
5511 mlir::WalkResult result =
5512 handlerRegion.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
5513 if (mlir::isa<cir::TryOp>(op))
5514 return mlir::WalkResult::skip();
5515 auto initOp = mlir::dyn_cast<cir::InitCatchParamOp>(op);
5517 return mlir::WalkResult::advance();
5519 cir::InitCatchKind
kind = initOp.getKind();
5521 constructOp && constructOp.getParamAddr() == initOp.getParamAddr();
5522 if (sameParam && constructOp.getKind() !=
kind) {
5523 initOp.emitOpError(
"kind '")
5524 << cir::stringifyInitCatchKind(
kind)
5525 <<
"' does not match the kind '"
5526 << cir::stringifyInitCatchKind(constructOp.getKind())
5527 <<
"' of the preceding 'cir.construct_catch_param'";
5528 return mlir::WalkResult::interrupt();
5530 if ((
kind == cir::InitCatchKind::ReferenceToPointer ||
5531 kind == cir::InitCatchKind::NonTrivialCopy) &&
5533 initOp.emitOpError(
"'")
5534 << cir::stringifyInitCatchKind(
kind)
5535 <<
"' requires a preceding 'cir.construct_catch_param' of the "
5536 "same kind on the same parameter";
5537 return mlir::WalkResult::interrupt();
5539 return mlir::WalkResult::advance();
5541 return failure(result.wasInterrupted());
5544LogicalResult cir::TryOp::verifyRegions() {
5545 mlir::ArrayAttr handlerTypes = getHandlerTypes();
5546 if (!handlerTypes) {
5547 if (!getHandlerRegions().empty())
5549 "handler regions must be empty when no handler types are present");
5553 mlir::MutableArrayRef<mlir::Region> handlerRegions = getHandlerRegions();
5557 if (handlerRegions.size() != handlerTypes.size())
5559 "number of handler regions and handler types must match");
5567 if (llvm::any_of(handlerTypes, [](mlir::Attribute typeAttr) {
5568 return mlir::isa<cir::EhFilterAttr, cir::EhUnexpectedAttr>(typeAttr);
5570 if (handlerTypes.size() != 2 ||
5571 !mlir::isa<cir::EhFilterAttr>(handlerTypes[0]) ||
5572 !mlir::isa<cir::EhUnexpectedAttr>(handlerTypes[1]))
5573 return emitOpError(
"a filter handler must be followed by an unexpected "
5574 "handler, and the two must be the only handlers");
5577 for (
const auto &[typeAttr, handlerRegion] :
5578 llvm::zip(handlerTypes, handlerRegions)) {
5580 mlir::Block &entryBlock = handlerRegion.front();
5581 if (entryBlock.getNumArguments() != 1 ||
5582 !mlir::isa<cir::EhTokenType>(entryBlock.getArgument(0).getType()))
5584 "handler region must have a single '!cir.eh_token' argument");
5588 if (mlir::isa<cir::UnwindAttr, cir::EhFilterAttr, cir::EhUnexpectedAttr>(
5592 if (entryBlock.empty())
5593 return emitOpError(
"catch handler region must not be empty");
5599 if (mlir::isa<cir::EhTerminateOp>(entryBlock.front())) {
5600 if (!mlir::isa<cir::CatchAllAttr>(typeAttr))
5601 return emitOpError(
"'cir.eh.terminate' is only allowed in a catch-all "
5620 mlir::Operation *firstOp = &entryBlock.front();
5621 if (mlir::isa<cir::LifetimeStartOp>(firstOp)) {
5622 mlir::Operation *next = firstOp->getNextNode();
5623 auto lifetimeScope = mlir::dyn_cast_if_present<cir::CleanupScopeOp>(next);
5625 return emitOpError(
"'cir.lifetime.start' in a catch handler region "
5626 "must be followed by the 'cir.cleanup.scope' of "
5627 "its lifetime-end cleanup");
5628 if (lifetimeScope.getBodyRegion().empty())
5630 "'cir.lifetime.start' in a catch handler region must be "
5631 "followed by the 'cir.cleanup.scope' of its lifetime-end "
5633 mlir::Block &scopeBody = lifetimeScope.getBodyRegion().front();
5634 firstOp = scopeBody.empty() ?
nullptr : &scopeBody.front();
5638 mlir::dyn_cast_if_present<cir::ConstructCatchParamOp>(firstOp);
5640 firstOp = firstOp->getNextNode();
5641 if (!mlir::isa_and_present<cir::BeginCatchOp>(firstOp))
5643 "catch handler region must start with 'cir.begin_catch'");
5653 mlir::OpAsmPrinter &printer, cir::TryOp op,
5654 mlir::MutableArrayRef<mlir::Region> handlerRegions,
5655 mlir::ArrayAttr handlerTypes) {
5659 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
5663 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
5664 printer <<
"catch all ";
5665 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
5666 printer <<
"unwind ";
5667 }
else if (
auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
5668 printer <<
"filter [";
5669 llvm::interleaveComma(
5670 filterAttr.getPermittedTypes(), printer,
5671 [&](mlir::Attribute sym) { printer.printAttribute(sym); });
5673 }
else if (mlir::isa<cir::EhUnexpectedAttr>(typeAttr)) {
5674 printer <<
"unexpected ";
5676 printer <<
"catch [type ";
5677 printer.printAttribute(typeAttr);
5682 mlir::Region ®ion = handlerRegions[typeIdx];
5683 if (!region.empty() && region.front().getNumArguments() > 0) {
5685 printer.printRegionArgument(region.front().getArgument(0));
5689 printer.printRegion(region,
5696 mlir::OpAsmParser &parser,
5698 mlir::ArrayAttr &handlerTypes) {
5700 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
5701 handlerRegions.emplace_back(
new mlir::Region);
5703 mlir::Region &currRegion = *handlerRegions.back();
5707 if (parser.parseLParen())
5709 mlir::OpAsmParser::Argument arg;
5710 if (parser.parseArgument(arg,
true))
5712 regionArgs.push_back(arg);
5713 if (parser.parseRParen())
5716 mlir::SMLoc regionLoc = parser.getCurrentLocation();
5717 if (parser.parseRegion(currRegion, regionArgs)) {
5718 handlerRegions.clear();
5722 if (currRegion.empty())
5723 return parser.emitError(regionLoc,
"handler region shall not be empty");
5725 if (!(currRegion.back().mightHaveTerminator() &&
5726 currRegion.back().getTerminator()))
5727 return parser.emitError(
5728 regionLoc,
"blocks are expected to be explicitly terminated");
5733 bool hasCatchAll =
false;
5735 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
5736 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
5738 llvm::StringRef attrStr;
5739 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
5740 return parser.emitError(parser.getCurrentLocation(),
5741 "expected 'all' or 'type' keyword");
5743 bool isCatchAll = attrStr ==
"all";
5746 return parser.emitError(parser.getCurrentLocation(),
5747 "can't have more than one catch all");
5751 mlir::Attribute exceptionRTTIAttr;
5752 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
5753 return parser.emitError(parser.getCurrentLocation(),
5754 "expected valid RTTI info attribute");
5756 catcherAttrs.push_back(isCatchAll
5757 ? cir::CatchAllAttr::get(parser.getContext())
5758 : exceptionRTTIAttr);
5760 if (hasLSquare && isCatchAll)
5761 return parser.emitError(parser.getCurrentLocation(),
5762 "catch all dosen't need RTTI info attribute");
5764 if (hasLSquare && parser.parseRSquare().failed())
5765 return parser.emitError(parser.getCurrentLocation(),
5766 "expected `]` after RTTI info attribute");
5768 if (parseCheckedCatcherRegion().failed())
5769 return mlir::failure();
5775 if (parser.parseOptionalKeyword(
"filter").succeeded()) {
5776 mlir::SMLoc filterLoc = parser.getCurrentLocation();
5778 auto parsePermittedType = [&]() -> mlir::ParseResult {
5779 mlir::SMLoc typeLoc = parser.getCurrentLocation();
5780 mlir::Attribute rtti;
5781 if (parser.parseAttribute(rtti).failed())
5782 return mlir::failure();
5783 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
5784 return parser.emitError(typeLoc,
"expected a type info symbol naming a "
5785 "permitted exception type");
5786 permittedTypes.push_back(rtti);
5787 return mlir::success();
5790 .parseCommaSeparatedList(mlir::OpAsmParser::Delimiter::Square,
5793 return mlir::failure();
5795 auto filterAttr = cir::EhFilterAttr::getChecked(
5796 [&]() {
return parser.emitError(filterLoc); }, parser.getContext(),
5797 parser.getBuilder().getArrayAttr(permittedTypes));
5799 return mlir::failure();
5800 catcherAttrs.push_back(filterAttr);
5801 if (parseCheckedCatcherRegion().failed())
5802 return mlir::failure();
5805 if (parser.parseOptionalKeyword(
"unexpected").succeeded()) {
5806 catcherAttrs.push_back(cir::EhUnexpectedAttr::get(parser.getContext()));
5807 if (parseCheckedCatcherRegion().failed())
5808 return mlir::failure();
5811 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
5813 return parser.emitError(parser.getCurrentLocation(),
5814 "unwind can't be used with catch all");
5816 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
5817 if (parseCheckedCatcherRegion().failed())
5818 return mlir::failure();
5821 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
5822 return mlir::success();
5830cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
5831 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
5832 if (!isa_and_nonnull<GlobalOp>(op))
5833 return emitOpError(
"'")
5834 << getTypeSym() <<
"' does not reference a valid cir.global";
5842LogicalResult cir::LifetimeStartOp::verify() {
5846LogicalResult cir::LifetimeEndOp::verify() {
5856 auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(attr);
5857 if (!intAttr || !intAttr.getType().isSignlessInteger(32))
5858 return std::nullopt;
5859 int64_t width = intAttr.getInt();
5862 return std::nullopt;
5863 return static_cast<unsigned>(width);
5866LogicalResult cir::MemChrOp::verify() {
5867 auto moduleOp = (*this)->getParentOfType<mlir::ModuleOp>();
5869 return emitOpError(
"expects an enclosing module");
5872 if (mlir::cast<cir::PointerType>(getSrc().
getType()).getAddrSpace())
5873 return emitOpError(
"src must be in the default address space");
5875 auto checkWidth = [&](cir::IntType type, llvm::StringRef operandName,
5876 llvm::StringRef attrName) -> LogicalResult {
5877 mlir::Attribute
attr = moduleOp->getAttr(attrName);
5879 return emitOpError(
"expects the module to record ") << attrName;
5882 return emitOpError(
"requires ")
5884 <<
" to be a signless i32 holding a fundamental integer width";
5885 if (type.getWidth() != *width)
5886 return emitOpError() << operandName <<
" must have the width recorded in "
5891 if (failed(checkWidth(getPattern().
getType(),
"pattern",
5892 cir::CIRDialect::getIntTypeWidthAttrName())))
5894 return checkWidth(getLen().
getType(),
"len",
5895 cir::CIRDialect::getSizeTypeWidthAttrName());
5906 cir::InitCatchKind
kind,
5907 cir::PointerType paramAddrType) {
5908 if (
kind != cir::InitCatchKind::ReferenceToPointer &&
5909 kind != cir::InitCatchKind::ReferenceToRecordPointer)
5912 auto refType = mlir::dyn_cast<cir::PointerType>(paramAddrType.getPointee());
5913 if (!refType || !mlir::isa<cir::PointerType>(refType.getPointee()))
5914 return op->emitOpError(
"'")
5915 << cir::stringifyInitCatchKind(
kind)
5916 <<
"' requires 'param_addr' to be the address of a reference to a "
5921LogicalResult cir::InitCatchParamOp::verify() {
5929LogicalResult cir::ConstructCatchParamOp::verify() {
5933LogicalResult cir::ConstructCatchParamOp::verifySymbolUses(
5934 SymbolTableCollection &symbolTable) {
5935 auto copyFnAttr = getCopyFnAttr();
5939 symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(*
this, getCopyFnAttr());
5941 return emitOpError(
"'")
5942 << *getCopyFn() <<
"' does not reference a valid cir.func";
5944 if (!fn->hasAttr(cir::CIRDialect::getCatchCopyThunkAttrName()))
5945 return emitOpError(
"catch-init copy_fn must be tagged with the ")
5946 << cir::CIRDialect::getCatchCopyThunkAttrName() <<
" attribute";
5948 cir::FuncType fnType = fn.getFunctionType();
5949 if (fnType.getNumInputs() != 2 || !fnType.hasVoidReturn())
5950 return emitOpError(
"catch-init copy_fn must take two pointer arguments and "
5953 if (fnType.getInput(0) != getParamAddr().
getType())
5954 return emitOpError(
"first argument of catch-init copy_fn must match the "
5955 "type of 'param_addr'");
5957 if (fnType.getInput(1) != getParamAddr().
getType())
5959 "second argument of catch-init copy_fn must be a pointer "
5960 "to the catch type");
5969LogicalResult cir::EhDispatchOp::verify() {
5970 mlir::ArrayAttr handlerTypes = getCatchTypesAttr();
5974 bool hasFilter =
false;
5975 for (mlir::Attribute typeAttr : handlerTypes) {
5976 if (!mlir::isa<cir::EhFilterAttr>(typeAttr))
5979 return emitOpError(
"can't have more than one 'filter' handler");
5987 if (hasFilter && getDefaultIsCatchAll())
5989 "'filter' handler requires an 'unwind' default destination");
5995 OpAsmParser &parser, mlir::ArrayAttr &catchTypes,
5996 SmallVectorImpl<Block *> &catchDestinations, Block *&defaultDestination,
5997 mlir::UnitAttr &defaultIsCatchAll) {
5999 if (parser.parseLSquare())
6003 bool hasCatchAll =
false;
6004 bool hasUnwind =
false;
6007 auto parseHandler = [&]() -> ParseResult {
6009 if (succeeded(parser.parseOptionalKeyword(
"catch_all"))) {
6011 return parser.emitError(parser.getCurrentLocation(),
6012 "duplicate 'catch_all' handler");
6014 return parser.emitError(parser.getCurrentLocation(),
6015 "cannot have both 'catch_all' and 'unwind'");
6018 if (parser.parseColon().failed())
6021 if (parser.parseSuccessor(defaultDestination).failed())
6027 if (succeeded(parser.parseOptionalKeyword(
"unwind"))) {
6029 return parser.emitError(parser.getCurrentLocation(),
6030 "duplicate 'unwind' handler");
6032 return parser.emitError(parser.getCurrentLocation(),
6033 "cannot have both 'catch_all' and 'unwind'");
6036 if (parser.parseColon().failed())
6039 if (parser.parseSuccessor(defaultDestination).failed())
6047 if (succeeded(parser.parseOptionalKeyword(
"filter"))) {
6048 SMLoc filterLoc = parser.getCurrentLocation();
6050 auto parsePermittedType = [&]() -> ParseResult {
6051 mlir::SMLoc
typeLoc = parser.getCurrentLocation();
6052 mlir::Attribute rtti;
6053 if (parser.parseAttribute(rtti).failed())
6055 if (!mlir::isa<cir::GlobalViewAttr>(rtti))
6056 return parser.emitError(typeLoc,
6057 "expected a type info symbol naming a "
6058 "permitted exception type");
6059 permittedTypes.push_back(rtti);
6063 .parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
6068 auto filterAttr = cir::EhFilterAttr::getChecked(
6069 [&]() {
return parser.emitError(filterLoc); }, parser.getContext(),
6070 parser.getBuilder().getArrayAttr(permittedTypes));
6073 handlerTypes.push_back(filterAttr);
6075 if (parser.parseColon().failed())
6079 if (parser.parseSuccessor(dest).failed())
6081 catchDestinations.push_back(dest);
6088 if (parser.parseKeyword(
"catch").failed())
6091 if (parser.parseLParen().failed())
6094 mlir::Attribute catchTypeAttr;
6095 if (parser.parseAttribute(catchTypeAttr).failed())
6097 handlerTypes.push_back(catchTypeAttr);
6099 if (parser.parseRParen().failed())
6102 if (parser.parseColon().failed())
6106 if (parser.parseSuccessor(dest).failed())
6108 catchDestinations.push_back(dest);
6112 if (parser.parseCommaSeparatedList(parseHandler).failed())
6115 if (parser.parseRSquare().failed())
6119 if (!hasCatchAll && !hasUnwind)
6120 return parser.emitError(parser.getCurrentLocation(),
6121 "must have either 'catch_all' or 'unwind' handler");
6124 if (!handlerTypes.empty())
6125 catchTypes = parser.getBuilder().getArrayAttr(handlerTypes);
6128 defaultIsCatchAll = parser.getBuilder().getUnitAttr();
6134 mlir::ArrayAttr catchTypes,
6135 SuccessorRange catchDestinations,
6136 Block *defaultDestination,
6137 mlir::UnitAttr defaultIsCatchAll) {
6145 llvm::zip(catchTypes, catchDestinations),
6147 mlir::Attribute typeAttr = std::get<0>(i);
6148 if (
auto filterAttr = mlir::dyn_cast<cir::EhFilterAttr>(typeAttr)) {
6150 llvm::interleaveComma(
6151 filterAttr.getPermittedTypes(), p,
6152 [&](mlir::Attribute sym) { p.printAttribute(sym); });
6155 p.printAttribute(typeAttr);
6158 p.printSuccessor(std::get<1>(i));
6170 if (defaultIsCatchAll)
6171 p <<
" catch_all : ";
6174 p.printSuccessor(defaultDestination);
6184bool cir::StdFindOp::signatureMatches(mlir::TypeRange operands,
6185 mlir::TypeRange results) {
6186 if (operands.size() != getNumArgs() || results.size() != 1)
6188 mlir::Type iterTy = operands[0];
6189 return iterTy == operands[1] && iterTy == operands[2] && iterTy == results[0];
static StringRef bytes(const std::vector< T, Allocator > &v)
static LogicalResult verifyLoopCleanup(LoopOpTy op)
static bool mayBreakOutOf(cir::LoopOpInterface loop)
Return true if a cir.break may leave loop.
static LogicalResult verifyOpenCLCXXVersion(ModuleOp module, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyCatchParamPairing(mlir::Region &handlerRegion, cir::ConstructCatchParamOp constructOp)
Verify that each cir.init_catch_param in handlerRegion, outside any nested cir.try,...
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static LogicalResult verifyOffloadContainer(mlir::Operation *op)
static std::optional< unsigned > getRecordedIntegerWidth(mlir::Attribute attr)
Reads a fundamental integer width from a signless i32 attribute.
static void getLoadEffects(OpOperand &addr, bool isVolatileOrAtomic, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Adds the effects of a load from addr.
static bool isCirFunctionPointerType(mlir::Type ty)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static bool isFloatingPointCastKind(cir::CastKind kind)
static LogicalResult verifyOffloadKind(mlir::ModuleOp module, cir::OffloadKind expected)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static mlir::Type memberPointeeType(cir::RecordType recordTy, unsigned idx)
static bool isIntOrBoolCast(cir::CastOp op)
static LogicalResult verifyCatchParamAddr(mlir::Operation *op, cir::InitCatchKind kind, cir::PointerType paramAddrType)
For the reference_to_pointer and reference_to_record_pointer kinds, emit an error on op unless paramA...
static void printConstant(OpAsmPrinter &p, Attribute value)
static ParseResult checkEffectAttrKinds(mlir::OpAsmParser &parser, llvm::SMLoc loc, const mlir::NamedAttrList &attrs)
Reject an attribute in an explicit attribute dictionary whose value is not the attribute class expect...
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, ArrayAttr argAttrs, ArrayAttr resAttrs, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static bool areOpenCLVersionsCompatible(cir::OpenCLVersionAttr openCLVersion, cir::OpenCLVersionAttr cxxVersion)
static LogicalResult verifyOpenCLVersionAttrPlacement(Operation *op, NamedAttribute attr)
static bool isInVarCtorRegion(mlir::Operation *op)
Returns true if op is nested in the ctor region of a cir.global or cir.local_init without crossing a ...
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
static LogicalResult verifyOpenCLVersionAttr(Operation *op, NamedAttribute attr)
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static bool isOpenCLVersionAttrName(StringRef attrName)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
static LogicalResult verifyProducedBy(Operation *op, Value operand, StringRef operandName)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printComdatName(OpAsmPrinter &p, StringAttr comdat)
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 bool omitRegionTerm(mlir::Region &r)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult verifyArrayCtorDtor(Op op)
static bool isFuncAttrInDict(llvm::StringRef name)
Declared cir.func attributes with no dedicated syntax, which print in and parse from the attribute di...
static bool isRedundantBeforeReturn(mlir::Region &cleanupRegion)
static mlir::LogicalResult verifyThrowOpImpl(ThrowOpTy op)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
#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
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
unsigned getProgramAddressSpace() const
C++ view class that accepts both !cir.struct and !cir.union types.
llvm::ArrayRef< mlir::Type > getMembers() const
static bool isSupportedCXXABI(const llvm::Triple &T, Kind Kind)
static bool isABI(StringRef Name)
Kind
The basic C++ ABI kind.
void addBytecodeInterface(CIRDialect *dialect)
Add the interfaces necessary for encoding the CIR dialect components in bytecode.
mlir::ParseResult parseEhDispatchDestinations(mlir::OpAsmParser &parser, mlir::ArrayAttr &catchTypes, llvm::SmallVectorImpl< mlir::Block * > &catchDestinations, mlir::Block *&defaultDestination, mlir::UnitAttr &defaultIsCatchAll)
mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
void printCopyTypes(mlir::OpAsmPrinter &printer, mlir::Operation *, mlir::Type srcType, mlir::Type dstType)
mlir::ParseResult parseCopyTypes(mlir::OpAsmParser &parser, mlir::Type &srcType, mlir::Type &dstType)
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
void printComdatName(mlir::OpAsmPrinter &p, cir::GlobalOp op, mlir::StringAttr comdat)
mlir::ParseResult parseGlobalOpTypeAndInitialValue(mlir::OpAsmParser &parser, mlir::TypeAttr &typeAttr, mlir::Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
uint64_t getVTableEntrySize(mlir::ModuleOp mod, const mlir::DataLayout &dataLayout)
The size in bytes of an entry of a C++ vtable in module.
mlir::ParseResult parseSwitchFlatOpCases(mlir::OpAsmParser &parser, mlir::Type flagType, mlir::ArrayAttr &caseValues, llvm::SmallVectorImpl< mlir::Block * > &caseDestinations, llvm::SmallVectorImpl< llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &caseOperands, llvm::SmallVectorImpl< llvm::SmallVector< mlir::Type > > &caseOperandTypes)
bool isValidFundamentalIntWidth(unsigned width)
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
mlir::ParseResult parseAssumeBundle(mlir::OpAsmParser &p, cir::AssumeBundleKindAttr &bundleKindAttr, llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand, 4 > &bundleArgs, llvm::SmallVector< mlir::Type, 1 > &bundleArgTypes)
mlir::ParseResult parseComdatName(mlir::OpAsmParser &parser, mlir::StringAttr &comdatAttr)
bool usesRelativeVTables(mlir::ModuleOp mod)
Whether the C++ vtables of module use the relative layout.
AllocaOp getUnderlyingAlloca(mlir::Value addr)
The alloca that defines addr, looking through casts that preserve the underlying storage.
void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
void printIndirectBrOpSucessors(mlir::OpAsmPrinter &p, cir::IndirectBrOp op, mlir::Type flagType, mlir::SuccessorRange succs, mlir::OperandRangeRange succOperands, const mlir::TypeRangeRange &succOperandsTypes)
mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
mlir::ParseResult parseIndirectBrOpSucessors(mlir::OpAsmParser &parser, mlir::Type &flagType, llvm::SmallVectorImpl< mlir::Block * > &succOperandBlocks, llvm::SmallVectorImpl< llvm::SmallVector< mlir::OpAsmParser::UnresolvedOperand > > &succOperands, llvm::SmallVectorImpl< llvm::SmallVector< mlir::Type > > &succOperandsTypes)
void printGlobalOpTypeAndInitialValue(mlir::OpAsmPrinter &p, cir::GlobalOp op, mlir::TypeAttr type, mlir::Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
std::optional< llvm::Triple > getTripleFromModule(mlir::ModuleOp mod)
Attempts to construct an llvm::Triple from a module's cir.triple attribute.
void printEhDispatchDestinations(mlir::OpAsmPrinter &p, cir::EhDispatchOp op, mlir::ArrayAttr catchTypes, mlir::SuccessorRange catchDestinations, mlir::Block *defaultDestination, mlir::UnitAttr defaultIsCatchAll)
void printAssumeBundle(mlir::OpAsmPrinter &p, cir::AssumeOp op, cir::AssumeBundleKindAttr kindAttr, mlir::OperandRange bundleArgs, mlir::TypeRange bundleArgTypes)
void printSwitchFlatOpCases(mlir::OpAsmPrinter &p, cir::SwitchFlatOp op, mlir::Type flagType, mlir::ArrayAttr caseValues, mlir::SuccessorRange caseDestinations, mlir::OperandRangeRange caseOperands, const mlir::TypeRangeRange &caseOperandTypes)
const AstTypeMatcher< BuiltinType > builtinType
const internal::VariadicAllOfMatcher< Attr > attr
const internal::VariadicAllOfMatcher< TypeLoc > typeLoc
Matches TypeLocs in the clang AST.
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool memberFuncPtrCast()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()
static bool coroUnwindRegion()