19#include "mlir/IR/Attributes.h"
20#include "mlir/IR/DialectImplementation.h"
21#include "mlir/IR/PatternMatch.h"
22#include "mlir/Interfaces/ControlFlowInterfaces.h"
23#include "mlir/Interfaces/FunctionImplementation.h"
24#include "mlir/Support/LLVM.h"
26#include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
27#include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
29#include "llvm/ADT/SetOperations.h"
30#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/TypeSwitch.h"
32#include "llvm/Support/LogicalResult.h"
41struct CIROpAsmDialectInterface :
public OpAsmDialectInterface {
42 using OpAsmDialectInterface::OpAsmDialectInterface;
44 AliasResult getAlias(Type type, raw_ostream &os)
const final {
45 if (
auto recordType = dyn_cast<cir::RecordType>(type)) {
48 os <<
"rec_anon_" <<
recordType.getKindAsStr();
50 os <<
"rec_" << nameAttr.getValue();
51 return AliasResult::OverridableAlias;
53 if (
auto intType = dyn_cast<cir::IntType>(type)) {
56 unsigned width = intType.getWidth();
57 if (width < 8 || !llvm::isPowerOf2_32(width))
58 return AliasResult::NoAlias;
59 os << intType.getAlias();
60 return AliasResult::OverridableAlias;
62 if (
auto voidType = dyn_cast<cir::VoidType>(type)) {
63 os << voidType.getAlias();
64 return AliasResult::OverridableAlias;
67 return AliasResult::NoAlias;
70 AliasResult getAlias(Attribute attr, raw_ostream &os)
const final {
71 if (
auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
72 os << (boolAttr.getValue() ?
"true" :
"false");
73 return AliasResult::FinalAlias;
75 if (
auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
76 os <<
"bfi_" << bitfield.getName().str();
77 return AliasResult::FinalAlias;
79 if (
auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
80 os << dynCastInfoAttr.getAlias();
81 return AliasResult::FinalAlias;
83 return AliasResult::NoAlias;
88void cir::CIRDialect::initialize() {
93#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
95 addInterfaces<CIROpAsmDialectInterface>();
98Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
99 mlir::Attribute value,
101 mlir::Location loc) {
102 return cir::ConstantOp::create(builder, loc, type,
103 mlir::cast<mlir::TypedAttr>(value));
115 for (
auto en : llvm::enumerate(keywords)) {
116 if (succeeded(parser.parseOptionalKeyword(en.value())))
123template <
typename Ty>
struct EnumTraits {};
125#define REGISTER_ENUM_TYPE(Ty) \
126 template <> struct EnumTraits<cir::Ty> { \
127 static llvm::StringRef stringify(cir::Ty value) { \
128 return stringify##Ty(value); \
130 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
141template <
typename EnumTy,
typename RetTy = EnumTy>
144 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
145 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
149 return static_cast<RetTy
>(defaultValue);
150 return static_cast<RetTy
>(index);
154template <
typename EnumTy,
typename RetTy = EnumTy>
157 for (
unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
158 names.push_back(EnumTraits<EnumTy>::stringify(
static_cast<EnumTy
>(i)));
163 result =
static_cast<RetTy
>(index);
171 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
172 OpBuilder builder(parser.getBuilder().getContext());
177 builder.createBlock(®ion);
179 Block &block = region.back();
181 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
185 if (!region.hasOneBlock())
186 return parser.emitError(errLoc,
187 "multi-block region must not omit terminator");
190 builder.setInsertionPointToEnd(&block);
191 cir::YieldOp::create(builder, eLoc);
197 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
198 const auto yieldsNothing = [&r]() {
199 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
200 return y && y.getArgs().empty();
202 return singleNonEmptyBlock && yieldsNothing();
206 cir::VisibilityAttr &visibility) {
207 switch (visibility.getValue()) {
208 case cir::VisibilityKind::Hidden:
211 case cir::VisibilityKind::Protected:
212 printer <<
"protected";
214 case cir::VisibilityKind::Default:
220 cir::VisibilityKind visibilityKind =
222 visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
230 cir::InlineKindAttr &inlineKindAttr) {
232 static constexpr llvm::StringRef keywords[] = {
"no_inline",
"always_inline",
236 llvm::StringRef keyword;
237 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
243 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
244 if (!inlineKindResult) {
245 return parser.emitError(parser.getCurrentLocation(),
"expected one of [")
247 <<
"] for inlineKind, got: " << keyword;
251 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
256 if (inlineKindAttr) {
257 p <<
" " << stringifyInlineKind(inlineKindAttr.getValue());
265 mlir::Region ®ion) {
266 auto regionLoc = parser.getCurrentLocation();
267 if (parser.parseRegion(region))
276 mlir::Region ®ion) {
277 printer.printRegion(region,
286void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
287 mlir::OperationState &odsState, mlir::Type addr,
288 mlir::Type allocaType, llvm::StringRef name,
289 mlir::IntegerAttr alignment) {
290 odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
291 mlir::TypeAttr::get(allocaType));
292 odsState.addAttribute(getNameAttrName(odsState.name),
293 odsBuilder.getStringAttr(name));
295 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
297 odsState.addTypes(addr);
304LogicalResult cir::BreakOp::verify() {
306 if (!getOperation()->getParentOfType<LoopOpInterface>() &&
307 !getOperation()->getParentOfType<SwitchOp>())
308 return emitOpError(
"must be within a loop");
320void cir::ConditionOp::getSuccessorRegions(
326 if (
auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
327 regions.emplace_back(&loopOp.getBody());
328 regions.push_back(RegionSuccessor::parent());
332 auto await = cast<AwaitOp>(getOperation()->getParentOp());
333 regions.emplace_back(&await.getResume());
334 regions.emplace_back(&await.getSuspend());
338cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
340 return MutableOperandRange(getOperation(), 0, 0);
343LogicalResult cir::ConditionOp::verify() {
344 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
345 return emitOpError(
"condition must be within a conditional region");
354 mlir::Attribute attrType) {
355 if (isa<cir::ConstPtrAttr>(attrType)) {
356 if (!mlir::isa<cir::PointerType>(opType))
357 return op->emitOpError(
358 "pointer constant initializing a non-pointer type");
362 if (isa<cir::DataMemberAttr, cir::MethodAttr>(attrType)) {
368 if (isa<cir::ZeroAttr>(attrType)) {
369 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
372 return op->emitOpError(
373 "zero expects struct, array, vector, or complex type");
376 if (mlir::isa<cir::UndefAttr>(attrType)) {
377 if (!mlir::isa<cir::VoidType>(opType))
379 return op->emitOpError(
"undef expects non-void type");
382 if (mlir::isa<cir::BoolAttr>(attrType)) {
383 if (!mlir::isa<cir::BoolType>(opType))
384 return op->emitOpError(
"result type (")
385 << opType <<
") must be '!cir.bool' for '" << attrType <<
"'";
389 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
390 auto at = cast<TypedAttr>(attrType);
391 if (at.getType() != opType) {
392 return op->emitOpError(
"result type (")
393 << opType <<
") does not match value type (" << at.getType()
399 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
400 cir::ConstComplexAttr, cir::ConstRecordAttr,
401 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
402 cir::VTableAttr>(attrType))
405 assert(isa<TypedAttr>(attrType) &&
"What else could we be looking at here?");
406 return op->emitOpError(
"global with type ")
407 << cast<TypedAttr>(attrType).getType() <<
" not yet supported";
410LogicalResult cir::ConstantOp::verify() {
417OpFoldResult cir::ConstantOp::fold(FoldAdaptor ) {
425LogicalResult cir::ContinueOp::verify() {
426 if (!getOperation()->getParentOfType<LoopOpInterface>())
427 return emitOpError(
"must be within a loop");
435LogicalResult cir::CastOp::verify() {
436 mlir::Type resType =
getType();
437 mlir::Type srcType = getSrc().getType();
441 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
442 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
443 if (srcPtrTy && resPtrTy && (
getKind() != cir::CastKind::address_space))
444 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
445 return emitOpError() <<
"result type address space does not match the "
446 "address space of the operand";
449 if (mlir::isa<cir::VectorType>(srcType) &&
450 mlir::isa<cir::VectorType>(resType)) {
453 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
454 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
458 case cir::CastKind::int_to_bool: {
459 if (!mlir::isa<cir::BoolType>(resType))
460 return emitOpError() <<
"requires !cir.bool type for result";
461 if (!mlir::isa<cir::IntType>(srcType))
462 return emitOpError() <<
"requires !cir.int type for source";
465 case cir::CastKind::ptr_to_bool: {
466 if (!mlir::isa<cir::BoolType>(resType))
467 return emitOpError() <<
"requires !cir.bool type for result";
468 if (!mlir::isa<cir::PointerType>(srcType))
469 return emitOpError() <<
"requires !cir.ptr type for source";
472 case cir::CastKind::integral: {
473 if (!mlir::isa<cir::IntType>(resType))
474 return emitOpError() <<
"requires !cir.int type for result";
475 if (!mlir::isa<cir::IntType>(srcType))
476 return emitOpError() <<
"requires !cir.int type for source";
479 case cir::CastKind::array_to_ptrdecay: {
480 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
481 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
482 if (!arrayPtrTy || !flatPtrTy)
483 return emitOpError() <<
"requires !cir.ptr type for source and result";
488 case cir::CastKind::bitcast: {
490 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
491 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
493 if (srcPtrTy && resPtrTy) {
499 case cir::CastKind::floating: {
500 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
501 !mlir::isa<cir::FPTypeInterface>(resType))
502 return emitOpError() <<
"requires !cir.float type for source and result";
505 case cir::CastKind::float_to_int: {
506 if (!mlir::isa<cir::FPTypeInterface>(srcType))
507 return emitOpError() <<
"requires !cir.float type for source";
508 if (!mlir::dyn_cast<cir::IntType>(resType))
509 return emitOpError() <<
"requires !cir.int type for result";
512 case cir::CastKind::int_to_ptr: {
513 if (!mlir::dyn_cast<cir::IntType>(srcType))
514 return emitOpError() <<
"requires !cir.int type for source";
515 if (!mlir::dyn_cast<cir::PointerType>(resType))
516 return emitOpError() <<
"requires !cir.ptr type for result";
519 case cir::CastKind::ptr_to_int: {
520 if (!mlir::dyn_cast<cir::PointerType>(srcType))
521 return emitOpError() <<
"requires !cir.ptr type for source";
522 if (!mlir::dyn_cast<cir::IntType>(resType))
523 return emitOpError() <<
"requires !cir.int type for result";
526 case cir::CastKind::float_to_bool: {
527 if (!mlir::isa<cir::FPTypeInterface>(srcType))
528 return emitOpError() <<
"requires !cir.float type for source";
529 if (!mlir::isa<cir::BoolType>(resType))
530 return emitOpError() <<
"requires !cir.bool type for result";
533 case cir::CastKind::bool_to_int: {
534 if (!mlir::isa<cir::BoolType>(srcType))
535 return emitOpError() <<
"requires !cir.bool type for source";
536 if (!mlir::isa<cir::IntType>(resType))
537 return emitOpError() <<
"requires !cir.int type for result";
540 case cir::CastKind::int_to_float: {
541 if (!mlir::isa<cir::IntType>(srcType))
542 return emitOpError() <<
"requires !cir.int type for source";
543 if (!mlir::isa<cir::FPTypeInterface>(resType))
544 return emitOpError() <<
"requires !cir.float type for result";
547 case cir::CastKind::bool_to_float: {
548 if (!mlir::isa<cir::BoolType>(srcType))
549 return emitOpError() <<
"requires !cir.bool type for source";
550 if (!mlir::isa<cir::FPTypeInterface>(resType))
551 return emitOpError() <<
"requires !cir.float type for result";
554 case cir::CastKind::address_space: {
555 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
556 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
557 if (!srcPtrTy || !resPtrTy)
558 return emitOpError() <<
"requires !cir.ptr type for source and result";
559 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
560 return emitOpError() <<
"requires two types differ in addrspace only";
563 case cir::CastKind::float_to_complex: {
564 if (!mlir::isa<cir::FPTypeInterface>(srcType))
565 return emitOpError() <<
"requires !cir.float type for source";
566 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
568 return emitOpError() <<
"requires !cir.complex type for result";
569 if (srcType != resComplexTy.getElementType())
570 return emitOpError() <<
"requires source type match result element type";
573 case cir::CastKind::int_to_complex: {
574 if (!mlir::isa<cir::IntType>(srcType))
575 return emitOpError() <<
"requires !cir.int type for source";
576 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
578 return emitOpError() <<
"requires !cir.complex type for result";
579 if (srcType != resComplexTy.getElementType())
580 return emitOpError() <<
"requires source type match result element type";
583 case cir::CastKind::float_complex_to_real: {
584 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
586 return emitOpError() <<
"requires !cir.complex type for source";
587 if (!mlir::isa<cir::FPTypeInterface>(resType))
588 return emitOpError() <<
"requires !cir.float type for result";
589 if (srcComplexTy.getElementType() != resType)
590 return emitOpError() <<
"requires source element type match result type";
593 case cir::CastKind::int_complex_to_real: {
594 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
596 return emitOpError() <<
"requires !cir.complex type for source";
597 if (!mlir::isa<cir::IntType>(resType))
598 return emitOpError() <<
"requires !cir.int type for result";
599 if (srcComplexTy.getElementType() != resType)
600 return emitOpError() <<
"requires source element type match result type";
603 case cir::CastKind::float_complex_to_bool: {
604 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
605 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
607 <<
"requires floating point !cir.complex type for source";
608 if (!mlir::isa<cir::BoolType>(resType))
609 return emitOpError() <<
"requires !cir.bool type for result";
612 case cir::CastKind::int_complex_to_bool: {
613 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
614 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
616 <<
"requires floating point !cir.complex type for source";
617 if (!mlir::isa<cir::BoolType>(resType))
618 return emitOpError() <<
"requires !cir.bool type for result";
621 case cir::CastKind::float_complex: {
622 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
623 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
625 <<
"requires floating point !cir.complex type for source";
626 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
627 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
629 <<
"requires floating point !cir.complex type for result";
632 case cir::CastKind::float_complex_to_int_complex: {
633 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
634 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
636 <<
"requires floating point !cir.complex type for source";
637 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
638 if (!resComplexTy || !resComplexTy.isIntegerComplex())
639 return emitOpError() <<
"requires integer !cir.complex type for result";
642 case cir::CastKind::int_complex: {
643 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
644 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
645 return emitOpError() <<
"requires integer !cir.complex type for source";
646 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
647 if (!resComplexTy || !resComplexTy.isIntegerComplex())
648 return emitOpError() <<
"requires integer !cir.complex type for result";
651 case cir::CastKind::int_complex_to_float_complex: {
652 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
653 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
654 return emitOpError() <<
"requires integer !cir.complex type for source";
655 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
656 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
658 <<
"requires floating point !cir.complex type for result";
661 case cir::CastKind::member_ptr_to_bool: {
662 if (!mlir::isa<cir::DataMemberType, cir::MethodType>(srcType))
664 <<
"requires !cir.data_member or !cir.method type for source";
665 if (!mlir::isa<cir::BoolType>(resType))
666 return emitOpError() <<
"requires !cir.bool type for result";
670 llvm_unreachable(
"Unknown CastOp kind?");
674 auto kind = op.getKind();
675 return kind == cir::CastKind::bool_to_int ||
676 kind == cir::CastKind::int_to_bool ||
kind == cir::CastKind::integral;
680 cir::CastOp head = op, tail = op;
686 op = head.getSrc().getDefiningOp<cir::CastOp>();
694 if (head.getKind() == cir::CastKind::bool_to_int &&
695 tail.getKind() == cir::CastKind::int_to_bool)
696 return head.getSrc();
701 if (head.getKind() == cir::CastKind::int_to_bool &&
702 tail.getKind() == cir::CastKind::int_to_bool)
703 return head.getResult();
708OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
709 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
711 return cir::PoisonAttr::get(getContext(),
getType());
716 case cir::CastKind::integral: {
718 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
719 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
720 return mlir::cast<mlir::Attribute>(foldResults[0]);
723 case cir::CastKind::bitcast:
724 case cir::CastKind::address_space:
725 case cir::CastKind::float_complex:
726 case cir::CastKind::int_complex: {
740 if (
auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
742 case cir::CastKind::integral: {
743 mlir::Type srcTy = getSrc().getType();
745 assert(mlir::isa<cir::VectorType>(srcTy) ==
746 mlir::isa<cir::VectorType>(
getType()));
747 if (mlir::isa<cir::VectorType>(srcTy))
750 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
751 auto dstIntTy = mlir::cast<cir::IntType>(
getType());
754 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
755 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
756 return cir::IntAttr::get(dstIntTy, newVal);
769mlir::OperandRange cir::CallOp::getArgOperands() {
771 return getArgs().drop_front(1);
775mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
776 mlir::MutableOperandRange args = getArgsMutable();
778 return args.slice(1, args.size() - 1);
782mlir::Value cir::CallOp::getIndirectCall() {
783 assert(isIndirect());
784 return getOperand(0);
788Value cir::CallOp::getArgOperand(
unsigned i) {
791 return getOperand(i);
795unsigned cir::CallOp::getNumArgOperands() {
797 return this->getOperation()->getNumOperands() - 1;
798 return this->getOperation()->getNumOperands();
801static mlir::ParseResult
803 mlir::OperationState &result) {
804 mlir::Block *normalDestSuccessor;
805 if (parser.parseSuccessor(normalDestSuccessor))
806 return mlir::failure();
808 if (parser.parseComma())
809 return mlir::failure();
811 mlir::Block *unwindDestSuccessor;
812 if (parser.parseSuccessor(unwindDestSuccessor))
813 return mlir::failure();
815 result.addSuccessors(normalDestSuccessor);
816 result.addSuccessors(unwindDestSuccessor);
817 return mlir::success();
821 mlir::OperationState &result,
822 bool hasDestinationBlocks =
false) {
825 mlir::FlatSymbolRefAttr calleeAttr;
830 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
833 OpAsmParser::UnresolvedOperand indirectVal;
835 if (parser.parseOperand(indirectVal).failed())
837 ops.push_back(indirectVal);
840 if (parser.parseLParen())
841 return mlir::failure();
843 opsLoc = parser.getCurrentLocation();
844 if (parser.parseOperandList(ops))
845 return mlir::failure();
846 if (parser.parseRParen())
847 return mlir::failure();
849 if (hasDestinationBlocks &&
851 return ::mlir::failure();
854 if (parser.parseOptionalKeyword(
"nothrow").succeeded())
855 result.addAttribute(CIRDialect::getNoThrowAttrName(),
856 mlir::UnitAttr::get(parser.getContext()));
858 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
859 if (parser.parseLParen().failed())
861 cir::SideEffect sideEffect;
864 if (parser.parseRParen().failed())
866 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
867 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
870 if (parser.parseOptionalAttrDict(result.attributes))
871 return ::mlir::failure();
873 if (parser.parseColon())
874 return ::mlir::failure();
876 mlir::FunctionType opsFnTy;
877 if (parser.parseType(opsFnTy))
878 return mlir::failure();
880 allResultTypes = opsFnTy.getResults();
881 result.addTypes(allResultTypes);
883 if (parser.resolveOperands(ops, opsFnTy.getInputs(), opsLoc, result.operands))
884 return mlir::failure();
886 return mlir::success();
890 mlir::FlatSymbolRefAttr calleeSym,
891 mlir::Value indirectCallee,
892 mlir::OpAsmPrinter &printer,
bool isNothrow,
893 cir::SideEffect sideEffect,
894 mlir::Block *normalDest =
nullptr,
895 mlir::Block *unwindDest =
nullptr) {
898 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
899 auto ops = callLikeOp.getArgOperands();
903 printer.printAttributeWithoutType(calleeSym);
906 assert(indirectCallee);
907 printer << indirectCallee;
910 printer <<
"(" << ops <<
")";
913 assert(unwindDest &&
"expected two successors");
914 auto tryCall = cast<cir::TryCallOp>(op);
915 printer <<
' ' << tryCall.getNormalDest();
918 printer << tryCall.getUnwindDest();
922 printer <<
" nothrow";
924 if (sideEffect != cir::SideEffect::All) {
925 printer <<
" side_effect(";
926 printer << stringifySideEffect(sideEffect);
931 CIRDialect::getCalleeAttrName(), CIRDialect::getNoThrowAttrName(),
932 CIRDialect::getSideEffectAttrName(),
933 CIRDialect::getOperandSegmentSizesAttrName()};
934 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
936 printer.printFunctionalType(op->getOperands().getTypes(),
937 op->getResultTypes());
940mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
941 mlir::OperationState &result) {
945void cir::CallOp::print(mlir::OpAsmPrinter &p) {
946 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
947 cir::SideEffect sideEffect = getSideEffect();
948 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
954 SymbolTableCollection &symbolTable) {
956 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
959 return mlir::success();
962 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
964 return op->emitOpError() <<
"'" << fnAttr.getValue()
965 <<
"' does not reference a valid function";
967 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
968 assert(callIf &&
"expected CIR call interface to be always available");
972 auto fnType = fn.getFunctionType();
973 if (!fn.getNoProto()) {
974 unsigned numCallOperands = callIf.getNumArgOperands();
975 unsigned numFnOpOperands = fnType.getNumInputs();
977 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
978 return op->emitOpError(
"incorrect number of operands for callee");
979 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
980 return op->emitOpError(
"too few operands for callee");
982 for (
unsigned i = 0, e = numFnOpOperands; i != e; ++i)
983 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
984 return op->emitOpError(
"operand type mismatch: expected operand type ")
985 << fnType.getInput(i) <<
", but provided "
986 << op->getOperand(i).getType() <<
" for operand number " << i;
992 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
993 return op->emitOpError(
"callee returns void but call has results");
996 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
997 return op->emitOpError(
"incorrect number of results for callee");
1000 if (!fnType.hasVoidReturn() &&
1001 op->getResultTypes().front() != fnType.getReturnType()) {
1002 return op->emitOpError(
"result type mismatch: expected ")
1003 << fnType.getReturnType() <<
", but provided "
1004 << op->getResult(0).getType();
1007 return mlir::success();
1011cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1019mlir::OperandRange cir::TryCallOp::getArgOperands() {
1021 return getArgs().drop_front(1);
1025mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1026 mlir::MutableOperandRange args = getArgsMutable();
1028 return args.slice(1, args.size() - 1);
1032mlir::Value cir::TryCallOp::getIndirectCall() {
1033 assert(isIndirect());
1034 return getOperand(0);
1038Value cir::TryCallOp::getArgOperand(
unsigned i) {
1041 return getOperand(i);
1045unsigned cir::TryCallOp::getNumArgOperands() {
1047 return this->getOperation()->getNumOperands() - 1;
1048 return this->getOperation()->getNumOperands();
1052cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1056mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1057 mlir::OperationState &result) {
1061void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1062 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() :
nullptr;
1063 cir::SideEffect sideEffect = getSideEffect();
1064 printCallCommon(*
this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1065 sideEffect, getNormalDest(), getUnwindDest());
1073 cir::FuncOp function) {
1075 if (op.getNumOperands() > 1)
1076 return op.emitOpError() <<
"expects at most 1 return operand";
1079 auto expectedTy = function.getFunctionType().getReturnType();
1081 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1082 : op.getOperand(0).getType());
1083 if (actualTy != expectedTy)
1084 return op.emitOpError() <<
"returns " << actualTy
1085 <<
" but enclosing function returns " << expectedTy;
1087 return mlir::success();
1090mlir::LogicalResult cir::ReturnOp::verify() {
1093 auto *fnOp = getOperation()->getParentOp();
1094 while (!isa<cir::FuncOp>(fnOp))
1095 fnOp = fnOp->getParentOp();
1108ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1110 result.regions.reserve(2);
1111 Region *thenRegion = result.addRegion();
1112 Region *elseRegion = result.addRegion();
1114 mlir::Builder &builder = parser.getBuilder();
1115 OpAsmParser::UnresolvedOperand cond;
1116 Type boolType = cir::BoolType::get(builder.getContext());
1118 if (parser.parseOperand(cond) ||
1119 parser.resolveOperand(cond, boolType, result.operands))
1123 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1124 if (parser.parseRegion(*thenRegion, {}, {}))
1131 if (!parser.parseOptionalKeyword(
"else")) {
1132 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1133 if (parser.parseRegion(*elseRegion, {}, {}))
1140 if (parser.parseOptionalAttrDict(result.attributes))
1145void cir::IfOp::print(OpAsmPrinter &p) {
1146 p <<
" " << getCondition() <<
" ";
1147 mlir::Region &thenRegion = this->getThenRegion();
1148 p.printRegion(thenRegion,
1153 mlir::Region &elseRegion = this->getElseRegion();
1154 if (!elseRegion.empty()) {
1156 p.printRegion(elseRegion,
1161 p.printOptionalAttrDict(getOperation()->getAttrs());
1167 cir::YieldOp::create(builder, loc);
1175void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1176 SmallVectorImpl<RegionSuccessor> ®ions) {
1178 if (!point.isParent()) {
1179 regions.push_back(RegionSuccessor::parent());
1184 Region *elseRegion = &this->getElseRegion();
1185 if (elseRegion->empty())
1186 elseRegion =
nullptr;
1189 regions.push_back(RegionSuccessor(&getThenRegion()));
1192 regions.push_back(RegionSuccessor(elseRegion));
1197mlir::ValueRange cir::IfOp::getSuccessorInputs(RegionSuccessor successor) {
1198 return successor.isParent() ? ValueRange(getOperation()->getResults())
1202void cir::IfOp::build(OpBuilder &builder, OperationState &result,
Value cond,
1205 assert(thenBuilder &&
"the builder callback for 'then' must be present");
1206 result.addOperands(cond);
1208 OpBuilder::InsertionGuard guard(builder);
1209 Region *thenRegion = result.addRegion();
1210 builder.createBlock(thenRegion);
1211 thenBuilder(builder, result.location);
1213 Region *elseRegion = result.addRegion();
1214 if (!withElseRegion)
1217 builder.createBlock(elseRegion);
1218 elseBuilder(builder, result.location);
1230void cir::ScopeOp::getSuccessorRegions(
1231 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1233 if (!point.isParent()) {
1234 regions.push_back(RegionSuccessor::parent());
1239 regions.push_back(RegionSuccessor(&getScopeRegion()));
1242mlir::ValueRange cir::ScopeOp::getSuccessorInputs(RegionSuccessor successor) {
1243 return successor.isParent() ? ValueRange(getOperation()->getResults())
1247void cir::ScopeOp::build(
1248 OpBuilder &builder, OperationState &result,
1249 function_ref<
void(OpBuilder &, Type &, Location)> scopeBuilder) {
1250 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1252 OpBuilder::InsertionGuard guard(builder);
1253 Region *scopeRegion = result.addRegion();
1254 builder.createBlock(scopeRegion);
1258 scopeBuilder(builder, yieldTy, result.location);
1261 result.addTypes(TypeRange{yieldTy});
1264void cir::ScopeOp::build(
1265 OpBuilder &builder, OperationState &result,
1266 function_ref<
void(OpBuilder &, Location)> scopeBuilder) {
1267 assert(scopeBuilder &&
"the builder callback for 'then' must be present");
1268 OpBuilder::InsertionGuard guard(builder);
1269 Region *scopeRegion = result.addRegion();
1270 builder.createBlock(scopeRegion);
1272 scopeBuilder(builder, result.location);
1275LogicalResult cir::ScopeOp::verify() {
1277 return emitOpError() <<
"cir.scope must not be empty since it should "
1278 "include at least an implicit cir.yield ";
1281 mlir::Block &lastBlock =
getRegion().back();
1282 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1283 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1284 return emitOpError() <<
"last block of cir.scope must be terminated";
1288LogicalResult cir::ScopeOp::fold(FoldAdaptor ,
1289 SmallVectorImpl<OpFoldResult> &results) {
1294 if (block.getOperations().size() != 1)
1297 auto yield = dyn_cast<cir::YieldOp>(block.front());
1302 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1305 results.push_back(yield.getOperand(0));
1321LogicalResult cir::BrOp::canonicalize(BrOp op, PatternRewriter &rewriter) {
1322 Block *src = op->getBlock();
1323 Block *
dst = op.getDest();
1330 if (src->getNumSuccessors() != 1 ||
dst->getSinglePredecessor() != src)
1335 if (isa<cir::LabelOp, cir::IndirectBrOp>(
dst->front()))
1338 auto operands = op.getDestOperands();
1339 rewriter.eraseOp(op);
1340 rewriter.mergeBlocks(dst, src, operands);
1344mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(
unsigned index) {
1345 assert(index == 0 &&
"invalid successor index");
1346 return mlir::SuccessorOperands(getDestOperandsMutable());
1357mlir::SuccessorOperands
1358cir::IndirectBrOp::getSuccessorOperands(
unsigned index) {
1359 assert(index < getNumSuccessors() &&
"invalid successor index");
1360 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1364 OpAsmParser &parser, Type &flagType,
1365 SmallVectorImpl<Block *> &succOperandBlocks,
1368 if (failed(parser.parseCommaSeparatedList(
1369 OpAsmParser::Delimiter::Square,
1371 Block *destination = nullptr;
1372 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1373 SmallVector<Type> operandTypes;
1375 if (parser.parseSuccessor(destination).failed())
1378 if (succeeded(parser.parseOptionalLParen())) {
1379 if (failed(parser.parseOperandList(
1380 operands, OpAsmParser::Delimiter::None)) ||
1381 failed(parser.parseColonTypeList(operandTypes)) ||
1382 failed(parser.parseRParen()))
1385 succOperandBlocks.push_back(destination);
1386 succOperands.emplace_back(operands);
1387 succOperandsTypes.emplace_back(operandTypes);
1390 "successor blocks")))
1396 Type flagType, SuccessorRange succs,
1397 OperandRangeRange succOperands,
1398 const TypeRangeRange &succOperandsTypes) {
1401 llvm::zip(succs, succOperands),
1404 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1407 if (!succOperands.empty())
1416mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(
unsigned index) {
1417 assert(index < getNumSuccessors() &&
"invalid successor index");
1418 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1419 : getDestOperandsFalseMutable());
1423 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1424 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1432void cir::CaseOp::getSuccessorRegions(
1433 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1434 if (!point.isParent()) {
1435 regions.push_back(RegionSuccessor::parent());
1438 regions.push_back(RegionSuccessor(&getCaseRegion()));
1441mlir::ValueRange cir::CaseOp::getSuccessorInputs(RegionSuccessor successor) {
1442 return successor.isParent() ? ValueRange(getOperation()->getResults())
1446void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1447 ArrayAttr value, CaseOpKind
kind,
1448 OpBuilder::InsertPoint &insertPoint) {
1449 OpBuilder::InsertionGuard guardSwitch(builder);
1450 result.addAttribute(
"value", value);
1451 result.getOrAddProperties<Properties>().
kind =
1452 cir::CaseOpKindAttr::get(builder.getContext(),
kind);
1453 Region *caseRegion = result.addRegion();
1454 builder.createBlock(caseRegion);
1456 insertPoint = builder.saveInsertionPoint();
1463void cir::SwitchOp::getSuccessorRegions(
1464 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ion) {
1465 if (!point.isParent()) {
1466 region.push_back(RegionSuccessor::parent());
1470 region.push_back(RegionSuccessor(&getBody()));
1473mlir::ValueRange cir::SwitchOp::getSuccessorInputs(RegionSuccessor successor) {
1474 return successor.isParent() ? ValueRange(getOperation()->getResults())
1478void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1480 assert(switchBuilder &&
"the builder callback for regions must be present");
1481 OpBuilder::InsertionGuard guardSwitch(builder);
1482 Region *switchRegion = result.addRegion();
1483 builder.createBlock(switchRegion);
1484 result.addOperands({cond});
1485 switchBuilder(builder, result.location, result);
1489 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1491 if (isa<cir::SwitchOp>(op) && op != *
this)
1492 return WalkResult::skip();
1494 if (
auto caseOp = dyn_cast<cir::CaseOp>(op))
1495 cases.push_back(caseOp);
1497 return WalkResult::advance();
1502 collectCases(cases);
1504 if (getBody().empty())
1507 if (!isa<YieldOp>(getBody().front().back()))
1510 if (!llvm::all_of(getBody().front(),
1511 [](Operation &op) {
return isa<CaseOp, YieldOp>(op); }))
1514 return llvm::all_of(cases, [
this](CaseOp op) {
1515 return op->getParentOfType<SwitchOp>() == *
this;
1523void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1524 Value value, Block *defaultDestination,
1525 ValueRange defaultOperands,
1527 BlockRange caseDestinations,
1530 std::vector<mlir::Attribute> caseValuesAttrs;
1531 for (
const APInt &val : caseValues)
1532 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1533 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1535 build(builder, result, value, defaultOperands, caseOperands, attrs,
1536 defaultDestination, caseDestinations);
1542 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1543 SmallVectorImpl<Block *> &caseDestinations,
1547 if (failed(parser.parseLSquare()))
1549 if (succeeded(parser.parseOptionalRSquare()))
1553 auto parseCase = [&]() {
1555 if (failed(parser.parseInteger(value)))
1558 values.push_back(cir::IntAttr::get(flagType, value));
1563 if (parser.parseColon() || parser.parseSuccessor(destination))
1565 if (!parser.parseOptionalLParen()) {
1566 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1568 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1571 caseDestinations.push_back(destination);
1572 caseOperands.emplace_back(operands);
1573 caseOperandTypes.emplace_back(operandTypes);
1576 if (failed(parser.parseCommaSeparatedList(parseCase)))
1579 caseValues = ArrayAttr::get(flagType.getContext(), values);
1581 return parser.parseRSquare();
1585 Type flagType, mlir::ArrayAttr caseValues,
1586 SuccessorRange caseDestinations,
1587 OperandRangeRange caseOperands,
1588 const TypeRangeRange &caseOperandTypes) {
1598 llvm::zip(caseValues, caseDestinations),
1601 mlir::Attribute a = std::get<0>(i);
1602 p << mlir::cast<cir::IntAttr>(a).getValue();
1604 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1619 mlir::Attribute &valueAttr) {
1621 return parser.parseAttribute(valueAttr,
"value", attr);
1625 p.printAttribute(value);
1628mlir::LogicalResult cir::GlobalOp::verify() {
1631 if (getInitialValue().has_value()) {
1643void cir::GlobalOp::build(
1644 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1645 mlir::Type sym_type,
bool isConstant, cir::GlobalLinkageKind linkage,
1646 function_ref<
void(OpBuilder &, Location)> ctorBuilder,
1647 function_ref<
void(OpBuilder &, Location)> dtorBuilder) {
1648 odsState.addAttribute(getSymNameAttrName(odsState.name),
1649 odsBuilder.getStringAttr(sym_name));
1650 odsState.addAttribute(getSymTypeAttrName(odsState.name),
1651 mlir::TypeAttr::get(sym_type));
1653 odsState.addAttribute(getConstantAttrName(odsState.name),
1654 odsBuilder.getUnitAttr());
1656 cir::GlobalLinkageKindAttr linkageAttr =
1657 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
1658 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
1660 Region *ctorRegion = odsState.addRegion();
1662 odsBuilder.createBlock(ctorRegion);
1663 ctorBuilder(odsBuilder, odsState.location);
1666 Region *dtorRegion = odsState.addRegion();
1668 odsBuilder.createBlock(dtorRegion);
1669 dtorBuilder(odsBuilder, odsState.location);
1672 odsState.addAttribute(getGlobalVisibilityAttrName(odsState.name),
1673 cir::VisibilityAttr::get(odsBuilder.getContext()));
1681void cir::GlobalOp::getSuccessorRegions(
1682 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
1684 if (!point.isParent()) {
1685 regions.push_back(RegionSuccessor::parent());
1690 Region *ctorRegion = &this->getCtorRegion();
1691 if (ctorRegion->empty())
1692 ctorRegion =
nullptr;
1695 Region *dtorRegion = &this->getCtorRegion();
1696 if (dtorRegion->empty())
1697 dtorRegion =
nullptr;
1701 regions.push_back(RegionSuccessor(ctorRegion));
1703 regions.push_back(RegionSuccessor(dtorRegion));
1706mlir::ValueRange cir::GlobalOp::getSuccessorInputs(RegionSuccessor successor) {
1707 return successor.isParent() ? ValueRange(getOperation()->getResults())
1712 TypeAttr type, Attribute initAttr,
1713 mlir::Region &ctorRegion,
1714 mlir::Region &dtorRegion) {
1715 auto printType = [&]() { p <<
": " << type; };
1716 if (!op.isDeclaration()) {
1718 if (!ctorRegion.empty()) {
1722 p.printRegion(ctorRegion,
1731 if (!dtorRegion.empty()) {
1733 p.printRegion(dtorRegion,
1744 Attribute &initialValueAttr,
1745 mlir::Region &ctorRegion,
1746 mlir::Region &dtorRegion) {
1748 if (parser.parseOptionalEqual().failed()) {
1751 if (parser.parseColonType(opTy))
1756 if (!parser.parseOptionalKeyword(
"ctor")) {
1757 if (parser.parseColonType(opTy))
1759 auto parseLoc = parser.getCurrentLocation();
1760 if (parser.parseRegion(ctorRegion, {}, {}))
1771 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
1772 "Non-typed attrs shouldn't appear here.");
1773 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
1774 opTy = typedAttr.getType();
1779 if (!parser.parseOptionalKeyword(
"dtor")) {
1780 auto parseLoc = parser.getCurrentLocation();
1781 if (parser.parseRegion(dtorRegion, {}, {}))
1788 typeAttr = TypeAttr::get(opTy);
1797cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1800 mlir::Operation *op =
1801 symbolTable.lookupNearestSymbolFrom(*
this, getNameAttr());
1802 if (op ==
nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
1803 return emitOpError(
"'")
1805 <<
"' does not reference a valid cir.global or cir.func";
1808 if (
auto g = dyn_cast<GlobalOp>(op)) {
1809 symTy = g.getSymType();
1813 if (getTls() && !g.getTlsModel())
1814 return emitOpError(
"access to global not marked thread local");
1815 }
else if (
auto f = dyn_cast<FuncOp>(op)) {
1816 symTy = f.getFunctionType();
1818 llvm_unreachable(
"Unexpected operation for GetGlobalOp");
1821 auto resultType = dyn_cast<PointerType>(getAddr().
getType());
1822 if (!resultType || symTy != resultType.getPointee())
1823 return emitOpError(
"result type pointee type '")
1824 << resultType.getPointee() <<
"' does not match type " << symTy
1825 <<
" of the global @" <<
getName();
1835cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1841 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
1843 return emitOpError(
"'")
1844 <<
name <<
"' does not reference a valid cir.global";
1845 std::optional<mlir::Attribute> init = op.getInitialValue();
1848 if (!isa<cir::VTableAttr>(*init))
1849 return emitOpError(
"Expected #cir.vtable in initializer for global '")
1859cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1868 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*
this, getNameAttr());
1870 return emitOpError(
"'")
1871 <<
name <<
"' does not reference a valid cir.global";
1872 std::optional<mlir::Attribute> init = op.getInitialValue();
1875 if (!isa<cir::ConstArrayAttr>(*init))
1877 "Expected constant array in initializer for global VTT '")
1882LogicalResult cir::VTTAddrPointOp::verify() {
1884 if (
getName() && getSymAddr())
1885 return emitOpError(
"should use either a symbol or value, but not both");
1891 mlir::Type resultType = getAddr().getType();
1892 mlir::Type resTy = cir::PointerType::get(
1893 cir::PointerType::get(cir::VoidType::get(getContext())));
1895 if (resultType != resTy)
1896 return emitOpError(
"result type must be ")
1897 << resTy <<
", but provided result type is " << resultType;
1909void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
1910 StringRef name, FuncType type,
1911 GlobalLinkageKind linkage) {
1913 result.addAttribute(SymbolTable::getSymbolAttrName(),
1914 builder.getStringAttr(name));
1915 result.addAttribute(getFunctionTypeAttrName(result.name),
1916 TypeAttr::get(type));
1917 result.addAttribute(
1919 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
1920 result.addAttribute(getGlobalVisibilityAttrName(result.name),
1921 cir::VisibilityAttr::get(builder.getContext()));
1924ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
1925 llvm::SMLoc loc = parser.getCurrentLocation();
1926 mlir::Builder &builder = parser.getBuilder();
1928 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
1929 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
1930 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
1931 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
1932 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
1933 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
1934 mlir::StringAttr visibilityNameAttr = getGlobalVisibilityAttrName(state.name);
1935 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
1936 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
1938 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
1939 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
1940 if (::mlir::succeeded(
1941 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
1942 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
1945 cir::InlineKindAttr inlineKindAttr;
1949 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
1951 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
1952 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
1953 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
1954 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
1958 GlobalLinkageKindAttr::get(
1959 parser.getContext(),
1961 parser, GlobalLinkageKind::ExternalLinkage)));
1963 ::llvm::StringRef visAttrStr;
1964 if (parser.parseOptionalKeyword(&visAttrStr, {
"private",
"public",
"nested"})
1966 state.addAttribute(visNameAttr,
1967 parser.getBuilder().getStringAttr(visAttrStr));
1970 cir::VisibilityAttr cirVisibilityAttr;
1972 state.addAttribute(visibilityNameAttr, cirVisibilityAttr);
1974 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
1975 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
1977 StringAttr nameAttr;
1978 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1984 bool isVariadic =
false;
1985 if (function_interface_impl::parseFunctionSignatureWithArguments(
1986 parser,
true, arguments, isVariadic, resultTypes,
1990 for (OpAsmParser::Argument &arg : arguments)
1991 argTypes.push_back(
arg.type);
1993 if (resultTypes.size() > 1) {
1994 return parser.emitError(
1995 loc,
"functions with multiple return types are not supported");
1998 mlir::Type returnType =
1999 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
2000 : resultTypes.front());
2002 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
2005 state.addAttribute(getFunctionTypeAttrName(state.name),
2006 TypeAttr::get(fnType));
2008 bool hasAlias =
false;
2009 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
2010 if (parser.parseOptionalKeyword(
"alias").succeeded()) {
2011 if (parser.parseLParen().failed())
2013 mlir::StringAttr aliaseeAttr;
2014 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
2016 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
2017 if (parser.parseRParen().failed())
2022 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
2023 if (parser.parseOptionalKeyword(
"personality").succeeded()) {
2024 if (parser.parseLParen().failed())
2026 mlir::StringAttr personalityAttr;
2027 if (parser.parseOptionalSymbolName(personalityAttr).failed())
2029 state.addAttribute(personalityNameAttr,
2030 FlatSymbolRefAttr::get(personalityAttr));
2031 if (parser.parseRParen().failed())
2035 auto parseGlobalDtorCtor =
2036 [&](StringRef keyword,
2037 llvm::function_ref<void(std::optional<int> prio)> createAttr)
2038 -> mlir::LogicalResult {
2039 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
2040 std::optional<int> priority;
2041 if (mlir::succeeded(parser.parseOptionalLParen())) {
2042 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
2043 if (mlir::failed(parsedPriority))
2044 return parser.emitError(parser.getCurrentLocation(),
2045 "failed to parse 'priority', of type 'int'");
2046 priority = parsedPriority.value_or(
int());
2048 if (parser.parseRParen())
2051 createAttr(priority);
2057 if (parser.parseOptionalKeyword(
"special_member").succeeded()) {
2058 cir::CXXCtorAttr ctorAttr;
2059 cir::CXXDtorAttr dtorAttr;
2060 cir::CXXAssignAttr assignAttr;
2061 if (parser.parseLess().failed())
2063 if (parser.parseOptionalAttribute(ctorAttr).has_value())
2064 state.addAttribute(specialMemberAttr, ctorAttr);
2065 else if (parser.parseOptionalAttribute(dtorAttr).has_value())
2066 state.addAttribute(specialMemberAttr, dtorAttr);
2067 else if (parser.parseOptionalAttribute(assignAttr).has_value())
2068 state.addAttribute(specialMemberAttr, assignAttr);
2069 if (parser.parseGreater().failed())
2073 if (parseGlobalDtorCtor(
"global_ctor", [&](std::optional<int> priority) {
2074 mlir::IntegerAttr globalCtorPriorityAttr =
2075 builder.getI32IntegerAttr(priority.value_or(65535));
2076 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2077 globalCtorPriorityAttr);
2081 if (parseGlobalDtorCtor(
"global_dtor", [&](std::optional<int> priority) {
2082 mlir::IntegerAttr globalDtorPriorityAttr =
2083 builder.getI32IntegerAttr(priority.value_or(65535));
2084 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2085 globalDtorPriorityAttr);
2089 if (parser.parseOptionalKeyword(
"side_effect").succeeded()) {
2090 cir::SideEffect sideEffect;
2092 if (parser.parseLParen().failed() ||
2094 parser.parseRParen().failed())
2097 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
2098 state.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
2102 NamedAttrList parsedAttrs;
2103 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2106 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2107 if (parsedAttrs.get(disallowed))
2108 return parser.emitError(loc,
"attribute '")
2110 <<
"' should not be specified in the explicit attribute list";
2113 state.attributes.append(parsedAttrs);
2116 auto *body = state.addRegion();
2117 OptionalParseResult parseResult = parser.parseOptionalRegion(
2118 *body, arguments,
false);
2119 if (parseResult.has_value()) {
2121 return parser.emitError(loc,
"function alias shall not have a body");
2122 if (failed(*parseResult))
2126 return parser.emitError(loc,
"expected non-empty function body");
2135bool cir::FuncOp::isDeclaration() {
2138 std::optional<StringRef> aliasee = getAliasee();
2140 return getFunctionBody().empty();
2146bool cir::FuncOp::isCXXSpecialMemberFunction() {
2147 return getCxxSpecialMemberAttr() !=
nullptr;
2150bool cir::FuncOp::isCxxConstructor() {
2151 auto attr = getCxxSpecialMemberAttr();
2152 return attr && dyn_cast<CXXCtorAttr>(attr);
2155bool cir::FuncOp::isCxxDestructor() {
2156 auto attr = getCxxSpecialMemberAttr();
2157 return attr && dyn_cast<CXXDtorAttr>(attr);
2160bool cir::FuncOp::isCxxSpecialAssignment() {
2161 auto attr = getCxxSpecialMemberAttr();
2162 return attr && dyn_cast<CXXAssignAttr>(attr);
2165std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2166 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2168 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2169 return ctor.getCtorKind();
2171 return std::nullopt;
2174std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2175 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2177 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2178 return assign.getAssignKind();
2180 return std::nullopt;
2183bool cir::FuncOp::isCxxTrivialMemberFunction() {
2184 mlir::Attribute
attr = getCxxSpecialMemberAttr();
2186 if (
auto ctor = dyn_cast<CXXCtorAttr>(attr))
2187 return ctor.getIsTrivial();
2188 if (
auto dtor = dyn_cast<CXXDtorAttr>(attr))
2189 return dtor.getIsTrivial();
2190 if (
auto assign = dyn_cast<CXXAssignAttr>(attr))
2191 return assign.getIsTrivial();
2196mlir::Region *cir::FuncOp::getCallableRegion() {
2202void cir::FuncOp::print(OpAsmPrinter &p) {
2220 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2221 p <<
' ' << stringifyGlobalLinkageKind(getLinkage());
2223 mlir::SymbolTable::Visibility vis = getVisibility();
2224 if (vis != mlir::SymbolTable::Visibility::Public)
2227 cir::VisibilityAttr cirVisibilityAttr = getGlobalVisibilityAttr();
2228 if (!cirVisibilityAttr.isDefault()) {
2237 p.printSymbolName(getSymName());
2238 cir::FuncType fnType = getFunctionType();
2239 function_interface_impl::printFunctionSignature(
2240 p, *
this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2242 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2244 p.printSymbolName(*aliaseeName);
2248 if (std::optional<StringRef> personalityName = getPersonality()) {
2249 p <<
" personality(";
2250 p.printSymbolName(*personalityName);
2254 if (
auto specialMemberAttr = getCxxSpecialMember()) {
2255 p <<
" special_member<";
2256 p.printAttribute(*specialMemberAttr);
2260 if (
auto globalCtorPriority = getGlobalCtorPriority()) {
2261 p <<
" global_ctor";
2262 if (globalCtorPriority.value() != 65535)
2263 p <<
"(" << globalCtorPriority.value() <<
")";
2266 if (
auto globalDtorPriority = getGlobalDtorPriority()) {
2267 p <<
" global_dtor";
2268 if (globalDtorPriority.value() != 65535)
2269 p <<
"(" << globalDtorPriority.value() <<
")";
2272 if (std::optional<cir::SideEffect> sideEffect = getSideEffect();
2273 sideEffect && *sideEffect != cir::SideEffect::All) {
2274 p <<
" side_effect(";
2275 p << stringifySideEffect(*sideEffect);
2279 function_interface_impl::printFunctionAttributes(
2280 p, *
this, cir::FuncOp::getAttributeNames());
2283 Region &body = getOperation()->getRegion(0);
2284 if (!body.empty()) {
2286 p.printRegion(body,
false,
2291mlir::LogicalResult cir::FuncOp::verify() {
2293 if (!isDeclaration() && getCoroutine()) {
2294 bool foundAwait =
false;
2295 this->walk([&](Operation *op) {
2296 if (
auto await = dyn_cast<AwaitOp>(op)) {
2302 return emitOpError()
2303 <<
"coroutine body must use at least one cir.await op";
2306 llvm::SmallSet<llvm::StringRef, 16> labels;
2307 llvm::SmallSet<llvm::StringRef, 16> gotos;
2308 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2309 bool invalidBlockAddress =
false;
2310 getOperation()->walk([&](mlir::Operation *op) {
2311 if (
auto lab = dyn_cast<cir::LabelOp>(op)) {
2312 labels.insert(lab.getLabel());
2313 }
else if (
auto goTo = dyn_cast<cir::GotoOp>(op)) {
2314 gotos.insert(goTo.getLabel());
2315 }
else if (
auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2316 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2318 invalidBlockAddress =
true;
2319 return mlir::WalkResult::interrupt();
2321 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2323 return mlir::WalkResult::advance();
2326 if (invalidBlockAddress)
2327 return emitOpError() <<
"blockaddress references a different function";
2329 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2330 if (!labels.empty() || !gotos.empty()) {
2331 mismatched = llvm::set_difference(gotos, labels);
2333 if (!mismatched.empty())
2334 return emitOpError() <<
"goto/label mismatch";
2339 if (!labels.empty() || !blockAddresses.empty()) {
2340 mismatched = llvm::set_difference(blockAddresses, labels);
2342 if (!mismatched.empty())
2343 return emitOpError()
2344 <<
"expects an existing label target in the referenced function";
2353LogicalResult cir::BinOp::verify() {
2354 bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
2355 bool saturated = getSaturated();
2357 if (!isa<cir::IntType>(
getType()) && noWrap)
2359 <<
"only operations on integer values may have nsw/nuw flags";
2361 bool noWrapOps =
getKind() == cir::BinOpKind::Add ||
2362 getKind() == cir::BinOpKind::Sub ||
2363 getKind() == cir::BinOpKind::Mul;
2366 getKind() == cir::BinOpKind::Add ||
getKind() == cir::BinOpKind::Sub;
2368 if (noWrap && !noWrapOps)
2369 return emitError() <<
"The nsw/nuw flags are applicable to opcodes: 'add', "
2371 if (saturated && !saturatedOps)
2372 return emitError() <<
"The saturated flag is applicable to opcodes: 'add' "
2374 if (noWrap && saturated)
2375 return emitError() <<
"The nsw/nuw flags and the saturated flag are "
2376 "mutually exclusive";
2378 return mlir::success();
2390void cir::TernaryOp::getSuccessorRegions(
2391 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2393 if (!point.isParent()) {
2394 regions.push_back(RegionSuccessor::parent());
2400 regions.push_back(RegionSuccessor(&getTrueRegion()));
2401 regions.push_back(RegionSuccessor(&getFalseRegion()));
2404mlir::ValueRange cir::TernaryOp::getSuccessorInputs(RegionSuccessor successor) {
2405 return successor.isParent() ? ValueRange(getOperation()->getResults())
2409void cir::TernaryOp::build(
2410 OpBuilder &builder, OperationState &result,
Value cond,
2411 function_ref<
void(OpBuilder &, Location)> trueBuilder,
2412 function_ref<
void(OpBuilder &, Location)> falseBuilder) {
2413 result.addOperands(cond);
2414 OpBuilder::InsertionGuard guard(builder);
2415 Region *trueRegion = result.addRegion();
2416 builder.createBlock(trueRegion);
2417 trueBuilder(builder, result.location);
2418 Region *falseRegion = result.addRegion();
2419 builder.createBlock(falseRegion);
2420 falseBuilder(builder, result.location);
2425 dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2427 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2429 assert((yield && yield.getNumOperands() <= 1) &&
2430 "expected zero or one result type");
2431 if (yield.getNumOperands() == 1)
2432 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2439OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2440 mlir::Attribute
condition = adaptor.getCondition();
2442 bool conditionValue = mlir::cast<cir::BoolAttr>(
condition).getValue();
2443 return conditionValue ? getTrueValue() : getFalseValue();
2447 mlir::Attribute trueValue = adaptor.getTrueValue();
2448 mlir::Attribute falseValue = adaptor.getFalseValue();
2449 if (trueValue == falseValue)
2451 if (getTrueValue() == getFalseValue())
2452 return getTrueValue();
2457LogicalResult cir::SelectOp::verify() {
2459 auto condTy = dyn_cast<cir::VectorType>(getCondition().
getType());
2466 if (!isa<cir::VectorType>(getTrueValue().
getType()) ||
2467 !isa<cir::VectorType>(getFalseValue().
getType())) {
2468 return emitOpError()
2469 <<
"expected both true and false operands to be vector types "
2470 "when the condition is a vector boolean type";
2479LogicalResult cir::ShiftOp::verify() {
2480 mlir::Operation *op = getOperation();
2481 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2482 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2483 if (!op0VecTy ^ !op1VecTy)
2484 return emitOpError() <<
"input types cannot be one vector and one scalar";
2487 if (op0VecTy.getSize() != op1VecTy.getSize())
2488 return emitOpError() <<
"input vector types must have the same size";
2490 auto opResultTy = mlir::dyn_cast<cir::VectorType>(
getType());
2492 return emitOpError() <<
"the type of the result must be a vector "
2493 <<
"if it is vector shift";
2495 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2496 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2497 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2498 return emitOpError()
2499 <<
"vector operands do not have the same elements sizes";
2501 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2502 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2503 return emitOpError() <<
"vector operands and result type do not have the "
2504 "same elements sizes";
2507 return mlir::success();
2514LogicalResult cir::LabelOp::verify() {
2515 mlir::Operation *op = getOperation();
2516 mlir::Block *blk = op->getBlock();
2517 if (&blk->front() != op)
2518 return emitError() <<
"must be the first operation in a block";
2520 return mlir::success();
2527LogicalResult cir::UnaryOp::verify() {
2529 case cir::UnaryOpKind::Inc:
2530 case cir::UnaryOpKind::Dec:
2531 case cir::UnaryOpKind::Plus:
2532 case cir::UnaryOpKind::Minus:
2533 case cir::UnaryOpKind::Not:
2538 llvm_unreachable(
"Unknown UnaryOp kind?");
2542 return isa<cir::BoolType>(op.getInput().getType()) &&
2543 op.getKind() == cir::UnaryOpKind::Not;
2555OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
2557 mlir::dyn_cast_if_present<cir::PoisonAttr>(adaptor.getInput())) {
2563 if (
auto previous = getInput().getDefiningOp<cir::UnaryOp>())
2565 return previous.getInput();
2571 if (
auto srcConst = getInput().getDefiningOp<cir::ConstantOp>()) {
2572 if (
getKind() == cir::UnaryOpKind::Plus ||
2573 (mlir::isa<cir::BoolType>(srcConst.getType()) &&
2574 getKind() == cir::UnaryOpKind::Minus))
2575 return srcConst.getResult();
2582 if (mlir::Attribute attr = adaptor.getInput()) {
2584 OpFoldResult result =
2585 llvm::TypeSwitch<mlir::Attribute, OpFoldResult>(attr)
2586 .Case<cir::IntAttr>([&](cir::IntAttr attrT) {
2588 case cir::UnaryOpKind::Not: {
2589 APInt val = attrT.getValue();
2591 return cir::IntAttr::get(
getType(), val);
2593 case cir::UnaryOpKind::Plus:
2595 case cir::UnaryOpKind::Minus: {
2596 APInt val = attrT.getValue();
2598 return cir::IntAttr::get(
getType(), val);
2601 return cir::IntAttr{};
2604 .Case<cir::FPAttr>([&](cir::FPAttr attrT) {
2606 case cir::UnaryOpKind::Plus:
2608 case cir::UnaryOpKind::Minus: {
2609 APFloat val = attrT.getValue();
2611 return cir::FPAttr::get(
getType(), val);
2614 return cir::FPAttr{};
2617 .Case<cir::BoolAttr>([&](cir::BoolAttr attrT) {
2619 case cir::UnaryOpKind::Not:
2620 return cir::BoolAttr::get(getContext(), !attrT.getValue());
2621 case cir::UnaryOpKind::Plus:
2622 case cir::UnaryOpKind::Minus:
2625 return cir::BoolAttr{};
2628 .
Default([&](
auto attrT) {
return mlir::Attribute{}; });
2641 mlir::Type resultTy) {
2644 mlir::Type inputMemberTy;
2645 mlir::Type resultMemberTy;
2646 if (mlir::isa<cir::DataMemberType>(src.getType())) {
2648 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
2649 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
2652 if (inputMemberTy != resultMemberTy)
2653 return op->emitOpError()
2654 <<
"member types of the operand and the result do not match";
2656 return mlir::success();
2659LogicalResult cir::BaseDataMemberOp::verify() {
2663LogicalResult cir::DerivedDataMemberOp::verify() {
2671LogicalResult cir::BaseMethodOp::verify() {
2675LogicalResult cir::DerivedMethodOp::verify() {
2683void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
2687 result.addAttribute(getKindAttrName(result.name),
2688 cir::AwaitKindAttr::get(builder.getContext(),
kind));
2690 OpBuilder::InsertionGuard guard(builder);
2691 Region *readyRegion = result.addRegion();
2692 builder.createBlock(readyRegion);
2693 readyBuilder(builder, result.location);
2697 OpBuilder::InsertionGuard guard(builder);
2698 Region *suspendRegion = result.addRegion();
2699 builder.createBlock(suspendRegion);
2700 suspendBuilder(builder, result.location);
2704 OpBuilder::InsertionGuard guard(builder);
2705 Region *resumeRegion = result.addRegion();
2706 builder.createBlock(resumeRegion);
2707 resumeBuilder(builder, result.location);
2711void cir::AwaitOp::getSuccessorRegions(
2712 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
2715 if (!point.isParent()) {
2716 regions.push_back(RegionSuccessor::parent());
2723 regions.push_back(RegionSuccessor(&this->getReady()));
2724 regions.push_back(RegionSuccessor(&this->getSuspend()));
2725 regions.push_back(RegionSuccessor(&this->getResume()));
2728mlir::ValueRange cir::AwaitOp::getSuccessorInputs(RegionSuccessor successor) {
2729 if (successor.isParent())
2730 return getOperation()->getResults();
2731 if (successor == &getReady())
2732 return getReady().getArguments();
2733 if (successor == &getSuspend())
2734 return getSuspend().getArguments();
2735 if (successor == &getResume())
2736 return getResume().getArguments();
2737 llvm_unreachable(
"invalid region successor");
2740LogicalResult cir::AwaitOp::verify() {
2741 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
2742 return emitOpError(
"ready region must end with cir.condition");
2750LogicalResult cir::CopyOp::verify() {
2752 if (!
getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
2753 return emitError() <<
"missing data layout for pointee type";
2755 if (getSrc() == getDst())
2756 return emitError() <<
"source and destination are the same";
2758 return mlir::success();
2765LogicalResult cir::GetRuntimeMemberOp::verify() {
2766 auto recordTy = mlir::cast<RecordType>(getAddr().
getType().getPointee());
2767 cir::DataMemberType memberPtrTy = getMember().getType();
2769 if (recordTy != memberPtrTy.getClassTy())
2770 return emitError() <<
"record type does not match the member pointer type";
2771 if (
getType().getPointee() != memberPtrTy.getMemberTy())
2772 return emitError() <<
"result type does not match the member pointer type";
2773 return mlir::success();
2780LogicalResult cir::GetMethodOp::verify() {
2781 cir::MethodType methodTy = getMethod().getType();
2784 cir::PointerType objectPtrTy = getObject().getType();
2785 mlir::Type objectTy = objectPtrTy.getPointee();
2787 if (methodTy.getClassTy() != objectTy)
2788 return emitError() <<
"method class type and object type do not match";
2791 auto calleeTy = mlir::cast<cir::FuncType>(getCallee().
getType().getPointee());
2792 cir::FuncType methodFuncTy = methodTy.getMemberFuncTy();
2799 if (methodFuncTy.getReturnType() != calleeTy.getReturnType())
2801 <<
"method return type and callee return type do not match";
2806 if (calleeArgsTy.empty())
2807 return emitError() <<
"callee parameter list lacks receiver object ptr";
2809 auto calleeThisArgPtrTy = mlir::dyn_cast<cir::PointerType>(calleeArgsTy[0]);
2810 if (!calleeThisArgPtrTy ||
2811 !mlir::isa<cir::VoidType>(calleeThisArgPtrTy.getPointee())) {
2813 <<
"the first parameter of callee must be a void pointer";
2816 if (calleeArgsTy.slice(1) != methodFuncArgsTy)
2818 <<
"callee parameters and method parameters do not match";
2820 return mlir::success();
2827LogicalResult cir::GetMemberOp::verify() {
2828 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
2830 return emitError() <<
"expected pointer to a record type";
2832 if (recordTy.getMembers().size() <=
getIndex())
2833 return emitError() <<
"member index out of bounds";
2836 return emitError() <<
"member type mismatch";
2838 return mlir::success();
2845LogicalResult cir::ExtractMemberOp::verify() {
2846 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
2847 if (recordTy.getKind() == cir::RecordType::Union)
2849 <<
"cir.extract_member currently does not support unions";
2850 if (recordTy.getMembers().size() <=
getIndex())
2851 return emitError() <<
"member index out of bounds";
2853 return emitError() <<
"member type mismatch";
2854 return mlir::success();
2861LogicalResult cir::InsertMemberOp::verify() {
2862 auto recordTy = mlir::cast<cir::RecordType>(getRecord().
getType());
2863 if (recordTy.getKind() == cir::RecordType::Union)
2864 return emitError() <<
"cir.insert_member currently does not support unions";
2865 if (recordTy.getMembers().size() <=
getIndex())
2866 return emitError() <<
"member index out of bounds";
2868 return emitError() <<
"member type mismatch";
2870 return mlir::success();
2877OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
2878 if (llvm::any_of(getElements(), [](mlir::Value value) {
2879 return !value.getDefiningOp<cir::ConstantOp>();
2883 return cir::ConstVectorAttr::get(
2884 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
2887LogicalResult cir::VecCreateOp::verify() {
2891 const cir::VectorType vecTy =
getType();
2892 if (getElements().size() != vecTy.getSize()) {
2893 return emitOpError() <<
"operand count of " << getElements().size()
2894 <<
" doesn't match vector type " << vecTy
2895 <<
" element count of " << vecTy.getSize();
2898 const mlir::Type elementType = vecTy.getElementType();
2899 for (
const mlir::Value element : getElements()) {
2900 if (element.getType() != elementType) {
2901 return emitOpError() <<
"operand type " << element.getType()
2902 <<
" doesn't match vector element type "
2914OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
2915 const auto vectorAttr =
2916 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
2920 const auto indexAttr =
2921 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
2925 const mlir::ArrayAttr elements = vectorAttr.getElts();
2926 const uint64_t index = indexAttr.getUInt();
2927 if (index >= elements.size())
2930 return elements[index];
2937OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
2939 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
2941 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
2942 if (!lhsVecAttr || !rhsVecAttr)
2945 mlir::Type inputElemTy =
2946 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
2947 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
2950 cir::CmpOpKind opKind = adaptor.getKind();
2951 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
2952 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
2953 uint64_t vecSize = lhsVecElhs.size();
2956 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
2957 for (uint64_t i = 0; i < vecSize; i++) {
2958 mlir::Attribute lhsAttr = lhsVecElhs[i];
2959 mlir::Attribute rhsAttr = rhsVecElhs[i];
2962 case cir::CmpOpKind::lt: {
2964 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
2965 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2967 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
2968 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2972 case cir::CmpOpKind::le: {
2974 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
2975 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2977 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
2978 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2982 case cir::CmpOpKind::gt: {
2984 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
2985 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2987 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
2988 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2992 case cir::CmpOpKind::ge: {
2994 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
2995 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2997 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
2998 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3002 case cir::CmpOpKind::eq: {
3004 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
3005 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3007 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
3008 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3012 case cir::CmpOpKind::ne: {
3014 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
3015 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
3017 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
3018 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
3024 elements[i] = cir::IntAttr::get(
getType().getElementType(), cmpResult);
3027 return cir::ConstVectorAttr::get(
3028 getType(), mlir::ArrayAttr::get(getContext(), elements));
3035OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
3037 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
3039 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
3040 if (!vec1Attr || !vec2Attr)
3043 mlir::Type vec1ElemTy =
3044 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
3046 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
3047 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
3048 mlir::ArrayAttr indicesElts = adaptor.getIndices();
3051 elements.reserve(indicesElts.size());
3053 uint64_t vec1Size = vec1Elts.size();
3054 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3055 if (idxAttr.getSInt() == -1) {
3056 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
3060 uint64_t idxValue = idxAttr.getUInt();
3061 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
3062 : vec2Elts[idxValue - vec1Size]);
3065 return cir::ConstVectorAttr::get(
3066 getType(), mlir::ArrayAttr::get(getContext(), elements));
3069LogicalResult cir::VecShuffleOp::verify() {
3072 if (getIndices().size() != getResult().
getType().getSize()) {
3073 return emitOpError() <<
": the number of elements in " << getIndices()
3074 <<
" and " << getResult().getType() <<
" don't match";
3079 if (getVec1().
getType().getElementType() !=
3080 getResult().
getType().getElementType()) {
3081 return emitOpError() <<
": element types of " << getVec1().getType()
3082 <<
" and " << getResult().getType() <<
" don't match";
3085 const uint64_t maxValidIndex =
3086 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
3088 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
3089 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
3091 return emitOpError() <<
": index for __builtin_shufflevector must be "
3092 "less than the total number of vector elements";
3101OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
3102 mlir::Attribute vec = adaptor.getVec();
3103 mlir::Attribute indices = adaptor.getIndices();
3104 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
3105 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
3106 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
3107 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
3109 mlir::ArrayAttr vecElts = vecAttr.getElts();
3110 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
3112 const uint64_t numElements = vecElts.size();
3115 elements.reserve(numElements);
3117 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
3118 for (
const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
3119 uint64_t idxValue = idxAttr.getUInt();
3120 uint64_t newIdx = idxValue & maskBits;
3121 elements.push_back(vecElts[newIdx]);
3124 return cir::ConstVectorAttr::get(
3125 getType(), mlir::ArrayAttr::get(getContext(), elements));
3131LogicalResult cir::VecShuffleDynamicOp::verify() {
3133 if (getVec().
getType().getSize() !=
3134 mlir::cast<cir::VectorType>(getIndices().
getType()).getSize()) {
3135 return emitOpError() <<
": the number of elements in " << getVec().getType()
3136 <<
" and " << getIndices().getType() <<
" don't match";
3145LogicalResult cir::VecTernaryOp::verify() {
3150 if (getCond().
getType().getSize() != getLhs().
getType().getSize()) {
3151 return emitOpError() <<
": the number of elements in "
3152 << getCond().getType() <<
" and " << getLhs().getType()
3158OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
3159 mlir::Attribute cond = adaptor.getCond();
3160 mlir::Attribute lhs = adaptor.getLhs();
3161 mlir::Attribute rhs = adaptor.getRhs();
3163 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
3164 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
3165 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
3167 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
3168 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
3169 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3171 mlir::ArrayAttr condElts = condVec.getElts();
3174 elements.reserve(condElts.size());
3176 for (
const auto &[idx, condAttr] :
3177 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3178 if (condAttr.getSInt()) {
3179 elements.push_back(lhsVec.getElts()[idx]);
3181 elements.push_back(rhsVec.getElts()[idx]);
3185 cir::VectorType vecTy = getLhs().getType();
3186 return cir::ConstVectorAttr::get(
3187 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3194LogicalResult cir::ComplexCreateOp::verify() {
3197 <<
"operand type of cir.complex.create does not match its result type";
3204OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3205 mlir::Attribute real = adaptor.getReal();
3206 mlir::Attribute imag = adaptor.getImag();
3212 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3213 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3214 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3221LogicalResult cir::ComplexRealOp::verify() {
3222 mlir::Type operandTy = getOperand().getType();
3223 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3224 operandTy = complexOperandTy.getElementType();
3227 emitOpError() <<
": result type does not match operand type";
3234OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3235 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3238 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3239 return complexCreateOp.getOperand(0);
3242 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3243 return complex ? complex.getReal() :
nullptr;
3250LogicalResult cir::ComplexImagOp::verify() {
3251 mlir::Type operandTy = getOperand().getType();
3252 if (
auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3253 operandTy = complexOperandTy.getElementType();
3256 emitOpError() <<
": result type does not match operand type";
3263OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3264 if (!mlir::isa<cir::ComplexType>(getOperand().
getType()))
3267 if (
auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3268 return complexCreateOp.getOperand(1);
3271 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3272 return complex ? complex.getImag() :
nullptr;
3279LogicalResult cir::ComplexRealPtrOp::verify() {
3280 mlir::Type resultPointeeTy =
getType().getPointee();
3281 cir::PointerType operandPtrTy = getOperand().getType();
3282 auto operandPointeeTy =
3283 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3285 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3286 return emitOpError() <<
": result type does not match operand type";
3296LogicalResult cir::ComplexImagPtrOp::verify() {
3297 mlir::Type resultPointeeTy =
getType().getPointee();
3298 cir::PointerType operandPtrTy = getOperand().getType();
3299 auto operandPointeeTy =
3300 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3302 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3303 return emitOpError()
3304 <<
"cir.complex.imag_ptr result type does not match operand type";
3315 llvm::function_ref<llvm::APInt(
const llvm::APInt &)> func,
3316 bool poisonZero =
false) {
3317 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3322 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3326 llvm::APInt inputValue = input.getValue();
3327 if (poisonZero && inputValue.isZero())
3328 return cir::PoisonAttr::get(input.getType());
3330 llvm::APInt resultValue = func(inputValue);
3331 return IntAttr::get(input.getType(), resultValue);
3334OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3335 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3336 unsigned resultValue =
3337 inputValue.getBitWidth() - inputValue.getSignificantBits();
3338 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3342OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3345 [](
const llvm::APInt &inputValue) {
3346 unsigned resultValue = inputValue.countLeadingZeros();
3347 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3352OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3355 [](
const llvm::APInt &inputValue) {
3356 return llvm::APInt(inputValue.getBitWidth(),
3357 inputValue.countTrailingZeros());
3362OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3363 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3364 unsigned trailingZeros = inputValue.countTrailingZeros();
3366 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3367 return llvm::APInt(inputValue.getBitWidth(), result);
3371OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3372 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3373 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3377OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3378 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3379 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3383OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3384 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3385 return inputValue.reverseBits();
3389OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3390 return foldUnaryBitOp(adaptor.getInput(), [](
const llvm::APInt &inputValue) {
3391 return inputValue.byteSwap();
3395OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3396 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3397 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3399 return cir::PoisonAttr::get(
getType());
3402 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3403 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3404 if (!input && !amount)
3413 llvm::APInt inputValue;
3415 inputValue = input.getValue();
3416 if (inputValue.isZero() || inputValue.isAllOnes()) {
3422 uint64_t amountValue;
3424 amountValue = amount.getValue().urem(getInput().
getType().getWidth());
3425 if (amountValue == 0) {
3431 if (!input || !amount)
3434 assert(inputValue.getBitWidth() == getInput().
getType().getWidth() &&
3435 "input value must have the same bit width as the input type");
3437 llvm::APInt resultValue;
3439 resultValue = inputValue.rotl(amountValue);
3441 resultValue = inputValue.rotr(amountValue);
3443 return IntAttr::get(input.getContext(), input.getType(), resultValue);
3450void cir::InlineAsmOp::print(OpAsmPrinter &p) {
3451 p <<
'(' << getAsmFlavor() <<
", ";
3456 auto *nameIt = names.begin();
3457 auto *attrIt = getOperandAttrs().begin();
3459 for (mlir::OperandRange ops : getAsmOperands()) {
3460 p << *nameIt <<
" = ";
3463 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
3465 p.printOperand(value);
3466 p <<
" : " << value.getType();
3468 p <<
" (maybe_memory)";
3477 p.printString(getAsmString());
3479 p.printString(getConstraints());
3483 if (getSideEffects())
3484 p <<
" side_effects";
3486 std::array elidedAttrs{
3487 llvm::StringRef(
"asm_flavor"), llvm::StringRef(
"asm_string"),
3488 llvm::StringRef(
"constraints"), llvm::StringRef(
"operand_attrs"),
3489 llvm::StringRef(
"operands_segments"), llvm::StringRef(
"side_effects")};
3490 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
3492 if (
auto v = getRes())
3493 p <<
" -> " << v.getType();
3496void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
3498 StringRef asmString, StringRef constraints,
3499 bool sideEffects, cir::AsmFlavor asmFlavor,
3503 for (
auto operandRange : asmOperands) {
3504 segments.push_back(operandRange.size());
3505 odsState.addOperands(operandRange);
3508 odsState.addAttribute(
3509 "operands_segments",
3510 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
3511 odsState.addAttribute(
"asm_string", odsBuilder.getStringAttr(asmString));
3512 odsState.addAttribute(
"constraints", odsBuilder.getStringAttr(constraints));
3513 odsState.addAttribute(
"asm_flavor",
3514 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
3517 odsState.addAttribute(
"side_effects", odsBuilder.getUnitAttr());
3519 odsState.addAttribute(
"operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
3522ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
3523 OperationState &result) {
3526 std::string asmString, constraints;
3528 MLIRContext *ctxt = parser.getBuilder().getContext();
3530 auto error = [&](
const Twine &msg) -> LogicalResult {
3531 return parser.emitError(parser.getCurrentLocation(), msg);
3534 auto expected = [&](
const std::string &
c) {
3535 return error(
"expected '" +
c +
"'");
3538 if (parser.parseLParen().failed())
3539 return expected(
"(");
3541 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
3543 return error(
"Unknown AsmFlavor");
3545 if (parser.parseComma().failed())
3546 return expected(
",");
3548 auto parseValue = [&](
Value &v) {
3549 OpAsmParser::UnresolvedOperand op;
3551 if (parser.parseOperand(op) || parser.parseColon())
3552 return error(
"can't parse operand");
3555 if (parser.parseType(typ).failed())
3556 return error(
"can't parse operand type");
3558 if (parser.resolveOperand(op, typ, tmp))
3559 return error(
"can't resolve operand");
3561 return mlir::success();
3564 auto parseOperands = [&](llvm::StringRef
name) {
3565 if (parser.parseKeyword(name).failed())
3566 return error(
"expected " + name +
" operands here");
3567 if (parser.parseEqual().failed())
3568 return expected(
"=");
3569 if (parser.parseLSquare().failed())
3570 return expected(
"[");
3573 if (parser.parseOptionalRSquare().succeeded()) {
3574 operandsGroupSizes.push_back(size);
3575 if (parser.parseComma())
3576 return expected(
",");
3577 return mlir::success();
3580 auto parseOperand = [&]() {
3582 if (parseValue(val).succeeded()) {
3583 result.operands.push_back(val);
3586 if (parser.parseOptionalLParen().failed()) {
3587 operandAttrs.push_back(mlir::Attribute());
3588 return mlir::success();
3591 if (parser.parseKeyword(
"maybe_memory").succeeded()) {
3592 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
3593 if (parser.parseRParen())
3594 return expected(
")");
3595 return mlir::success();
3597 return expected(
"maybe_memory");
3600 return mlir::failure();
3603 if (parser.parseCommaSeparatedList(parseOperand).failed())
3604 return mlir::failure();
3606 if (parser.parseRSquare().failed() || parser.parseComma().failed())
3607 return expected(
"]");
3608 operandsGroupSizes.push_back(size);
3609 return mlir::success();
3612 if (parseOperands(
"out").failed() || parseOperands(
"in").failed() ||
3613 parseOperands(
"in_out").failed())
3614 return error(
"failed to parse operands");
3616 if (parser.parseLBrace())
3617 return expected(
"{");
3618 if (parser.parseString(&asmString))
3619 return error(
"asm string parsing failed");
3620 if (parser.parseString(&constraints))
3621 return error(
"constraints string parsing failed");
3622 if (parser.parseRBrace())
3623 return expected(
"}");
3624 if (parser.parseRParen())
3625 return expected(
")");
3627 if (parser.parseOptionalKeyword(
"side_effects").succeeded())
3628 result.attributes.set(
"side_effects", UnitAttr::get(ctxt));
3630 if (parser.parseOptionalArrow().succeeded() &&
3631 parser.parseType(resType).failed())
3632 return mlir::failure();
3634 if (parser.parseOptionalAttrDict(result.attributes).failed())
3635 return mlir::failure();
3637 result.attributes.set(
"asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
3638 result.attributes.set(
"asm_string", StringAttr::get(ctxt, asmString));
3639 result.attributes.set(
"constraints", StringAttr::get(ctxt, constraints));
3640 result.attributes.set(
"operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
3641 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
3642 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
3644 result.addTypes(TypeRange{resType});
3646 return mlir::success();
3653mlir::LogicalResult cir::ThrowOp::verify() {
3658 if (getNumOperands() != 0) {
3661 return emitOpError() <<
"'type_info' symbol attribute missing";
3671LogicalResult cir::AtomicFetchOp::verify() {
3672 if (getBinop() != cir::AtomicFetchKind::Add &&
3673 getBinop() != cir::AtomicFetchKind::Sub &&
3674 getBinop() != cir::AtomicFetchKind::Max &&
3675 getBinop() != cir::AtomicFetchKind::Min &&
3676 !mlir::isa<cir::IntType>(getVal().
getType()))
3677 return emitError(
"only atomic add, sub, max, and min operation could "
3678 "operate on floating-point values");
3686LogicalResult cir::TypeInfoAttr::verify(
3687 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
3688 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
3690 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
3700void cir::TryOp::getSuccessorRegions(
3701 mlir::RegionBranchPoint point,
3704 if (!point.isParent()) {
3705 regions.push_back(RegionSuccessor::parent());
3709 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
3713 for (mlir::Region &handlerRegion : this->getHandlerRegions())
3714 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
3717mlir::ValueRange cir::TryOp::getSuccessorInputs(RegionSuccessor successor) {
3718 return successor.isParent() ? ValueRange(getOperation()->getResults())
3724 mlir::MutableArrayRef<mlir::Region> handlerRegions,
3725 mlir::ArrayAttr handlerTypes) {
3729 for (
const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
3733 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
3734 printer <<
"catch all ";
3735 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
3736 printer <<
"unwind ";
3738 printer <<
"catch [type ";
3739 printer.printAttribute(typeAttr);
3743 printer.printRegion(handlerRegions[typeIdx],
3750 mlir::OpAsmParser &parser,
3752 mlir::ArrayAttr &handlerTypes) {
3754 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
3755 handlerRegions.emplace_back(
new mlir::Region);
3757 mlir::Region &currRegion = *handlerRegions.back();
3758 mlir::SMLoc regionLoc = parser.getCurrentLocation();
3759 if (parser.parseRegion(currRegion)) {
3760 handlerRegions.clear();
3764 if (currRegion.empty())
3765 return parser.emitError(regionLoc,
"handler region shall not be empty");
3767 if (!(currRegion.back().mightHaveTerminator() &&
3768 currRegion.back().getTerminator()))
3769 return parser.emitError(
3770 regionLoc,
"blocks are expected to be explicitly terminated");
3775 bool hasCatchAll =
false;
3777 while (parser.parseOptionalKeyword(
"catch").succeeded()) {
3778 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
3780 llvm::StringRef attrStr;
3781 if (parser.parseOptionalKeyword(&attrStr, {
"all",
"type"}).failed())
3782 return parser.emitError(parser.getCurrentLocation(),
3783 "expected 'all' or 'type' keyword");
3785 bool isCatchAll = attrStr ==
"all";
3788 return parser.emitError(parser.getCurrentLocation(),
3789 "can't have more than one catch all");
3793 mlir::Attribute exceptionRTTIAttr;
3794 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
3795 return parser.emitError(parser.getCurrentLocation(),
3796 "expected valid RTTI info attribute");
3798 catcherAttrs.push_back(isCatchAll
3799 ? cir::CatchAllAttr::get(parser.getContext())
3800 : exceptionRTTIAttr);
3802 if (hasLSquare && isCatchAll)
3803 return parser.emitError(parser.getCurrentLocation(),
3804 "catch all dosen't need RTTI info attribute");
3806 if (hasLSquare && parser.parseRSquare().failed())
3807 return parser.emitError(parser.getCurrentLocation(),
3808 "expected `]` after RTTI info attribute");
3810 if (parseCheckedCatcherRegion().failed())
3811 return mlir::failure();
3814 if (parser.parseOptionalKeyword(
"unwind").succeeded()) {
3816 return parser.emitError(parser.getCurrentLocation(),
3817 "unwind can't be used with catch all");
3819 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
3820 if (parseCheckedCatcherRegion().failed())
3821 return mlir::failure();
3824 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
3825 return mlir::success();
3833cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
3834 Operation *op = symbolTable.lookupNearestSymbolFrom(*
this, getTypeSymAttr());
3835 if (!isa_and_nonnull<GlobalOp>(op))
3836 return emitOpError(
"'")
3837 << getTypeSym() <<
"' does not reference a valid cir.global";
3845#define GET_OP_CLASSES
3846#include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op, cir::FuncOp function)
static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src, mlir::Type resultTy)
static bool isBoolNot(cir::UnaryOp op)
static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser, mlir::OperationState &result, bool hasDestinationBlocks=false)
static bool isIntOrBoolCast(cir::CastOp op)
static void printConstant(OpAsmPrinter &p, Attribute value)
static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser, mlir::Region ®ion)
ParseResult parseInlineKindAttr(OpAsmParser &parser, cir::InlineKindAttr &inlineKindAttr)
void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr)
void printVisibilityAttr(OpAsmPrinter &printer, cir::VisibilityAttr &visibility)
static ParseResult parseSwitchFlatOpCases(OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues, SmallVectorImpl< Block * > &caseDestinations, SmallVectorImpl< llvm::SmallVector< OpAsmParser::UnresolvedOperand > > &caseOperands, SmallVectorImpl< llvm::SmallVector< Type > > &caseOperandTypes)
<cases> ::= [ (case (, case )* )?
static LogicalResult verifyCallCommInSymbolUses(mlir::Operation *op, SymbolTableCollection &symbolTable)
static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region ®ion, SMLoc errLoc)
static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, Attribute &initialValueAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op, Type flagType, SuccessorRange succs, OperandRangeRange succOperands, const TypeRangeRange &succOperandsTypes)
static OpFoldResult foldUnaryBitOp(mlir::Attribute inputAttr, llvm::function_ref< llvm::APInt(const llvm::APInt &)> func, bool poisonZero=false)
static llvm::StringRef getLinkageAttrNameString()
Returns the name used for the linkage attribute.
static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue)
Parse an enum from the keyword, or default to the provided default value.
static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op, Type flagType, mlir::ArrayAttr caseValues, SuccessorRange caseDestinations, OperandRangeRange caseOperands, const TypeRangeRange &caseOperandTypes)
static mlir::ParseResult parseTryCallDestinations(mlir::OpAsmParser &parser, mlir::OperationState &result)
static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op, TypeAttr type, Attribute initAttr, mlir::Region &ctorRegion, mlir::Region &dtorRegion)
static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result)
Parse an enum from the keyword, return failure if the keyword is not found.
static Value tryFoldCastChain(cir::CastOp op)
void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility)
static void printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op, mlir::MutableArrayRef< mlir::Region > handlerRegions, mlir::ArrayAttr handlerTypes)
ParseResult parseIndirectBrOpSucessors(OpAsmParser &parser, Type &flagType, SmallVectorImpl< Block * > &succOperandBlocks, SmallVectorImpl< SmallVector< OpAsmParser::UnresolvedOperand > > &succOperands, SmallVectorImpl< SmallVector< Type > > &succOperandsTypes)
static bool omitRegionTerm(mlir::Region &r)
static void printCallCommon(mlir::Operation *op, mlir::FlatSymbolRefAttr calleeSym, mlir::Value indirectCallee, mlir::OpAsmPrinter &printer, bool isNothrow, cir::SideEffect sideEffect, mlir::Block *normalDest=nullptr, mlir::Block *unwindDest=nullptr)
static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer, cir::ScopeOp &op, mlir::Region ®ion)
static ParseResult parseConstantValue(OpAsmParser &parser, mlir::Attribute &valueAttr)
static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType, mlir::Attribute attrType)
static mlir::ParseResult parseTryHandlerRegions(mlir::OpAsmParser &parser, llvm::SmallVectorImpl< std::unique_ptr< mlir::Region > > &handlerRegions, mlir::ArrayAttr &handlerTypes)
#define REGISTER_ENUM_TYPE(Ty)
static int parseOptionalKeywordAlternative(AsmParser &parser, ArrayRef< llvm::StringRef > keywords)
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
llvm::function_ref< void( mlir::OpBuilder &, mlir::Location, mlir::OperationState &)> BuilderOpStateCallbackRef
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a an optional score condition
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__device__ __2f16 float c
void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc)
const internal::VariadicAllOfMatcher< Attr > attr
const AstTypeMatcher< RecordType > recordType
StringRef getName(const HeaderType T)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
const half4 dst(half4 Src0, half4 Src1)
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static bool memberFuncPtrCast()
static bool addressSpace()
static bool opCallCallConv()
static bool opScopeCleanupRegion()
static bool supportIFuncAttr()