clang 24.0.0git
CIRAttrs.cpp
Go to the documentation of this file.
1//===- CIRAttrs.cpp - MLIR CIR Attributes ---------------------------------===//
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 defines the attributes in the CIR dialect.
10//
11//===----------------------------------------------------------------------===//
12
13#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
15
16#include "mlir/IR/Attributes.h"
17#include "mlir/IR/DialectImplementation.h"
18#include "llvm/ADT/TypeSwitch.h"
19
20//===-----------------------------------------------------------------===//
21// RecordMembers
22//===-----------------------------------------------------------------===//
23
24static void printRecordMembers(mlir::AsmPrinter &p, mlir::ArrayAttr members);
25static mlir::ParseResult parseRecordMembers(mlir::AsmParser &parser,
26 mlir::ArrayAttr &members);
27
28//===-----------------------------------------------------------------===//
29// IntLiteral
30//===-----------------------------------------------------------------===//
31
32static void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value,
33 cir::IntTypeInterface ty);
34static mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser,
35 llvm::APInt &value,
36 cir::IntTypeInterface ty);
37//===-----------------------------------------------------------------===//
38// FloatLiteral
39//===-----------------------------------------------------------------===//
40
41static void printFloatLiteral(mlir::AsmPrinter &p, llvm::APFloat value,
42 mlir::Type ty);
43static mlir::ParseResult
44parseFloatLiteral(mlir::AsmParser &parser,
45 mlir::FailureOr<llvm::APFloat> &value,
46 cir::FPTypeInterface fpType);
47
48static mlir::ParseResult parseConstPtr(mlir::AsmParser &parser,
49 mlir::IntegerAttr &value);
50
51static void printConstPtr(mlir::AsmPrinter &p, mlir::IntegerAttr value);
52
53static mlir::ParseResult
54parseDataMemberPath(mlir::AsmParser &parser,
55 mlir::DenseI32ArrayAttr &memberPath);
56
57static void printDataMemberPath(mlir::AsmPrinter &p,
58 mlir::DenseI32ArrayAttr memberPath);
59
60#define GET_ATTRDEF_CLASSES
61#include "clang/CIR/Dialect/IR/CIROpsAttributes.cpp.inc"
62
63using namespace mlir;
64using namespace cir;
65
66//===----------------------------------------------------------------------===//
67// MemorySpaceAttrInterface implementations for Lang and Target address space
68// attributes
69//===----------------------------------------------------------------------===//
70
71bool LangAddressSpaceAttr::isValidLoad(
72 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
73 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
74 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
75 llvm_unreachable("isValidLoad for LangAddressSpaceAttr NYI");
76}
77
78bool LangAddressSpaceAttr::isValidStore(
79 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
80 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
81 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
82 llvm_unreachable("isValidStore for LangAddressSpaceAttr NYI");
83}
84
85bool LangAddressSpaceAttr::isValidAtomicOp(
86 mlir::ptr::AtomicBinOp op, mlir::Type type,
87 mlir::ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
88 const mlir::DataLayout *dataLayout,
89 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
90 llvm_unreachable("isValidAtomicOp for LangAddressSpaceAttr NYI");
91}
92
93bool LangAddressSpaceAttr::isValidAtomicXchg(
94 mlir::Type type, mlir::ptr::AtomicOrdering successOrdering,
95 mlir::ptr::AtomicOrdering failureOrdering, std::optional<int64_t> alignment,
96 const mlir::DataLayout *dataLayout,
97 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
98 llvm_unreachable("isValidAtomicXchg for LangAddressSpaceAttr NYI");
99}
100
101bool LangAddressSpaceAttr::isValidAddrSpaceCast(
102 mlir::Type tgt, mlir::Type src,
103 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
104 llvm_unreachable("isValidAddrSpaceCast for LangAddressSpaceAttr NYI");
105}
106
107bool LangAddressSpaceAttr::isValidPtrIntCast(
108 mlir::Type intLikeTy, mlir::Type ptrLikeTy,
109 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
110 llvm_unreachable("isValidPtrIntCast for LangAddressSpaceAttr NYI");
111}
112
113bool TargetAddressSpaceAttr::isValidLoad(
114 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
115 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
116 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
117 llvm_unreachable("isValidLoad for TargetAddressSpaceAttr NYI");
118}
119
120bool TargetAddressSpaceAttr::isValidStore(
121 mlir::Type type, mlir::ptr::AtomicOrdering ordering,
122 std::optional<int64_t> alignment, const mlir::DataLayout *dataLayout,
123 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
124 llvm_unreachable("isValidStore for TargetAddressSpaceAttr NYI");
125}
126
127bool TargetAddressSpaceAttr::isValidAtomicOp(
128 mlir::ptr::AtomicBinOp op, mlir::Type type,
129 mlir::ptr::AtomicOrdering ordering, std::optional<int64_t> alignment,
130 const mlir::DataLayout *dataLayout,
131 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
132 llvm_unreachable("isValidAtomicOp for TargetAddressSpaceAttr NYI");
133}
134
135bool TargetAddressSpaceAttr::isValidAtomicXchg(
136 mlir::Type type, mlir::ptr::AtomicOrdering successOrdering,
137 mlir::ptr::AtomicOrdering failureOrdering, std::optional<int64_t> alignment,
138 const mlir::DataLayout *dataLayout,
139 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
140 llvm_unreachable("isValidAtomicXchg for TargetAddressSpaceAttr NYI");
141}
142
143bool TargetAddressSpaceAttr::isValidAddrSpaceCast(
144 mlir::Type tgt, mlir::Type src,
145 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
146 llvm_unreachable("isValidAddrSpaceCast for TargetAddressSpaceAttr NYI");
147}
148
149bool TargetAddressSpaceAttr::isValidPtrIntCast(
150 mlir::Type intLikeTy, mlir::Type ptrLikeTy,
151 llvm::function_ref<mlir::InFlightDiagnostic()> emitError) const {
152 llvm_unreachable("isValidPtrIntCast for TargetAddressSpaceAttr NYI");
153}
154
155//===----------------------------------------------------------------------===//
156// PtrSpecAttr definitions
157//===----------------------------------------------------------------------===//
158
159LogicalResult PtrSpecAttr::verify(function_ref<InFlightDiagnostic()> emitError,
160 uint32_t size, uint32_t abi,
161 uint32_t preferred, uint32_t index) {
162 constexpr unsigned kBitsInByte = 8;
163 if (size % kBitsInByte != 0)
164 return emitError() << "size entry must be divisible by 8";
165 if (abi % kBitsInByte != 0)
166 return emitError() << "abi entry must be divisible by 8";
167 if (preferred % kBitsInByte != 0)
168 return emitError() << "preferred entry must be divisible by 8";
169 if (index != kOptionalSpecValue && index % kBitsInByte != 0)
170 return emitError() << "index entry must be divisible by 8";
171 if (abi > preferred)
172 return emitError() << "preferred alignment is expected to be at least "
173 "as large as ABI alignment";
174 return success();
175}
176
177//===----------------------------------------------------------------------===//
178// BitFieldDeclAttr definitions
179//===----------------------------------------------------------------------===//
180
181LogicalResult
182BitFieldDeclAttr::verify(function_ref<InFlightDiagnostic()> emitError,
183 mlir::Type declaredType, uint64_t width,
184 bool isUnnamed) {
185 if (width == 0 && !isUnnamed)
186 return emitError() << "zero-width bit-field cannot be named";
187 return success();
188}
189
190//===----------------------------------------------------------------------===//
191// General CIR parsing / printing
192//===----------------------------------------------------------------------===//
193
194static void printRecordMembers(mlir::AsmPrinter &printer,
195 mlir::ArrayAttr members) {
196 printer << '{';
197 llvm::interleaveComma(members, printer);
198 printer << '}';
199}
200
201static ParseResult parseRecordMembers(mlir::AsmParser &parser,
202 mlir::ArrayAttr &members) {
204
205 auto delimiter = AsmParser::Delimiter::Braces;
206 auto result = parser.parseCommaSeparatedList(delimiter, [&]() {
207 mlir::TypedAttr attr;
208 if (parser.parseAttribute(attr).failed())
209 return mlir::failure();
210 elts.push_back(attr);
211 return mlir::success();
212 });
213
214 if (result.failed())
215 return mlir::failure();
216
217 members = mlir::ArrayAttr::get(parser.getContext(), elts);
218 return mlir::success();
219}
220
221//===----------------------------------------------------------------------===//
222// ConstRecordAttr definitions
223//===----------------------------------------------------------------------===//
224
225LogicalResult
226ConstRecordAttr::verify(function_ref<InFlightDiagnostic()> emitError,
227 mlir::Type type, ArrayAttr members) {
228 auto sTy = mlir::dyn_cast_if_present<cir::RecordType>(type);
229 if (!sTy)
230 return emitError() << "expected !cir.struct or !cir.union type";
231
232 // union record initializer is just a single element that has to match one of
233 // the fields in the union (the new active member).
234 if (sTy.isUnion()) {
235 if (members.size() != 1)
236 return emitError() << "union constant must have exactly one element, got "
237 << members.size();
238 auto m = mlir::cast<mlir::TypedAttr>(members[0]);
239 // A bit-field variant is initialized as the access unit it owns.
240 if (!llvm::any_of(sTy.getMembers(), [&](mlir::Type memberTy) {
241 return cir::memberStorageType(memberTy) == m.getType();
242 }))
243 return emitError() << "union element type " << m.getType()
244 << " is not a member of " << sTy;
245 return success();
246 }
247
248 // A member that owns no bytes is not stored, so it takes no element. A
249 // bit-field's bits are packed into the element of the member that owns its
250 // access unit, and a zero-width bit-field has no bits to store at all.
251 llvm::SmallVector<mlir::Type> storedMembers;
252 for (mlir::Type memberTy : sTy.getMembers())
253 if (cir::memberOwnsBytes(memberTy))
254 storedMembers.push_back(cir::memberStorageType(memberTy));
255
256 if (storedMembers.size() != members.size())
257 return emitError() << "number of elements must match";
258
259 for (const auto &[attrIdx, member] : llvm::enumerate(storedMembers)) {
260 auto m = mlir::cast<mlir::TypedAttr>(members[attrIdx]);
261
262 // As a special case, we allow a flexible array member. This can only be the
263 // last element, the rest of the array type has to match (that is, the
264 // element type has to match), and the array member must be size zero.
265 if (attrIdx == storedMembers.size() - 1) {
266 auto memArrayTy = dyn_cast<cir::ArrayType>(member);
267 if (memArrayTy && memArrayTy.getSize() == 0) {
268
269 // The FAM must only match another array type initializer.
270 if (!isa<cir::ArrayType>(m.getType()))
271 return emitError()
272 << "element at index " << attrIdx << " has type "
273 << m.getType() << " but the expected type for this element is "
274 << member;
275
276 cir::ArrayType initArrayTy = cast<cir::ArrayType>(m.getType());
277 // The FAM only matches an equivalent array type.
278 if (initArrayTy.getElementType() != memArrayTy.getElementType())
279 return emitError()
280 << "flexible array member at index " << attrIdx << " has type "
281 << m.getType()
282 << " which doesn't match the expected element type of member "
283 << member;
284 continue;
285 }
286 }
287
288 if (member != m.getType())
289 return emitError() << "element at index " << attrIdx << " has type "
290 << m.getType()
291 << " but the expected type for this element is "
292 << member;
293 }
294
295 return success();
296}
297
298//===----------------------------------------------------------------------===//
299// OptInfoAttr definitions
300//===----------------------------------------------------------------------===//
301
302LogicalResult OptInfoAttr::verify(function_ref<InFlightDiagnostic()> emitError,
303 unsigned level, unsigned size) {
304 if (level > 3)
305 return emitError()
306 << "optimization level must be between 0 and 3 inclusive";
307 if (size > 2)
308 return emitError()
309 << "size optimization level must be between 0 and 2 inclusive";
310 return success();
311}
312
313//===----------------------------------------------------------------------===//
314// ConstPtrAttr definitions
315//===----------------------------------------------------------------------===//
316
317// TODO(CIR): Consider encoding the null value differently and use conditional
318// assembly format instead of custom parsing/printing.
319static ParseResult parseConstPtr(AsmParser &parser, mlir::IntegerAttr &value) {
320
321 if (parser.parseOptionalKeyword("null").succeeded()) {
322 value = parser.getBuilder().getI64IntegerAttr(0);
323 return success();
324 }
325
326 return parser.parseAttribute(value);
327}
328
329static void printConstPtr(AsmPrinter &p, mlir::IntegerAttr value) {
330 if (!value.getInt())
331 p << "null";
332 else
333 p << value;
334}
335
336static ParseResult parseDataMemberPath(AsmParser &parser,
337 mlir::DenseI32ArrayAttr &memberPath) {
338 if (parser.parseOptionalKeyword("null").succeeded())
339 return success();
340
341 auto parsed = mlir::FieldParser<mlir::DenseI32ArrayAttr>::parse(parser);
342 if (mlir::failed(parsed))
343 return failure();
344 memberPath = *parsed;
345 return success();
346}
347
348static void printDataMemberPath(AsmPrinter &p,
349 mlir::DenseI32ArrayAttr memberPath) {
350 if (!memberPath)
351 p << "null";
352 else
353 p.printStrippedAttrOrType(memberPath);
354}
355
356//===----------------------------------------------------------------------===//
357// IntAttr definitions
358//===----------------------------------------------------------------------===//
359
360mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser, llvm::APInt &value,
361 cir::IntTypeInterface ty) {
362 llvm::SMLoc loc = parser.getCurrentLocation();
363 llvm::APInt parsed;
364 mlir::OptionalParseResult result = parser.parseOptionalInteger(parsed);
365 if (!result.has_value() || failed(*result))
366 return parser.emitError(loc, "expected integer value");
367
368 const unsigned width = ty.getWidth();
369 const bool fits =
370 ty.isSigned() ? parsed.getSignificantBits() <= width
371 : !parsed.isNegative() && parsed.getActiveBits() <= width;
372 if (!fits)
373 return parser.emitError(loc, "integer value too large for the given type");
374
375 value = ty.isSigned() ? parsed.sextOrTrunc(width) : parsed.zextOrTrunc(width);
376 return success();
377}
378
379void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value,
380 cir::IntTypeInterface ty) {
382 value.toString(str, /*radix=*/10, /*isSigned=*/ty.isSigned());
383 p << str;
384}
385
386LogicalResult IntAttr::verify(function_ref<InFlightDiagnostic()> emitError,
387 cir::IntTypeInterface type, llvm::APInt value) {
388 if (value.getBitWidth() != type.getWidth())
389 return emitError() << "type and value bitwidth mismatch: "
390 << type.getWidth() << " != " << value.getBitWidth();
391 return success();
392}
393
394//===----------------------------------------------------------------------===//
395// FPAttr definitions
396//===----------------------------------------------------------------------===//
397
398static void printFloatLiteral(AsmPrinter &p, APFloat value, Type ty) {
399 p << value;
400}
401
402static ParseResult parseFloatLiteral(AsmParser &parser,
403 FailureOr<APFloat> &value,
404 cir::FPTypeInterface fpType) {
405
406 APFloat parsedValue(0.0);
407 if (parser.parseFloat(fpType.getFloatSemantics(), parsedValue))
408 return failure();
409
410 value.emplace(parsedValue);
411 return success();
412}
413
414FPAttr FPAttr::getZero(Type type) {
415 return get(type,
416 APFloat::getZero(
417 mlir::cast<cir::FPTypeInterface>(type).getFloatSemantics()));
418}
419
420LogicalResult FPAttr::verify(function_ref<InFlightDiagnostic()> emitError,
421 cir::FPTypeInterface fpType, APFloat value) {
422 if (APFloat::SemanticsToEnum(fpType.getFloatSemantics()) !=
423 APFloat::SemanticsToEnum(value.getSemantics()))
424 return emitError() << "floating-point semantics mismatch";
425
426 return success();
427}
428
429//===----------------------------------------------------------------------===//
430// CmpThreeWayInfoAttr definitions
431//===----------------------------------------------------------------------===//
432
433std::string CmpThreeWayInfoAttr::getAlias() const {
434 std::string alias = "cmpinfo";
435
436 switch (getOrdering()) {
437 case CmpOrdering::Strong:
438 alias.append("_strong_");
439 break;
440 case CmpOrdering::Weak:
441 alias.append("_weak_");
442 break;
443 case CmpOrdering::Partial:
444 alias.append("_partial_");
445 break;
446 }
447
448 auto appendInt = [&](int64_t value) {
449 if (value < 0) {
450 alias.push_back('n');
451 value = -value;
452 }
453 alias.append(std::to_string(value));
454 };
455
456 alias.append("lt");
457 appendInt(getLt());
458 alias.append("eq");
459 appendInt(getEq());
460 alias.append("gt");
461 appendInt(getGt());
462
463 if (std::optional<int> unordered = getUnordered()) {
464 alias.append("un");
465 appendInt(unordered.value());
466 }
467
468 return alias;
469}
470
471LogicalResult
472CmpThreeWayInfoAttr::verify(function_ref<InFlightDiagnostic()> emitError,
473 CmpOrdering ordering, int64_t lt, int64_t eq,
474 int64_t gt, std::optional<int64_t> unordered) {
475 // The presence of unordered must match the value of ordering.
476 if ((ordering == CmpOrdering::Strong || ordering == CmpOrdering::Weak) &&
477 unordered) {
478 emitError() << "strong and weak ordering do not include unordered";
479 return failure();
480 }
481 if (ordering == CmpOrdering::Partial && !unordered) {
482 emitError() << "partial ordering requires unordered value";
483 return failure();
484 }
485
486 return success();
487}
488
489//===----------------------------------------------------------------------===//
490// ConstComplexAttr definitions
491//===----------------------------------------------------------------------===//
492
493LogicalResult
494ConstComplexAttr::verify(function_ref<InFlightDiagnostic()> emitError,
495 cir::ComplexType type, mlir::TypedAttr real,
496 mlir::TypedAttr imag) {
497 mlir::Type elemType = type.getElementType();
498 if (real.getType() != elemType)
499 return emitError()
500 << "type of the real part does not match the complex type";
501
502 if (imag.getType() != elemType)
503 return emitError()
504 << "type of the imaginary part does not match the complex type";
505
506 return success();
507}
508
509//===----------------------------------------------------------------------===//
510// CIR_CUDAVarRegistrationInfoAttr definitions
511//===----------------------------------------------------------------------===//
512
513void CUDAVarRegistrationInfoAttr::print(AsmPrinter &p) const {
514 p << "<" << getDeviceSideName();
515 p << ", " << stringifyEnum(getKind());
516 if (getIsExtern())
517 p << ", extern";
518 if (getIsConstant())
519 p << ", constant";
520 if (getIsManaged())
521 p << ", managed";
522 p << ">";
523}
524
525Attribute CUDAVarRegistrationInfoAttr::parse(AsmParser &parser, Type odsType) {
526 if (parser.parseLess())
527 return {};
528
529 std::string deviceSideName;
530 if (parser.parseKeywordOrString(&deviceSideName)) {
531 parser.emitError(parser.getCurrentLocation(),
532 "expected device variable name");
533 return {};
534 }
535
536 if (parser.parseComma())
537 return {};
538
539 // Parse the device variable kind (Variable, Surface, Texture)
540 StringRef kindStr;
541 if (parser.parseKeyword(&kindStr))
542 return {};
543
544 std::optional<CUDADeviceVarKind> kind = symbolizeCUDADeviceVarKind(kindStr);
545 if (!kind) {
546 parser.emitError(parser.getCurrentLocation(),
547 "unknown device variable kind: ")
548 << kindStr;
549 return {};
550 }
551
552 // Parse optional flags: extern, constant, managed
553 bool isExtern = false;
554 bool isConstant = false;
555 bool isManaged = false;
556
557 while (parser.parseOptionalGreater().failed()) {
558 if (parser.parseComma())
559 return {};
560
561 StringRef flag;
562 if (parser.parseKeyword(&flag))
563 return {};
564
565 if (flag == "extern")
566 isExtern = true;
567 else if (flag == "constant")
568 isConstant = true;
569 else if (flag == "managed")
570 isManaged = true;
571 else {
572 parser.emitError(parser.getCurrentLocation(), "unknown flag: ") << flag;
573 return {};
574 }
575 }
576
577 return get(parser.getContext(), deviceSideName, *kind, isExtern, isConstant,
578 isManaged);
579}
580
581//===----------------------------------------------------------------------===//
582// DataMemberAttr definitions
583//===----------------------------------------------------------------------===//
584
585LogicalResult
586DataMemberAttr::verify(function_ref<InFlightDiagnostic()> emitError,
587 cir::DataMemberType ty,
588 mlir::DenseI32ArrayAttr memberPath) {
589 if (!memberPath)
590 return success(); // null pointer — always valid
591
592 if (memberPath.empty())
593 return emitError() << "#cir.data_member path must not be empty";
594
595 mlir::Type currentTy = ty.getClassTy();
596 for (auto [step, idx] : llvm::enumerate(memberPath.asArrayRef())) {
597 auto recTy = mlir::dyn_cast<cir::RecordType>(currentTy);
598 if (!recTy)
599 return emitError() << "#cir.data_member path step " << step
600 << " reaches a non-record type";
601
602 if (recTy.isIncomplete())
603 return success(); // cannot validate further; trust the builder
604
605 if (idx < 0 || static_cast<unsigned>(idx) >= recTy.getNumElements())
606 return emitError() << "#cir.data_member path index " << idx << " at step "
607 << step << " is out of range";
608
609 currentTy = recTy.getMembers()[idx];
610 }
611
612 if (currentTy != ty.getMemberTy())
613 return emitError()
614 << "member type of a #cir.data_member attribute must match "
615 "the attribute type";
616
617 return success();
618}
619
620//===----------------------------------------------------------------------===//
621// MethodAttr definitions
622//===----------------------------------------------------------------------===//
623
624LogicalResult MethodAttr::verify(function_ref<InFlightDiagnostic()> emitError,
625 cir::MethodType type,
626 std::optional<FlatSymbolRefAttr> symbol,
627 std::optional<uint64_t> vtable_offset) {
628 if (symbol.has_value() && vtable_offset.has_value())
629 return emitError()
630 << "at most one of symbol and vtable_offset can be present "
631 "in #cir.method";
632
633 return success();
634}
635
636Attribute MethodAttr::parse(AsmParser &parser, Type odsType) {
637 auto ty = mlir::cast<cir::MethodType>(odsType);
638
639 if (parser.parseLess().failed())
640 return {};
641
642 // Try to parse the null pointer constant.
643 if (parser.parseOptionalKeyword("null").succeeded()) {
644 if (parser.parseGreater().failed())
645 return {};
646 return get(ty);
647 }
648
649 // Try to parse a flat symbol ref for a pointer to non-virtual member
650 // function.
651 FlatSymbolRefAttr symbol;
652 mlir::OptionalParseResult parseSymbolRefResult =
653 parser.parseOptionalAttribute(symbol);
654 if (parseSymbolRefResult.has_value()) {
655 if (parseSymbolRefResult.value().failed())
656 return {};
657 if (parser.parseGreater().failed())
658 return {};
659 return get(ty, symbol);
660 }
661
662 // Parse a uint64 that represents the vtable offset.
663 std::uint64_t vtableOffset = 0;
664 if (parser.parseKeyword("vtable_offset"))
665 return {};
666 if (parser.parseEqual())
667 return {};
668 if (parser.parseInteger(vtableOffset))
669 return {};
670
671 if (parser.parseGreater())
672 return {};
673
674 return get(ty, vtableOffset);
675}
676
677void MethodAttr::print(AsmPrinter &printer) const {
678 auto symbol = getSymbol();
679 auto vtableOffset = getVtableOffset();
680
681 printer << '<';
682 if (symbol.has_value()) {
683 printer << *symbol;
684 } else if (vtableOffset.has_value()) {
685 printer << "vtable_offset = " << *vtableOffset;
686 } else {
687 printer << "null";
688 }
689 printer << '>';
690}
691
692//===----------------------------------------------------------------------===//
693// CIR ConstArrayAttr
694//===----------------------------------------------------------------------===//
695
696LogicalResult
697ConstArrayAttr::verify(function_ref<InFlightDiagnostic()> emitError, Type type,
698 Attribute elts, int trailingZerosNum) {
699
700 if (!(mlir::isa<ArrayAttr, StringAttr>(elts)))
701 return emitError() << "constant array expects ArrayAttr or StringAttr";
702
703 if (auto strAttr = mlir::dyn_cast<StringAttr>(elts)) {
704 const auto arrayTy = mlir::cast<ArrayType>(type);
705 const auto intTy = mlir::dyn_cast<IntType>(arrayTy.getElementType());
706
707 // TODO: add CIR type for char.
708 if (!intTy || intTy.getWidth() != 8)
709 return emitError()
710 << "constant array element for string literals expects "
711 "!cir.int<u, 8> element type";
712 return success();
713 }
714
715 assert(mlir::isa<ArrayAttr>(elts));
716 const auto arrayAttr = mlir::cast<mlir::ArrayAttr>(elts);
717 const auto arrayTy = mlir::cast<ArrayType>(type);
718
719 // Make sure both number of elements and subelement types match type.
720 if (arrayAttr.size() > arrayTy.getSize())
721 return emitError() << "constant array has " << arrayAttr.size()
722 << " values but array type has size "
723 << arrayTy.getSize();
724 if (arrayTy.getSize() != arrayAttr.size() + trailingZerosNum)
725 return emitError() << "constant array size should match type size";
726 return success();
727}
728
729Attribute ConstArrayAttr::parse(AsmParser &parser, Type type) {
730 mlir::FailureOr<Type> resultTy;
731 mlir::FailureOr<Attribute> resultVal;
732
733 // Parse literal '<'
734 if (parser.parseLess())
735 return {};
736
737 // Parse variable 'value'
738 resultVal = FieldParser<Attribute>::parse(parser);
739 if (failed(resultVal)) {
740 parser.emitError(
741 parser.getCurrentLocation(),
742 "failed to parse ConstArrayAttr parameter 'value' which is "
743 "to be a `Attribute`");
744 return {};
745 }
746
747 // ArrayAttrrs have per-element type, not the type of the array...
748 if (mlir::isa<ArrayAttr>(*resultVal)) {
749 // Array has implicit type: infer from const array type.
750 if (parser.parseOptionalColon().failed()) {
751 resultTy = type;
752 } else { // Array has explicit type: parse it.
753 resultTy = FieldParser<Type>::parse(parser);
754 if (failed(resultTy)) {
755 parser.emitError(
756 parser.getCurrentLocation(),
757 "failed to parse ConstArrayAttr parameter 'type' which is "
758 "to be a `::mlir::Type`");
759 return {};
760 }
761 }
762 } else {
763 auto ta = mlir::cast<TypedAttr>(*resultVal);
764 resultTy = ta.getType();
765 if (mlir::isa<mlir::NoneType>(*resultTy)) {
766 parser.emitError(parser.getCurrentLocation(),
767 "expected type declaration for string literal");
768 return {};
769 }
770 }
771
772 unsigned zeros = 0;
773 if (parser.parseOptionalComma().succeeded()) {
774 if (parser.parseOptionalKeyword("trailing_zeros").succeeded()) {
775 unsigned totalSize = mlir::cast<cir::ArrayType>(type).getSize();
776 mlir::Attribute elts = resultVal.value();
777 if (auto str = mlir::dyn_cast<mlir::StringAttr>(elts))
778 zeros = totalSize - str.size();
779 else
780 zeros = totalSize - mlir::cast<mlir::ArrayAttr>(elts).size();
781 } else {
782 return {};
783 }
784 }
785
786 // Parse literal '>'
787 if (parser.parseGreater())
788 return {};
789
790 return parser.getChecked<ConstArrayAttr>(parser.getCurrentLocation(),
791 parser.getContext(), type,
792 resultVal.value(), zeros);
793}
794
795void ConstArrayAttr::print(AsmPrinter &printer) const {
796 printer << "<";
797 printer.printStrippedAttrOrType(getElts());
798 if (getTrailingZerosNum())
799 printer << ", trailing_zeros";
800 printer << ">";
801}
802
803//===----------------------------------------------------------------------===//
804// CIR ConstVectorAttr
805//===----------------------------------------------------------------------===//
806
807LogicalResult
808cir::ConstVectorAttr::verify(function_ref<InFlightDiagnostic()> emitError,
809 Type type, ArrayAttr elts) {
810
811 if (!mlir::isa<cir::VectorType>(type))
812 return emitError() << "type of cir::ConstVectorAttr is not a "
813 "cir::VectorType: "
814 << type;
815
816 const auto vecType = mlir::cast<cir::VectorType>(type);
817
818 if (vecType.getSize() != elts.size())
819 return emitError()
820 << "number of constant elements should match vector size";
821
822 // Check if the types of the elements match
823 LogicalResult elementTypeCheck = success();
824 elts.walkImmediateSubElements(
825 [&](Attribute element) {
826 if (elementTypeCheck.failed()) {
827 // An earlier element didn't match
828 return;
829 }
830 auto typedElement = mlir::dyn_cast<TypedAttr>(element);
831 if (!typedElement ||
832 typedElement.getType() != vecType.getElementType()) {
833 elementTypeCheck = failure();
834 emitError() << "constant type should match vector element type";
835 }
836 },
837 [&](Type) {});
838
839 return elementTypeCheck;
840}
841
842//===----------------------------------------------------------------------===//
843// CIR VTableAttr
844//===----------------------------------------------------------------------===//
845
846LogicalResult cir::VTableAttr::verify(
847 llvm::function_ref<mlir::InFlightDiagnostic()> emitError, mlir::Type type,
848 mlir::ArrayAttr data) {
849 auto sTy = mlir::dyn_cast_if_present<cir::RecordType>(type);
850 if (!sTy)
851 return emitError() << "expected !cir.struct or !cir.union type result";
852 if (sTy.getMembers().empty() || data.empty())
853 return emitError() << "expected record type with one or more subtype";
854
855 if (cir::ConstRecordAttr::verify(emitError, type, data).failed())
856 return failure();
857
858 for (const auto &element : data.getAsRange<mlir::Attribute>()) {
859 const auto &constArrayAttr = mlir::dyn_cast<cir::ConstArrayAttr>(element);
860 if (!constArrayAttr)
861 return emitError() << "expected constant array subtype";
862
863 LogicalResult eltTypeCheck = success();
864 auto arrayElts = mlir::cast<ArrayAttr>(constArrayAttr.getElts());
865 arrayElts.walkImmediateSubElements(
866 [&](mlir::Attribute attr) {
867 if (mlir::isa<ConstPtrAttr, GlobalViewAttr>(attr))
868 return;
869
870 eltTypeCheck = emitError()
871 << "expected GlobalViewAttr or ConstPtrAttr";
872 },
873 [&](mlir::Type type) {});
874 if (eltTypeCheck.failed())
875 return eltTypeCheck;
876 }
877 return success();
878}
879
880//===----------------------------------------------------------------------===//
881// DynamicCastInfoAtttr definitions
882//===----------------------------------------------------------------------===//
883
884std::string DynamicCastInfoAttr::getAlias() const {
885 // The alias looks like: `dyn_cast_info_<src>_<dest>`
886
887 std::string alias = "dyn_cast_info_";
888
889 alias.append(getSrcRtti().getSymbol().getValue());
890 alias.push_back('_');
891 alias.append(getDestRtti().getSymbol().getValue());
892
893 return alias;
894}
895
896LogicalResult DynamicCastInfoAttr::verify(
897 function_ref<InFlightDiagnostic()> emitError, cir::GlobalViewAttr srcRtti,
898 cir::GlobalViewAttr destRtti, mlir::FlatSymbolRefAttr runtimeFunc,
899 mlir::FlatSymbolRefAttr badCastFunc, cir::IntAttr offsetHint) {
900 auto isRttiPtr = [](mlir::Type ty) {
901 // RTTI pointers are !cir.ptr<!u8i>.
902
903 auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
904 if (!ptrTy)
905 return false;
906
907 auto pointeeIntTy = mlir::dyn_cast<cir::IntType>(ptrTy.getPointee());
908 if (!pointeeIntTy)
909 return false;
910
911 return pointeeIntTy.isUnsigned() && pointeeIntTy.getWidth() == 8;
912 };
913
914 if (!isRttiPtr(srcRtti.getType()))
915 return emitError() << "srcRtti must be an RTTI pointer";
916
917 if (!isRttiPtr(destRtti.getType()))
918 return emitError() << "destRtti must be an RTTI pointer";
919
920 return success();
921}
922
923//===----------------------------------------------------------------------===//
924// RecordLayout lookup
925//===----------------------------------------------------------------------===//
926
927RecordLayoutAttr cir::tryGetRecordLayout(mlir::ModuleOp mod,
928 mlir::StringAttr name) {
929 if (!name)
930 return {};
931 auto dict = mod->getAttrOfType<mlir::DictionaryAttr>(
932 CIRDialect::getRecordLayoutsAttrName());
933 if (!dict)
934 return {};
935 return dict.getAs<RecordLayoutAttr>(name);
936}
937
938RecordLayoutAttr cir::getRecordLayout(mlir::ModuleOp mod,
939 mlir::StringAttr name) {
940 RecordLayoutAttr attr = tryGetRecordLayout(mod, name);
941 assert(attr && "record layout entry missing for named record");
942 return attr;
943}
944
945//===----------------------------------------------------------------------===//
946// CIR Dialect
947//===----------------------------------------------------------------------===//
948
949void CIRDialect::registerAttributes() {
950 addAttributes<
951#define GET_ATTRDEF_LIST
952#include "clang/CIR/Dialect/IR/CIROpsAttributes.cpp.inc"
953 >();
954}
static mlir::ParseResult parseFloatLiteral(mlir::AsmParser &parser, mlir::FailureOr< llvm::APFloat > &value, cir::FPTypeInterface fpType)
static void printConstPtr(mlir::AsmPrinter &p, mlir::IntegerAttr value)
static void printRecordMembers(mlir::AsmPrinter &p, mlir::ArrayAttr members)
Definition CIRAttrs.cpp:194
static mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser, llvm::APInt &value, cir::IntTypeInterface ty)
Definition CIRAttrs.cpp:360
static void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value, cir::IntTypeInterface ty)
Definition CIRAttrs.cpp:379
static mlir::ParseResult parseConstPtr(mlir::AsmParser &parser, mlir::IntegerAttr &value)
static void printFloatLiteral(mlir::AsmPrinter &p, llvm::APFloat value, mlir::Type ty)
static mlir::ParseResult parseDataMemberPath(mlir::AsmParser &parser, mlir::DenseI32ArrayAttr &memberPath)
static void printDataMemberPath(mlir::AsmPrinter &p, mlir::DenseI32ArrayAttr memberPath)
static mlir::ParseResult parseRecordMembers(mlir::AsmParser &parser, mlir::ArrayAttr &members)
Definition CIRAttrs.cpp:201
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
RecordLayoutAttr tryGetRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Same lookup as getRecordLayout, but returns a null attribute instead of asserting when the record has...
Definition CIRAttrs.cpp:927
RecordLayoutAttr getRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Look up the RecordLayoutAttr for a named record in the module's cir.record_layouts dictionary.
Definition CIRAttrs.cpp:938
mlir::Type memberStorageType(mlir::Type memberTy)
The storage a member is stored as: the access unit for a bit-field member, and the member type itself...
Definition CIRTypes.h:134
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:125
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token. ID is the node's binding in the match result.
float __ovld __cnfn step(float, float)
Returns 0.0 if x < edge, otherwise it returns 1.0.
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t