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
225static bool isValidFlexibleArrayInit(mlir::Type memberType,
226 mlir::Type initType) {
227 auto memberArrayType = mlir::dyn_cast<cir::ArrayType>(memberType);
228 auto initArrayType = mlir::dyn_cast<cir::ArrayType>(initType);
229 return memberArrayType && memberArrayType.getSize() == 0 && initArrayType &&
230 memberArrayType.getElementType() == initArrayType.getElementType();
231}
232
233LogicalResult
234ConstRecordAttr::verify(function_ref<InFlightDiagnostic()> emitError,
235 mlir::Type type, ArrayAttr members) {
236 auto sTy = mlir::dyn_cast_if_present<cir::RecordType>(type);
237 if (!sTy)
238 return emitError() << "expected !cir.struct or !cir.union type";
239
240 // union record initializer is just a single element that has to match one of
241 // the fields in the union (the new active member).
242 if (sTy.isUnion()) {
243 if (members.size() != 1)
244 return emitError() << "union constant must have exactly one element, got "
245 << members.size();
246 auto m = mlir::cast<mlir::TypedAttr>(members[0]);
247 // A bit-field variant is initialized as the access unit it owns.
248 if (!llvm::any_of(sTy.getMembers(), [&](mlir::Type memberTy) {
249 mlir::Type storageType = cir::memberStorageType(memberTy);
250 return storageType == m.getType() ||
251 isValidFlexibleArrayInit(storageType, m.getType());
252 }))
253 return emitError() << "union element type " << m.getType()
254 << " is not a member of " << sTy;
255 return success();
256 }
257
258 // A member that owns no bytes is not stored, so it takes no element. A
259 // bit-field's bits are packed into the element of the member that owns its
260 // access unit, and a zero-width bit-field has no bits to store at all.
261 llvm::SmallVector<mlir::Type> storedMembers;
262 for (mlir::Type memberTy : sTy.getMembers())
263 if (cir::memberOwnsBytes(memberTy))
264 storedMembers.push_back(cir::memberStorageType(memberTy));
265
266 if (storedMembers.size() != members.size())
267 return emitError() << "number of elements must match";
268
269 for (const auto &[attrIdx, member] : llvm::enumerate(storedMembers)) {
270 auto m = mlir::cast<mlir::TypedAttr>(members[attrIdx]);
271
272 // As a special case, we allow a flexible array member. This can only be the
273 // last element, the rest of the array type has to match (that is, the
274 // element type has to match), and the array member must be size zero.
275 if (attrIdx == storedMembers.size() - 1) {
276 auto memArrayTy = dyn_cast<cir::ArrayType>(member);
277 if (memArrayTy && memArrayTy.getSize() == 0) {
278
279 // The FAM must only match another array type initializer.
280 if (!isa<cir::ArrayType>(m.getType()))
281 return emitError()
282 << "element at index " << attrIdx << " has type "
283 << m.getType() << " but the expected type for this element is "
284 << member;
285
286 cir::ArrayType initArrayTy = cast<cir::ArrayType>(m.getType());
287 // The FAM only matches an equivalent array type.
288 if (initArrayTy.getElementType() != memArrayTy.getElementType())
289 return emitError()
290 << "flexible array member at index " << attrIdx << " has type "
291 << m.getType()
292 << " which doesn't match the expected element type of member "
293 << member;
294 continue;
295 }
296 }
297
298 if (member != m.getType())
299 return emitError() << "element at index " << attrIdx << " has type "
300 << m.getType()
301 << " but the expected type for this element is "
302 << member;
303 }
304
305 return success();
306}
307
308//===----------------------------------------------------------------------===//
309// OptInfoAttr definitions
310//===----------------------------------------------------------------------===//
311
312LogicalResult OptInfoAttr::verify(function_ref<InFlightDiagnostic()> emitError,
313 unsigned level, unsigned size) {
314 if (level > 3)
315 return emitError()
316 << "optimization level must be between 0 and 3 inclusive";
317 if (size > 2)
318 return emitError()
319 << "size optimization level must be between 0 and 2 inclusive";
320 return success();
321}
322
323//===----------------------------------------------------------------------===//
324// ConstPtrAttr definitions
325//===----------------------------------------------------------------------===//
326
327// TODO(CIR): Consider encoding the null value differently and use conditional
328// assembly format instead of custom parsing/printing.
329static ParseResult parseConstPtr(AsmParser &parser, mlir::IntegerAttr &value) {
330
331 if (parser.parseOptionalKeyword("null").succeeded()) {
332 value = parser.getBuilder().getI64IntegerAttr(0);
333 return success();
334 }
335
336 return parser.parseAttribute(value);
337}
338
339static void printConstPtr(AsmPrinter &p, mlir::IntegerAttr value) {
340 if (!value.getInt())
341 p << "null";
342 else
343 p << value;
344}
345
346static ParseResult parseDataMemberPath(AsmParser &parser,
347 mlir::DenseI32ArrayAttr &memberPath) {
348 if (parser.parseOptionalKeyword("null").succeeded())
349 return success();
350
351 auto parsed = mlir::FieldParser<mlir::DenseI32ArrayAttr>::parse(parser);
352 if (mlir::failed(parsed))
353 return failure();
354 memberPath = *parsed;
355 return success();
356}
357
358static void printDataMemberPath(AsmPrinter &p,
359 mlir::DenseI32ArrayAttr memberPath) {
360 if (!memberPath)
361 p << "null";
362 else
363 p.printStrippedAttrOrType(memberPath);
364}
365
366//===----------------------------------------------------------------------===//
367// IntAttr definitions
368//===----------------------------------------------------------------------===//
369
370mlir::ParseResult parseIntLiteral(mlir::AsmParser &parser, llvm::APInt &value,
371 cir::IntTypeInterface ty) {
372 llvm::SMLoc loc = parser.getCurrentLocation();
373 llvm::APInt parsed;
374 mlir::OptionalParseResult result = parser.parseOptionalInteger(parsed);
375 if (!result.has_value() || failed(*result))
376 return parser.emitError(loc, "expected integer value");
377
378 const unsigned width = ty.getWidth();
379 const bool fits =
380 ty.isSigned() ? parsed.getSignificantBits() <= width
381 : !parsed.isNegative() && parsed.getActiveBits() <= width;
382 if (!fits)
383 return parser.emitError(loc, "integer value too large for the given type");
384
385 value = ty.isSigned() ? parsed.sextOrTrunc(width) : parsed.zextOrTrunc(width);
386 return success();
387}
388
389void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value,
390 cir::IntTypeInterface ty) {
392 value.toString(str, /*radix=*/10, /*isSigned=*/ty.isSigned());
393 p << str;
394}
395
396LogicalResult IntAttr::verify(function_ref<InFlightDiagnostic()> emitError,
397 cir::IntTypeInterface type, llvm::APInt value) {
398 if (value.getBitWidth() != type.getWidth())
399 return emitError() << "type and value bitwidth mismatch: "
400 << type.getWidth() << " != " << value.getBitWidth();
401 return success();
402}
403
404//===----------------------------------------------------------------------===//
405// FPAttr definitions
406//===----------------------------------------------------------------------===//
407
408static void printFloatLiteral(AsmPrinter &p, APFloat value, Type ty) {
409 p << value;
410}
411
412static ParseResult parseFloatLiteral(AsmParser &parser,
413 FailureOr<APFloat> &value,
414 cir::FPTypeInterface fpType) {
415
416 APFloat parsedValue(0.0);
417 if (parser.parseFloat(fpType.getFloatSemantics(), parsedValue))
418 return failure();
419
420 value.emplace(parsedValue);
421 return success();
422}
423
424//===----------------------------------------------------------------------===//
425// MemoryEffectsAttr definitions
426//===----------------------------------------------------------------------===//
427
428MemoryEffectsAttr MemoryEffectsAttr::none(MLIRContext *ctx) {
429 return get(ctx, ModRefInfo::NoModRef);
430}
431
432MemoryEffectsAttr MemoryEffectsAttr::readOnly(MLIRContext *ctx) {
433 return get(ctx, ModRefInfo::Ref);
434}
435
436MemoryEffectsAttr MemoryEffectsAttr::writeOnly(MLIRContext *ctx) {
437 return get(ctx, ModRefInfo::Mod);
438}
439
440MemoryEffectsAttr MemoryEffectsAttr::argMemOnly(MLIRContext *ctx,
441 ModRefInfo mr) {
442 return get(ctx, /*other=*/ModRefInfo::NoModRef, /*arg_mem=*/mr,
443 /*inaccessible_mem=*/ModRefInfo::NoModRef,
444 /*errno_mem=*/ModRefInfo::NoModRef,
445 /*target_mem0=*/ModRefInfo::NoModRef,
446 /*target_mem1=*/ModRefInfo::NoModRef);
447}
448
449MemoryEffectsAttr MemoryEffectsAttr::inaccessibleMemOnly(MLIRContext *ctx,
450 ModRefInfo mr) {
451 return get(ctx, /*other=*/ModRefInfo::NoModRef,
452 /*arg_mem=*/ModRefInfo::NoModRef, /*inaccessible_mem=*/mr,
453 /*errno_mem=*/ModRefInfo::NoModRef,
454 /*target_mem0=*/ModRefInfo::NoModRef,
455 /*target_mem1=*/ModRefInfo::NoModRef);
456}
457
458MemoryEffectsAttr MemoryEffectsAttr::errnoMemOnly(MLIRContext *ctx,
459 ModRefInfo mr) {
460 return get(ctx, /*other=*/ModRefInfo::NoModRef,
461 /*arg_mem=*/ModRefInfo::NoModRef,
462 /*inaccessible_mem=*/ModRefInfo::NoModRef, /*errno_mem=*/mr,
463 /*target_mem0=*/ModRefInfo::NoModRef,
464 /*target_mem1=*/ModRefInfo::NoModRef);
465}
466
467MemoryEffectsAttr MemoryEffectsAttr::otherMemOnly(MLIRContext *ctx,
468 ModRefInfo mr) {
469 return get(ctx, /*other=*/mr, /*arg_mem=*/ModRefInfo::NoModRef,
470 /*inaccessible_mem=*/ModRefInfo::NoModRef,
471 /*errno_mem=*/ModRefInfo::NoModRef,
472 /*target_mem0=*/ModRefInfo::NoModRef,
473 /*target_mem1=*/ModRefInfo::NoModRef);
474}
475
476MemoryEffectsAttr MemoryEffectsAttr::inaccessibleOrArgMemOnly(MLIRContext *ctx,
477 ModRefInfo mr) {
478 return get(ctx, /*other=*/ModRefInfo::NoModRef, /*arg_mem=*/mr,
479 /*inaccessible_mem=*/mr, /*errno_mem=*/ModRefInfo::NoModRef,
480 /*target_mem0=*/ModRefInfo::NoModRef,
481 /*target_mem1=*/ModRefInfo::NoModRef);
482}
483
484MemoryEffectsAttr MemoryEffectsAttr::inaccessibleOrErrnoMemOnly(
485 MLIRContext *ctx, ModRefInfo inaccessibleMr, ModRefInfo errnoMr) {
486 return get(ctx, /*other=*/ModRefInfo::NoModRef,
487 /*arg_mem=*/ModRefInfo::NoModRef,
488 /*inaccessible_mem=*/inaccessibleMr, /*errno_mem=*/errnoMr,
489 /*target_mem0=*/ModRefInfo::NoModRef,
490 /*target_mem1=*/ModRefInfo::NoModRef);
491}
492
493MemoryEffectsAttr MemoryEffectsAttr::inaccessibleOrArgOrErrnoMemOnly(
494 MLIRContext *ctx, ModRefInfo inaccessibleOrArgMr, ModRefInfo errnoMr) {
495 return get(ctx, /*other=*/ModRefInfo::NoModRef,
496 /*arg_mem=*/inaccessibleOrArgMr,
497 /*inaccessible_mem=*/inaccessibleOrArgMr, /*errno_mem=*/errnoMr,
498 /*target_mem0=*/ModRefInfo::NoModRef,
499 /*target_mem1=*/ModRefInfo::NoModRef);
500}
501
502MemoryEffectsAttr
503MemoryEffectsAttr::argumentOrErrnoMemOnly(MLIRContext *ctx, ModRefInfo argMr,
504 ModRefInfo errnoMr) {
505 return get(ctx, /*other=*/ModRefInfo::NoModRef, /*arg_mem=*/argMr,
506 /*inaccessible_mem=*/ModRefInfo::NoModRef, /*errno_mem=*/errnoMr,
507 /*target_mem0=*/ModRefInfo::NoModRef,
508 /*target_mem1=*/ModRefInfo::NoModRef);
509}
510
511FPAttr FPAttr::getZero(Type type) {
512 return get(type,
513 APFloat::getZero(
514 mlir::cast<cir::FPTypeInterface>(type).getFloatSemantics()));
515}
516
517LogicalResult FPAttr::verify(function_ref<InFlightDiagnostic()> emitError,
518 cir::FPTypeInterface fpType, APFloat value) {
519 if (APFloat::SemanticsToEnum(fpType.getFloatSemantics()) !=
520 APFloat::SemanticsToEnum(value.getSemantics()))
521 return emitError() << "floating-point semantics mismatch";
522
523 return success();
524}
525
526//===----------------------------------------------------------------------===//
527// CmpThreeWayInfoAttr definitions
528//===----------------------------------------------------------------------===//
529
530std::string CmpThreeWayInfoAttr::getAlias() const {
531 std::string alias = "cmpinfo";
532
533 switch (getOrdering()) {
534 case CmpOrdering::Strong:
535 alias.append("_strong_");
536 break;
537 case CmpOrdering::Weak:
538 alias.append("_weak_");
539 break;
540 case CmpOrdering::Partial:
541 alias.append("_partial_");
542 break;
543 }
544
545 auto appendInt = [&](int64_t value) {
546 if (value < 0) {
547 alias.push_back('n');
548 value = -value;
549 }
550 alias.append(std::to_string(value));
551 };
552
553 alias.append("lt");
554 appendInt(getLt());
555 alias.append("eq");
556 appendInt(getEq());
557 alias.append("gt");
558 appendInt(getGt());
559
560 if (std::optional<int> unordered = getUnordered()) {
561 alias.append("un");
562 appendInt(unordered.value());
563 }
564
565 return alias;
566}
567
568LogicalResult
569CmpThreeWayInfoAttr::verify(function_ref<InFlightDiagnostic()> emitError,
570 CmpOrdering ordering, int64_t lt, int64_t eq,
571 int64_t gt, std::optional<int64_t> unordered) {
572 // The presence of unordered must match the value of ordering.
573 if ((ordering == CmpOrdering::Strong || ordering == CmpOrdering::Weak) &&
574 unordered) {
575 emitError() << "strong and weak ordering do not include unordered";
576 return failure();
577 }
578 if (ordering == CmpOrdering::Partial && !unordered) {
579 emitError() << "partial ordering requires unordered value";
580 return failure();
581 }
582
583 return success();
584}
585
586//===----------------------------------------------------------------------===//
587// ConstComplexAttr definitions
588//===----------------------------------------------------------------------===//
589
590LogicalResult
591ConstComplexAttr::verify(function_ref<InFlightDiagnostic()> emitError,
592 cir::ComplexType type, mlir::TypedAttr real,
593 mlir::TypedAttr imag) {
594 mlir::Type elemType = type.getElementType();
595 if (real.getType() != elemType)
596 return emitError()
597 << "type of the real part does not match the complex type";
598
599 if (imag.getType() != elemType)
600 return emitError()
601 << "type of the imaginary part does not match the complex type";
602
603 return success();
604}
605
606//===----------------------------------------------------------------------===//
607// CIR_CUDAVarRegistrationInfoAttr definitions
608//===----------------------------------------------------------------------===//
609
610void CUDAVarRegistrationInfoAttr::print(AsmPrinter &p) const {
611 p << "<" << getDeviceSideName();
612 p << ", " << stringifyEnum(getKind());
613 if (getIsExtern())
614 p << ", extern";
615 if (getIsConstant())
616 p << ", constant";
617 if (getIsManaged())
618 p << ", managed";
619 p << ">";
620}
621
622Attribute CUDAVarRegistrationInfoAttr::parse(AsmParser &parser, Type odsType) {
623 if (parser.parseLess())
624 return {};
625
626 std::string deviceSideName;
627 if (parser.parseKeywordOrString(&deviceSideName)) {
628 parser.emitError(parser.getCurrentLocation(),
629 "expected device variable name");
630 return {};
631 }
632
633 if (parser.parseComma())
634 return {};
635
636 // Parse the device variable kind (Variable, Surface, Texture)
637 StringRef kindStr;
638 if (parser.parseKeyword(&kindStr))
639 return {};
640
641 std::optional<CUDADeviceVarKind> kind = symbolizeCUDADeviceVarKind(kindStr);
642 if (!kind) {
643 parser.emitError(parser.getCurrentLocation(),
644 "unknown device variable kind: ")
645 << kindStr;
646 return {};
647 }
648
649 // Parse optional flags: extern, constant, managed
650 bool isExtern = false;
651 bool isConstant = false;
652 bool isManaged = false;
653
654 while (parser.parseOptionalGreater().failed()) {
655 if (parser.parseComma())
656 return {};
657
658 StringRef flag;
659 if (parser.parseKeyword(&flag))
660 return {};
661
662 if (flag == "extern")
663 isExtern = true;
664 else if (flag == "constant")
665 isConstant = true;
666 else if (flag == "managed")
667 isManaged = true;
668 else {
669 parser.emitError(parser.getCurrentLocation(), "unknown flag: ") << flag;
670 return {};
671 }
672 }
673
674 return get(parser.getContext(), deviceSideName, *kind, isExtern, isConstant,
675 isManaged);
676}
677
678//===----------------------------------------------------------------------===//
679// DataMemberAttr definitions
680//===----------------------------------------------------------------------===//
681
682LogicalResult
683DataMemberAttr::verify(function_ref<InFlightDiagnostic()> emitError,
684 cir::DataMemberType ty,
685 mlir::DenseI32ArrayAttr memberPath) {
686 if (!memberPath)
687 return success(); // null pointer — always valid
688
689 if (memberPath.empty())
690 return emitError() << "#cir.data_member path must not be empty";
691
692 mlir::Type currentTy = ty.getClassTy();
693 for (auto [step, idx] : llvm::enumerate(memberPath.asArrayRef())) {
694 auto recTy = mlir::dyn_cast<cir::RecordType>(currentTy);
695 if (!recTy)
696 return emitError() << "#cir.data_member path step " << step
697 << " reaches a non-record type";
698
699 if (recTy.isIncomplete())
700 return success(); // cannot validate further; trust the builder
701
702 if (idx < 0 || static_cast<unsigned>(idx) >= recTy.getNumElements())
703 return emitError() << "#cir.data_member path index " << idx << " at step "
704 << step << " is out of range";
705
706 currentTy = recTy.getMembers()[idx];
707 }
708
709 if (currentTy != ty.getMemberTy())
710 return emitError()
711 << "member type of a #cir.data_member attribute must match "
712 "the attribute type";
713
714 return success();
715}
716
717//===----------------------------------------------------------------------===//
718// MethodAttr definitions
719//===----------------------------------------------------------------------===//
720
721LogicalResult MethodAttr::verify(function_ref<InFlightDiagnostic()> emitError,
722 cir::MethodType type,
723 std::optional<FlatSymbolRefAttr> symbol,
724 std::optional<uint64_t> vtable_offset) {
725 if (symbol.has_value() && vtable_offset.has_value())
726 return emitError()
727 << "at most one of symbol and vtable_offset can be present "
728 "in #cir.method";
729
730 return success();
731}
732
733Attribute MethodAttr::parse(AsmParser &parser, Type odsType) {
734 auto ty = mlir::cast<cir::MethodType>(odsType);
735
736 if (parser.parseLess().failed())
737 return {};
738
739 // Try to parse the null pointer constant.
740 if (parser.parseOptionalKeyword("null").succeeded()) {
741 if (parser.parseGreater().failed())
742 return {};
743 return get(ty);
744 }
745
746 // Try to parse a flat symbol ref for a pointer to non-virtual member
747 // function.
748 FlatSymbolRefAttr symbol;
749 mlir::OptionalParseResult parseSymbolRefResult =
750 parser.parseOptionalAttribute(symbol);
751 if (parseSymbolRefResult.has_value()) {
752 if (parseSymbolRefResult.value().failed())
753 return {};
754 if (parser.parseGreater().failed())
755 return {};
756 return get(ty, symbol);
757 }
758
759 // Parse a uint64 that represents the vtable offset.
760 std::uint64_t vtableOffset = 0;
761 if (parser.parseKeyword("vtable_offset"))
762 return {};
763 if (parser.parseEqual())
764 return {};
765 if (parser.parseInteger(vtableOffset))
766 return {};
767
768 if (parser.parseGreater())
769 return {};
770
771 return get(ty, vtableOffset);
772}
773
774void MethodAttr::print(AsmPrinter &printer) const {
775 auto symbol = getSymbol();
776 auto vtableOffset = getVtableOffset();
777
778 printer << '<';
779 if (symbol.has_value()) {
780 printer << *symbol;
781 } else if (vtableOffset.has_value()) {
782 printer << "vtable_offset = " << *vtableOffset;
783 } else {
784 printer << "null";
785 }
786 printer << '>';
787}
788
789//===----------------------------------------------------------------------===//
790// CIR ConstArrayAttr
791//===----------------------------------------------------------------------===//
792
793LogicalResult
794ConstArrayAttr::verify(function_ref<InFlightDiagnostic()> emitError, Type type,
795 Attribute elts, int trailingZerosNum) {
796
797 if (!(mlir::isa<ArrayAttr, StringAttr>(elts)))
798 return emitError() << "constant array expects ArrayAttr or StringAttr";
799
800 if (auto strAttr = mlir::dyn_cast<StringAttr>(elts)) {
801 const auto arrayTy = mlir::cast<ArrayType>(type);
802 const auto intTy = mlir::dyn_cast<IntType>(arrayTy.getElementType());
803
804 // TODO: add CIR type for char.
805 if (!intTy || intTy.getWidth() != 8)
806 return emitError()
807 << "constant array element for string literals expects "
808 "!cir.int<u, 8> element type";
809 return success();
810 }
811
812 assert(mlir::isa<ArrayAttr>(elts));
813 const auto arrayAttr = mlir::cast<mlir::ArrayAttr>(elts);
814 const auto arrayTy = mlir::cast<ArrayType>(type);
815
816 // Make sure both number of elements and subelement types match type.
817 if (arrayAttr.size() > arrayTy.getSize())
818 return emitError() << "constant array has " << arrayAttr.size()
819 << " values but array type has size "
820 << arrayTy.getSize();
821 if (arrayTy.getSize() != arrayAttr.size() + trailingZerosNum)
822 return emitError() << "constant array size should match type size";
823 return success();
824}
825
826Attribute ConstArrayAttr::parse(AsmParser &parser, Type type) {
827 mlir::FailureOr<Type> resultTy;
828 mlir::FailureOr<Attribute> resultVal;
829
830 // Parse literal '<'
831 if (parser.parseLess())
832 return {};
833
834 // Parse variable 'value'
835 resultVal = FieldParser<Attribute>::parse(parser);
836 if (failed(resultVal)) {
837 parser.emitError(
838 parser.getCurrentLocation(),
839 "failed to parse ConstArrayAttr parameter 'value' which is "
840 "to be a `Attribute`");
841 return {};
842 }
843
844 // ArrayAttrrs have per-element type, not the type of the array...
845 if (mlir::isa<ArrayAttr>(*resultVal)) {
846 // Array has implicit type: infer from const array type.
847 if (parser.parseOptionalColon().failed()) {
848 resultTy = type;
849 } else { // Array has explicit type: parse it.
850 resultTy = FieldParser<Type>::parse(parser);
851 if (failed(resultTy)) {
852 parser.emitError(
853 parser.getCurrentLocation(),
854 "failed to parse ConstArrayAttr parameter 'type' which is "
855 "to be a `::mlir::Type`");
856 return {};
857 }
858 }
859 } else {
860 auto ta = mlir::cast<TypedAttr>(*resultVal);
861 resultTy = ta.getType();
862 if (mlir::isa<mlir::NoneType>(*resultTy)) {
863 parser.emitError(parser.getCurrentLocation(),
864 "expected type declaration for string literal");
865 return {};
866 }
867 }
868
869 unsigned zeros = 0;
870 if (parser.parseOptionalComma().succeeded()) {
871 if (parser.parseOptionalKeyword("trailing_zeros").succeeded()) {
872 unsigned totalSize = mlir::cast<cir::ArrayType>(type).getSize();
873 mlir::Attribute elts = resultVal.value();
874 if (auto str = mlir::dyn_cast<mlir::StringAttr>(elts))
875 zeros = totalSize - str.size();
876 else
877 zeros = totalSize - mlir::cast<mlir::ArrayAttr>(elts).size();
878 } else {
879 return {};
880 }
881 }
882
883 // Parse literal '>'
884 if (parser.parseGreater())
885 return {};
886
887 return parser.getChecked<ConstArrayAttr>(parser.getCurrentLocation(),
888 parser.getContext(), type,
889 resultVal.value(), zeros);
890}
891
892void ConstArrayAttr::print(AsmPrinter &printer) const {
893 printer << "<";
894 printer.printStrippedAttrOrType(getElts());
895 if (getTrailingZerosNum())
896 printer << ", trailing_zeros";
897 printer << ">";
898}
899
900//===----------------------------------------------------------------------===//
901// CIR ConstVectorAttr
902//===----------------------------------------------------------------------===//
903
904LogicalResult
905cir::ConstVectorAttr::verify(function_ref<InFlightDiagnostic()> emitError,
906 Type type, ArrayAttr elts) {
907
908 if (!mlir::isa<cir::VectorType>(type))
909 return emitError() << "type of cir::ConstVectorAttr is not a "
910 "cir::VectorType: "
911 << type;
912
913 const auto vecType = mlir::cast<cir::VectorType>(type);
914
915 if (vecType.isScalable())
916 return emitError() << "scalable vector constants are not supported";
917
918 if (vecType.getFixedSize() != elts.size())
919 return emitError()
920 << "number of constant elements should match vector size";
921
922 // Check if the types of the elements match
923 LogicalResult elementTypeCheck = success();
924 elts.walkImmediateSubElements(
925 [&](Attribute element) {
926 if (elementTypeCheck.failed()) {
927 // An earlier element didn't match
928 return;
929 }
930 auto typedElement = mlir::dyn_cast<TypedAttr>(element);
931 if (!typedElement ||
932 typedElement.getType() != vecType.getElementType()) {
933 elementTypeCheck = failure();
934 emitError() << "constant type should match vector element type";
935 }
936 },
937 [&](Type) {});
938
939 return elementTypeCheck;
940}
941
942//===----------------------------------------------------------------------===//
943// CIR VTableAttr
944//===----------------------------------------------------------------------===//
945
946LogicalResult cir::VTableAttr::verify(
947 llvm::function_ref<mlir::InFlightDiagnostic()> emitError, mlir::Type type,
948 mlir::ArrayAttr data) {
949 auto sTy = mlir::dyn_cast_if_present<cir::RecordType>(type);
950 if (!sTy)
951 return emitError() << "expected !cir.struct or !cir.union type result";
952 if (sTy.getMembers().empty() || data.empty())
953 return emitError() << "expected record type with one or more subtype";
954
955 if (cir::ConstRecordAttr::verify(emitError, type, data).failed())
956 return failure();
957
958 for (const auto &element : data.getAsRange<mlir::Attribute>()) {
959 const auto &constArrayAttr = mlir::dyn_cast<cir::ConstArrayAttr>(element);
960 if (!constArrayAttr)
961 return emitError() << "expected constant array subtype";
962
963 LogicalResult eltTypeCheck = success();
964 auto arrayElts = mlir::cast<ArrayAttr>(constArrayAttr.getElts());
965 arrayElts.walkImmediateSubElements(
966 [&](mlir::Attribute attr) {
967 if (mlir::isa<ConstPtrAttr, GlobalViewAttr>(attr))
968 return;
969
970 eltTypeCheck = emitError()
971 << "expected GlobalViewAttr or ConstPtrAttr";
972 },
973 [&](mlir::Type type) {});
974 if (eltTypeCheck.failed())
975 return eltTypeCheck;
976 }
977 return success();
978}
979
980//===----------------------------------------------------------------------===//
981// DynamicCastInfoAtttr definitions
982//===----------------------------------------------------------------------===//
983
984std::string DynamicCastInfoAttr::getAlias() const {
985 // The alias looks like: `dyn_cast_info_<src>_<dest>`
986
987 std::string alias = "dyn_cast_info_";
988
989 alias.append(getSrcRtti().getSymbol().getValue());
990 alias.push_back('_');
991 alias.append(getDestRtti().getSymbol().getValue());
992
993 return alias;
994}
995
996// TODO: Give type_info a distinct CIR type so we can verify that a
997// FlatSymbolRefAttr actually names a type_info global.
998static bool isRttiPtr(mlir::Type ty) {
999 auto ptrTy = mlir::dyn_cast<cir::PointerType>(ty);
1000 if (!ptrTy)
1001 return false;
1002
1003 auto pointeeIntTy = mlir::dyn_cast<cir::IntType>(ptrTy.getPointee());
1004 if (!pointeeIntTy)
1005 return false;
1006
1007 return pointeeIntTy.isUnsigned() && pointeeIntTy.getWidth() == 8;
1008}
1009
1010LogicalResult DynamicCastInfoAttr::verify(
1011 function_ref<InFlightDiagnostic()> emitError, cir::GlobalViewAttr srcRtti,
1012 cir::GlobalViewAttr destRtti, mlir::FlatSymbolRefAttr runtimeFunc,
1013 mlir::FlatSymbolRefAttr badCastFunc, cir::IntAttr offsetHint) {
1014 if (!isRttiPtr(srcRtti.getType()))
1015 return emitError() << "srcRtti must be an RTTI pointer";
1016
1017 if (!isRttiPtr(destRtti.getType()))
1018 return emitError() << "destRtti must be an RTTI pointer";
1019
1020 return success();
1021}
1022
1023//===----------------------------------------------------------------------===//
1024// EhFilterAttr definitions
1025//===----------------------------------------------------------------------===//
1026
1027LogicalResult EhFilterAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1028 mlir::ArrayAttr permittedTypes) {
1029 for (mlir::Attribute typeAttr : permittedTypes) {
1030 auto rtti = mlir::dyn_cast<cir::GlobalViewAttr>(typeAttr);
1031 if (!rtti || !isRttiPtr(rtti.getType()))
1032 return emitError() << "permitted type list must contain only type info "
1033 "symbols";
1034 }
1035
1036 return success();
1037}
1038
1039//===----------------------------------------------------------------------===//
1040// RecordLayout lookup
1041//===----------------------------------------------------------------------===//
1042
1043RecordLayoutAttr cir::tryGetRecordLayout(mlir::ModuleOp mod,
1044 mlir::StringAttr name) {
1045 if (!name)
1046 return {};
1047 auto dict = mod->getAttrOfType<mlir::DictionaryAttr>(
1048 CIRDialect::getRecordLayoutsAttrName());
1049 if (!dict)
1050 return {};
1051 return dict.getAs<RecordLayoutAttr>(name);
1052}
1053
1054RecordLayoutAttr cir::getRecordLayout(mlir::ModuleOp mod,
1055 mlir::StringAttr name) {
1056 RecordLayoutAttr attr = tryGetRecordLayout(mod, name);
1057 assert(attr && "record layout entry missing for named record");
1058 return attr;
1059}
1060
1061//===----------------------------------------------------------------------===//
1062// CIR Dialect
1063//===----------------------------------------------------------------------===//
1064
1065void CIRDialect::registerAttributes() {
1066 addAttributes<
1067#define GET_ATTRDEF_LIST
1068#include "clang/CIR/Dialect/IR/CIROpsAttributes.cpp.inc"
1069 >();
1070}
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:370
static void printIntLiteral(mlir::AsmPrinter &p, llvm::APInt value, cir::IntTypeInterface ty)
Definition CIRAttrs.cpp:389
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 bool isRttiPtr(mlir::Type ty)
Definition CIRAttrs.cpp:998
static void printDataMemberPath(mlir::AsmPrinter &p, mlir::DenseI32ArrayAttr memberPath)
static mlir::ParseResult parseRecordMembers(mlir::AsmParser &parser, mlir::ArrayAttr &members)
Definition CIRAttrs.cpp:201
static bool isValidFlexibleArrayInit(mlir::Type memberType, mlir::Type initType)
Definition CIRAttrs.cpp:225
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...
RecordLayoutAttr getRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Look up the RecordLayoutAttr for a named record in the module's cir.record_layouts dictionary.
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:135
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:126
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.