Debian Codegraph @

clang/lib/CIR/Dialect/IR/CIRDialect.cpp

raw
1 //===- CIRDialect.cpp - MLIR CIR ops implementation -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CIR dialect and its operations.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/CIR/Dialect/IR/CIRDialect.h"
14
15 #include "clang/CIR/Dialect/IR/CIRAttrs.h"
16 #include "clang/CIR/Dialect/IR/CIROpsEnums.h"
17 #include "clang/CIR/Dialect/IR/CIRTypes.h"
18
19 #include "mlir/IR/Attributes.h"
20 #include "mlir/IR/DialectImplementation.h"
21 #include "mlir/Interfaces/ControlFlowInterfaces.h"
22 #include "mlir/Interfaces/FunctionImplementation.h"
23 #include "mlir/Support/LLVM.h"
24
25 #include "clang/CIR/Dialect/IR/CIROpsDialect.cpp.inc"
26 #include "clang/CIR/Dialect/IR/CIROpsEnums.cpp.inc"
27 #include "clang/CIR/MissingFeatures.h"
28 #include "llvm/ADT/SetOperations.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/TypeSwitch.h"
31 #include "llvm/Support/LogicalResult.h"
32
33 using namespace mlir;
34 using namespace cir;
35
36 //===----------------------------------------------------------------------===//
37 // CIR Dialect
38 //===----------------------------------------------------------------------===//
39 namespace {
40 struct CIROpAsmDialectInterface : public OpAsmDialectInterface {
41 using OpAsmDialectInterface::OpAsmDialectInterface;
42
43 AliasResult getAlias(Type type, raw_ostream &os) const final {
44 if (auto recordType = dyn_cast<cir::RecordType>(type)) {
45 StringAttr nameAttr = recordType.getName();
46 if (!nameAttr)
47 os << "rec_anon_" << recordType.getKindAsStr();
48 else
49 os << "rec_" << nameAttr.getValue();
50 return AliasResult::OverridableAlias;
51 }
52 if (auto intType = dyn_cast<cir::IntType>(type)) {
53 // We only provide alias for standard integer types (i.e. integer types
54 // whose width is a power of 2 and at least 8).
55 unsigned width = intType.getWidth();
56 if (width < 8 || !llvm::isPowerOf2_32(width))
57 return AliasResult::NoAlias;
58 os << intType.getAlias();
59 return AliasResult::OverridableAlias;
60 }
61 if (auto voidType = dyn_cast<cir::VoidType>(type)) {
62 os << voidType.getAlias();
63 return AliasResult::OverridableAlias;
64 }
65
66 return AliasResult::NoAlias;
67 }
68
69 AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
70 if (auto boolAttr = mlir::dyn_cast<cir::BoolAttr>(attr)) {
71 os << (boolAttr.getValue() ? "true" : "false");
72 return AliasResult::FinalAlias;
73 }
74 if (auto bitfield = mlir::dyn_cast<cir::BitfieldInfoAttr>(attr)) {
75 os << "bfi_" << bitfield.getName().str();
76 return AliasResult::FinalAlias;
77 }
78 if (auto dynCastInfoAttr = mlir::dyn_cast<cir::DynamicCastInfoAttr>(attr)) {
79 os << dynCastInfoAttr.getAlias();
80 return AliasResult::FinalAlias;
81 }
82 return AliasResult::NoAlias;
83 }
84 };
85 } // namespace
86
87 void cir::CIRDialect::initialize() {
88 registerTypes();
89 registerAttributes();
90 addOperations<
91 #define GET_OP_LIST
92 #include "clang/CIR/Dialect/IR/CIROps.cpp.inc"
93 >();
94 addInterfaces<CIROpAsmDialectInterface>();
95 }
96
97 Operation *cir::CIRDialect::materializeConstant(mlir::OpBuilder &builder,
98 mlir::Attribute value,
99 mlir::Type type,
100 mlir::Location loc) {
101 return cir::ConstantOp::create(builder, loc, type,
102 mlir::cast<mlir::TypedAttr>(value));
103 }
104
105 //===----------------------------------------------------------------------===//
106 // Helpers
107 //===----------------------------------------------------------------------===//
108
109 // Parses one of the keywords provided in the list `keywords` and returns the
110 // position of the parsed keyword in the list. If none of the keywords from the
111 // list is parsed, returns -1.
112 static int parseOptionalKeywordAlternative(AsmParser &parser,
113 ArrayRef<llvm::StringRef> keywords) {
114 for (auto en : llvm::enumerate(keywords)) {
115 if (succeeded(parser.parseOptionalKeyword(en.value())))
116 return en.index();
117 }
118 return -1;
119 }
120
121 namespace {
122 template <typename Ty> struct EnumTraits {};
123
124 #define REGISTER_ENUM_TYPE(Ty) \
125 template <> struct EnumTraits<cir::Ty> { \
126 static llvm::StringRef stringify(cir::Ty value) { \
127 return stringify##Ty(value); \
128 } \
129 static unsigned getMaxEnumVal() { return cir::getMaxEnumValFor##Ty(); } \
130 }
131
132 REGISTER_ENUM_TYPE(GlobalLinkageKind);
133 REGISTER_ENUM_TYPE(VisibilityKind);
134 REGISTER_ENUM_TYPE(SideEffect);
135 } // namespace
136
137 /// Parse an enum from the keyword, or default to the provided default value.
138 /// The return type is the enum type by default, unless overriden with the
139 /// second template argument.
140 template <typename EnumTy, typename RetTy = EnumTy>
141 static RetTy parseOptionalCIRKeyword(AsmParser &parser, EnumTy defaultValue) {
142 llvm::SmallVector<llvm::StringRef, 10> names;
143 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
144 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
145
146 int index = parseOptionalKeywordAlternative(parser, names);
147 if (index == -1)
148 return static_cast<RetTy>(defaultValue);
149 return static_cast<RetTy>(index);
150 }
151
152 /// Parse an enum from the keyword, return failure if the keyword is not found.
153 template <typename EnumTy, typename RetTy = EnumTy>
154 static ParseResult parseCIRKeyword(AsmParser &parser, RetTy &result) {
155 llvm::SmallVector<llvm::StringRef, 10> names;
156 for (unsigned i = 0, e = EnumTraits<EnumTy>::getMaxEnumVal(); i <= e; ++i)
157 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i)));
158
159 int index = parseOptionalKeywordAlternative(parser, names);
160 if (index == -1)
161 return failure();
162 result = static_cast<RetTy>(index);
163 return success();
164 }
165
166 // Check if a region's termination omission is valid and, if so, creates and
167 // inserts the omitted terminator into the region.
168 static LogicalResult ensureRegionTerm(OpAsmParser &parser, Region &region,
169 SMLoc errLoc) {
170 Location eLoc = parser.getEncodedSourceLoc(parser.getCurrentLocation());
171 OpBuilder builder(parser.getBuilder().getContext());
172
173 // Insert empty block in case the region is empty to ensure the terminator
174 // will be inserted
175 if (region.empty())
176 builder.createBlock(&region);
177
178 Block &block = region.back();
179 // Region is properly terminated: nothing to do.
180 if (!block.empty() && block.back().hasTrait<OpTrait::IsTerminator>())
181 return success();
182
183 // Check for invalid terminator omissions.
184 if (!region.hasOneBlock())
185 return parser.emitError(errLoc,
186 "multi-block region must not omit terminator");
187
188 // Terminator was omitted correctly: recreate it.
189 builder.setInsertionPointToEnd(&block);
190 cir::YieldOp::create(builder, eLoc);
191 return success();
192 }
193
194 // True if the region's terminator should be omitted.
195 static bool omitRegionTerm(mlir::Region &r) {
196 const auto singleNonEmptyBlock = r.hasOneBlock() && !r.back().empty();
197 const auto yieldsNothing = [&r]() {
198 auto y = dyn_cast<cir::YieldOp>(r.back().getTerminator());
199 return y && y.getArgs().empty();
200 };
201 return singleNonEmptyBlock && yieldsNothing();
202 }
203
204 void printVisibilityAttr(OpAsmPrinter &printer,
205 cir::VisibilityAttr &visibility) {
206 switch (visibility.getValue()) {
207 case cir::VisibilityKind::Hidden:
208 printer << "hidden";
209 break;
210 case cir::VisibilityKind::Protected:
211 printer << "protected";
212 break;
213 case cir::VisibilityKind::Default:
214 break;
215 }
216 }
217
218 void parseVisibilityAttr(OpAsmParser &parser, cir::VisibilityAttr &visibility) {
219 cir::VisibilityKind visibilityKind =
220 parseOptionalCIRKeyword(parser, cir::VisibilityKind::Default);
221 visibility = cir::VisibilityAttr::get(parser.getContext(), visibilityKind);
222 }
223
224 //===----------------------------------------------------------------------===//
225 // InlineKindAttr (FIXME: remove once FuncOp uses assembly format)
226 //===----------------------------------------------------------------------===//
227
228 ParseResult parseInlineKindAttr(OpAsmParser &parser,
229 cir::InlineKindAttr &inlineKindAttr) {
230 // Static list of possible inline kind keywords
231 static constexpr llvm::StringRef keywords[] = {"no_inline", "always_inline",
232 "inline_hint"};
233
234 // Parse the inline kind keyword (optional)
235 llvm::StringRef keyword;
236 if (parser.parseOptionalKeyword(&keyword, keywords).failed()) {
237 // Not an inline kind keyword, leave inlineKindAttr empty
238 return success();
239 }
240
241 // Parse the enum value from the keyword
242 auto inlineKindResult = ::cir::symbolizeEnum<::cir::InlineKind>(keyword);
243 if (!inlineKindResult) {
244 return parser.emitError(parser.getCurrentLocation(), "expected one of [")
245 << llvm::join(llvm::ArrayRef(keywords), ", ")
246 << "] for inlineKind, got: " << keyword;
247 }
248
249 inlineKindAttr =
250 ::cir::InlineKindAttr::get(parser.getContext(), *inlineKindResult);
251 return success();
252 }
253
254 void printInlineKindAttr(OpAsmPrinter &p, cir::InlineKindAttr inlineKindAttr) {
255 if (inlineKindAttr) {
256 p << " " << stringifyInlineKind(inlineKindAttr.getValue());
257 }
258 }
259 //===----------------------------------------------------------------------===//
260 // CIR Custom Parsers/Printers
261 //===----------------------------------------------------------------------===//
262
263 static mlir::ParseResult parseOmittedTerminatorRegion(mlir::OpAsmParser &parser,
264 mlir::Region &region) {
265 auto regionLoc = parser.getCurrentLocation();
266 if (parser.parseRegion(region))
267 return failure();
268 if (ensureRegionTerm(parser, region, regionLoc).failed())
269 return failure();
270 return success();
271 }
272
273 static void printOmittedTerminatorRegion(mlir::OpAsmPrinter &printer,
274 cir::ScopeOp &op,
275 mlir::Region &region) {
276 printer.printRegion(region,
277 /*printEntryBlockArgs=*/false,
278 /*printBlockTerminators=*/!omitRegionTerm(region));
279 }
280
281 //===----------------------------------------------------------------------===//
282 // AllocaOp
283 //===----------------------------------------------------------------------===//
284
285 void cir::AllocaOp::build(mlir::OpBuilder &odsBuilder,
286 mlir::OperationState &odsState, mlir::Type addr,
287 mlir::Type allocaType, llvm::StringRef name,
288 mlir::IntegerAttr alignment) {
289 odsState.addAttribute(getAllocaTypeAttrName(odsState.name),
290 mlir::TypeAttr::get(allocaType));
291 odsState.addAttribute(getNameAttrName(odsState.name),
292 odsBuilder.getStringAttr(name));
293 if (alignment) {
294 odsState.addAttribute(getAlignmentAttrName(odsState.name), alignment);
295 }
296 odsState.addTypes(addr);
297 }
298
299 //===----------------------------------------------------------------------===//
300 // BreakOp
301 //===----------------------------------------------------------------------===//
302
303 LogicalResult cir::BreakOp::verify() {
304 assert(!cir::MissingFeatures::switchOp());
305 if (!getOperation()->getParentOfType<LoopOpInterface>() &&
306 !getOperation()->getParentOfType<SwitchOp>())
307 return emitOpError("must be within a loop");
308 return success();
309 }
310
311 //===----------------------------------------------------------------------===//
312 // ConditionOp
313 //===----------------------------------------------------------------------===//
314
315 //===----------------------------------
316 // BranchOpTerminatorInterface Methods
317 //===----------------------------------
318
319 void cir::ConditionOp::getSuccessorRegions(
320 ArrayRef<Attribute> operands, SmallVectorImpl<RegionSuccessor> &regions) {
321 // TODO(cir): The condition value may be folded to a constant, narrowing
322 // down its list of possible successors.
323
324 // Parent is a loop: condition may branch to the body or to the parent op.
325 if (auto loopOp = dyn_cast<LoopOpInterface>(getOperation()->getParentOp())) {
326 regions.emplace_back(&loopOp.getBody(), loopOp.getBody().getArguments());
327 regions.emplace_back(getOperation(), loopOp->getResults());
328 }
329
330 // Parent is an await: condition may branch to resume or suspend regions.
331 auto await = cast<AwaitOp>(getOperation()->getParentOp());
332 regions.emplace_back(&await.getResume(), await.getResume().getArguments());
333 regions.emplace_back(&await.getSuspend(), await.getSuspend().getArguments());
334 }
335
336 MutableOperandRange
337 cir::ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
338 // No values are yielded to the successor region.
339 return MutableOperandRange(getOperation(), 0, 0);
340 }
341
342 LogicalResult cir::ConditionOp::verify() {
343 if (!isa<LoopOpInterface, AwaitOp>(getOperation()->getParentOp()))
344 return emitOpError("condition must be within a conditional region");
345 return success();
346 }
347
348 //===----------------------------------------------------------------------===//
349 // ConstantOp
350 //===----------------------------------------------------------------------===//
351
352 static LogicalResult checkConstantTypes(mlir::Operation *op, mlir::Type opType,
353 mlir::Attribute attrType) {
354 if (isa<cir::ConstPtrAttr>(attrType)) {
355 if (!mlir::isa<cir::PointerType>(opType))
356 return op->emitOpError(
357 "pointer constant initializing a non-pointer type");
358 return success();
359 }
360
361 if (isa<cir::DataMemberAttr>(attrType)) {
362 // More detailed type verifications are already done in
363 // DataMemberAttr::verify. Don't need to repeat here.
364 return success();
365 }
366
367 if (isa<cir::ZeroAttr>(attrType)) {
368 if (isa<cir::RecordType, cir::ArrayType, cir::VectorType, cir::ComplexType>(
369 opType))
370 return success();
371 return op->emitOpError(
372 "zero expects struct, array, vector, or complex type");
373 }
374
375 if (mlir::isa<cir::UndefAttr>(attrType)) {
376 if (!mlir::isa<cir::VoidType>(opType))
377 return success();
378 return op->emitOpError("undef expects non-void type");
379 }
380
381 if (mlir::isa<cir::BoolAttr>(attrType)) {
382 if (!mlir::isa<cir::BoolType>(opType))
383 return op->emitOpError("result type (")
384 << opType << ") must be '!cir.bool' for '" << attrType << "'";
385 return success();
386 }
387
388 if (mlir::isa<cir::IntAttr, cir::FPAttr>(attrType)) {
389 auto at = cast<TypedAttr>(attrType);
390 if (at.getType() != opType) {
391 return op->emitOpError("result type (")
392 << opType << ") does not match value type (" << at.getType()
393 << ")";
394 }
395 return success();
396 }
397
398 if (mlir::isa<cir::ConstArrayAttr, cir::ConstVectorAttr,
399 cir::ConstComplexAttr, cir::ConstRecordAttr,
400 cir::GlobalViewAttr, cir::PoisonAttr, cir::TypeInfoAttr,
401 cir::VTableAttr>(attrType))
402 return success();
403
404 assert(isa<TypedAttr>(attrType) && "What else could we be looking at here?");
405 return op->emitOpError("global with type ")
406 << cast<TypedAttr>(attrType).getType() << " not yet supported";
407 }
408
409 LogicalResult cir::ConstantOp::verify() {
410 // ODS already generates checks to make sure the result type is valid. We just
411 // need to additionally check that the value's attribute type is consistent
412 // with the result type.
413 return checkConstantTypes(getOperation(), getType(), getValue());
414 }
415
416 OpFoldResult cir::ConstantOp::fold(FoldAdaptor /*adaptor*/) {
417 return getValue();
418 }
419
420 //===----------------------------------------------------------------------===//
421 // ContinueOp
422 //===----------------------------------------------------------------------===//
423
424 LogicalResult cir::ContinueOp::verify() {
425 if (!getOperation()->getParentOfType<LoopOpInterface>())
426 return emitOpError("must be within a loop");
427 return success();
428 }
429
430 //===----------------------------------------------------------------------===//
431 // CastOp
432 //===----------------------------------------------------------------------===//
433
434 LogicalResult cir::CastOp::verify() {
435 mlir::Type resType = getType();
436 mlir::Type srcType = getSrc().getType();
437
438 // Verify address space casts for pointer types. given that
439 // casts for within a different address space are illegal.
440 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
441 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
442 if (srcPtrTy && resPtrTy && (getKind() != cir::CastKind::address_space))
443 if (srcPtrTy.getAddrSpace() != resPtrTy.getAddrSpace()) {
444 return emitOpError() << "result type address space does not match the "
445 "address space of the operand";
446 }
447
448 if (mlir::isa<cir::VectorType>(srcType) &&
449 mlir::isa<cir::VectorType>(resType)) {
450 // Use the element type of the vector to verify the cast kind. (Except for
451 // bitcast, see below.)
452 srcType = mlir::dyn_cast<cir::VectorType>(srcType).getElementType();
453 resType = mlir::dyn_cast<cir::VectorType>(resType).getElementType();
454 }
455
456 switch (getKind()) {
457 case cir::CastKind::int_to_bool: {
458 if (!mlir::isa<cir::BoolType>(resType))
459 return emitOpError() << "requires !cir.bool type for result";
460 if (!mlir::isa<cir::IntType>(srcType))
461 return emitOpError() << "requires !cir.int type for source";
462 return success();
463 }
464 case cir::CastKind::ptr_to_bool: {
465 if (!mlir::isa<cir::BoolType>(resType))
466 return emitOpError() << "requires !cir.bool type for result";
467 if (!mlir::isa<cir::PointerType>(srcType))
468 return emitOpError() << "requires !cir.ptr type for source";
469 return success();
470 }
471 case cir::CastKind::integral: {
472 if (!mlir::isa<cir::IntType>(resType))
473 return emitOpError() << "requires !cir.int type for result";
474 if (!mlir::isa<cir::IntType>(srcType))
475 return emitOpError() << "requires !cir.int type for source";
476 return success();
477 }
478 case cir::CastKind::array_to_ptrdecay: {
479 const auto arrayPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
480 const auto flatPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
481 if (!arrayPtrTy || !flatPtrTy)
482 return emitOpError() << "requires !cir.ptr type for source and result";
483
484 // TODO(CIR): Make sure the AddrSpace of both types are equals
485 return success();
486 }
487 case cir::CastKind::bitcast: {
488 // Handle the pointer types first.
489 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
490 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
491
492 if (srcPtrTy && resPtrTy) {
493 return success();
494 }
495
496 return success();
497 }
498 case cir::CastKind::floating: {
499 if (!mlir::isa<cir::FPTypeInterface>(srcType) ||
500 !mlir::isa<cir::FPTypeInterface>(resType))
501 return emitOpError() << "requires !cir.float type for source and result";
502 return success();
503 }
504 case cir::CastKind::float_to_int: {
505 if (!mlir::isa<cir::FPTypeInterface>(srcType))
506 return emitOpError() << "requires !cir.float type for source";
507 if (!mlir::dyn_cast<cir::IntType>(resType))
508 return emitOpError() << "requires !cir.int type for result";
509 return success();
510 }
511 case cir::CastKind::int_to_ptr: {
512 if (!mlir::dyn_cast<cir::IntType>(srcType))
513 return emitOpError() << "requires !cir.int type for source";
514 if (!mlir::dyn_cast<cir::PointerType>(resType))
515 return emitOpError() << "requires !cir.ptr type for result";
516 return success();
517 }
518 case cir::CastKind::ptr_to_int: {
519 if (!mlir::dyn_cast<cir::PointerType>(srcType))
520 return emitOpError() << "requires !cir.ptr type for source";
521 if (!mlir::dyn_cast<cir::IntType>(resType))
522 return emitOpError() << "requires !cir.int type for result";
523 return success();
524 }
525 case cir::CastKind::float_to_bool: {
526 if (!mlir::isa<cir::FPTypeInterface>(srcType))
527 return emitOpError() << "requires !cir.float type for source";
528 if (!mlir::isa<cir::BoolType>(resType))
529 return emitOpError() << "requires !cir.bool type for result";
530 return success();
531 }
532 case cir::CastKind::bool_to_int: {
533 if (!mlir::isa<cir::BoolType>(srcType))
534 return emitOpError() << "requires !cir.bool type for source";
535 if (!mlir::isa<cir::IntType>(resType))
536 return emitOpError() << "requires !cir.int type for result";
537 return success();
538 }
539 case cir::CastKind::int_to_float: {
540 if (!mlir::isa<cir::IntType>(srcType))
541 return emitOpError() << "requires !cir.int type for source";
542 if (!mlir::isa<cir::FPTypeInterface>(resType))
543 return emitOpError() << "requires !cir.float type for result";
544 return success();
545 }
546 case cir::CastKind::bool_to_float: {
547 if (!mlir::isa<cir::BoolType>(srcType))
548 return emitOpError() << "requires !cir.bool type for source";
549 if (!mlir::isa<cir::FPTypeInterface>(resType))
550 return emitOpError() << "requires !cir.float type for result";
551 return success();
552 }
553 case cir::CastKind::address_space: {
554 auto srcPtrTy = mlir::dyn_cast<cir::PointerType>(srcType);
555 auto resPtrTy = mlir::dyn_cast<cir::PointerType>(resType);
556 if (!srcPtrTy || !resPtrTy)
557 return emitOpError() << "requires !cir.ptr type for source and result";
558 if (srcPtrTy.getPointee() != resPtrTy.getPointee())
559 return emitOpError() << "requires two types differ in addrspace only";
560 return success();
561 }
562 case cir::CastKind::float_to_complex: {
563 if (!mlir::isa<cir::FPTypeInterface>(srcType))
564 return emitOpError() << "requires !cir.float type for source";
565 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
566 if (!resComplexTy)
567 return emitOpError() << "requires !cir.complex type for result";
568 if (srcType != resComplexTy.getElementType())
569 return emitOpError() << "requires source type match result element type";
570 return success();
571 }
572 case cir::CastKind::int_to_complex: {
573 if (!mlir::isa<cir::IntType>(srcType))
574 return emitOpError() << "requires !cir.int type for source";
575 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
576 if (!resComplexTy)
577 return emitOpError() << "requires !cir.complex type for result";
578 if (srcType != resComplexTy.getElementType())
579 return emitOpError() << "requires source type match result element type";
580 return success();
581 }
582 case cir::CastKind::float_complex_to_real: {
583 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
584 if (!srcComplexTy)
585 return emitOpError() << "requires !cir.complex type for source";
586 if (!mlir::isa<cir::FPTypeInterface>(resType))
587 return emitOpError() << "requires !cir.float type for result";
588 if (srcComplexTy.getElementType() != resType)
589 return emitOpError() << "requires source element type match result type";
590 return success();
591 }
592 case cir::CastKind::int_complex_to_real: {
593 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
594 if (!srcComplexTy)
595 return emitOpError() << "requires !cir.complex type for source";
596 if (!mlir::isa<cir::IntType>(resType))
597 return emitOpError() << "requires !cir.int type for result";
598 if (srcComplexTy.getElementType() != resType)
599 return emitOpError() << "requires source element type match result type";
600 return success();
601 }
602 case cir::CastKind::float_complex_to_bool: {
603 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
604 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
605 return emitOpError()
606 << "requires floating point !cir.complex type for source";
607 if (!mlir::isa<cir::BoolType>(resType))
608 return emitOpError() << "requires !cir.bool type for result";
609 return success();
610 }
611 case cir::CastKind::int_complex_to_bool: {
612 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
613 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
614 return emitOpError()
615 << "requires floating point !cir.complex type for source";
616 if (!mlir::isa<cir::BoolType>(resType))
617 return emitOpError() << "requires !cir.bool type for result";
618 return success();
619 }
620 case cir::CastKind::float_complex: {
621 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
622 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
623 return emitOpError()
624 << "requires floating point !cir.complex type for source";
625 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
626 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
627 return emitOpError()
628 << "requires floating point !cir.complex type for result";
629 return success();
630 }
631 case cir::CastKind::float_complex_to_int_complex: {
632 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
633 if (!srcComplexTy || !srcComplexTy.isFloatingPointComplex())
634 return emitOpError()
635 << "requires floating point !cir.complex type for source";
636 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
637 if (!resComplexTy || !resComplexTy.isIntegerComplex())
638 return emitOpError() << "requires integer !cir.complex type for result";
639 return success();
640 }
641 case cir::CastKind::int_complex: {
642 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
643 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
644 return emitOpError() << "requires integer !cir.complex type for source";
645 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
646 if (!resComplexTy || !resComplexTy.isIntegerComplex())
647 return emitOpError() << "requires integer !cir.complex type for result";
648 return success();
649 }
650 case cir::CastKind::int_complex_to_float_complex: {
651 auto srcComplexTy = mlir::dyn_cast<cir::ComplexType>(srcType);
652 if (!srcComplexTy || !srcComplexTy.isIntegerComplex())
653 return emitOpError() << "requires integer !cir.complex type for source";
654 auto resComplexTy = mlir::dyn_cast<cir::ComplexType>(resType);
655 if (!resComplexTy || !resComplexTy.isFloatingPointComplex())
656 return emitOpError()
657 << "requires floating point !cir.complex type for result";
658 return success();
659 }
660 default:
661 llvm_unreachable("Unknown CastOp kind?");
662 }
663 }
664
665 static bool isIntOrBoolCast(cir::CastOp op) {
666 auto kind = op.getKind();
667 return kind == cir::CastKind::bool_to_int ||
668 kind == cir::CastKind::int_to_bool || kind == cir::CastKind::integral;
669 }
670
671 static Value tryFoldCastChain(cir::CastOp op) {
672 cir::CastOp head = op, tail = op;
673
674 while (op) {
675 if (!isIntOrBoolCast(op))
676 break;
677 head = op;
678 op = head.getSrc().getDefiningOp<cir::CastOp>();
679 }
680
681 if (head == tail)
682 return {};
683
684 // if bool_to_int -> ... -> int_to_bool: take the bool
685 // as we had it was before all casts
686 if (head.getKind() == cir::CastKind::bool_to_int &&
687 tail.getKind() == cir::CastKind::int_to_bool)
688 return head.getSrc();
689
690 // if int_to_bool -> ... -> int_to_bool: take the result
691 // of the first one, as no other casts (and ext casts as well)
692 // don't change the first result
693 if (head.getKind() == cir::CastKind::int_to_bool &&
694 tail.getKind() == cir::CastKind::int_to_bool)
695 return head.getResult();
696
697 return {};
698 }
699
700 OpFoldResult cir::CastOp::fold(FoldAdaptor adaptor) {
701 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getSrc())) {
702 // Propagate poison value
703 return cir::PoisonAttr::get(getContext(), getType());
704 }
705
706 if (getSrc().getType() == getType()) {
707 switch (getKind()) {
708 case cir::CastKind::integral: {
709 llvm::SmallVector<mlir::OpFoldResult, 1> foldResults;
710 auto foldOrder = getSrc().getDefiningOp()->fold(foldResults);
711 if (foldOrder.succeeded() && mlir::isa<mlir::Attribute>(foldResults[0]))
712 return mlir::cast<mlir::Attribute>(foldResults[0]);
713 return {};
714 }
715 case cir::CastKind::bitcast:
716 case cir::CastKind::address_space:
717 case cir::CastKind::float_complex:
718 case cir::CastKind::int_complex: {
719 return getSrc();
720 }
721 default:
722 return {};
723 }
724 }
725
726 // Handle cases where a chain of casts cancel out.
727 Value result = tryFoldCastChain(*this);
728 if (result)
729 return result;
730
731 // Handle simple constant casts.
732 if (auto srcConst = getSrc().getDefiningOp<cir::ConstantOp>()) {
733 switch (getKind()) {
734 case cir::CastKind::integral: {
735 mlir::Type srcTy = getSrc().getType();
736 // Don't try to fold vector casts for now.
737 assert(mlir::isa<cir::VectorType>(srcTy) ==
738 mlir::isa<cir::VectorType>(getType()));
739 if (mlir::isa<cir::VectorType>(srcTy))
740 break;
741
742 auto srcIntTy = mlir::cast<cir::IntType>(srcTy);
743 auto dstIntTy = mlir::cast<cir::IntType>(getType());
744 APInt newVal =
745 srcIntTy.isSigned()
746 ? srcConst.getIntValue().sextOrTrunc(dstIntTy.getWidth())
747 : srcConst.getIntValue().zextOrTrunc(dstIntTy.getWidth());
748 return cir::IntAttr::get(dstIntTy, newVal);
749 }
750 default:
751 break;
752 }
753 }
754 return {};
755 }
756
757 //===----------------------------------------------------------------------===//
758 // CallOp
759 //===----------------------------------------------------------------------===//
760
761 mlir::OperandRange cir::CallOp::getArgOperands() {
762 if (isIndirect())
763 return getArgs().drop_front(1);
764 return getArgs();
765 }
766
767 mlir::MutableOperandRange cir::CallOp::getArgOperandsMutable() {
768 mlir::MutableOperandRange args = getArgsMutable();
769 if (isIndirect())
770 return args.slice(1, args.size() - 1);
771 return args;
772 }
773
774 mlir::Value cir::CallOp::getIndirectCall() {
775 assert(isIndirect());
776 return getOperand(0);
777 }
778
779 /// Return the operand at index 'i'.
780 Value cir::CallOp::getArgOperand(unsigned i) {
781 if (isIndirect())
782 ++i;
783 return getOperand(i);
784 }
785
786 /// Return the number of operands.
787 unsigned cir::CallOp::getNumArgOperands() {
788 if (isIndirect())
789 return this->getOperation()->getNumOperands() - 1;
790 return this->getOperation()->getNumOperands();
791 }
792
793 static mlir::ParseResult
794 parseTryCallDestinations(mlir::OpAsmParser &parser,
795 mlir::OperationState &result) {
796 mlir::Block *normalDestSuccessor;
797 if (parser.parseSuccessor(normalDestSuccessor))
798 return mlir::failure();
799
800 if (parser.parseComma())
801 return mlir::failure();
802
803 mlir::Block *unwindDestSuccessor;
804 if (parser.parseSuccessor(unwindDestSuccessor))
805 return mlir::failure();
806
807 result.addSuccessors(normalDestSuccessor);
808 result.addSuccessors(unwindDestSuccessor);
809 return mlir::success();
810 }
811
812 static mlir::ParseResult parseCallCommon(mlir::OpAsmParser &parser,
813 mlir::OperationState &result,
814 bool hasDestinationBlocks = false) {
815 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand, 4> ops;
816 llvm::SMLoc opsLoc;
817 mlir::FlatSymbolRefAttr calleeAttr;
818 llvm::ArrayRef<mlir::Type> allResultTypes;
819
820 // If we cannot parse a string callee, it means this is an indirect call.
821 if (!parser
822 .parseOptionalAttribute(calleeAttr, CIRDialect::getCalleeAttrName(),
823 result.attributes)
824 .has_value()) {
825 OpAsmParser::UnresolvedOperand indirectVal;
826 // Do not resolve right now, since we need to figure out the type
827 if (parser.parseOperand(indirectVal).failed())
828 return failure();
829 ops.push_back(indirectVal);
830 }
831
832 if (parser.parseLParen())
833 return mlir::failure();
834
835 opsLoc = parser.getCurrentLocation();
836 if (parser.parseOperandList(ops))
837 return mlir::failure();
838 if (parser.parseRParen())
839 return mlir::failure();
840
841 if (hasDestinationBlocks &&
842 parseTryCallDestinations(parser, result).failed()) {
843 return ::mlir::failure();
844 }
845
846 if (parser.parseOptionalKeyword("nothrow").succeeded())
847 result.addAttribute(CIRDialect::getNoThrowAttrName(),
848 mlir::UnitAttr::get(parser.getContext()));
849
850 if (parser.parseOptionalKeyword("side_effect").succeeded()) {
851 if (parser.parseLParen().failed())
852 return failure();
853 cir::SideEffect sideEffect;
854 if (parseCIRKeyword<cir::SideEffect>(parser, sideEffect).failed())
855 return failure();
856 if (parser.parseRParen().failed())
857 return failure();
858 auto attr = cir::SideEffectAttr::get(parser.getContext(), sideEffect);
859 result.addAttribute(CIRDialect::getSideEffectAttrName(), attr);
860 }
861
862 if (parser.parseOptionalAttrDict(result.attributes))
863 return ::mlir::failure();
864
865 if (parser.parseColon())
866 return ::mlir::failure();
867
868 mlir::FunctionType opsFnTy;
869 if (parser.parseType(opsFnTy))
870 return mlir::failure();
871
872 allResultTypes = opsFnTy.getResults();
873 result.addTypes(allResultTypes);
874
875 if (parser.resolveOperands(ops, opsFnTy.getInputs(), opsLoc, result.operands))
876 return mlir::failure();
877
878 return mlir::success();
879 }
880
881 static void printCallCommon(mlir::Operation *op,
882 mlir::FlatSymbolRefAttr calleeSym,
883 mlir::Value indirectCallee,
884 mlir::OpAsmPrinter &printer, bool isNothrow,
885 cir::SideEffect sideEffect,
886 mlir::Block *normalDest = nullptr,
887 mlir::Block *unwindDest = nullptr) {
888 printer << ' ';
889
890 auto callLikeOp = mlir::cast<cir::CIRCallOpInterface>(op);
891 auto ops = callLikeOp.getArgOperands();
892
893 if (calleeSym) {
894 // Direct calls
895 printer.printAttributeWithoutType(calleeSym);
896 } else {
897 // Indirect calls
898 assert(indirectCallee);
899 printer << indirectCallee;
900 }
901
902 printer << "(" << ops << ")";
903
904 if (normalDest) {
905 assert(unwindDest && "expected two successors");
906 auto tryCall = cast<cir::TryCallOp>(op);
907 printer << ' ' << tryCall.getNormalDest();
908 printer << ",";
909 printer << ' ';
910 printer << tryCall.getUnwindDest();
911 }
912
913 if (isNothrow)
914 printer << " nothrow";
915
916 if (sideEffect != cir::SideEffect::All) {
917 printer << " side_effect(";
918 printer << stringifySideEffect(sideEffect);
919 printer << ")";
920 }
921
922 llvm::SmallVector<::llvm::StringRef> elidedAttrs = {
923 CIRDialect::getCalleeAttrName(), CIRDialect::getNoThrowAttrName(),
924 CIRDialect::getSideEffectAttrName(),
925 CIRDialect::getOperandSegmentSizesAttrName()};
926 printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
927 printer << " : ";
928 printer.printFunctionalType(op->getOperands().getTypes(),
929 op->getResultTypes());
930 }
931
932 mlir::ParseResult cir::CallOp::parse(mlir::OpAsmParser &parser,
933 mlir::OperationState &result) {
934 return parseCallCommon(parser, result);
935 }
936
937 void cir::CallOp::print(mlir::OpAsmPrinter &p) {
938 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
939 cir::SideEffect sideEffect = getSideEffect();
940 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
941 sideEffect);
942 }
943
944 static LogicalResult
945 verifyCallCommInSymbolUses(mlir::Operation *op,
946 SymbolTableCollection &symbolTable) {
947 auto fnAttr =
948 op->getAttrOfType<FlatSymbolRefAttr>(CIRDialect::getCalleeAttrName());
949 if (!fnAttr) {
950 // This is an indirect call, thus we don't have to check the symbol uses.
951 return mlir::success();
952 }
953
954 auto fn = symbolTable.lookupNearestSymbolFrom<cir::FuncOp>(op, fnAttr);
955 if (!fn)
956 return op->emitOpError() << "'" << fnAttr.getValue()
957 << "' does not reference a valid function";
958
959 auto callIf = dyn_cast<cir::CIRCallOpInterface>(op);
960 assert(callIf && "expected CIR call interface to be always available");
961
962 // Verify that the operand and result types match the callee. Note that
963 // argument-checking is disabled for functions without a prototype.
964 auto fnType = fn.getFunctionType();
965 if (!fn.getNoProto()) {
966 unsigned numCallOperands = callIf.getNumArgOperands();
967 unsigned numFnOpOperands = fnType.getNumInputs();
968
969 if (!fnType.isVarArg() && numCallOperands != numFnOpOperands)
970 return op->emitOpError("incorrect number of operands for callee");
971 if (fnType.isVarArg() && numCallOperands < numFnOpOperands)
972 return op->emitOpError("too few operands for callee");
973
974 for (unsigned i = 0, e = numFnOpOperands; i != e; ++i)
975 if (callIf.getArgOperand(i).getType() != fnType.getInput(i))
976 return op->emitOpError("operand type mismatch: expected operand type ")
977 << fnType.getInput(i) << ", but provided "
978 << op->getOperand(i).getType() << " for operand number " << i;
979 }
980
981 assert(!cir::MissingFeatures::opCallCallConv());
982
983 // Void function must not return any results.
984 if (fnType.hasVoidReturn() && op->getNumResults() != 0)
985 return op->emitOpError("callee returns void but call has results");
986
987 // Non-void function calls must return exactly one result.
988 if (!fnType.hasVoidReturn() && op->getNumResults() != 1)
989 return op->emitOpError("incorrect number of results for callee");
990
991 // Parent function and return value types must match.
992 if (!fnType.hasVoidReturn() &&
993 op->getResultTypes().front() != fnType.getReturnType()) {
994 return op->emitOpError("result type mismatch: expected ")
995 << fnType.getReturnType() << ", but provided "
996 << op->getResult(0).getType();
997 }
998
999 return mlir::success();
1000 }
1001
1002 LogicalResult
1003 cir::CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1004 return verifyCallCommInSymbolUses(*this, symbolTable);
1005 }
1006
1007 //===----------------------------------------------------------------------===//
1008 // TryCallOp
1009 //===----------------------------------------------------------------------===//
1010
1011 mlir::OperandRange cir::TryCallOp::getArgOperands() {
1012 if (isIndirect())
1013 return getArgs().drop_front(1);
1014 return getArgs();
1015 }
1016
1017 mlir::MutableOperandRange cir::TryCallOp::getArgOperandsMutable() {
1018 mlir::MutableOperandRange args = getArgsMutable();
1019 if (isIndirect())
1020 return args.slice(1, args.size() - 1);
1021 return args;
1022 }
1023
1024 mlir::Value cir::TryCallOp::getIndirectCall() {
1025 assert(isIndirect());
1026 return getOperand(0);
1027 }
1028
1029 /// Return the operand at index 'i'.
1030 Value cir::TryCallOp::getArgOperand(unsigned i) {
1031 if (isIndirect())
1032 ++i;
1033 return getOperand(i);
1034 }
1035
1036 /// Return the number of operands.
1037 unsigned cir::TryCallOp::getNumArgOperands() {
1038 if (isIndirect())
1039 return this->getOperation()->getNumOperands() - 1;
1040 return this->getOperation()->getNumOperands();
1041 }
1042
1043 LogicalResult
1044 cir::TryCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1045 return verifyCallCommInSymbolUses(*this, symbolTable);
1046 }
1047
1048 mlir::ParseResult cir::TryCallOp::parse(mlir::OpAsmParser &parser,
1049 mlir::OperationState &result) {
1050 return parseCallCommon(parser, result, /*hasDestinationBlocks=*/true);
1051 }
1052
1053 void cir::TryCallOp::print(::mlir::OpAsmPrinter &p) {
1054 mlir::Value indirectCallee = isIndirect() ? getIndirectCall() : nullptr;
1055 cir::SideEffect sideEffect = getSideEffect();
1056 printCallCommon(*this, getCalleeAttr(), indirectCallee, p, getNothrow(),
1057 sideEffect, getNormalDest(), getUnwindDest());
1058 }
1059
1060 //===----------------------------------------------------------------------===//
1061 // ReturnOp
1062 //===----------------------------------------------------------------------===//
1063
1064 static mlir::LogicalResult checkReturnAndFunction(cir::ReturnOp op,
1065 cir::FuncOp function) {
1066 // ReturnOps currently only have a single optional operand.
1067 if (op.getNumOperands() > 1)
1068 return op.emitOpError() << "expects at most 1 return operand";
1069
1070 // Ensure returned type matches the function signature.
1071 auto expectedTy = function.getFunctionType().getReturnType();
1072 auto actualTy =
1073 (op.getNumOperands() == 0 ? cir::VoidType::get(op.getContext())
1074 : op.getOperand(0).getType());
1075 if (actualTy != expectedTy)
1076 return op.emitOpError() << "returns " << actualTy
1077 << " but enclosing function returns " << expectedTy;
1078
1079 return mlir::success();
1080 }
1081
1082 mlir::LogicalResult cir::ReturnOp::verify() {
1083 // Returns can be present in multiple different scopes, get the
1084 // wrapping function and start from there.
1085 auto *fnOp = getOperation()->getParentOp();
1086 while (!isa<cir::FuncOp>(fnOp))
1087 fnOp = fnOp->getParentOp();
1088
1089 // Make sure return types match function return type.
1090 if (checkReturnAndFunction(*this, cast<cir::FuncOp>(fnOp)).failed())
1091 return failure();
1092
1093 return success();
1094 }
1095
1096 //===----------------------------------------------------------------------===//
1097 // IfOp
1098 //===----------------------------------------------------------------------===//
1099
1100 ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
1101 // create the regions for 'then'.
1102 result.regions.reserve(2);
1103 Region *thenRegion = result.addRegion();
1104 Region *elseRegion = result.addRegion();
1105
1106 mlir::Builder &builder = parser.getBuilder();
1107 OpAsmParser::UnresolvedOperand cond;
1108 Type boolType = cir::BoolType::get(builder.getContext());
1109
1110 if (parser.parseOperand(cond) ||
1111 parser.resolveOperand(cond, boolType, result.operands))
1112 return failure();
1113
1114 // Parse 'then' region.
1115 mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
1116 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
1117 return failure();
1118
1119 if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
1120 return failure();
1121
1122 // If we find an 'else' keyword, parse the 'else' region.
1123 if (!parser.parseOptionalKeyword("else")) {
1124 mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
1125 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
1126 return failure();
1127 if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
1128 return failure();
1129 }
1130
1131 // Parse the optional attribute list.
1132 if (parser.parseOptionalAttrDict(result.attributes))
1133 return failure();
1134 return success();
1135 }
1136
1137 void cir::IfOp::print(OpAsmPrinter &p) {
1138 p << " " << getCondition() << " ";
1139 mlir::Region &thenRegion = this->getThenRegion();
1140 p.printRegion(thenRegion,
1141 /*printEntryBlockArgs=*/false,
1142 /*printBlockTerminators=*/!omitRegionTerm(thenRegion));
1143
1144 // Print the 'else' regions if it exists and has a block.
1145 mlir::Region &elseRegion = this->getElseRegion();
1146 if (!elseRegion.empty()) {
1147 p << " else ";
1148 p.printRegion(elseRegion,
1149 /*printEntryBlockArgs=*/false,
1150 /*printBlockTerminators=*/!omitRegionTerm(elseRegion));
1151 }
1152
1153 p.printOptionalAttrDict(getOperation()->getAttrs());
1154 }
1155
1156 /// Default callback for IfOp builders.
1157 void cir::buildTerminatedBody(OpBuilder &builder, Location loc) {
1158 // add cir.yield to end of the block
1159 cir::YieldOp::create(builder, loc);
1160 }
1161
1162 /// Given the region at `index`, or the parent operation if `index` is None,
1163 /// return the successor regions. These are the regions that may be selected
1164 /// during the flow of control. `operands` is a set of optional attributes that
1165 /// correspond to a constant value for each operand, or null if that operand is
1166 /// not a constant.
1167 void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
1168 SmallVectorImpl<RegionSuccessor> &regions) {
1169 // The `then` and the `else` region branch back to the parent operation.
1170 if (!point.isParent()) {
1171 regions.push_back(
1172 RegionSuccessor(getOperation(), getOperation()->getResults()));
1173 return;
1174 }
1175
1176 // Don't consider the else region if it is empty.
1177 Region *elseRegion = &this->getElseRegion();
1178 if (elseRegion->empty())
1179 elseRegion = nullptr;
1180
1181 // If the condition isn't constant, both regions may be executed.
1182 regions.push_back(RegionSuccessor(&getThenRegion()));
1183 // If the else region does not exist, it is not a viable successor.
1184 if (elseRegion)
1185 regions.push_back(RegionSuccessor(elseRegion));
1186
1187 return;
1188 }
1189
1190 void cir::IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
1191 bool withElseRegion, BuilderCallbackRef thenBuilder,
1192 BuilderCallbackRef elseBuilder) {
1193 assert(thenBuilder && "the builder callback for 'then' must be present");
1194 result.addOperands(cond);
1195
1196 OpBuilder::InsertionGuard guard(builder);
1197 Region *thenRegion = result.addRegion();
1198 builder.createBlock(thenRegion);
1199 thenBuilder(builder, result.location);
1200
1201 Region *elseRegion = result.addRegion();
1202 if (!withElseRegion)
1203 return;
1204
1205 builder.createBlock(elseRegion);
1206 elseBuilder(builder, result.location);
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // ScopeOp
1211 //===----------------------------------------------------------------------===//
1212
1213 /// Given the region at `index`, or the parent operation if `index` is None,
1214 /// return the successor regions. These are the regions that may be selected
1215 /// during the flow of control. `operands` is a set of optional attributes
1216 /// that correspond to a constant value for each operand, or null if that
1217 /// operand is not a constant.
1218 void cir::ScopeOp::getSuccessorRegions(
1219 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1220 // The only region always branch back to the parent operation.
1221 if (!point.isParent()) {
1222 regions.push_back(RegionSuccessor(getOperation(), getODSResults(0)));
1223 return;
1224 }
1225
1226 // If the condition isn't constant, both regions may be executed.
1227 regions.push_back(RegionSuccessor(&getScopeRegion()));
1228 }
1229
1230 void cir::ScopeOp::build(
1231 OpBuilder &builder, OperationState &result,
1232 function_ref<void(OpBuilder &, Type &, Location)> scopeBuilder) {
1233 assert(scopeBuilder && "the builder callback for 'then' must be present");
1234
1235 OpBuilder::InsertionGuard guard(builder);
1236 Region *scopeRegion = result.addRegion();
1237 builder.createBlock(scopeRegion);
1238 assert(!cir::MissingFeatures::opScopeCleanupRegion());
1239
1240 mlir::Type yieldTy;
1241 scopeBuilder(builder, yieldTy, result.location);
1242
1243 if (yieldTy)
1244 result.addTypes(TypeRange{yieldTy});
1245 }
1246
1247 void cir::ScopeOp::build(
1248 OpBuilder &builder, OperationState &result,
1249 function_ref<void(OpBuilder &, Location)> scopeBuilder) {
1250 assert(scopeBuilder && "the builder callback for 'then' must be present");
1251 OpBuilder::InsertionGuard guard(builder);
1252 Region *scopeRegion = result.addRegion();
1253 builder.createBlock(scopeRegion);
1254 assert(!cir::MissingFeatures::opScopeCleanupRegion());
1255 scopeBuilder(builder, result.location);
1256 }
1257
1258 LogicalResult cir::ScopeOp::verify() {
1259 if (getRegion().empty()) {
1260 return emitOpError() << "cir.scope must not be empty since it should "
1261 "include at least an implicit cir.yield ";
1262 }
1263
1264 mlir::Block &lastBlock = getRegion().back();
1265 if (lastBlock.empty() || !lastBlock.mightHaveTerminator() ||
1266 !lastBlock.getTerminator()->hasTrait<OpTrait::IsTerminator>())
1267 return emitOpError() << "last block of cir.scope must be terminated";
1268 return success();
1269 }
1270
1271 LogicalResult cir::ScopeOp::fold(FoldAdaptor /*adaptor*/,
1272 SmallVectorImpl<OpFoldResult> &results) {
1273 // Only fold "trivial" scopes: a single block containing only a `cir.yield`.
1274 if (!getRegion().hasOneBlock())
1275 return failure();
1276 Block &block = getRegion().front();
1277 if (block.getOperations().size() != 1)
1278 return failure();
1279
1280 auto yield = dyn_cast<cir::YieldOp>(block.front());
1281 if (!yield)
1282 return failure();
1283
1284 // Only fold when the scope produces a value.
1285 if (getNumResults() != 1 || yield.getNumOperands() != 1)
1286 return failure();
1287
1288 results.push_back(yield.getOperand(0));
1289 return success();
1290 }
1291
1292 //===----------------------------------------------------------------------===//
1293 // BrOp
1294 //===----------------------------------------------------------------------===//
1295
1296 mlir::SuccessorOperands cir::BrOp::getSuccessorOperands(unsigned index) {
1297 assert(index == 0 && "invalid successor index");
1298 return mlir::SuccessorOperands(getDestOperandsMutable());
1299 }
1300
1301 Block *cir::BrOp::getSuccessorForOperands(ArrayRef<Attribute>) {
1302 return getDest();
1303 }
1304
1305 //===----------------------------------------------------------------------===//
1306 // IndirectBrCondOp
1307 //===----------------------------------------------------------------------===//
1308
1309 mlir::SuccessorOperands
1310 cir::IndirectBrOp::getSuccessorOperands(unsigned index) {
1311 assert(index < getNumSuccessors() && "invalid successor index");
1312 return mlir::SuccessorOperands(getSuccOperandsMutable()[index]);
1313 }
1314
1315 ParseResult parseIndirectBrOpSucessors(
1316 OpAsmParser &parser, Type &flagType,
1317 SmallVectorImpl<Block *> &succOperandBlocks,
1318 SmallVectorImpl<SmallVector<OpAsmParser::UnresolvedOperand>> &succOperands,
1319 SmallVectorImpl<SmallVector<Type>> &succOperandsTypes) {
1320 if (failed(parser.parseCommaSeparatedList(
1321 OpAsmParser::Delimiter::Square,
1322 [&]() {
1323 Block *destination = nullptr;
1324 SmallVector<OpAsmParser::UnresolvedOperand> operands;
1325 SmallVector<Type> operandTypes;
1326
1327 if (parser.parseSuccessor(destination).failed())
1328 return failure();
1329
1330 if (succeeded(parser.parseOptionalLParen())) {
1331 if (failed(parser.parseOperandList(
1332 operands, OpAsmParser::Delimiter::None)) ||
1333 failed(parser.parseColonTypeList(operandTypes)) ||
1334 failed(parser.parseRParen()))
1335 return failure();
1336 }
1337 succOperandBlocks.push_back(destination);
1338 succOperands.emplace_back(operands);
1339 succOperandsTypes.emplace_back(operandTypes);
1340 return success();
1341 },
1342 "successor blocks")))
1343 return failure();
1344 return success();
1345 }
1346
1347 void printIndirectBrOpSucessors(OpAsmPrinter &p, cir::IndirectBrOp op,
1348 Type flagType, SuccessorRange succs,
1349 OperandRangeRange succOperands,
1350 const TypeRangeRange &succOperandsTypes) {
1351 p << "[";
1352 llvm::interleave(
1353 llvm::zip(succs, succOperands),
1354 [&](auto i) {
1355 p.printNewline();
1356 p.printSuccessorAndUseList(std::get<0>(i), std::get<1>(i));
1357 },
1358 [&] { p << ','; });
1359 if (!succOperands.empty())
1360 p.printNewline();
1361 p << "]";
1362 }
1363
1364 //===----------------------------------------------------------------------===//
1365 // BrCondOp
1366 //===----------------------------------------------------------------------===//
1367
1368 mlir::SuccessorOperands cir::BrCondOp::getSuccessorOperands(unsigned index) {
1369 assert(index < getNumSuccessors() && "invalid successor index");
1370 return SuccessorOperands(index == 0 ? getDestOperandsTrueMutable()
1371 : getDestOperandsFalseMutable());
1372 }
1373
1374 Block *cir::BrCondOp::getSuccessorForOperands(ArrayRef<Attribute> operands) {
1375 if (IntegerAttr condAttr = dyn_cast_if_present<IntegerAttr>(operands.front()))
1376 return condAttr.getValue().isOne() ? getDestTrue() : getDestFalse();
1377 return nullptr;
1378 }
1379
1380 //===----------------------------------------------------------------------===//
1381 // CaseOp
1382 //===----------------------------------------------------------------------===//
1383
1384 void cir::CaseOp::getSuccessorRegions(
1385 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1386 if (!point.isParent()) {
1387 regions.push_back(
1388 RegionSuccessor(getOperation(), getOperation()->getResults()));
1389 return;
1390 }
1391 regions.push_back(RegionSuccessor(&getCaseRegion()));
1392 }
1393
1394 void cir::CaseOp::build(OpBuilder &builder, OperationState &result,
1395 ArrayAttr value, CaseOpKind kind,
1396 OpBuilder::InsertPoint &insertPoint) {
1397 OpBuilder::InsertionGuard guardSwitch(builder);
1398 result.addAttribute("value", value);
1399 result.getOrAddProperties<Properties>().kind =
1400 cir::CaseOpKindAttr::get(builder.getContext(), kind);
1401 Region *caseRegion = result.addRegion();
1402 builder.createBlock(caseRegion);
1403
1404 insertPoint = builder.saveInsertionPoint();
1405 }
1406
1407 //===----------------------------------------------------------------------===//
1408 // SwitchOp
1409 //===----------------------------------------------------------------------===//
1410
1411 void cir::SwitchOp::getSuccessorRegions(
1412 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &region) {
1413 if (!point.isParent()) {
1414 region.push_back(
1415 RegionSuccessor(getOperation(), getOperation()->getResults()));
1416 return;
1417 }
1418
1419 region.push_back(RegionSuccessor(&getBody()));
1420 }
1421
1422 void cir::SwitchOp::build(OpBuilder &builder, OperationState &result,
1423 Value cond, BuilderOpStateCallbackRef switchBuilder) {
1424 assert(switchBuilder && "the builder callback for regions must be present");
1425 OpBuilder::InsertionGuard guardSwitch(builder);
1426 Region *switchRegion = result.addRegion();
1427 builder.createBlock(switchRegion);
1428 result.addOperands({cond});
1429 switchBuilder(builder, result.location, result);
1430 }
1431
1432 void cir::SwitchOp::collectCases(llvm::SmallVectorImpl<CaseOp> &cases) {
1433 walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1434 // Don't walk in nested switch op.
1435 if (isa<cir::SwitchOp>(op) && op != *this)
1436 return WalkResult::skip();
1437
1438 if (auto caseOp = dyn_cast<cir::CaseOp>(op))
1439 cases.push_back(caseOp);
1440
1441 return WalkResult::advance();
1442 });
1443 }
1444
1445 bool cir::SwitchOp::isSimpleForm(llvm::SmallVectorImpl<CaseOp> &cases) {
1446 collectCases(cases);
1447
1448 if (getBody().empty())
1449 return false;
1450
1451 if (!isa<YieldOp>(getBody().front().back()))
1452 return false;
1453
1454 if (!llvm::all_of(getBody().front(),
1455 [](Operation &op) { return isa<CaseOp, YieldOp>(op); }))
1456 return false;
1457
1458 return llvm::all_of(cases, [this](CaseOp op) {
1459 return op->getParentOfType<SwitchOp>() == *this;
1460 });
1461 }
1462
1463 //===----------------------------------------------------------------------===//
1464 // SwitchFlatOp
1465 //===----------------------------------------------------------------------===//
1466
1467 void cir::SwitchFlatOp::build(OpBuilder &builder, OperationState &result,
1468 Value value, Block *defaultDestination,
1469 ValueRange defaultOperands,
1470 ArrayRef<APInt> caseValues,
1471 BlockRange caseDestinations,
1472 ArrayRef<ValueRange> caseOperands) {
1473
1474 std::vector<mlir::Attribute> caseValuesAttrs;
1475 for (const APInt &val : caseValues)
1476 caseValuesAttrs.push_back(cir::IntAttr::get(value.getType(), val));
1477 mlir::ArrayAttr attrs = ArrayAttr::get(builder.getContext(), caseValuesAttrs);
1478
1479 build(builder, result, value, defaultOperands, caseOperands, attrs,
1480 defaultDestination, caseDestinations);
1481 }
1482
1483 /// <cases> ::= `[` (case (`,` case )* )? `]`
1484 /// <case> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
1485 static ParseResult parseSwitchFlatOpCases(
1486 OpAsmParser &parser, Type flagType, mlir::ArrayAttr &caseValues,
1487 SmallVectorImpl<Block *> &caseDestinations,
1488 SmallVectorImpl<llvm::SmallVector<OpAsmParser::UnresolvedOperand>>
1489 &caseOperands,
1490 SmallVectorImpl<llvm::SmallVector<Type>> &caseOperandTypes) {
1491 if (failed(parser.parseLSquare()))
1492 return failure();
1493 if (succeeded(parser.parseOptionalRSquare()))
1494 return success();
1495 llvm::SmallVector<mlir::Attribute> values;
1496
1497 auto parseCase = [&]() {
1498 int64_t value = 0;
1499 if (failed(parser.parseInteger(value)))
1500 return failure();
1501
1502 values.push_back(cir::IntAttr::get(flagType, value));
1503
1504 Block *destination;
1505 llvm::SmallVector<OpAsmParser::UnresolvedOperand> operands;
1506 llvm::SmallVector<Type> operandTypes;
1507 if (parser.parseColon() || parser.parseSuccessor(destination))
1508 return failure();
1509 if (!parser.parseOptionalLParen()) {
1510 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::None,
1511 /*allowResultNumber=*/false) ||
1512 parser.parseColonTypeList(operandTypes) || parser.parseRParen())
1513 return failure();
1514 }
1515 caseDestinations.push_back(destination);
1516 caseOperands.emplace_back(operands);
1517 caseOperandTypes.emplace_back(operandTypes);
1518 return success();
1519 };
1520 if (failed(parser.parseCommaSeparatedList(parseCase)))
1521 return failure();
1522
1523 caseValues = ArrayAttr::get(flagType.getContext(), values);
1524
1525 return parser.parseRSquare();
1526 }
1527
1528 static void printSwitchFlatOpCases(OpAsmPrinter &p, cir::SwitchFlatOp op,
1529 Type flagType, mlir::ArrayAttr caseValues,
1530 SuccessorRange caseDestinations,
1531 OperandRangeRange caseOperands,
1532 const TypeRangeRange &caseOperandTypes) {
1533 p << '[';
1534 p.printNewline();
1535 if (!caseValues) {
1536 p << ']';
1537 return;
1538 }
1539
1540 size_t index = 0;
1541 llvm::interleave(
1542 llvm::zip(caseValues, caseDestinations),
1543 [&](auto i) {
1544 p << " ";
1545 mlir::Attribute a = std::get<0>(i);
1546 p << mlir::cast<cir::IntAttr>(a).getValue();
1547 p << ": ";
1548 p.printSuccessorAndUseList(std::get<1>(i), caseOperands[index++]);
1549 },
1550 [&] {
1551 p << ',';
1552 p.printNewline();
1553 });
1554 p.printNewline();
1555 p << ']';
1556 }
1557
1558 //===----------------------------------------------------------------------===//
1559 // GlobalOp
1560 //===----------------------------------------------------------------------===//
1561
1562 static ParseResult parseConstantValue(OpAsmParser &parser,
1563 mlir::Attribute &valueAttr) {
1564 NamedAttrList attr;
1565 return parser.parseAttribute(valueAttr, "value", attr);
1566 }
1567
1568 static void printConstant(OpAsmPrinter &p, Attribute value) {
1569 p.printAttribute(value);
1570 }
1571
1572 mlir::LogicalResult cir::GlobalOp::verify() {
1573 // Verify that the initial value, if present, is either a unit attribute or
1574 // an attribute CIR supports.
1575 if (getInitialValue().has_value()) {
1576 if (checkConstantTypes(getOperation(), getSymType(), *getInitialValue())
1577 .failed())
1578 return failure();
1579 }
1580
1581 // TODO(CIR): Many other checks for properties that haven't been upstreamed
1582 // yet.
1583
1584 return success();
1585 }
1586
1587 void cir::GlobalOp::build(
1588 OpBuilder &odsBuilder, OperationState &odsState, llvm::StringRef sym_name,
1589 mlir::Type sym_type, bool isConstant, cir::GlobalLinkageKind linkage,
1590 function_ref<void(OpBuilder &, Location)> ctorBuilder,
1591 function_ref<void(OpBuilder &, Location)> dtorBuilder) {
1592 odsState.addAttribute(getSymNameAttrName(odsState.name),
1593 odsBuilder.getStringAttr(sym_name));
1594 odsState.addAttribute(getSymTypeAttrName(odsState.name),
1595 mlir::TypeAttr::get(sym_type));
1596 if (isConstant)
1597 odsState.addAttribute(getConstantAttrName(odsState.name),
1598 odsBuilder.getUnitAttr());
1599
1600 cir::GlobalLinkageKindAttr linkageAttr =
1601 cir::GlobalLinkageKindAttr::get(odsBuilder.getContext(), linkage);
1602 odsState.addAttribute(getLinkageAttrName(odsState.name), linkageAttr);
1603
1604 Region *ctorRegion = odsState.addRegion();
1605 if (ctorBuilder) {
1606 odsBuilder.createBlock(ctorRegion);
1607 ctorBuilder(odsBuilder, odsState.location);
1608 }
1609
1610 Region *dtorRegion = odsState.addRegion();
1611 if (dtorBuilder) {
1612 odsBuilder.createBlock(dtorRegion);
1613 dtorBuilder(odsBuilder, odsState.location);
1614 }
1615
1616 odsState.addAttribute(getGlobalVisibilityAttrName(odsState.name),
1617 cir::VisibilityAttr::get(odsBuilder.getContext()));
1618 }
1619
1620 /// Given the region at `index`, or the parent operation if `index` is None,
1621 /// return the successor regions. These are the regions that may be selected
1622 /// during the flow of control. `operands` is a set of optional attributes that
1623 /// correspond to a constant value for each operand, or null if that operand is
1624 /// not a constant.
1625 void cir::GlobalOp::getSuccessorRegions(
1626 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
1627 // The `ctor` and `dtor` regions always branch back to the parent operation.
1628 if (!point.isParent()) {
1629 regions.push_back(
1630 RegionSuccessor(getOperation(), getOperation()->getResults()));
1631 return;
1632 }
1633
1634 // Don't consider the ctor region if it is empty.
1635 Region *ctorRegion = &this->getCtorRegion();
1636 if (ctorRegion->empty())
1637 ctorRegion = nullptr;
1638
1639 // Don't consider the dtor region if it is empty.
1640 Region *dtorRegion = &this->getCtorRegion();
1641 if (dtorRegion->empty())
1642 dtorRegion = nullptr;
1643
1644 // If the condition isn't constant, both regions may be executed.
1645 if (ctorRegion)
1646 regions.push_back(RegionSuccessor(ctorRegion));
1647 if (dtorRegion)
1648 regions.push_back(RegionSuccessor(dtorRegion));
1649 }
1650
1651 static void printGlobalOpTypeAndInitialValue(OpAsmPrinter &p, cir::GlobalOp op,
1652 TypeAttr type, Attribute initAttr,
1653 mlir::Region &ctorRegion,
1654 mlir::Region &dtorRegion) {
1655 auto printType = [&]() { p << ": " << type; };
1656 if (!op.isDeclaration()) {
1657 p << "= ";
1658 if (!ctorRegion.empty()) {
1659 p << "ctor ";
1660 printType();
1661 p << " ";
1662 p.printRegion(ctorRegion,
1663 /*printEntryBlockArgs=*/false,
1664 /*printBlockTerminators=*/false);
1665 } else {
1666 // This also prints the type...
1667 if (initAttr)
1668 printConstant(p, initAttr);
1669 }
1670
1671 if (!dtorRegion.empty()) {
1672 p << " dtor ";
1673 p.printRegion(dtorRegion,
1674 /*printEntryBlockArgs=*/false,
1675 /*printBlockTerminators=*/false);
1676 }
1677 } else {
1678 printType();
1679 }
1680 }
1681
1682 static ParseResult parseGlobalOpTypeAndInitialValue(OpAsmParser &parser,
1683 TypeAttr &typeAttr,
1684 Attribute &initialValueAttr,
1685 mlir::Region &ctorRegion,
1686 mlir::Region &dtorRegion) {
1687 mlir::Type opTy;
1688 if (parser.parseOptionalEqual().failed()) {
1689 // Absence of equal means a declaration, so we need to parse the type.
1690 // cir.global @a : !cir.int<s, 32>
1691 if (parser.parseColonType(opTy))
1692 return failure();
1693 } else {
1694 // Parse contructor, example:
1695 // cir.global @rgb = ctor : type { ... }
1696 if (!parser.parseOptionalKeyword("ctor")) {
1697 if (parser.parseColonType(opTy))
1698 return failure();
1699 auto parseLoc = parser.getCurrentLocation();
1700 if (parser.parseRegion(ctorRegion, /*arguments=*/{}, /*argTypes=*/{}))
1701 return failure();
1702 if (ensureRegionTerm(parser, ctorRegion, parseLoc).failed())
1703 return failure();
1704 } else {
1705 // Parse constant with initializer, examples:
1706 // cir.global @y = 3.400000e+00 : f32
1707 // cir.global @rgb = #cir.const_array<[...] : !cir.array<i8 x 3>>
1708 if (parseConstantValue(parser, initialValueAttr).failed())
1709 return failure();
1710
1711 assert(mlir::isa<mlir::TypedAttr>(initialValueAttr) &&
1712 "Non-typed attrs shouldn't appear here.");
1713 auto typedAttr = mlir::cast<mlir::TypedAttr>(initialValueAttr);
1714 opTy = typedAttr.getType();
1715 }
1716
1717 // Parse destructor, example:
1718 // dtor { ... }
1719 if (!parser.parseOptionalKeyword("dtor")) {
1720 auto parseLoc = parser.getCurrentLocation();
1721 if (parser.parseRegion(dtorRegion, /*arguments=*/{}, /*argTypes=*/{}))
1722 return failure();
1723 if (ensureRegionTerm(parser, dtorRegion, parseLoc).failed())
1724 return failure();
1725 }
1726 }
1727
1728 typeAttr = TypeAttr::get(opTy);
1729 return success();
1730 }
1731
1732 //===----------------------------------------------------------------------===//
1733 // GetGlobalOp
1734 //===----------------------------------------------------------------------===//
1735
1736 LogicalResult
1737 cir::GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1738 // Verify that the result type underlying pointer type matches the type of
1739 // the referenced cir.global or cir.func op.
1740 mlir::Operation *op =
1741 symbolTable.lookupNearestSymbolFrom(*this, getNameAttr());
1742 if (op == nullptr || !(isa<GlobalOp>(op) || isa<FuncOp>(op)))
1743 return emitOpError("'")
1744 << getName()
1745 << "' does not reference a valid cir.global or cir.func";
1746
1747 mlir::Type symTy;
1748 if (auto g = dyn_cast<GlobalOp>(op)) {
1749 symTy = g.getSymType();
1750 assert(!cir::MissingFeatures::addressSpace());
1751 // Verify that for thread local global access, the global needs to
1752 // be marked with tls bits.
1753 if (getTls() && !g.getTlsModel())
1754 return emitOpError("access to global not marked thread local");
1755 } else if (auto f = dyn_cast<FuncOp>(op)) {
1756 symTy = f.getFunctionType();
1757 } else {
1758 llvm_unreachable("Unexpected operation for GetGlobalOp");
1759 }
1760
1761 auto resultType = dyn_cast<PointerType>(getAddr().getType());
1762 if (!resultType || symTy != resultType.getPointee())
1763 return emitOpError("result type pointee type '")
1764 << resultType.getPointee() << "' does not match type " << symTy
1765 << " of the global @" << getName();
1766
1767 return success();
1768 }
1769
1770 //===----------------------------------------------------------------------===//
1771 // VTableAddrPointOp
1772 //===----------------------------------------------------------------------===//
1773
1774 LogicalResult
1775 cir::VTableAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1776 StringRef name = getName();
1777
1778 // Verify that the result type underlying pointer type matches the type of
1779 // the referenced cir.global.
1780 auto op =
1781 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
1782 if (!op)
1783 return emitOpError("'")
1784 << name << "' does not reference a valid cir.global";
1785 std::optional<mlir::Attribute> init = op.getInitialValue();
1786 if (!init)
1787 return success();
1788 if (!isa<cir::VTableAttr>(*init))
1789 return emitOpError("Expected #cir.vtable in initializer for global '")
1790 << name << "'";
1791 return success();
1792 }
1793
1794 //===----------------------------------------------------------------------===//
1795 // VTTAddrPointOp
1796 //===----------------------------------------------------------------------===//
1797
1798 LogicalResult
1799 cir::VTTAddrPointOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1800 // VTT ptr is not coming from a symbol.
1801 if (!getName())
1802 return success();
1803 StringRef name = *getName();
1804
1805 // Verify that the result type underlying pointer type matches the type of
1806 // the referenced cir.global op.
1807 auto op =
1808 symbolTable.lookupNearestSymbolFrom<cir::GlobalOp>(*this, getNameAttr());
1809 if (!op)
1810 return emitOpError("'")
1811 << name << "' does not reference a valid cir.global";
1812 std::optional<mlir::Attribute> init = op.getInitialValue();
1813 if (!init)
1814 return success();
1815 if (!isa<cir::ConstArrayAttr>(*init))
1816 return emitOpError(
1817 "Expected constant array in initializer for global VTT '")
1818 << name << "'";
1819 return success();
1820 }
1821
1822 LogicalResult cir::VTTAddrPointOp::verify() {
1823 // The operation uses either a symbol or a value to operate, but not both
1824 if (getName() && getSymAddr())
1825 return emitOpError("should use either a symbol or value, but not both");
1826
1827 // If not a symbol, stick with the concrete type used for getSymAddr.
1828 if (getSymAddr())
1829 return success();
1830
1831 mlir::Type resultType = getAddr().getType();
1832 mlir::Type resTy = cir::PointerType::get(
1833 cir::PointerType::get(cir::VoidType::get(getContext())));
1834
1835 if (resultType != resTy)
1836 return emitOpError("result type must be ")
1837 << resTy << ", but provided result type is " << resultType;
1838 return success();
1839 }
1840
1841 //===----------------------------------------------------------------------===//
1842 // FuncOp
1843 //===----------------------------------------------------------------------===//
1844
1845 /// Returns the name used for the linkage attribute. This *must* correspond to
1846 /// the name of the attribute in ODS.
1847 static llvm::StringRef getLinkageAttrNameString() { return "linkage"; }
1848
1849 void cir::FuncOp::build(OpBuilder &builder, OperationState &result,
1850 StringRef name, FuncType type,
1851 GlobalLinkageKind linkage) {
1852 result.addRegion();
1853 result.addAttribute(SymbolTable::getSymbolAttrName(),
1854 builder.getStringAttr(name));
1855 result.addAttribute(getFunctionTypeAttrName(result.name),
1856 TypeAttr::get(type));
1857 result.addAttribute(
1858 getLinkageAttrNameString(),
1859 GlobalLinkageKindAttr::get(builder.getContext(), linkage));
1860 result.addAttribute(getGlobalVisibilityAttrName(result.name),
1861 cir::VisibilityAttr::get(builder.getContext()));
1862 }
1863
1864 ParseResult cir::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
1865 llvm::SMLoc loc = parser.getCurrentLocation();
1866 mlir::Builder &builder = parser.getBuilder();
1867
1868 mlir::StringAttr builtinNameAttr = getBuiltinAttrName(state.name);
1869 mlir::StringAttr coroutineNameAttr = getCoroutineAttrName(state.name);
1870 mlir::StringAttr inlineKindNameAttr = getInlineKindAttrName(state.name);
1871 mlir::StringAttr lambdaNameAttr = getLambdaAttrName(state.name);
1872 mlir::StringAttr noProtoNameAttr = getNoProtoAttrName(state.name);
1873 mlir::StringAttr visNameAttr = getSymVisibilityAttrName(state.name);
1874 mlir::StringAttr visibilityNameAttr = getGlobalVisibilityAttrName(state.name);
1875 mlir::StringAttr dsoLocalNameAttr = getDsoLocalAttrName(state.name);
1876 mlir::StringAttr specialMemberAttr = getCxxSpecialMemberAttrName(state.name);
1877
1878 if (::mlir::succeeded(parser.parseOptionalKeyword(builtinNameAttr.strref())))
1879 state.addAttribute(builtinNameAttr, parser.getBuilder().getUnitAttr());
1880 if (::mlir::succeeded(
1881 parser.parseOptionalKeyword(coroutineNameAttr.strref())))
1882 state.addAttribute(coroutineNameAttr, parser.getBuilder().getUnitAttr());
1883
1884 // Parse optional inline kind attribute
1885 cir::InlineKindAttr inlineKindAttr;
1886 if (failed(parseInlineKindAttr(parser, inlineKindAttr)))
1887 return failure();
1888 if (inlineKindAttr)
1889 state.addAttribute(inlineKindNameAttr, inlineKindAttr);
1890
1891 if (::mlir::succeeded(parser.parseOptionalKeyword(lambdaNameAttr.strref())))
1892 state.addAttribute(lambdaNameAttr, parser.getBuilder().getUnitAttr());
1893 if (parser.parseOptionalKeyword(noProtoNameAttr).succeeded())
1894 state.addAttribute(noProtoNameAttr, parser.getBuilder().getUnitAttr());
1895
1896 // Default to external linkage if no keyword is provided.
1897 state.addAttribute(getLinkageAttrNameString(),
1898 GlobalLinkageKindAttr::get(
1899 parser.getContext(),
1900 parseOptionalCIRKeyword<GlobalLinkageKind>(
1901 parser, GlobalLinkageKind::ExternalLinkage)));
1902
1903 ::llvm::StringRef visAttrStr;
1904 if (parser.parseOptionalKeyword(&visAttrStr, {"private", "public", "nested"})
1905 .succeeded()) {
1906 state.addAttribute(visNameAttr,
1907 parser.getBuilder().getStringAttr(visAttrStr));
1908 }
1909
1910 cir::VisibilityAttr cirVisibilityAttr;
1911 parseVisibilityAttr(parser, cirVisibilityAttr);
1912 state.addAttribute(visibilityNameAttr, cirVisibilityAttr);
1913
1914 if (parser.parseOptionalKeyword(dsoLocalNameAttr).succeeded())
1915 state.addAttribute(dsoLocalNameAttr, parser.getBuilder().getUnitAttr());
1916
1917 StringAttr nameAttr;
1918 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
1919 state.attributes))
1920 return failure();
1921 llvm::SmallVector<OpAsmParser::Argument, 8> arguments;
1922 llvm::SmallVector<mlir::Type> resultTypes;
1923 llvm::SmallVector<DictionaryAttr> resultAttrs;
1924 bool isVariadic = false;
1925 if (function_interface_impl::parseFunctionSignatureWithArguments(
1926 parser, /*allowVariadic=*/true, arguments, isVariadic, resultTypes,
1927 resultAttrs))
1928 return failure();
1929 llvm::SmallVector<mlir::Type> argTypes;
1930 for (OpAsmParser::Argument &arg : arguments)
1931 argTypes.push_back(arg.type);
1932
1933 if (resultTypes.size() > 1) {
1934 return parser.emitError(
1935 loc, "functions with multiple return types are not supported");
1936 }
1937
1938 mlir::Type returnType =
1939 (resultTypes.empty() ? cir::VoidType::get(builder.getContext())
1940 : resultTypes.front());
1941
1942 cir::FuncType fnType = cir::FuncType::get(argTypes, returnType, isVariadic);
1943 if (!fnType)
1944 return failure();
1945 state.addAttribute(getFunctionTypeAttrName(state.name),
1946 TypeAttr::get(fnType));
1947
1948 bool hasAlias = false;
1949 mlir::StringAttr aliaseeNameAttr = getAliaseeAttrName(state.name);
1950 if (parser.parseOptionalKeyword("alias").succeeded()) {
1951 if (parser.parseLParen().failed())
1952 return failure();
1953 mlir::StringAttr aliaseeAttr;
1954 if (parser.parseOptionalSymbolName(aliaseeAttr).failed())
1955 return failure();
1956 state.addAttribute(aliaseeNameAttr, FlatSymbolRefAttr::get(aliaseeAttr));
1957 if (parser.parseRParen().failed())
1958 return failure();
1959 hasAlias = true;
1960 }
1961
1962 mlir::StringAttr personalityNameAttr = getPersonalityAttrName(state.name);
1963 if (parser.parseOptionalKeyword("personality").succeeded()) {
1964 if (parser.parseLParen().failed())
1965 return failure();
1966 mlir::StringAttr personalityAttr;
1967 if (parser.parseOptionalSymbolName(personalityAttr).failed())
1968 return failure();
1969 state.addAttribute(personalityNameAttr,
1970 FlatSymbolRefAttr::get(personalityAttr));
1971 if (parser.parseRParen().failed())
1972 return failure();
1973 }
1974
1975 auto parseGlobalDtorCtor =
1976 [&](StringRef keyword,
1977 llvm::function_ref<void(std::optional<int> prio)> createAttr)
1978 -> mlir::LogicalResult {
1979 if (mlir::succeeded(parser.parseOptionalKeyword(keyword))) {
1980 std::optional<int> priority;
1981 if (mlir::succeeded(parser.parseOptionalLParen())) {
1982 auto parsedPriority = mlir::FieldParser<int>::parse(parser);
1983 if (mlir::failed(parsedPriority))
1984 return parser.emitError(parser.getCurrentLocation(),
1985 "failed to parse 'priority', of type 'int'");
1986 priority = parsedPriority.value_or(int());
1987 // Parse literal ')'
1988 if (parser.parseRParen())
1989 return failure();
1990 }
1991 createAttr(priority);
1992 }
1993 return success();
1994 };
1995
1996 // Parse CXXSpecialMember attribute
1997 if (parser.parseOptionalKeyword("special_member").succeeded()) {
1998 cir::CXXCtorAttr ctorAttr;
1999 cir::CXXDtorAttr dtorAttr;
2000 cir::CXXAssignAttr assignAttr;
2001 if (parser.parseLess().failed())
2002 return failure();
2003 if (parser.parseOptionalAttribute(ctorAttr).has_value())
2004 state.addAttribute(specialMemberAttr, ctorAttr);
2005 else if (parser.parseOptionalAttribute(dtorAttr).has_value())
2006 state.addAttribute(specialMemberAttr, dtorAttr);
2007 else if (parser.parseOptionalAttribute(assignAttr).has_value())
2008 state.addAttribute(specialMemberAttr, assignAttr);
2009 if (parser.parseGreater().failed())
2010 return failure();
2011 }
2012
2013 if (parseGlobalDtorCtor("global_ctor", [&](std::optional<int> priority) {
2014 mlir::IntegerAttr globalCtorPriorityAttr =
2015 builder.getI32IntegerAttr(priority.value_or(65535));
2016 state.addAttribute(getGlobalCtorPriorityAttrName(state.name),
2017 globalCtorPriorityAttr);
2018 }).failed())
2019 return failure();
2020
2021 if (parseGlobalDtorCtor("global_dtor", [&](std::optional<int> priority) {
2022 mlir::IntegerAttr globalDtorPriorityAttr =
2023 builder.getI32IntegerAttr(priority.value_or(65535));
2024 state.addAttribute(getGlobalDtorPriorityAttrName(state.name),
2025 globalDtorPriorityAttr);
2026 }).failed())
2027 return failure();
2028
2029 // Parse the rest of the attributes.
2030 NamedAttrList parsedAttrs;
2031 if (parser.parseOptionalAttrDictWithKeyword(parsedAttrs))
2032 return failure();
2033
2034 for (StringRef disallowed : cir::FuncOp::getAttributeNames()) {
2035 if (parsedAttrs.get(disallowed))
2036 return parser.emitError(loc, "attribute '")
2037 << disallowed
2038 << "' should not be specified in the explicit attribute list";
2039 }
2040
2041 state.attributes.append(parsedAttrs);
2042
2043 // Parse the optional function body.
2044 auto *body = state.addRegion();
2045 OptionalParseResult parseResult = parser.parseOptionalRegion(
2046 *body, arguments, /*enableNameShadowing=*/false);
2047 if (parseResult.has_value()) {
2048 if (hasAlias)
2049 return parser.emitError(loc, "function alias shall not have a body");
2050 if (failed(*parseResult))
2051 return failure();
2052 // Function body was parsed, make sure its not empty.
2053 if (body->empty())
2054 return parser.emitError(loc, "expected non-empty function body");
2055 }
2056
2057 return success();
2058 }
2059
2060 // This function corresponds to `llvm::GlobalValue::isDeclaration` and should
2061 // have a similar implementation. We don't currently ifuncs or materializable
2062 // functions, but those should be handled here as they are implemented.
2063 bool cir::FuncOp::isDeclaration() {
2064 assert(!cir::MissingFeatures::supportIFuncAttr());
2065
2066 std::optional<StringRef> aliasee = getAliasee();
2067 if (!aliasee)
2068 return getFunctionBody().empty();
2069
2070 // Aliases are always definitions.
2071 return false;
2072 }
2073
2074 bool cir::FuncOp::isCXXSpecialMemberFunction() {
2075 return getCxxSpecialMemberAttr() != nullptr;
2076 }
2077
2078 bool cir::FuncOp::isCxxConstructor() {
2079 auto attr = getCxxSpecialMemberAttr();
2080 return attr && dyn_cast<CXXCtorAttr>(attr);
2081 }
2082
2083 bool cir::FuncOp::isCxxDestructor() {
2084 auto attr = getCxxSpecialMemberAttr();
2085 return attr && dyn_cast<CXXDtorAttr>(attr);
2086 }
2087
2088 bool cir::FuncOp::isCxxSpecialAssignment() {
2089 auto attr = getCxxSpecialMemberAttr();
2090 return attr && dyn_cast<CXXAssignAttr>(attr);
2091 }
2092
2093 std::optional<CtorKind> cir::FuncOp::getCxxConstructorKind() {
2094 mlir::Attribute attr = getCxxSpecialMemberAttr();
2095 if (attr) {
2096 if (auto ctor = dyn_cast<CXXCtorAttr>(attr))
2097 return ctor.getCtorKind();
2098 }
2099 return std::nullopt;
2100 }
2101
2102 std::optional<AssignKind> cir::FuncOp::getCxxSpecialAssignKind() {
2103 mlir::Attribute attr = getCxxSpecialMemberAttr();
2104 if (attr) {
2105 if (auto assign = dyn_cast<CXXAssignAttr>(attr))
2106 return assign.getAssignKind();
2107 }
2108 return std::nullopt;
2109 }
2110
2111 bool cir::FuncOp::isCxxTrivialMemberFunction() {
2112 mlir::Attribute attr = getCxxSpecialMemberAttr();
2113 if (attr) {
2114 if (auto ctor = dyn_cast<CXXCtorAttr>(attr))
2115 return ctor.getIsTrivial();
2116 if (auto dtor = dyn_cast<CXXDtorAttr>(attr))
2117 return dtor.getIsTrivial();
2118 if (auto assign = dyn_cast<CXXAssignAttr>(attr))
2119 return assign.getIsTrivial();
2120 }
2121 return false;
2122 }
2123
2124 mlir::Region *cir::FuncOp::getCallableRegion() {
2125 // TODO(CIR): This function will have special handling for aliases and a
2126 // check for an external function, once those features have been upstreamed.
2127 return &getBody();
2128 }
2129
2130 void cir::FuncOp::print(OpAsmPrinter &p) {
2131 if (getBuiltin())
2132 p << " builtin";
2133
2134 if (getCoroutine())
2135 p << " coroutine";
2136
2137 printInlineKindAttr(p, getInlineKindAttr());
2138
2139 if (getLambda())
2140 p << " lambda";
2141
2142 if (getNoProto())
2143 p << " no_proto";
2144
2145 if (getComdat())
2146 p << " comdat";
2147
2148 if (getLinkage() != GlobalLinkageKind::ExternalLinkage)
2149 p << ' ' << stringifyGlobalLinkageKind(getLinkage());
2150
2151 mlir::SymbolTable::Visibility vis = getVisibility();
2152 if (vis != mlir::SymbolTable::Visibility::Public)
2153 p << ' ' << vis;
2154
2155 cir::VisibilityAttr cirVisibilityAttr = getGlobalVisibilityAttr();
2156 if (!cirVisibilityAttr.isDefault()) {
2157 p << ' ';
2158 printVisibilityAttr(p, cirVisibilityAttr);
2159 }
2160
2161 if (getDsoLocal())
2162 p << " dso_local";
2163
2164 p << ' ';
2165 p.printSymbolName(getSymName());
2166 cir::FuncType fnType = getFunctionType();
2167 function_interface_impl::printFunctionSignature(
2168 p, *this, fnType.getInputs(), fnType.isVarArg(), fnType.getReturnTypes());
2169
2170 if (std::optional<StringRef> aliaseeName = getAliasee()) {
2171 p << " alias(";
2172 p.printSymbolName(*aliaseeName);
2173 p << ")";
2174 }
2175
2176 if (std::optional<StringRef> personalityName = getPersonality()) {
2177 p << " personality(";
2178 p.printSymbolName(*personalityName);
2179 p << ")";
2180 }
2181
2182 if (auto specialMemberAttr = getCxxSpecialMember()) {
2183 p << " special_member<";
2184 p.printAttribute(*specialMemberAttr);
2185 p << '>';
2186 }
2187
2188 if (auto globalCtorPriority = getGlobalCtorPriority()) {
2189 p << " global_ctor";
2190 if (globalCtorPriority.value() != 65535)
2191 p << "(" << globalCtorPriority.value() << ")";
2192 }
2193
2194 if (auto globalDtorPriority = getGlobalDtorPriority()) {
2195 p << " global_dtor";
2196 if (globalDtorPriority.value() != 65535)
2197 p << "(" << globalDtorPriority.value() << ")";
2198 }
2199
2200 function_interface_impl::printFunctionAttributes(
2201 p, *this, cir::FuncOp::getAttributeNames());
2202
2203 // Print the body if this is not an external function.
2204 Region &body = getOperation()->getRegion(0);
2205 if (!body.empty()) {
2206 p << ' ';
2207 p.printRegion(body, /*printEntryBlockArgs=*/false,
2208 /*printBlockTerminators=*/true);
2209 }
2210 }
2211
2212 mlir::LogicalResult cir::FuncOp::verify() {
2213
2214 if (!isDeclaration() && getCoroutine()) {
2215 bool foundAwait = false;
2216 this->walk([&](Operation *op) {
2217 if (auto await = dyn_cast<AwaitOp>(op)) {
2218 foundAwait = true;
2219 return;
2220 }
2221 });
2222 if (!foundAwait)
2223 return emitOpError()
2224 << "coroutine body must use at least one cir.await op";
2225 }
2226
2227 llvm::SmallSet<llvm::StringRef, 16> labels;
2228 llvm::SmallSet<llvm::StringRef, 16> gotos;
2229 llvm::SmallSet<llvm::StringRef, 16> blockAddresses;
2230 bool invalidBlockAddress = false;
2231 getOperation()->walk([&](mlir::Operation *op) {
2232 if (auto lab = dyn_cast<cir::LabelOp>(op)) {
2233 labels.insert(lab.getLabel());
2234 } else if (auto goTo = dyn_cast<cir::GotoOp>(op)) {
2235 gotos.insert(goTo.getLabel());
2236 } else if (auto blkAdd = dyn_cast<cir::BlockAddressOp>(op)) {
2237 if (blkAdd.getBlockAddrInfoAttr().getFunc().getAttr() != getSymName()) {
2238 // Stop the walk early, no need to continue
2239 invalidBlockAddress = true;
2240 return mlir::WalkResult::interrupt();
2241 }
2242 blockAddresses.insert(blkAdd.getBlockAddrInfoAttr().getLabel());
2243 }
2244 return mlir::WalkResult::advance();
2245 });
2246
2247 if (invalidBlockAddress)
2248 return emitOpError() << "blockaddress references a different function";
2249
2250 llvm::SmallSet<llvm::StringRef, 16> mismatched;
2251 if (!labels.empty() || !gotos.empty()) {
2252 mismatched = llvm::set_difference(gotos, labels);
2253
2254 if (!mismatched.empty())
2255 return emitOpError() << "goto/label mismatch";
2256 }
2257
2258 mismatched.clear();
2259
2260 if (!labels.empty() || !blockAddresses.empty()) {
2261 mismatched = llvm::set_difference(blockAddresses, labels);
2262
2263 if (!mismatched.empty())
2264 return emitOpError()
2265 << "expects an existing label target in the referenced function";
2266 }
2267
2268 return success();
2269 }
2270
2271 //===----------------------------------------------------------------------===//
2272 // BinOp
2273 //===----------------------------------------------------------------------===//
2274 LogicalResult cir::BinOp::verify() {
2275 bool noWrap = getNoUnsignedWrap() || getNoSignedWrap();
2276 bool saturated = getSaturated();
2277
2278 if (!isa<cir::IntType>(getType()) && noWrap)
2279 return emitError()
2280 << "only operations on integer values may have nsw/nuw flags";
2281
2282 bool noWrapOps = getKind() == cir::BinOpKind::Add ||
2283 getKind() == cir::BinOpKind::Sub ||
2284 getKind() == cir::BinOpKind::Mul;
2285
2286 bool saturatedOps =
2287 getKind() == cir::BinOpKind::Add || getKind() == cir::BinOpKind::Sub;
2288
2289 if (noWrap && !noWrapOps)
2290 return emitError() << "The nsw/nuw flags are applicable to opcodes: 'add', "
2291 "'sub' and 'mul'";
2292 if (saturated && !saturatedOps)
2293 return emitError() << "The saturated flag is applicable to opcodes: 'add' "
2294 "and 'sub'";
2295 if (noWrap && saturated)
2296 return emitError() << "The nsw/nuw flags and the saturated flag are "
2297 "mutually exclusive";
2298
2299 return mlir::success();
2300 }
2301
2302 //===----------------------------------------------------------------------===//
2303 // TernaryOp
2304 //===----------------------------------------------------------------------===//
2305
2306 /// Given the region at `point`, or the parent operation if `point` is None,
2307 /// return the successor regions. These are the regions that may be selected
2308 /// during the flow of control. `operands` is a set of optional attributes that
2309 /// correspond to a constant value for each operand, or null if that operand is
2310 /// not a constant.
2311 void cir::TernaryOp::getSuccessorRegions(
2312 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
2313 // The `true` and the `false` region branch back to the parent operation.
2314 if (!point.isParent()) {
2315 regions.push_back(RegionSuccessor(getOperation(), this->getODSResults(0)));
2316 return;
2317 }
2318
2319 // When branching from the parent operation, both the true and false
2320 // regions are considered possible successors
2321 regions.push_back(RegionSuccessor(&getTrueRegion()));
2322 regions.push_back(RegionSuccessor(&getFalseRegion()));
2323 }
2324
2325 void cir::TernaryOp::build(
2326 OpBuilder &builder, OperationState &result, Value cond,
2327 function_ref<void(OpBuilder &, Location)> trueBuilder,
2328 function_ref<void(OpBuilder &, Location)> falseBuilder) {
2329 result.addOperands(cond);
2330 OpBuilder::InsertionGuard guard(builder);
2331 Region *trueRegion = result.addRegion();
2332 builder.createBlock(trueRegion);
2333 trueBuilder(builder, result.location);
2334 Region *falseRegion = result.addRegion();
2335 builder.createBlock(falseRegion);
2336 falseBuilder(builder, result.location);
2337
2338 // Get result type from whichever branch has a yield (the other may have
2339 // unreachable from a throw expression)
2340 auto yield =
2341 dyn_cast_or_null<cir::YieldOp>(trueRegion->back().getTerminator());
2342 if (!yield)
2343 yield = dyn_cast_or_null<cir::YieldOp>(falseRegion->back().getTerminator());
2344
2345 assert((yield && yield.getNumOperands() <= 1) &&
2346 "expected zero or one result type");
2347 if (yield.getNumOperands() == 1)
2348 result.addTypes(TypeRange{yield.getOperandTypes().front()});
2349 }
2350
2351 //===----------------------------------------------------------------------===//
2352 // SelectOp
2353 //===----------------------------------------------------------------------===//
2354
2355 OpFoldResult cir::SelectOp::fold(FoldAdaptor adaptor) {
2356 mlir::Attribute condition = adaptor.getCondition();
2357 if (condition) {
2358 bool conditionValue = mlir::cast<cir::BoolAttr>(condition).getValue();
2359 return conditionValue ? getTrueValue() : getFalseValue();
2360 }
2361
2362 // cir.select if %0 then x else x -> x
2363 mlir::Attribute trueValue = adaptor.getTrueValue();
2364 mlir::Attribute falseValue = adaptor.getFalseValue();
2365 if (trueValue == falseValue)
2366 return trueValue;
2367 if (getTrueValue() == getFalseValue())
2368 return getTrueValue();
2369
2370 return {};
2371 }
2372
2373 LogicalResult cir::SelectOp::verify() {
2374 // AllTypesMatch already guarantees trueVal and falseVal have matching types.
2375 auto condTy = dyn_cast<cir::VectorType>(getCondition().getType());
2376
2377 // If condition is not a vector, no further checks are needed.
2378 if (!condTy)
2379 return success();
2380
2381 // When condition is a vector, both other operands must also be vectors.
2382 if (!isa<cir::VectorType>(getTrueValue().getType()) ||
2383 !isa<cir::VectorType>(getFalseValue().getType())) {
2384 return emitOpError()
2385 << "expected both true and false operands to be vector types "
2386 "when the condition is a vector boolean type";
2387 }
2388
2389 return success();
2390 }
2391
2392 //===----------------------------------------------------------------------===//
2393 // ShiftOp
2394 //===----------------------------------------------------------------------===//
2395 LogicalResult cir::ShiftOp::verify() {
2396 mlir::Operation *op = getOperation();
2397 auto op0VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(0).getType());
2398 auto op1VecTy = mlir::dyn_cast<cir::VectorType>(op->getOperand(1).getType());
2399 if (!op0VecTy ^ !op1VecTy)
2400 return emitOpError() << "input types cannot be one vector and one scalar";
2401
2402 if (op0VecTy) {
2403 if (op0VecTy.getSize() != op1VecTy.getSize())
2404 return emitOpError() << "input vector types must have the same size";
2405
2406 auto opResultTy = mlir::dyn_cast<cir::VectorType>(getType());
2407 if (!opResultTy)
2408 return emitOpError() << "the type of the result must be a vector "
2409 << "if it is vector shift";
2410
2411 auto op0VecEleTy = mlir::cast<cir::IntType>(op0VecTy.getElementType());
2412 auto op1VecEleTy = mlir::cast<cir::IntType>(op1VecTy.getElementType());
2413 if (op0VecEleTy.getWidth() != op1VecEleTy.getWidth())
2414 return emitOpError()
2415 << "vector operands do not have the same elements sizes";
2416
2417 auto resVecEleTy = mlir::cast<cir::IntType>(opResultTy.getElementType());
2418 if (op0VecEleTy.getWidth() != resVecEleTy.getWidth())
2419 return emitOpError() << "vector operands and result type do not have the "
2420 "same elements sizes";
2421 }
2422
2423 return mlir::success();
2424 }
2425
2426 //===----------------------------------------------------------------------===//
2427 // LabelOp Definitions
2428 //===----------------------------------------------------------------------===//
2429
2430 LogicalResult cir::LabelOp::verify() {
2431 mlir::Operation *op = getOperation();
2432 mlir::Block *blk = op->getBlock();
2433 if (&blk->front() != op)
2434 return emitError() << "must be the first operation in a block";
2435
2436 return mlir::success();
2437 }
2438
2439 //===----------------------------------------------------------------------===//
2440 // UnaryOp
2441 //===----------------------------------------------------------------------===//
2442
2443 LogicalResult cir::UnaryOp::verify() {
2444 switch (getKind()) {
2445 case cir::UnaryOpKind::Inc:
2446 case cir::UnaryOpKind::Dec:
2447 case cir::UnaryOpKind::Plus:
2448 case cir::UnaryOpKind::Minus:
2449 case cir::UnaryOpKind::Not:
2450 // Nothing to verify.
2451 return success();
2452 }
2453
2454 llvm_unreachable("Unknown UnaryOp kind?");
2455 }
2456
2457 static bool isBoolNot(cir::UnaryOp op) {
2458 return isa<cir::BoolType>(op.getInput().getType()) &&
2459 op.getKind() == cir::UnaryOpKind::Not;
2460 }
2461
2462 // This folder simplifies the sequential boolean not operations.
2463 // For instance, the next two unary operations will be eliminated:
2464 //
2465 // ```mlir
2466 // %1 = cir.unary(not, %0) : !cir.bool, !cir.bool
2467 // %2 = cir.unary(not, %1) : !cir.bool, !cir.bool
2468 // ```
2469 //
2470 // and the argument of the first one (%0) will be used instead.
2471 OpFoldResult cir::UnaryOp::fold(FoldAdaptor adaptor) {
2472 if (auto poison =
2473 mlir::dyn_cast_if_present<cir::PoisonAttr>(adaptor.getInput())) {
2474 // Propagate poison values
2475 return poison;
2476 }
2477
2478 if (isBoolNot(*this))
2479 if (auto previous = getInput().getDefiningOp<cir::UnaryOp>())
2480 if (isBoolNot(previous))
2481 return previous.getInput();
2482
2483 // Avoid introducing unnecessary duplicate constants in cases where we are
2484 // just folding the operation to its input value. If we return the
2485 // input attribute from the adapter, a new constant is materialized, but
2486 // if we return the input value directly, it avoids that.
2487 if (auto srcConst = getInput().getDefiningOp<cir::ConstantOp>()) {
2488 if (getKind() == cir::UnaryOpKind::Plus ||
2489 (mlir::isa<cir::BoolType>(srcConst.getType()) &&
2490 getKind() == cir::UnaryOpKind::Minus))
2491 return srcConst.getResult();
2492 }
2493
2494 // Fold unary operations with constant inputs. If the input is a ConstantOp,
2495 // it "folds" to its value attribute. If it was some other operation that
2496 // was folded, it will be an mlir::Attribute that hasn't yet been
2497 // materialized. If it was a value that couldn't be folded, it will be null.
2498 if (mlir::Attribute attr = adaptor.getInput()) {
2499 // For now, we only attempt to fold simple scalar values.
2500 OpFoldResult result =
2501 llvm::TypeSwitch<mlir::Attribute, OpFoldResult>(attr)
2502 .Case<cir::IntAttr>([&](cir::IntAttr attrT) {
2503 switch (getKind()) {
2504 case cir::UnaryOpKind::Not: {
2505 APInt val = attrT.getValue();
2506 val.flipAllBits();
2507 return cir::IntAttr::get(getType(), val);
2508 }
2509 case cir::UnaryOpKind::Plus:
2510 return attrT;
2511 case cir::UnaryOpKind::Minus: {
2512 APInt val = attrT.getValue();
2513 val.negate();
2514 return cir::IntAttr::get(getType(), val);
2515 }
2516 default:
2517 return cir::IntAttr{};
2518 }
2519 })
2520 .Case<cir::FPAttr>([&](cir::FPAttr attrT) {
2521 switch (getKind()) {
2522 case cir::UnaryOpKind::Plus:
2523 return attrT;
2524 case cir::UnaryOpKind::Minus: {
2525 APFloat val = attrT.getValue();
2526 val.changeSign();
2527 return cir::FPAttr::get(getType(), val);
2528 }
2529 default:
2530 return cir::FPAttr{};
2531 }
2532 })
2533 .Case<cir::BoolAttr>([&](cir::BoolAttr attrT) {
2534 switch (getKind()) {
2535 case cir::UnaryOpKind::Not:
2536 return cir::BoolAttr::get(getContext(), !attrT.getValue());
2537 case cir::UnaryOpKind::Plus:
2538 case cir::UnaryOpKind::Minus:
2539 return attrT;
2540 default:
2541 return cir::BoolAttr{};
2542 }
2543 })
2544 .Default([&](auto attrT) { return mlir::Attribute{}; });
2545 if (result)
2546 return result;
2547 }
2548
2549 return {};
2550 }
2551
2552 //===----------------------------------------------------------------------===//
2553 // BaseDataMemberOp & DerivedDataMemberOp
2554 //===----------------------------------------------------------------------===//
2555
2556 static LogicalResult verifyMemberPtrCast(Operation *op, mlir::Value src,
2557 mlir::Type resultTy) {
2558 // Let the operand type be T1 C1::*, let the result type be T2 C2::*.
2559 // Verify that T1 and T2 are the same type.
2560 mlir::Type inputMemberTy;
2561 mlir::Type resultMemberTy;
2562 if (mlir::isa<cir::DataMemberType>(src.getType())) {
2563 inputMemberTy =
2564 mlir::cast<cir::DataMemberType>(src.getType()).getMemberTy();
2565 resultMemberTy = mlir::cast<cir::DataMemberType>(resultTy).getMemberTy();
2566 }
2567 assert(!cir::MissingFeatures::memberFuncPtrCast());
2568 if (inputMemberTy != resultMemberTy)
2569 return op->emitOpError()
2570 << "member types of the operand and the result do not match";
2571
2572 return mlir::success();
2573 }
2574
2575 LogicalResult cir::BaseDataMemberOp::verify() {
2576 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
2577 }
2578
2579 LogicalResult cir::DerivedDataMemberOp::verify() {
2580 return verifyMemberPtrCast(getOperation(), getSrc(), getType());
2581 }
2582
2583 //===----------------------------------------------------------------------===//
2584 // AwaitOp
2585 //===----------------------------------------------------------------------===//
2586
2587 void cir::AwaitOp::build(OpBuilder &builder, OperationState &result,
2588 cir::AwaitKind kind, BuilderCallbackRef readyBuilder,
2589 BuilderCallbackRef suspendBuilder,
2590 BuilderCallbackRef resumeBuilder) {
2591 result.addAttribute(getKindAttrName(result.name),
2592 cir::AwaitKindAttr::get(builder.getContext(), kind));
2593 {
2594 OpBuilder::InsertionGuard guard(builder);
2595 Region *readyRegion = result.addRegion();
2596 builder.createBlock(readyRegion);
2597 readyBuilder(builder, result.location);
2598 }
2599
2600 {
2601 OpBuilder::InsertionGuard guard(builder);
2602 Region *suspendRegion = result.addRegion();
2603 builder.createBlock(suspendRegion);
2604 suspendBuilder(builder, result.location);
2605 }
2606
2607 {
2608 OpBuilder::InsertionGuard guard(builder);
2609 Region *resumeRegion = result.addRegion();
2610 builder.createBlock(resumeRegion);
2611 resumeBuilder(builder, result.location);
2612 }
2613 }
2614
2615 void cir::AwaitOp::getSuccessorRegions(
2616 mlir::RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
2617 // If any index all the underlying regions branch back to the parent
2618 // operation.
2619 if (!point.isParent()) {
2620 regions.push_back(
2621 RegionSuccessor(getOperation(), getOperation()->getResults()));
2622 return;
2623 }
2624
2625 // TODO: retrieve information from the promise and only push the
2626 // necessary ones. Example: `std::suspend_never` on initial or final
2627 // await's might allow suspend region to be skipped.
2628 regions.push_back(RegionSuccessor(&this->getReady()));
2629 regions.push_back(RegionSuccessor(&this->getSuspend()));
2630 regions.push_back(RegionSuccessor(&this->getResume()));
2631 }
2632
2633 LogicalResult cir::AwaitOp::verify() {
2634 if (!isa<ConditionOp>(this->getReady().back().getTerminator()))
2635 return emitOpError("ready region must end with cir.condition");
2636 return success();
2637 }
2638
2639 //===----------------------------------------------------------------------===//
2640 // CopyOp Definitions
2641 //===----------------------------------------------------------------------===//
2642
2643 LogicalResult cir::CopyOp::verify() {
2644 // A data layout is required for us to know the number of bytes to be copied.
2645 if (!getType().getPointee().hasTrait<DataLayoutTypeInterface::Trait>())
2646 return emitError() << "missing data layout for pointee type";
2647
2648 if (getSrc() == getDst())
2649 return emitError() << "source and destination are the same";
2650
2651 return mlir::success();
2652 }
2653
2654 //===----------------------------------------------------------------------===//
2655 // GetRuntimeMemberOp Definitions
2656 //===----------------------------------------------------------------------===//
2657
2658 LogicalResult cir::GetRuntimeMemberOp::verify() {
2659 auto recordTy = mlir::cast<RecordType>(getAddr().getType().getPointee());
2660 cir::DataMemberType memberPtrTy = getMember().getType();
2661
2662 if (recordTy != memberPtrTy.getClassTy())
2663 return emitError() << "record type does not match the member pointer type";
2664 if (getType().getPointee() != memberPtrTy.getMemberTy())
2665 return emitError() << "result type does not match the member pointer type";
2666 return mlir::success();
2667 }
2668
2669 //===----------------------------------------------------------------------===//
2670 // GetMemberOp Definitions
2671 //===----------------------------------------------------------------------===//
2672
2673 LogicalResult cir::GetMemberOp::verify() {
2674 const auto recordTy = dyn_cast<RecordType>(getAddrTy().getPointee());
2675 if (!recordTy)
2676 return emitError() << "expected pointer to a record type";
2677
2678 if (recordTy.getMembers().size() <= getIndex())
2679 return emitError() << "member index out of bounds";
2680
2681 if (recordTy.getMembers()[getIndex()] != getType().getPointee())
2682 return emitError() << "member type mismatch";
2683
2684 return mlir::success();
2685 }
2686
2687 //===----------------------------------------------------------------------===//
2688 // ExtractMemberOp Definitions
2689 //===----------------------------------------------------------------------===//
2690
2691 LogicalResult cir::ExtractMemberOp::verify() {
2692 auto recordTy = mlir::cast<cir::RecordType>(getRecord().getType());
2693 if (recordTy.getKind() == cir::RecordType::Union)
2694 return emitError()
2695 << "cir.extract_member currently does not support unions";
2696 if (recordTy.getMembers().size() <= getIndex())
2697 return emitError() << "member index out of bounds";
2698 if (recordTy.getMembers()[getIndex()] != getType())
2699 return emitError() << "member type mismatch";
2700 return mlir::success();
2701 }
2702
2703 //===----------------------------------------------------------------------===//
2704 // VecCreateOp
2705 //===----------------------------------------------------------------------===//
2706
2707 OpFoldResult cir::VecCreateOp::fold(FoldAdaptor adaptor) {
2708 if (llvm::any_of(getElements(), [](mlir::Value value) {
2709 return !value.getDefiningOp<cir::ConstantOp>();
2710 }))
2711 return {};
2712
2713 return cir::ConstVectorAttr::get(
2714 getType(), mlir::ArrayAttr::get(getContext(), adaptor.getElements()));
2715 }
2716
2717 LogicalResult cir::VecCreateOp::verify() {
2718 // Verify that the number of arguments matches the number of elements in the
2719 // vector, and that the type of all the arguments matches the type of the
2720 // elements in the vector.
2721 const cir::VectorType vecTy = getType();
2722 if (getElements().size() != vecTy.getSize()) {
2723 return emitOpError() << "operand count of " << getElements().size()
2724 << " doesn't match vector type " << vecTy
2725 << " element count of " << vecTy.getSize();
2726 }
2727
2728 const mlir::Type elementType = vecTy.getElementType();
2729 for (const mlir::Value element : getElements()) {
2730 if (element.getType() != elementType) {
2731 return emitOpError() << "operand type " << element.getType()
2732 << " doesn't match vector element type "
2733 << elementType;
2734 }
2735 }
2736
2737 return success();
2738 }
2739
2740 //===----------------------------------------------------------------------===//
2741 // VecExtractOp
2742 //===----------------------------------------------------------------------===//
2743
2744 OpFoldResult cir::VecExtractOp::fold(FoldAdaptor adaptor) {
2745 const auto vectorAttr =
2746 llvm::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec());
2747 if (!vectorAttr)
2748 return {};
2749
2750 const auto indexAttr =
2751 llvm::dyn_cast_if_present<cir::IntAttr>(adaptor.getIndex());
2752 if (!indexAttr)
2753 return {};
2754
2755 const mlir::ArrayAttr elements = vectorAttr.getElts();
2756 const uint64_t index = indexAttr.getUInt();
2757 if (index >= elements.size())
2758 return {};
2759
2760 return elements[index];
2761 }
2762
2763 //===----------------------------------------------------------------------===//
2764 // VecCmpOp
2765 //===----------------------------------------------------------------------===//
2766
2767 OpFoldResult cir::VecCmpOp::fold(FoldAdaptor adaptor) {
2768 auto lhsVecAttr =
2769 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getLhs());
2770 auto rhsVecAttr =
2771 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getRhs());
2772 if (!lhsVecAttr || !rhsVecAttr)
2773 return {};
2774
2775 mlir::Type inputElemTy =
2776 mlir::cast<cir::VectorType>(lhsVecAttr.getType()).getElementType();
2777 if (!isAnyIntegerOrFloatingPointType(inputElemTy))
2778 return {};
2779
2780 cir::CmpOpKind opKind = adaptor.getKind();
2781 mlir::ArrayAttr lhsVecElhs = lhsVecAttr.getElts();
2782 mlir::ArrayAttr rhsVecElhs = rhsVecAttr.getElts();
2783 uint64_t vecSize = lhsVecElhs.size();
2784
2785 SmallVector<mlir::Attribute, 16> elements(vecSize);
2786 bool isIntAttr = vecSize && mlir::isa<cir::IntAttr>(lhsVecElhs[0]);
2787 for (uint64_t i = 0; i < vecSize; i++) {
2788 mlir::Attribute lhsAttr = lhsVecElhs[i];
2789 mlir::Attribute rhsAttr = rhsVecElhs[i];
2790 int cmpResult = 0;
2791 switch (opKind) {
2792 case cir::CmpOpKind::lt: {
2793 if (isIntAttr) {
2794 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <
2795 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2796 } else {
2797 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <
2798 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2799 }
2800 break;
2801 }
2802 case cir::CmpOpKind::le: {
2803 if (isIntAttr) {
2804 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() <=
2805 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2806 } else {
2807 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() <=
2808 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2809 }
2810 break;
2811 }
2812 case cir::CmpOpKind::gt: {
2813 if (isIntAttr) {
2814 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >
2815 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2816 } else {
2817 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >
2818 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2819 }
2820 break;
2821 }
2822 case cir::CmpOpKind::ge: {
2823 if (isIntAttr) {
2824 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() >=
2825 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2826 } else {
2827 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() >=
2828 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2829 }
2830 break;
2831 }
2832 case cir::CmpOpKind::eq: {
2833 if (isIntAttr) {
2834 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() ==
2835 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2836 } else {
2837 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() ==
2838 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2839 }
2840 break;
2841 }
2842 case cir::CmpOpKind::ne: {
2843 if (isIntAttr) {
2844 cmpResult = mlir::cast<cir::IntAttr>(lhsAttr).getSInt() !=
2845 mlir::cast<cir::IntAttr>(rhsAttr).getSInt();
2846 } else {
2847 cmpResult = mlir::cast<cir::FPAttr>(lhsAttr).getValue() !=
2848 mlir::cast<cir::FPAttr>(rhsAttr).getValue();
2849 }
2850 break;
2851 }
2852 }
2853
2854 elements[i] = cir::IntAttr::get(getType().getElementType(), cmpResult);
2855 }
2856
2857 return cir::ConstVectorAttr::get(
2858 getType(), mlir::ArrayAttr::get(getContext(), elements));
2859 }
2860
2861 //===----------------------------------------------------------------------===//
2862 // VecShuffleOp
2863 //===----------------------------------------------------------------------===//
2864
2865 OpFoldResult cir::VecShuffleOp::fold(FoldAdaptor adaptor) {
2866 auto vec1Attr =
2867 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec1());
2868 auto vec2Attr =
2869 mlir::dyn_cast_if_present<cir::ConstVectorAttr>(adaptor.getVec2());
2870 if (!vec1Attr || !vec2Attr)
2871 return {};
2872
2873 mlir::Type vec1ElemTy =
2874 mlir::cast<cir::VectorType>(vec1Attr.getType()).getElementType();
2875
2876 mlir::ArrayAttr vec1Elts = vec1Attr.getElts();
2877 mlir::ArrayAttr vec2Elts = vec2Attr.getElts();
2878 mlir::ArrayAttr indicesElts = adaptor.getIndices();
2879
2880 SmallVector<mlir::Attribute, 16> elements;
2881 elements.reserve(indicesElts.size());
2882
2883 uint64_t vec1Size = vec1Elts.size();
2884 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2885 if (idxAttr.getSInt() == -1) {
2886 elements.push_back(cir::UndefAttr::get(vec1ElemTy));
2887 continue;
2888 }
2889
2890 uint64_t idxValue = idxAttr.getUInt();
2891 elements.push_back(idxValue < vec1Size ? vec1Elts[idxValue]
2892 : vec2Elts[idxValue - vec1Size]);
2893 }
2894
2895 return cir::ConstVectorAttr::get(
2896 getType(), mlir::ArrayAttr::get(getContext(), elements));
2897 }
2898
2899 LogicalResult cir::VecShuffleOp::verify() {
2900 // The number of elements in the indices array must match the number of
2901 // elements in the result type.
2902 if (getIndices().size() != getResult().getType().getSize()) {
2903 return emitOpError() << ": the number of elements in " << getIndices()
2904 << " and " << getResult().getType() << " don't match";
2905 }
2906
2907 // The element types of the two input vectors and of the result type must
2908 // match.
2909 if (getVec1().getType().getElementType() !=
2910 getResult().getType().getElementType()) {
2911 return emitOpError() << ": element types of " << getVec1().getType()
2912 << " and " << getResult().getType() << " don't match";
2913 }
2914
2915 const uint64_t maxValidIndex =
2916 getVec1().getType().getSize() + getVec2().getType().getSize() - 1;
2917 if (llvm::any_of(
2918 getIndices().getAsRange<cir::IntAttr>(), [&](cir::IntAttr idxAttr) {
2919 return idxAttr.getSInt() != -1 && idxAttr.getUInt() > maxValidIndex;
2920 })) {
2921 return emitOpError() << ": index for __builtin_shufflevector must be "
2922 "less than the total number of vector elements";
2923 }
2924 return success();
2925 }
2926
2927 //===----------------------------------------------------------------------===//
2928 // VecShuffleDynamicOp
2929 //===----------------------------------------------------------------------===//
2930
2931 OpFoldResult cir::VecShuffleDynamicOp::fold(FoldAdaptor adaptor) {
2932 mlir::Attribute vec = adaptor.getVec();
2933 mlir::Attribute indices = adaptor.getIndices();
2934 if (mlir::isa_and_nonnull<cir::ConstVectorAttr>(vec) &&
2935 mlir::isa_and_nonnull<cir::ConstVectorAttr>(indices)) {
2936 auto vecAttr = mlir::cast<cir::ConstVectorAttr>(vec);
2937 auto indicesAttr = mlir::cast<cir::ConstVectorAttr>(indices);
2938
2939 mlir::ArrayAttr vecElts = vecAttr.getElts();
2940 mlir::ArrayAttr indicesElts = indicesAttr.getElts();
2941
2942 const uint64_t numElements = vecElts.size();
2943
2944 SmallVector<mlir::Attribute, 16> elements;
2945 elements.reserve(numElements);
2946
2947 const uint64_t maskBits = llvm::NextPowerOf2(numElements - 1) - 1;
2948 for (const auto &idxAttr : indicesElts.getAsRange<cir::IntAttr>()) {
2949 uint64_t idxValue = idxAttr.getUInt();
2950 uint64_t newIdx = idxValue & maskBits;
2951 elements.push_back(vecElts[newIdx]);
2952 }
2953
2954 return cir::ConstVectorAttr::get(
2955 getType(), mlir::ArrayAttr::get(getContext(), elements));
2956 }
2957
2958 return {};
2959 }
2960
2961 LogicalResult cir::VecShuffleDynamicOp::verify() {
2962 // The number of elements in the two input vectors must match.
2963 if (getVec().getType().getSize() !=
2964 mlir::cast<cir::VectorType>(getIndices().getType()).getSize()) {
2965 return emitOpError() << ": the number of elements in " << getVec().getType()
2966 << " and " << getIndices().getType() << " don't match";
2967 }
2968 return success();
2969 }
2970
2971 //===----------------------------------------------------------------------===//
2972 // VecTernaryOp
2973 //===----------------------------------------------------------------------===//
2974
2975 LogicalResult cir::VecTernaryOp::verify() {
2976 // Verify that the condition operand has the same number of elements as the
2977 // other operands. (The automatic verification already checked that all
2978 // operands are vector types and that the second and third operands are the
2979 // same type.)
2980 if (getCond().getType().getSize() != getLhs().getType().getSize()) {
2981 return emitOpError() << ": the number of elements in "
2982 << getCond().getType() << " and " << getLhs().getType()
2983 << " don't match";
2984 }
2985 return success();
2986 }
2987
2988 OpFoldResult cir::VecTernaryOp::fold(FoldAdaptor adaptor) {
2989 mlir::Attribute cond = adaptor.getCond();
2990 mlir::Attribute lhs = adaptor.getLhs();
2991 mlir::Attribute rhs = adaptor.getRhs();
2992
2993 if (!mlir::isa_and_nonnull<cir::ConstVectorAttr>(cond) ||
2994 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(lhs) ||
2995 !mlir::isa_and_nonnull<cir::ConstVectorAttr>(rhs))
2996 return {};
2997 auto condVec = mlir::cast<cir::ConstVectorAttr>(cond);
2998 auto lhsVec = mlir::cast<cir::ConstVectorAttr>(lhs);
2999 auto rhsVec = mlir::cast<cir::ConstVectorAttr>(rhs);
3000
3001 mlir::ArrayAttr condElts = condVec.getElts();
3002
3003 SmallVector<mlir::Attribute, 16> elements;
3004 elements.reserve(condElts.size());
3005
3006 for (const auto &[idx, condAttr] :
3007 llvm::enumerate(condElts.getAsRange<cir::IntAttr>())) {
3008 if (condAttr.getSInt()) {
3009 elements.push_back(lhsVec.getElts()[idx]);
3010 } else {
3011 elements.push_back(rhsVec.getElts()[idx]);
3012 }
3013 }
3014
3015 cir::VectorType vecTy = getLhs().getType();
3016 return cir::ConstVectorAttr::get(
3017 vecTy, mlir::ArrayAttr::get(getContext(), elements));
3018 }
3019
3020 //===----------------------------------------------------------------------===//
3021 // ComplexCreateOp
3022 //===----------------------------------------------------------------------===//
3023
3024 LogicalResult cir::ComplexCreateOp::verify() {
3025 if (getType().getElementType() != getReal().getType()) {
3026 emitOpError()
3027 << "operand type of cir.complex.create does not match its result type";
3028 return failure();
3029 }
3030
3031 return success();
3032 }
3033
3034 OpFoldResult cir::ComplexCreateOp::fold(FoldAdaptor adaptor) {
3035 mlir::Attribute real = adaptor.getReal();
3036 mlir::Attribute imag = adaptor.getImag();
3037 if (!real || !imag)
3038 return {};
3039
3040 // When both of real and imag are constants, we can fold the operation into an
3041 // `#cir.const_complex` operation.
3042 auto realAttr = mlir::cast<mlir::TypedAttr>(real);
3043 auto imagAttr = mlir::cast<mlir::TypedAttr>(imag);
3044 return cir::ConstComplexAttr::get(realAttr, imagAttr);
3045 }
3046
3047 //===----------------------------------------------------------------------===//
3048 // ComplexRealOp
3049 //===----------------------------------------------------------------------===//
3050
3051 LogicalResult cir::ComplexRealOp::verify() {
3052 mlir::Type operandTy = getOperand().getType();
3053 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3054 operandTy = complexOperandTy.getElementType();
3055
3056 if (getType() != operandTy) {
3057 emitOpError() << ": result type does not match operand type";
3058 return failure();
3059 }
3060
3061 return success();
3062 }
3063
3064 OpFoldResult cir::ComplexRealOp::fold(FoldAdaptor adaptor) {
3065 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
3066 return nullptr;
3067
3068 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3069 return complexCreateOp.getOperand(0);
3070
3071 auto complex =
3072 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3073 return complex ? complex.getReal() : nullptr;
3074 }
3075
3076 //===----------------------------------------------------------------------===//
3077 // ComplexImagOp
3078 //===----------------------------------------------------------------------===//
3079
3080 LogicalResult cir::ComplexImagOp::verify() {
3081 mlir::Type operandTy = getOperand().getType();
3082 if (auto complexOperandTy = mlir::dyn_cast<cir::ComplexType>(operandTy))
3083 operandTy = complexOperandTy.getElementType();
3084
3085 if (getType() != operandTy) {
3086 emitOpError() << ": result type does not match operand type";
3087 return failure();
3088 }
3089
3090 return success();
3091 }
3092
3093 OpFoldResult cir::ComplexImagOp::fold(FoldAdaptor adaptor) {
3094 if (!mlir::isa<cir::ComplexType>(getOperand().getType()))
3095 return nullptr;
3096
3097 if (auto complexCreateOp = getOperand().getDefiningOp<cir::ComplexCreateOp>())
3098 return complexCreateOp.getOperand(1);
3099
3100 auto complex =
3101 mlir::cast_if_present<cir::ConstComplexAttr>(adaptor.getOperand());
3102 return complex ? complex.getImag() : nullptr;
3103 }
3104
3105 //===----------------------------------------------------------------------===//
3106 // ComplexRealPtrOp
3107 //===----------------------------------------------------------------------===//
3108
3109 LogicalResult cir::ComplexRealPtrOp::verify() {
3110 mlir::Type resultPointeeTy = getType().getPointee();
3111 cir::PointerType operandPtrTy = getOperand().getType();
3112 auto operandPointeeTy =
3113 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3114
3115 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3116 return emitOpError() << ": result type does not match operand type";
3117 }
3118
3119 return success();
3120 }
3121
3122 //===----------------------------------------------------------------------===//
3123 // ComplexImagPtrOp
3124 //===----------------------------------------------------------------------===//
3125
3126 LogicalResult cir::ComplexImagPtrOp::verify() {
3127 mlir::Type resultPointeeTy = getType().getPointee();
3128 cir::PointerType operandPtrTy = getOperand().getType();
3129 auto operandPointeeTy =
3130 mlir::cast<cir::ComplexType>(operandPtrTy.getPointee());
3131
3132 if (resultPointeeTy != operandPointeeTy.getElementType()) {
3133 return emitOpError()
3134 << "cir.complex.imag_ptr result type does not match operand type";
3135 }
3136 return success();
3137 }
3138
3139 //===----------------------------------------------------------------------===//
3140 // Bit manipulation operations
3141 //===----------------------------------------------------------------------===//
3142
3143 static OpFoldResult
3144 foldUnaryBitOp(mlir::Attribute inputAttr,
3145 llvm::function_ref<llvm::APInt(const llvm::APInt &)> func,
3146 bool poisonZero = false) {
3147 if (mlir::isa_and_present<cir::PoisonAttr>(inputAttr)) {
3148 // Propagate poison value
3149 return inputAttr;
3150 }
3151
3152 auto input = mlir::dyn_cast_if_present<IntAttr>(inputAttr);
3153 if (!input)
3154 return nullptr;
3155
3156 llvm::APInt inputValue = input.getValue();
3157 if (poisonZero && inputValue.isZero())
3158 return cir::PoisonAttr::get(input.getType());
3159
3160 llvm::APInt resultValue = func(inputValue);
3161 return IntAttr::get(input.getType(), resultValue);
3162 }
3163
3164 OpFoldResult BitClrsbOp::fold(FoldAdaptor adaptor) {
3165 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
3166 unsigned resultValue =
3167 inputValue.getBitWidth() - inputValue.getSignificantBits();
3168 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3169 });
3170 }
3171
3172 OpFoldResult BitClzOp::fold(FoldAdaptor adaptor) {
3173 return foldUnaryBitOp(
3174 adaptor.getInput(),
3175 [](const llvm::APInt &inputValue) {
3176 unsigned resultValue = inputValue.countLeadingZeros();
3177 return llvm::APInt(inputValue.getBitWidth(), resultValue);
3178 },
3179 getPoisonZero());
3180 }
3181
3182 OpFoldResult BitCtzOp::fold(FoldAdaptor adaptor) {
3183 return foldUnaryBitOp(
3184 adaptor.getInput(),
3185 [](const llvm::APInt &inputValue) {
3186 return llvm::APInt(inputValue.getBitWidth(),
3187 inputValue.countTrailingZeros());
3188 },
3189 getPoisonZero());
3190 }
3191
3192 OpFoldResult BitFfsOp::fold(FoldAdaptor adaptor) {
3193 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
3194 unsigned trailingZeros = inputValue.countTrailingZeros();
3195 unsigned result =
3196 trailingZeros == inputValue.getBitWidth() ? 0 : trailingZeros + 1;
3197 return llvm::APInt(inputValue.getBitWidth(), result);
3198 });
3199 }
3200
3201 OpFoldResult BitParityOp::fold(FoldAdaptor adaptor) {
3202 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
3203 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount() % 2);
3204 });
3205 }
3206
3207 OpFoldResult BitPopcountOp::fold(FoldAdaptor adaptor) {
3208 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
3209 return llvm::APInt(inputValue.getBitWidth(), inputValue.popcount());
3210 });
3211 }
3212
3213 OpFoldResult BitReverseOp::fold(FoldAdaptor adaptor) {
3214 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
3215 return inputValue.reverseBits();
3216 });
3217 }
3218
3219 OpFoldResult ByteSwapOp::fold(FoldAdaptor adaptor) {
3220 return foldUnaryBitOp(adaptor.getInput(), [](const llvm::APInt &inputValue) {
3221 return inputValue.byteSwap();
3222 });
3223 }
3224
3225 OpFoldResult RotateOp::fold(FoldAdaptor adaptor) {
3226 if (mlir::isa_and_present<cir::PoisonAttr>(adaptor.getInput()) ||
3227 mlir::isa_and_present<cir::PoisonAttr>(adaptor.getAmount())) {
3228 // Propagate poison values
3229 return cir::PoisonAttr::get(getType());
3230 }
3231
3232 auto input = mlir::dyn_cast_if_present<IntAttr>(adaptor.getInput());
3233 auto amount = mlir::dyn_cast_if_present<IntAttr>(adaptor.getAmount());
3234 if (!input && !amount)
3235 return nullptr;
3236
3237 // We could fold cir.rotate even if one of its two operands is not a constant:
3238 // - `cir.rotate left/right %0, 0` could be folded into just %0 even if %0
3239 // is not a constant.
3240 // - `cir.rotate left/right 0/0b111...111, %0` could be folded into 0 or
3241 // 0b111...111 even if %0 is not a constant.
3242
3243 llvm::APInt inputValue;
3244 if (input) {
3245 inputValue = input.getValue();
3246 if (inputValue.isZero() || inputValue.isAllOnes()) {
3247 // An input value of all 0s or all 1s will not change after rotation
3248 return input;
3249 }
3250 }
3251
3252 uint64_t amountValue;
3253 if (amount) {
3254 amountValue = amount.getValue().urem(getInput().getType().getWidth());
3255 if (amountValue == 0) {
3256 // A shift amount of 0 will not change the input value
3257 return getInput();
3258 }
3259 }
3260
3261 if (!input || !amount)
3262 return nullptr;
3263
3264 assert(inputValue.getBitWidth() == getInput().getType().getWidth() &&
3265 "input value must have the same bit width as the input type");
3266
3267 llvm::APInt resultValue;
3268 if (isRotateLeft())
3269 resultValue = inputValue.rotl(amountValue);
3270 else
3271 resultValue = inputValue.rotr(amountValue);
3272
3273 return IntAttr::get(input.getContext(), input.getType(), resultValue);
3274 }
3275
3276 //===----------------------------------------------------------------------===//
3277 // InlineAsmOp
3278 //===----------------------------------------------------------------------===//
3279
3280 void cir::InlineAsmOp::print(OpAsmPrinter &p) {
3281 p << '(' << getAsmFlavor() << ", ";
3282 p.increaseIndent();
3283 p.printNewline();
3284
3285 llvm::SmallVector<std::string, 3> names{"out", "in", "in_out"};
3286 auto *nameIt = names.begin();
3287 auto *attrIt = getOperandAttrs().begin();
3288
3289 for (mlir::OperandRange ops : getAsmOperands()) {
3290 p << *nameIt << " = ";
3291
3292 p << '[';
3293 llvm::interleaveComma(llvm::make_range(ops.begin(), ops.end()), p,
3294 [&](Value value) {
3295 p.printOperand(value);
3296 p << " : " << value.getType();
3297 if (*attrIt)
3298 p << " (maybe_memory)";
3299 attrIt++;
3300 });
3301 p << "],";
3302 p.printNewline();
3303 ++nameIt;
3304 }
3305
3306 p << "{";
3307 p.printString(getAsmString());
3308 p << " ";
3309 p.printString(getConstraints());
3310 p << "}";
3311 p.decreaseIndent();
3312 p << ')';
3313 if (getSideEffects())
3314 p << " side_effects";
3315
3316 std::array elidedAttrs{
3317 llvm::StringRef("asm_flavor"), llvm::StringRef("asm_string"),
3318 llvm::StringRef("constraints"), llvm::StringRef("operand_attrs"),
3319 llvm::StringRef("operands_segments"), llvm::StringRef("side_effects")};
3320 p.printOptionalAttrDict(getOperation()->getAttrs(), elidedAttrs);
3321
3322 if (auto v = getRes())
3323 p << " -> " << v.getType();
3324 }
3325
3326 void cir::InlineAsmOp::build(OpBuilder &odsBuilder, OperationState &odsState,
3327 ArrayRef<ValueRange> asmOperands,
3328 StringRef asmString, StringRef constraints,
3329 bool sideEffects, cir::AsmFlavor asmFlavor,
3330 ArrayRef<Attribute> operandAttrs) {
3331 // Set up the operands_segments for VariadicOfVariadic
3332 SmallVector<int32_t> segments;
3333 for (auto operandRange : asmOperands) {
3334 segments.push_back(operandRange.size());
3335 odsState.addOperands(operandRange);
3336 }
3337
3338 odsState.addAttribute(
3339 "operands_segments",
3340 DenseI32ArrayAttr::get(odsBuilder.getContext(), segments));
3341 odsState.addAttribute("asm_string", odsBuilder.getStringAttr(asmString));
3342 odsState.addAttribute("constraints", odsBuilder.getStringAttr(constraints));
3343 odsState.addAttribute("asm_flavor",
3344 AsmFlavorAttr::get(odsBuilder.getContext(), asmFlavor));
3345
3346 if (sideEffects)
3347 odsState.addAttribute("side_effects", odsBuilder.getUnitAttr());
3348
3349 odsState.addAttribute("operand_attrs", odsBuilder.getArrayAttr(operandAttrs));
3350 }
3351
3352 ParseResult cir::InlineAsmOp::parse(OpAsmParser &parser,
3353 OperationState &result) {
3354 llvm::SmallVector<mlir::Attribute> operandAttrs;
3355 llvm::SmallVector<int32_t> operandsGroupSizes;
3356 std::string asmString, constraints;
3357 Type resType;
3358 MLIRContext *ctxt = parser.getBuilder().getContext();
3359
3360 auto error = [&](const Twine &msg) -> LogicalResult {
3361 return parser.emitError(parser.getCurrentLocation(), msg);
3362 };
3363
3364 auto expected = [&](const std::string &c) {
3365 return error("expected '" + c + "'");
3366 };
3367
3368 if (parser.parseLParen().failed())
3369 return expected("(");
3370
3371 auto flavor = FieldParser<AsmFlavor, AsmFlavor>::parse(parser);
3372 if (failed(flavor))
3373 return error("Unknown AsmFlavor");
3374
3375 if (parser.parseComma().failed())
3376 return expected(",");
3377
3378 auto parseValue = [&](Value &v) {
3379 OpAsmParser::UnresolvedOperand op;
3380
3381 if (parser.parseOperand(op) || parser.parseColon())
3382 return error("can't parse operand");
3383
3384 Type typ;
3385 if (parser.parseType(typ).failed())
3386 return error("can't parse operand type");
3387 llvm::SmallVector<mlir::Value> tmp;
3388 if (parser.resolveOperand(op, typ, tmp))
3389 return error("can't resolve operand");
3390 v = tmp[0];
3391 return mlir::success();
3392 };
3393
3394 auto parseOperands = [&](llvm::StringRef name) {
3395 if (parser.parseKeyword(name).failed())
3396 return error("expected " + name + " operands here");
3397 if (parser.parseEqual().failed())
3398 return expected("=");
3399 if (parser.parseLSquare().failed())
3400 return expected("[");
3401
3402 int size = 0;
3403 if (parser.parseOptionalRSquare().succeeded()) {
3404 operandsGroupSizes.push_back(size);
3405 if (parser.parseComma())
3406 return expected(",");
3407 return mlir::success();
3408 }
3409
3410 auto parseOperand = [&]() {
3411 Value val;
3412 if (parseValue(val).succeeded()) {
3413 result.operands.push_back(val);
3414 size++;
3415
3416 if (parser.parseOptionalLParen().failed()) {
3417 operandAttrs.push_back(mlir::Attribute());
3418 return mlir::success();
3419 }
3420
3421 if (parser.parseKeyword("maybe_memory").succeeded()) {
3422 operandAttrs.push_back(mlir::UnitAttr::get(ctxt));
3423 if (parser.parseRParen())
3424 return expected(")");
3425 return mlir::success();
3426 } else {
3427 return expected("maybe_memory");
3428 }
3429 }
3430 return mlir::failure();
3431 };
3432
3433 if (parser.parseCommaSeparatedList(parseOperand).failed())
3434 return mlir::failure();
3435
3436 if (parser.parseRSquare().failed() || parser.parseComma().failed())
3437 return expected("]");
3438 operandsGroupSizes.push_back(size);
3439 return mlir::success();
3440 };
3441
3442 if (parseOperands("out").failed() || parseOperands("in").failed() ||
3443 parseOperands("in_out").failed())
3444 return error("failed to parse operands");
3445
3446 if (parser.parseLBrace())
3447 return expected("{");
3448 if (parser.parseString(&asmString))
3449 return error("asm string parsing failed");
3450 if (parser.parseString(&constraints))
3451 return error("constraints string parsing failed");
3452 if (parser.parseRBrace())
3453 return expected("}");
3454 if (parser.parseRParen())
3455 return expected(")");
3456
3457 if (parser.parseOptionalKeyword("side_effects").succeeded())
3458 result.attributes.set("side_effects", UnitAttr::get(ctxt));
3459
3460 if (parser.parseOptionalArrow().succeeded() &&
3461 parser.parseType(resType).failed())
3462 return mlir::failure();
3463
3464 if (parser.parseOptionalAttrDict(result.attributes).failed())
3465 return mlir::failure();
3466
3467 result.attributes.set("asm_flavor", AsmFlavorAttr::get(ctxt, *flavor));
3468 result.attributes.set("asm_string", StringAttr::get(ctxt, asmString));
3469 result.attributes.set("constraints", StringAttr::get(ctxt, constraints));
3470 result.attributes.set("operand_attrs", ArrayAttr::get(ctxt, operandAttrs));
3471 result.getOrAddProperties<InlineAsmOp::Properties>().operands_segments =
3472 parser.getBuilder().getDenseI32ArrayAttr(operandsGroupSizes);
3473 if (resType)
3474 result.addTypes(TypeRange{resType});
3475
3476 return mlir::success();
3477 }
3478
3479 //===----------------------------------------------------------------------===//
3480 // ThrowOp
3481 //===----------------------------------------------------------------------===//
3482
3483 mlir::LogicalResult cir::ThrowOp::verify() {
3484 // For the no-rethrow version, it must have at least the exception pointer.
3485 if (rethrows())
3486 return success();
3487
3488 if (getNumOperands() != 0) {
3489 if (getTypeInfo())
3490 return success();
3491 return emitOpError() << "'type_info' symbol attribute missing";
3492 }
3493
3494 return failure();
3495 }
3496
3497 //===----------------------------------------------------------------------===//
3498 // AtomicFetchOp
3499 //===----------------------------------------------------------------------===//
3500
3501 LogicalResult cir::AtomicFetchOp::verify() {
3502 if (getBinop() != cir::AtomicFetchKind::Add &&
3503 getBinop() != cir::AtomicFetchKind::Sub &&
3504 getBinop() != cir::AtomicFetchKind::Max &&
3505 getBinop() != cir::AtomicFetchKind::Min &&
3506 !mlir::isa<cir::IntType>(getVal().getType()))
3507 return emitError("only atomic add, sub, max, and min operation could "
3508 "operate on floating-point values");
3509 return success();
3510 }
3511
3512 //===----------------------------------------------------------------------===//
3513 // TypeInfoAttr
3514 //===----------------------------------------------------------------------===//
3515
3516 LogicalResult cir::TypeInfoAttr::verify(
3517 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
3518 ::mlir::Type type, ::mlir::ArrayAttr typeInfoData) {
3519
3520 if (cir::ConstRecordAttr::verify(emitError, type, typeInfoData).failed())
3521 return failure();
3522
3523 return success();
3524 }
3525
3526 //===----------------------------------------------------------------------===//
3527 // TryOp
3528 //===----------------------------------------------------------------------===//
3529
3530 void cir::TryOp::getSuccessorRegions(
3531 mlir::RegionBranchPoint point,
3532 llvm::SmallVectorImpl<mlir::RegionSuccessor> &regions) {
3533 // The `try` and the `catchers` region branch back to the parent operation.
3534 if (!point.isParent()) {
3535 regions.push_back(
3536 RegionSuccessor(getOperation(), getOperation()->getResults()));
3537 return;
3538 }
3539
3540 regions.push_back(mlir::RegionSuccessor(&getTryRegion()));
3541
3542 // TODO(CIR): If we know a target function never throws a specific type, we
3543 // can remove the catch handler.
3544 for (mlir::Region &handlerRegion : this->getHandlerRegions())
3545 regions.push_back(mlir::RegionSuccessor(&handlerRegion));
3546 }
3547
3548 static void
3549 printTryHandlerRegions(mlir::OpAsmPrinter &printer, cir::TryOp op,
3550 mlir::MutableArrayRef<mlir::Region> handlerRegions,
3551 mlir::ArrayAttr handlerTypes) {
3552 if (!handlerTypes)
3553 return;
3554
3555 for (const auto [typeIdx, typeAttr] : llvm::enumerate(handlerTypes)) {
3556 if (typeIdx)
3557 printer << " ";
3558
3559 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
3560 printer << "catch all ";
3561 } else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
3562 printer << "unwind ";
3563 } else {
3564 printer << "catch [type ";
3565 printer.printAttribute(typeAttr);
3566 printer << "] ";
3567 }
3568
3569 printer.printRegion(handlerRegions[typeIdx],
3570 /*printEntryBLockArgs=*/false,
3571 /*printBlockTerminators=*/true);
3572 }
3573 }
3574
3575 static mlir::ParseResult parseTryHandlerRegions(
3576 mlir::OpAsmParser &parser,
3577 llvm::SmallVectorImpl<std::unique_ptr<mlir::Region>> &handlerRegions,
3578 mlir::ArrayAttr &handlerTypes) {
3579
3580 auto parseCheckedCatcherRegion = [&]() -> mlir::ParseResult {
3581 handlerRegions.emplace_back(new mlir::Region);
3582
3583 mlir::Region &currRegion = *handlerRegions.back();
3584 mlir::SMLoc regionLoc = parser.getCurrentLocation();
3585 if (parser.parseRegion(currRegion)) {
3586 handlerRegions.clear();
3587 return failure();
3588 }
3589
3590 if (currRegion.empty())
3591 return parser.emitError(regionLoc, "handler region shall not be empty");
3592
3593 if (!(currRegion.back().mightHaveTerminator() &&
3594 currRegion.back().getTerminator()))
3595 return parser.emitError(
3596 regionLoc, "blocks are expected to be explicitly terminated");
3597
3598 return success();
3599 };
3600
3601 bool hasCatchAll = false;
3602 llvm::SmallVector<mlir::Attribute, 4> catcherAttrs;
3603 while (parser.parseOptionalKeyword("catch").succeeded()) {
3604 bool hasLSquare = parser.parseOptionalLSquare().succeeded();
3605
3606 llvm::StringRef attrStr;
3607 if (parser.parseOptionalKeyword(&attrStr, {"all", "type"}).failed())
3608 return parser.emitError(parser.getCurrentLocation(),
3609 "expected 'all' or 'type' keyword");
3610
3611 bool isCatchAll = attrStr == "all";
3612 if (isCatchAll) {
3613 if (hasCatchAll)
3614 return parser.emitError(parser.getCurrentLocation(),
3615 "can't have more than one catch all");
3616 hasCatchAll = true;
3617 }
3618
3619 mlir::Attribute exceptionRTTIAttr;
3620 if (!isCatchAll && parser.parseAttribute(exceptionRTTIAttr).failed())
3621 return parser.emitError(parser.getCurrentLocation(),
3622 "expected valid RTTI info attribute");
3623
3624 catcherAttrs.push_back(isCatchAll
3625 ? cir::CatchAllAttr::get(parser.getContext())
3626 : exceptionRTTIAttr);
3627
3628 if (hasLSquare && isCatchAll)
3629 return parser.emitError(parser.getCurrentLocation(),
3630 "catch all dosen't need RTTI info attribute");
3631
3632 if (hasLSquare && parser.parseRSquare().failed())
3633 return parser.emitError(parser.getCurrentLocation(),
3634 "expected `]` after RTTI info attribute");
3635
3636 if (parseCheckedCatcherRegion().failed())
3637 return mlir::failure();
3638 }
3639
3640 if (parser.parseOptionalKeyword("unwind").succeeded()) {
3641 if (hasCatchAll)
3642 return parser.emitError(parser.getCurrentLocation(),
3643 "unwind can't be used with catch all");
3644
3645 catcherAttrs.push_back(cir::UnwindAttr::get(parser.getContext()));
3646 if (parseCheckedCatcherRegion().failed())
3647 return mlir::failure();
3648 }
3649
3650 handlerTypes = parser.getBuilder().getArrayAttr(catcherAttrs);
3651 return mlir::success();
3652 }
3653
3654 //===----------------------------------------------------------------------===//
3655 // EhTypeIdOp
3656 //===----------------------------------------------------------------------===//
3657
3658 LogicalResult
3659 cir::EhTypeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
3660 Operation *op = symbolTable.lookupNearestSymbolFrom(*this, getTypeSymAttr());
3661 if (!isa_and_nonnull<GlobalOp>(op))
3662 return emitOpError("'")
3663 << getTypeSym() << "' does not reference a valid cir.global";
3664 return success();
3665 }
3666
3667 //===----------------------------------------------------------------------===//
3668 // TableGen'd op method definitions
3669 //===----------------------------------------------------------------------===//
3670
3671 #define GET_OP_CLASSES
3672 #include "clang/CIR/Dialect/IR/CIROps.cpp.inc"