https://github.com/edtice-goog created
https://github.com/llvm/llvm-project/pull/246911
P0466R5 added `std::is_pointer_interconvertible_with_class` and
`std::is_corresponding_member`, which a standard library cannot implement
without compiler support. GCC provides
`__builtin_is_pointer_interconvertible_with_class(m)` and
`__builtin_is_corresponding_member(m1, m2)`, and libstdc++ uses them. This adds
both to Clang, with the same spelling and semantics.
```c++
struct A { int x; int y; };
struct B { int p; int q; };
static_assert(__builtin_is_pointer_interconvertible_with_class(&A::x));
static_assert(!__builtin_is_pointer_interconvertible_with_class(&A::y));
static_assert(__builtin_is_corresponding_member(&A::y, &B::q));
```
Each trait checks the class in the type of the pointer to member, and that
class must be complete.
- **Shared logic.** `ASTContext::isPointerInterconvertibleWithClass` and
`ASTContext::isCorrespondingMember` follow [meta.member], [basic.compound] and
[class.mem.general]. The constant evaluator, the bytecode interpreter and
CodeGen all use them.
- **Run time.** For pointers that are not constants, CodeGen compares each
pointer with the members that the trait accepts, using the C++ ABI's member
pointer comparison. This works for both the Itanium and Microsoft ABIs.
- **Refactoring.** `isLayoutCompatible` moves unchanged from Sema to
`ASTContext`, so that the AST library can use it.
Where the standard leaves a question open, this follows GCC:
- An unnamed bit-field counts as a first member, because the member after it is
not at the start of the struct.
- A member of an anonymous struct corresponds to the member at the same
position in an anonymous struct at the same position, if both are in the common
initial sequence of those structs.
- A member of an anonymous union does not correspond to any member. (GCC
rejects this case with a "sorry".)
There is one intended difference from GCC: a union that is not standard-layout
is not pointer-interconvertible with its members, because [meta.member]
requires a standard-layout type. GCC returns true in that case.
Tests:
- `clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp` checks both
evaluators on Itanium and MSVC triples. It covers inheritance, unions,
bit-fields, alignment, `[[no_unique_address]]`, enums, anonymous structs and
unions, null pointers, member function pointers, the standard library's
function-template shape, and the error cases.
- `clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp` checks
the run-time comparisons for both ABIs.
- The expected values agree with GCC 15, apart from the difference above. I
compiled a probe of 114 cases with GCC and with this patch, covering both
constant and run-time evaluation, and compared the output.
The libc++ side (`std::is_pointer_interconvertible_with_class` and
`std::is_corresponding_member`) would be a follow-up. MSVC's own spellings of
these traits (#48204) would be a separate PR.
Addresses #100013.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
>From 25dd9d25189a0b34b24e69a96e14a72728942d81 Mon Sep 17 00:00:00 2001
From: Ed Tice <[email protected]>
Date: Sat, 28 Nov 2026 22:29:06 +0000
Subject: [PATCH] [clang] Add __builtin_is_pointer_interconvertible_with_class
and __builtin_is_corresponding_member
P0466R5 added std::is_pointer_interconvertible_with_class and
std::is_corresponding_member, which a standard library cannot implement
without compiler support. GCC provides
__builtin_is_pointer_interconvertible_with_class(m) and
__builtin_is_corresponding_member(m1, m2), which libstdc++ uses. Clang now
provides both, with the same spelling and semantics.
The class that each trait checks is the class in the type of the pointer to
member, which must be complete. The constant evaluator and the bytecode
interpreter share ASTContext::isPointerInterconvertibleWithClass and
isCorrespondingMember, which follow [meta.member], [basic.compound] and
[class.mem.general]. Where those leave a question open, they follow GCC: an
unnamed bit-field counts as a first member, a member of an anonymous struct
corresponds to the member at the same position in an anonymous struct at the
same position, and a member of an anonymous union does not correspond to any
member (GCC rejects that case). Unlike GCC, a union that is not standard-layout
is not pointer-interconvertible with its members, as [meta.member] requires.
At run time, CodeGen compares each pointer with the members that the trait
accepts, using the C++ ABI's member pointer comparison, so the builtins work
for the Itanium and Microsoft ABIs.
isLayoutCompatible moves from Sema to ASTContext so that the AST library can
use it; it is unchanged.
Addresses #100013.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
clang/docs/LanguageExtensions.md | 23 ++
clang/docs/ReleaseNotes.md | 5 +
clang/include/clang/AST/ASTContext.h | 18 ++
clang/include/clang/Basic/Builtins.td | 12 +
.../clang/Basic/DiagnosticSemaKinds.td | 2 +
clang/lib/AST/ASTContext.cpp | 261 ++++++++++++++++++
clang/lib/AST/ByteCode/InterpBuiltin.cpp | 28 ++
clang/lib/AST/ExprConstant.cpp | 25 ++
clang/lib/CodeGen/CGBuiltin.cpp | 92 ++++++
clang/lib/Sema/SemaChecking.cpp | 196 ++++---------
...uiltin-pointer-interconvertible-traits.cpp | 106 +++++++
...uiltin-pointer-interconvertible-traits.cpp | 260 +++++++++++++++++
12 files changed, 881 insertions(+), 147 deletions(-)
create mode 100644
clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
create mode 100644
clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
diff --git a/clang/docs/LanguageExtensions.md b/clang/docs/LanguageExtensions.md
index a4c7c2ddca5070..ed9b22da04c04b 100644
--- a/clang/docs/LanguageExtensions.md
+++ b/clang/docs/LanguageExtensions.md
@@ -2200,6 +2200,29 @@ static_assert(__builtin_structured_binding_size(S) == 2);
static_assert(get_binding<1>(S{}) == 42);
```
+### `__builtin_is_pointer_interconvertible_with_class` and
`__builtin_is_corresponding_member` (C++)
+
+`__builtin_is_pointer_interconvertible_with_class(m)` and
+`__builtin_is_corresponding_member(m1, m2)` take pointers to members and return
+what `std::is_pointer_interconvertible_with_class` and
+`std::is_corresponding_member` ([meta.member]) return for them. The class that
+each trait checks is the class in the type of the pointer to member, which must
+be complete. GCC provides the same builtins.
+
+```c++
+struct A { int x; int y; };
+struct B { int p; int q; };
+static_assert(__builtin_is_pointer_interconvertible_with_class(&A::x));
+static_assert(!__builtin_is_pointer_interconvertible_with_class(&A::y));
+static_assert(__builtin_is_corresponding_member(&A::y, &B::q));
+```
+
+Both builtins can be used in constant expressions and at run time. As in GCC,
+a member of an anonymous struct corresponds to the member at the same position
+in an anonymous struct at the same position in the other class, if both are in
+the common initial sequence of those anonymous structs. A member of an
+anonymous union does not correspond to any member.
+
## Blocks
The syntax and high-level language feature description is in
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 6bbc910d86b5aa..0f1d4490b4aadf 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -309,6 +309,11 @@ documentation](CIR/index.md) for more information
regarding ClangIR's status and
#### C++20 Feature Support
+- Added `__builtin_is_pointer_interconvertible_with_class` and
+ `__builtin_is_corresponding_member`, with GCC's spelling and semantics, for
+ standard libraries to implement `std::is_pointer_interconvertible_with_class`
+ and `std::is_corresponding_member` from P0466R5. (#GH100013)
+
- Now clang-scan-deps in P1689 format can find the dependencies described in
module map file. See the documents of standard C++ modules for details.
diff --git a/clang/include/clang/AST/ASTContext.h
b/clang/include/clang/AST/ASTContext.h
index 9ad16898b32563..fe96f1297cc395 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3181,6 +3181,24 @@ class ASTContext : public RefCountedBase<ASTContext> {
/// those qualifiers are also ignored in the 'similarity' check.
bool hasSimilarType(QualType T1, QualType T2) const;
+ /// Determine whether two types are layout-compatible
+ /// ([basic.types.general]).
+ bool isLayoutCompatible(QualType T1, QualType T2) const;
+
+ /// Determine whether a pointer to member of \p RD that points to \p Member
+ /// (null for a null pointer) is pointer-interconvertible with its class, as
+ /// std::is_pointer_interconvertible_with_class determines ([meta.member]).
+ bool isPointerInterconvertibleWithClass(const CXXRecordDecl *RD,
+ const ValueDecl *Member) const;
+
+ /// Determine whether pointers to members of \p RD1 and \p RD2 that point
+ /// to \p Member1 and \p Member2 (null for null pointers) point to
+ /// corresponding members of the common initial sequence of the classes, as
+ /// std::is_corresponding_member determines ([meta.member]).
+ bool isCorrespondingMember(const CXXRecordDecl *RD1, const ValueDecl
*Member1,
+ const CXXRecordDecl *RD2,
+ const ValueDecl *Member2) const;
+
/// Determine if two types are similar, ignoring only CVR qualifiers.
bool hasCvrSimilarType(QualType T1, QualType T2);
diff --git a/clang/include/clang/Basic/Builtins.td
b/clang/include/clang/Basic/Builtins.td
index 820123e8f6a0f4..1107757f6a34cd 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1259,6 +1259,18 @@ def IsWithinLifetime : LangBuiltin<"CXX_LANG"> {
let Prototype = "bool(void*)";
}
+def IsPointerInterconvertibleWithClass : LangBuiltin<"CXX_LANG"> {
+ let Spellings = ["__builtin_is_pointer_interconvertible_with_class"];
+ let Attributes = [NoThrow, Const, CustomTypeChecking, Constexpr];
+ let Prototype = "bool(...)";
+}
+
+def IsCorrespondingMember : LangBuiltin<"CXX_LANG"> {
+ let Spellings = ["__builtin_is_corresponding_member"];
+ let Attributes = [NoThrow, Const, CustomTypeChecking, Constexpr];
+ let Prototype = "bool(...)";
+}
+
def ClearPadding : Builtin {
let Spellings = ["__builtin_clear_padding"];
let Attributes = [NoThrow, CustomTypeChecking];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2ae80dc3223501..50f456b6216bac 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13567,6 +13567,8 @@ def err_builtin_assume_aligned_invalid_arg : Error<
def err_builtin_is_within_lifetime_invalid_arg : Error<
"%select{non-|function }0pointer argument to '__builtin_is_within_lifetime' "
"is not allowed">;
+def err_builtin_member_pointer_trait_arg : Error<
+ "argument to %0 must be a pointer to member, not %1">;
// A multi-component builtin type diagnostic. The first component broadly
// selects a scalar or container type (scalar, vector or matrix). The second
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 3c46873c41359f..9fa4efa0c83163 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7305,6 +7305,267 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1,
QualType &T2,
return false;
}
+//===--- Layout compatibility ----------------------------------------------//
+
+static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
+
+/// Check if two enumeration types are layout-compatible.
+static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
+ const EnumDecl *ED2) {
+ // C++11 [dcl.enum] p8:
+ // Two enumeration types are layout-compatible if they have the same
+ // underlying type.
+ return ED1->isComplete() && ED2->isComplete() &&
+ C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
+}
+
+/// Check if two fields are layout-compatible.
+/// Can be used on union members, which are exempt from alignment requirement
+/// of common initial sequence.
+static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
+ const FieldDecl *Field2,
+ bool AreUnionMembers = false) {
+#ifndef NDEBUG
+ CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
+ CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
+ assert(((Field1Parent->isStructureOrClassType() &&
+ Field2Parent->isStructureOrClassType()) ||
+ (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
+ "Can't evaluate layout compatibility between a struct field and a "
+ "union field.");
+ assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
+ (AreUnionMembers && Field1Parent->isUnionType())) &&
+ "AreUnionMembers should be 'true' for union fields (only).");
+#endif
+
+ if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
+ return false;
+
+ if (Field1->isBitField() != Field2->isBitField())
+ return false;
+
+ if (Field1->isBitField()) {
+ // Make sure that the bit-fields are the same length.
+ unsigned Bits1 = Field1->getBitWidthValue();
+ unsigned Bits2 = Field2->getBitWidthValue();
+
+ if (Bits1 != Bits2)
+ return false;
+ }
+
+ if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
+ Field2->hasAttr<clang::NoUniqueAddressAttr>())
+ return false;
+
+ if (!AreUnionMembers &&
+ Field1->getMaxAlignment() != Field2->getMaxAlignment())
+ return false;
+
+ return true;
+}
+
+/// Check if two standard-layout structs are layout-compatible.
+/// (C++11 [class.mem] p17)
+static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl
*RD1,
+ const RecordDecl *RD2) {
+ // Get to the class where the fields are declared
+ if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
+ RD1 = D1CXX->getStandardLayoutBaseWithFields();
+
+ if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
+ RD2 = D2CXX->getStandardLayoutBaseWithFields();
+
+ // Check the fields.
+ return llvm::equal(RD1->fields(), RD2->fields(),
+ [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
+ return isLayoutCompatible(C, F1, F2);
+ });
+}
+
+/// Check if two standard-layout unions are layout-compatible.
+/// (C++11 [class.mem] p18)
+static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
+ const RecordDecl *RD2) {
+ llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
+ RD2->fields());
+
+ for (auto *Field1 : RD1->fields()) {
+ auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
+ return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
+ });
+ if (It == UnmatchedFields.end())
+ return false;
+ [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
+ assert(Result);
+ }
+
+ return UnmatchedFields.empty();
+}
+
+static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
+ const RecordDecl *RD2) {
+ if (RD1->isUnion() != RD2->isUnion())
+ return false;
+
+ if (RD1->isUnion())
+ return isLayoutCompatibleUnion(C, RD1, RD2);
+ else
+ return isLayoutCompatibleStruct(C, RD1, RD2);
+}
+
+/// Check if two types are layout-compatible in C++11 sense.
+static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
+ if (T1.isNull() || T2.isNull())
+ return false;
+
+ // C++20 [basic.types] p11:
+ // Two types cv1 T1 and cv2 T2 are layout-compatible types
+ // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
+ // or layout-compatible standard-layout class types (11.4).
+ T1 = T1.getCanonicalType().getUnqualifiedType();
+ T2 = T2.getCanonicalType().getUnqualifiedType();
+
+ if (C.hasSameType(T1, T2))
+ return true;
+
+ const Type::TypeClass TC1 = T1->getTypeClass();
+ const Type::TypeClass TC2 = T2->getTypeClass();
+
+ if (TC1 != TC2)
+ return false;
+
+ if (TC1 == Type::Enum)
+ return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
+ if (TC1 == Type::Record) {
+ if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
+ return false;
+
+ return isLayoutCompatible(C, T1->castAsRecordDecl(),
+ T2->castAsRecordDecl());
+ }
+
+ return false;
+}
+
+bool ASTContext::isLayoutCompatible(QualType T1, QualType T2) const {
+ return ::isLayoutCompatible(*this, T1, T2);
+}
+
+//===--- Pointer-interconvertibility and corresponding members -----------===//
+
+/// The fields from the class of a pointer to member down to the member \p M:
+/// one field, or for a member of an anonymous struct or union, the chain of
+/// anonymous members that leads to it. Empty if \p M is not a data member.
+static SmallVector<const FieldDecl *, 4> getFieldChain(const ValueDecl *M) {
+ SmallVector<const FieldDecl *, 4> Chain;
+ if (const auto *FD = dyn_cast_or_null<FieldDecl>(M))
+ Chain.push_back(FD);
+ else if (const auto *IFD = dyn_cast_or_null<IndirectFieldDecl>(M))
+ for (const NamedDecl *ND : IFD->chain())
+ Chain.push_back(cast<FieldDecl>(ND));
+ return Chain;
+}
+
+bool ASTContext::isPointerInterconvertibleWithClass(
+ const CXXRecordDecl *RD, const ValueDecl *Member) const {
+ // C++20 [meta.member]p2: true if S is a standard-layout type, M is an object
+ // type, m is not null, and each object s of type S is
+ // pointer-interconvertible with its subobject s.*m.
+ RD = RD ? RD->getDefinition() : nullptr;
+ SmallVector<const FieldDecl *, 4> Chain = getFieldChain(Member);
+ if (!RD || !RD->isStandardLayout() || Chain.empty())
+ return false;
+
+ // The data members of a standard-layout class are all declared in one class,
+ // which is RD or one of its bases.
+ if (Chain.front()->getParent()->getCanonicalDecl() !=
+ RD->getStandardLayoutBaseWithFields()->getCanonicalDecl())
+ return false;
+
+ // [basic.compound]p4: a union is pointer-interconvertible with each of its
+ // members, a standard-layout struct with its first member, and the relation
+ // is transitive, so each field in the chain must be one of those. An unnamed
+ // bit-field is not a member, but the member after it is not at the start of
+ // the struct; like GCC, treat it as coming first.
+ for (const FieldDecl *FD : Chain) {
+ const RecordDecl *Parent = FD->getParent();
+ if (!Parent->isUnion() && *Parent->field_begin() != FD)
+ return false;
+ }
+ return true;
+}
+
+/// Whether \p F1 and \p F2 are corresponding entities in the common initial
+/// sequence of two standard-layout structs ([class.mem.general]p23).
+static bool areCorrespondingFields(const ASTContext &C, const FieldDecl *F1,
+ const FieldDecl *F2) {
+ if (!C.isLayoutCompatible(F1->getType(), F2->getType()))
+ return false;
+ if (F1->hasAttr<NoUniqueAddressAttr>() != F2->hasAttr<NoUniqueAddressAttr>())
+ return false;
+ if (F1->isBitField() != F2->isBitField())
+ return false;
+ if (F1->isBitField() && F1->getBitWidthValue() != F2->getBitWidthValue())
+ return false;
+ // C++23 [class.mem.general]p23 also requires the same alignment.
+ return F1->getMaxAlignment() == F2->getMaxAlignment();
+}
+
+/// Whether the members at the end of \p Chain1 and \p Chain2 correspond in the
+/// common initial sequence of the structs \p RD1 and \p RD2, whose fields are
+/// the first entries of the chains.
+static bool areCorrespondingMembers(const ASTContext &C, const RecordDecl *RD1,
+ ArrayRef<const FieldDecl *> Chain1,
+ const RecordDecl *RD2,
+ ArrayRef<const FieldDecl *> Chain2) {
+ for (auto I1 = RD1->field_begin(), E1 = RD1->field_end(),
+ I2 = RD2->field_begin(), E2 = RD2->field_end();
+ I1 != E1 && I2 != E2; ++I1, ++I2) {
+ bool Corresponding = areCorrespondingFields(C, *I1, *I2);
+ if (*I1 != Chain1.front() || *I2 != Chain2.front()) {
+ if (!Corresponding)
+ return false;
+ continue;
+ }
+ if (Chain1.size() == 1 && Chain2.size() == 1)
+ return Corresponding;
+ // Both members are in anonymous structs at the same position. As GCC
+ // does, look for them in the common initial sequence of those structs,
+ // even if the structs differ after it. Members of anonymous unions have
+ // no defined correspondence.
+ const RecordDecl *Anon1 = (*I1)->getType()->getAsRecordDecl();
+ const RecordDecl *Anon2 = (*I2)->getType()->getAsRecordDecl();
+ if (Chain1.size() == 1 || Chain2.size() == 1 || Anon1->isUnion() ||
+ Anon2->isUnion() ||
+ (*I1)->hasAttr<NoUniqueAddressAttr>() !=
+ (*I2)->hasAttr<NoUniqueAddressAttr>())
+ return false;
+ return areCorrespondingMembers(C, Anon1, Chain1.drop_front(), Anon2,
+ Chain2.drop_front());
+ }
+ return false;
+}
+
+bool ASTContext::isCorrespondingMember(const CXXRecordDecl *RD1,
+ const ValueDecl *Member1,
+ const CXXRecordDecl *RD2,
+ const ValueDecl *Member2) const {
+ // C++20 [meta.member]p5: true if S1 and S2 are standard-layout struct types,
+ // M1 and M2 are object types, m1 and m2 are not null, and m1 and m2 point to
+ // corresponding members of the common initial sequence of S1 and S2.
+ RD1 = RD1 ? RD1->getDefinition() : nullptr;
+ RD2 = RD2 ? RD2->getDefinition() : nullptr;
+ SmallVector<const FieldDecl *, 4> Chain1 = getFieldChain(Member1);
+ SmallVector<const FieldDecl *, 4> Chain2 = getFieldChain(Member2);
+ if (!RD1 || !RD2 || RD1->isUnion() || RD2->isUnion() ||
+ !RD1->isStandardLayout() || !RD2->isStandardLayout() || Chain1.empty() ||
+ Chain2.empty())
+ return false;
+ return areCorrespondingMembers(*this, RD1->getStandardLayoutBaseWithFields(),
+ Chain1,
RD2->getStandardLayoutBaseWithFields(),
+ Chain2);
+}
+
bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
while (true) {
Qualifiers Quals;
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 35c0eba31ef830..c1dc42ddec8092 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -2668,6 +2668,30 @@ static bool
interp__builtin_is_within_lifetime(InterpState &S, CodePtr OpPC,
return true;
}
+static bool interp__builtin_member_pointer_trait(InterpState &S, CodePtr OpPC,
+ const CallExpr *Call) {
+ const CXXRecordDecl *Classes[2] = {};
+ const ValueDecl *Members[2] = {};
+ for (unsigned I = Call->getNumArgs(); I != 0; --I) {
+ MemberPointer MP = S.Stk.pop<MemberPointer>();
+ Classes[I - 1] = Call->getArg(I - 1)
+ ->getType()
+ ->castAs<MemberPointerType>()
+ ->getMostRecentCXXRecordDecl();
+ // After a cast to a pointer to member of a base class, the member is one
+ // of a derived class, not one of the pointer's class.
+ Members[I - 1] = MP.isDerivedMember() ? nullptr : MP.getDecl();
+ }
+ const ASTContext &Ctx = S.getASTContext();
+ bool Result =
+ Call->getBuiltinCallee() == Builtin::BI__builtin_is_corresponding_member
+ ? Ctx.isCorrespondingMember(Classes[0], Members[0], Classes[1],
+ Members[1])
+ : Ctx.isPointerInterconvertibleWithClass(Classes[0], Members[0]);
+ pushInteger(S, Result, Call->getType());
+ return true;
+}
+
static bool interp__builtin_elementwise_int_unaryop(
InterpState &S, CodePtr OpPC, const CallExpr *Call,
llvm::function_ref<APInt(const APSInt &)> Fn) {
@@ -5628,6 +5652,10 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC,
const CallExpr *Call,
case Builtin::BI__builtin_is_within_lifetime:
return interp__builtin_is_within_lifetime(S, OpPC, Call);
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ case Builtin::BI__builtin_is_corresponding_member:
+ return interp__builtin_member_pointer_trait(S, OpPC, Call);
+
case Builtin::BI__builtin_elementwise_add_sat:
return interp__builtin_elementwise_int_binop(
S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3ead1325191ea1..5cb40f086e4ab1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -17650,6 +17650,31 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const
CallExpr *E,
return Success(*result, E);
return false;
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ case Builtin::BI__builtin_is_corresponding_member: {
+ const CXXRecordDecl *Classes[2] = {};
+ const ValueDecl *Members[2] = {};
+ for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
+ Classes[I] = E->getArg(I)
+ ->getType()
+ ->castAs<MemberPointerType>()
+ ->getMostRecentCXXRecordDecl();
+ MemberPtr MP;
+ if (!EvaluateMemberPointer(E->getArg(I), MP, Info))
+ return false;
+ // After a cast to a pointer to member of a base class, the member is
+ // one of a derived class, not one of the pointer's class.
+ Members[I] = MP.isDerivedMember() ? nullptr : MP.getDecl();
+ }
+ const ASTContext &Ctx = Info.Ctx;
+ if (BuiltinOp == Builtin::BI__builtin_is_corresponding_member)
+ return Success(Ctx.isCorrespondingMember(Classes[0], Members[0],
+ Classes[1], Members[1]),
+ E);
+ return Success(
+ Ctx.isPointerInterconvertibleWithClass(Classes[0], Members[0]), E);
+ }
+
case Builtin::BI__builtin_ctz:
case Builtin::BI__builtin_ctzl:
case Builtin::BI__builtin_ctzll:
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 0b28bc9f43d5d3..ffee68dcf309e4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -24,6 +24,7 @@
#include "ConstantEmitter.h"
#include "PatternInit.h"
#include "TargetInfo.h"
+#include "clang/AST/CXXInheritance.h"
#include "clang/AST/OSLog.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/DiagnosticFrontend.h"
@@ -2773,6 +2774,92 @@ static void ClearPadding(CodeGenFunction &CGF, Address
Src,
}
}
+/// __builtin_is_pointer_interconvertible_with_class and
+/// __builtin_is_corresponding_member on pointers to members that are not
+/// constants: compare each pointer with the members the trait accepts.
+static RValue EmitMemberPointerTrait(CodeGenFunction &CGF, const CallExpr *E,
+ bool Corresponding) {
+ ASTContext &Ctx = CGF.getContext();
+ unsigned N = Corresponding ? 2 : 1;
+ const MemberPointerType *Types[2] = {};
+ const CXXRecordDecl *Classes[2] = {};
+ llvm::Value *Values[2] = {};
+ for (unsigned I = 0; I != N; ++I) {
+ Types[I] = E->getArg(I)->getType()->castAs<MemberPointerType>();
+ Classes[I] = Types[I]->getMostRecentCXXRecordDecl();
+ Values[I] = CGF.EmitScalarExpr(E->getArg(I));
+ }
+
+ // The data members that a pointer of the I'th type can point to: the
+ // named, non-bit-field members of the class's standard-layout base with
+ // fields, including those of its anonymous structs and unions.
+ auto Candidates = [&](unsigned I) {
+ SmallVector<const ValueDecl *, 8> Out;
+ const CXXRecordDecl *RD = Classes[I]->getDefinition();
+ if (!Types[I]->isMemberDataPointer() || !RD || !RD->isStandardLayout())
+ return Out;
+ QualType Pointee = Types[I]->getPointeeType();
+ for (const Decl *D : RD->getStandardLayoutBaseWithFields()->decls()) {
+ const FieldDecl *FD = nullptr;
+ if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
+ FD = IFD->getAnonField();
+ else if ((FD = dyn_cast<FieldDecl>(D)) && !FD->getDeclName())
+ continue;
+ if (FD && !FD->isBitField() &&
+ Ctx.hasSameUnqualifiedType(FD->getType(), Pointee))
+ Out.push_back(cast<ValueDecl>(D));
+ }
+ return Out;
+ };
+ // Whether the I'th pointer points to D.
+ auto PointsTo = [&](unsigned I, const ValueDecl *D) {
+ SmallVector<const CXXRecordDecl *, 4> Path;
+ const auto *Owner = cast<CXXRecordDecl>(D->getDeclContext());
+ if (Owner->getCanonicalDecl() != Classes[I]->getCanonicalDecl()) {
+ CXXBasePaths Paths;
+ [[maybe_unused]] bool IsBase = Classes[I]->isDerivedFrom(Owner, Paths);
+ assert(IsBase && "the member's class is a base of the pointer's class");
+ for (const CXXBasePathElement &Elt : llvm::reverse(Paths.front()))
+ Path.push_back(Elt.Class);
+ }
+ CGCXXABI &ABI = CGF.CGM.getCXXABI();
+ llvm::Constant *MP = ABI.EmitMemberPointer(
+ APValue(D, /*IsDerivedMember=*/false, Path), QualType(Types[I], 0));
+ return ABI.EmitMemberPointerComparison(CGF, Values[I], MP, Types[I],
+ /*Inequality=*/false);
+ };
+
+ llvm::Value *Result = CGF.Builder.getFalse();
+ SmallVector<const ValueDecl *, 8> C0 = Candidates(0);
+ if (!Corresponding) {
+ for (const ValueDecl *D : C0)
+ if (Ctx.isPointerInterconvertibleWithClass(Classes[0], D))
+ Result = CGF.Builder.CreateOr(Result, PointsTo(0, D));
+ return RValue::get(Result);
+ }
+ // Corresponding members have the same field indices, down any chain of
+ // anonymous members.
+ auto Position = [](const ValueDecl *D) {
+ SmallVector<unsigned, 4> Pos;
+ if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
+ for (const NamedDecl *ND : IFD->chain())
+ Pos.push_back(cast<FieldDecl>(ND)->getFieldIndex());
+ else
+ Pos.push_back(cast<FieldDecl>(D)->getFieldIndex());
+ return Pos;
+ };
+ SmallVector<const ValueDecl *, 8> C1 = Candidates(1);
+ for (const ValueDecl *D0 : C0) {
+ SmallVector<unsigned, 4> Pos = Position(D0);
+ for (const ValueDecl *D1 : C1)
+ if (Position(D1) == Pos &&
+ Ctx.isCorrespondingMember(Classes[0], D0, Classes[1], D1))
+ Result = CGF.Builder.CreateOr(
+ Result, CGF.Builder.CreateAnd(PointsTo(0, D0), PointsTo(1, D1)));
+ }
+ return RValue::get(Result);
+}
+
RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned
BuiltinID,
const CallExpr *E,
ReturnValueSlot ReturnValue) {
@@ -6094,6 +6181,11 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl
GD, unsigned BuiltinID,
E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
return RValue::get(nullptr);
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ case Builtin::BI__builtin_is_corresponding_member:
+ return EmitMemberPointerTrait(
+ *this, E, BuiltinID == Builtin::BI__builtin_is_corresponding_member);
+
case Builtin::BI__builtin_is_aligned:
return EmitBuiltinIsAligned(E);
case Builtin::BI__builtin_align_up:
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ccb303624182f2..d9e929c1197d98 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2347,6 +2347,47 @@ static ExprResult BuiltinIsWithinLifetime(Sema &S,
CallExpr *TheCall) {
return TheCall;
}
+/// Check a call to __builtin_is_pointer_interconvertible_with_class (one
+/// argument) or __builtin_is_corresponding_member (two arguments). Each
+/// argument is a pointer to member of a complete class.
+static ExprResult BuiltinMemberPointerTrait(Sema &S, CallExpr *TheCall,
+ unsigned NumArgs) {
+ if (S.checkArgCount(TheCall, NumArgs))
+ return ExprError();
+ TheCall->setType(S.Context.BoolTy);
+
+ for (unsigned I = 0; I != NumArgs; ++I) {
+ ExprResult Arg =
S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
+ if (Arg.isInvalid())
+ return ExprError();
+ TheCall->setArg(I, Arg.get());
+ QualType ArgTy = Arg.get()->getType();
+ SourceLocation Loc = Arg.get()->getExprLoc();
+ const auto *MPT = ArgTy->getAs<MemberPointerType>();
+ if (!MPT) {
+ S.Diag(Loc, diag::err_builtin_member_pointer_trait_arg)
+ << TheCall->getDirectCallee() << ArgTy <<
Arg.get()->getSourceRange();
+ return ExprError();
+ }
+ CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
+ if (S.RequireCompleteType(Loc, S.Context.getCanonicalTagType(RD),
+ diag::err_incomplete_type) ||
+ S.RequireCompleteType(Loc, ArgTy, diag::err_incomplete_type))
+ return ExprError();
+ // At run time, CodeGen compares the argument with pointers to members of
+ // the class's bases, whose members a standard-layout class can have; in
+ // the Microsoft ABI those classes need an inheritance model too.
+ if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
+ RD->getDefinition()->forallBases([&](const CXXRecordDecl *Base) {
+ (void)S.isCompleteType(
+ Loc, S.Context.getMemberPointerType(
+ S.Context.CharTy, /*Qualifier=*/std::nullopt, Base));
+ return true;
+ });
+ }
+ return TheCall;
+}
+
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
if (S.checkArgCount(TheCall, 3))
return ExprError();
@@ -3502,6 +3543,10 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID,
return BuiltinLaunder(*this, TheCall);
case Builtin::BI__builtin_is_within_lifetime:
return BuiltinIsWithinLifetime(*this, TheCall);
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ return BuiltinMemberPointerTrait(*this, TheCall, 1);
+ case Builtin::BI__builtin_is_corresponding_member:
+ return BuiltinMemberPointerTrait(*this, TheCall, 2);
case Builtin::BI__builtin_trivially_relocate:
return BuiltinTriviallyRelocate(*this, TheCall);
case Builtin::BI__builtin_clear_padding: {
@@ -16795,150 +16840,8 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr,
const Expr *RHSExpr,
<< RHSExpr->getSourceRange();
}
-//===--- Layout compatibility ----------------------------------------------//
-
-static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
-
-/// Check if two enumeration types are layout-compatible.
-static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
- const EnumDecl *ED2) {
- // C++11 [dcl.enum] p8:
- // Two enumeration types are layout-compatible if they have the same
- // underlying type.
- return ED1->isComplete() && ED2->isComplete() &&
- C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
-}
-
-/// Check if two fields are layout-compatible.
-/// Can be used on union members, which are exempt from alignment requirement
-/// of common initial sequence.
-static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
- const FieldDecl *Field2,
- bool AreUnionMembers = false) {
-#ifndef NDEBUG
- CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
- CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
- assert(((Field1Parent->isStructureOrClassType() &&
- Field2Parent->isStructureOrClassType()) ||
- (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
- "Can't evaluate layout compatibility between a struct field and a "
- "union field.");
- assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
- (AreUnionMembers && Field1Parent->isUnionType())) &&
- "AreUnionMembers should be 'true' for union fields (only).");
-#endif
-
- if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
- return false;
-
- if (Field1->isBitField() != Field2->isBitField())
- return false;
-
- if (Field1->isBitField()) {
- // Make sure that the bit-fields are the same length.
- unsigned Bits1 = Field1->getBitWidthValue();
- unsigned Bits2 = Field2->getBitWidthValue();
-
- if (Bits1 != Bits2)
- return false;
- }
-
- if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
- Field2->hasAttr<clang::NoUniqueAddressAttr>())
- return false;
-
- if (!AreUnionMembers &&
- Field1->getMaxAlignment() != Field2->getMaxAlignment())
- return false;
-
- return true;
-}
-
-/// Check if two standard-layout structs are layout-compatible.
-/// (C++11 [class.mem] p17)
-static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl
*RD1,
- const RecordDecl *RD2) {
- // Get to the class where the fields are declared
- if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
- RD1 = D1CXX->getStandardLayoutBaseWithFields();
-
- if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
- RD2 = D2CXX->getStandardLayoutBaseWithFields();
-
- // Check the fields.
- return llvm::equal(RD1->fields(), RD2->fields(),
- [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
- return isLayoutCompatible(C, F1, F2);
- });
-}
-
-/// Check if two standard-layout unions are layout-compatible.
-/// (C++11 [class.mem] p18)
-static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
- const RecordDecl *RD2) {
- llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
- RD2->fields());
-
- for (auto *Field1 : RD1->fields()) {
- auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
- return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
- });
- if (It == UnmatchedFields.end())
- return false;
- [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
- assert(Result);
- }
-
- return UnmatchedFields.empty();
-}
-
-static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
- const RecordDecl *RD2) {
- if (RD1->isUnion() != RD2->isUnion())
- return false;
-
- if (RD1->isUnion())
- return isLayoutCompatibleUnion(C, RD1, RD2);
- else
- return isLayoutCompatibleStruct(C, RD1, RD2);
-}
-
-/// Check if two types are layout-compatible in C++11 sense.
-static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
- if (T1.isNull() || T2.isNull())
- return false;
-
- // C++20 [basic.types] p11:
- // Two types cv1 T1 and cv2 T2 are layout-compatible types
- // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
- // or layout-compatible standard-layout class types (11.4).
- T1 = T1.getCanonicalType().getUnqualifiedType();
- T2 = T2.getCanonicalType().getUnqualifiedType();
-
- if (C.hasSameType(T1, T2))
- return true;
-
- const Type::TypeClass TC1 = T1->getTypeClass();
- const Type::TypeClass TC2 = T2->getTypeClass();
-
- if (TC1 != TC2)
- return false;
-
- if (TC1 == Type::Enum)
- return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
- if (TC1 == Type::Record) {
- if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
- return false;
-
- return isLayoutCompatible(C, T1->castAsRecordDecl(),
- T2->castAsRecordDecl());
- }
-
- return false;
-}
-
bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
- return isLayoutCompatible(getASTContext(), T1, T2);
+ return getASTContext().isLayoutCompatible(T1, T2);
}
//===-------------- Pointer interconvertibility ----------------------------//
@@ -17211,11 +17114,10 @@ void Sema::CheckArgumentWithTypeTag(const
ArgumentWithTypeTagAttr *Attr,
mismatch = false;
} else
if (IsPointerAttr)
- mismatch = !isLayoutCompatible(Context,
- ArgumentType->getPointeeType(),
- RequiredType->getPointeeType());
+ mismatch = !Context.isLayoutCompatible(ArgumentType->getPointeeType(),
+ RequiredType->getPointeeType());
else
- mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
+ mismatch = !Context.isLayoutCompatible(ArgumentType, RequiredType);
if (mismatch)
Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
diff --git a/clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
b/clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
new file mode 100644
index 00000000000000..e3a69e32df326c
--- /dev/null
+++ b/clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
@@ -0,0 +1,106 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -emit-llvm -o - %s |
FileCheck %s --check-prefixes=CHECK,ITANIUM -DINT=i64
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -std=c++20 -emit-llvm -o - %s |
FileCheck %s --check-prefixes=CHECK,MSABI -DINT=i32
+
+// Pointers to members that are not constants are compared with each member
+// that the trait accepts.
+
+struct A { int x; int y; };
+struct B { int p; int q; };
+struct Base { int b0; int b1; };
+struct D : Base {};
+union V { int a; float b; };
+struct Anon { int x; struct { int a; int b; }; };
+
+// ITANIUM-LABEL: define {{.*}} @_Z16interconvertibleM1Ai(
+// MSABI-LABEL: define {{.*}} @"?interconvertible@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: [[R:%.*]] = or i1 false, [[EQ]]
+// CHECK-NEXT: ret i1 [[R]]
+bool interconvertible(int A::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// Each member of a union is at offset 0.
+// ITANIUM-LABEL: define {{.*}} @_Z22interconvertible_unionM1Vi(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_union@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: [[R:%.*]] = or i1 false, [[EQ]]
+// CHECK-NEXT: ret i1 [[R]]
+bool interconvertible_union(int V::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// The members of D are those of its base.
+// ITANIUM-LABEL: define {{.*}} @_Z26interconvertible_inheritedM1Di(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_inherited@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: [[R:%.*]] = or i1 false, [[EQ]]
+// CHECK-NEXT: ret i1 [[R]]
+bool interconvertible_inherited(int D::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// No member of A has type float.
+// ITANIUM-LABEL: define {{.*}} @_Z21interconvertible_noneM1Af(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_none@@
+// CHECK-NOT: icmp
+// CHECK: ret i1 false
+bool interconvertible_none(float A::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z13correspondingM1AiM1Bi(
+// MSABI-LABEL: define {{.*}} @"?corresponding@@
+// CHECK: [[M1:%.*]] = load [[INT]]
+// CHECK-NEXT: [[M2:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ2:%.*]] = icmp eq [[INT]] [[M2]], 0
+// CHECK-NEXT: [[EQ1:%.*]] = icmp eq [[INT]] [[M1]], 0
+// CHECK-NEXT: [[AND:%.*]] = and i1 [[EQ1]], [[EQ2]]
+// CHECK-NEXT: [[OR:%.*]] = or i1 false, [[AND]]
+// CHECK-NEXT: [[EQ2:%.*]] = icmp eq [[INT]] [[M2]], 4
+// CHECK-NEXT: [[EQ1:%.*]] = icmp eq [[INT]] [[M1]], 4
+// CHECK-NEXT: [[AND:%.*]] = and i1 [[EQ1]], [[EQ2]]
+// CHECK-NEXT: [[R:%.*]] = or i1 [[OR]], [[AND]]
+// CHECK-NEXT: ret i1 [[R]]
+bool corresponding(int A::*m1, int B::*m2) {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z23corresponding_inheritedM1AiM1Di(
+// MSABI-LABEL: define {{.*}} @"?corresponding_inherited@@
+// CHECK: icmp eq [[INT]] %{{.*}}, 0
+// CHECK-NEXT: icmp eq [[INT]] %{{.*}}, 0
+// CHECK: icmp eq [[INT]] %{{.*}}, 4
+// CHECK-NEXT: icmp eq [[INT]] %{{.*}}, 4
+// CHECK-NOT: icmp
+// CHECK: ret i1
+bool corresponding_inherited(int A::*m1, int D::*m2) {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+
+// Anon::a and Anon::b are members of an anonymous struct at offset 4.
+// ITANIUM-LABEL: define {{.*}} @_Z23corresponding_anonymousM4AnoniS0_(
+// MSABI-LABEL: define {{.*}} @"?corresponding_anonymous@@
+// CHECK: icmp eq [[INT]] %{{.*}}, 0
+// CHECK-NEXT: icmp eq [[INT]] %{{.*}}, 0
+// CHECK: icmp eq [[INT]] %{{.*}}, 4
+// CHECK-NEXT: icmp eq [[INT]] %{{.*}}, 4
+// CHECK: icmp eq [[INT]] %{{.*}}, 8
+// CHECK-NEXT: icmp eq [[INT]] %{{.*}}, 8
+// CHECK-NOT: icmp
+// CHECK: ret i1
+bool corresponding_anonymous(int Anon::*m1, int Anon::*m2) {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z9constantsv(
+// MSABI-LABEL: define {{.*}} @"?constants@@
+// CHECK-NOT: icmp
+// CHECK: ret i1 true
+bool constants() {
+ return __builtin_is_pointer_interconvertible_with_class(&A::x) &&
+ !__builtin_is_corresponding_member(&A::x, &B::q);
+}
diff --git a/clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
b/clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
new file mode 100644
index 00000000000000..8ad2f1583931d1
--- /dev/null
+++ b/clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
@@ -0,0 +1,260 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -fsyntax-only -verify
%s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -std=c++20 -fsyntax-only
-verify %s
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -std=c++20 -fsyntax-only
-verify %s -fexperimental-new-constant-interpreter
+
+// __builtin_is_pointer_interconvertible_with_class(m) and
+// __builtin_is_corresponding_member(m1, m2), as GCC spells them, implement
+// std::is_pointer_interconvertible_with_class and std::is_corresponding_member
+// ([meta.member]). The class each trait checks is the class of the pointer to
+// member's type.
+
+static_assert(__has_builtin(__builtin_is_pointer_interconvertible_with_class));
+static_assert(__has_builtin(__builtin_is_corresponding_member));
+static_assert(__has_constexpr_builtin(__builtin_is_pointer_interconvertible_with_class));
+static_assert(__has_constexpr_builtin(__builtin_is_corresponding_member));
+
+#define IC(m) __builtin_is_pointer_interconvertible_with_class(m)
+#define CM(m1, m2) __builtin_is_corresponding_member(m1, m2)
+
+#if __has_cpp_attribute(no_unique_address)
+#define NO_UNIQUE_ADDRESS [[no_unique_address]]
+#else
+#define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
+#endif
+
+struct A { int x; int y; };
+struct B { int p; int q; };
+union V { int a; float b; };
+struct Base { int b0; int b1; };
+struct D : Base {};
+struct NSL { int x; private: int y; };
+struct NSL2 { int x; private: int y; };
+struct E {};
+struct DE : E { int x; };
+struct Mf { int x; void f(); };
+struct C1 { const int x; volatile int y; };
+struct C2 { int x; int y; };
+struct Arr { int a[2]; int b; };
+struct Arr2 { int a[2]; int c; };
+struct Arr3 { int a[3]; int c; };
+
+// Pointer-interconvertibility ([basic.compound]): a standard-layout struct and
+// its first member, a union and each of its members.
+static_assert(IC(&A::x));
+static_assert(!IC(&A::y));
+static_assert(IC(&V::a));
+static_assert(IC(&V::b));
+static_assert(IC(&C1::x));
+static_assert(!IC(&C1::y));
+static_assert(IC(&Arr::a));
+static_assert(!IC(&NSL::x)); // not standard-layout
+static_assert(!IC(&Mf::f)); // not a data member
+static_assert(!IC(static_cast<int A::*>(nullptr)));
+
+// Members in a base class: the class is the one in the pointer's type.
+static_assert(IC(&D::b0)); // int Base::*
+static_assert(IC(static_cast<int D::*>(&D::b0)));
+static_assert(!IC(static_cast<int D::*>(&D::b1)));
+static_assert(IC(&DE::x)); // empty base
+static_assert(!IC(static_cast<int E::*>(&DE::x))); // a member of DE, not of E
+
+// A union that is not standard-layout. GCC accepts this; [meta.member] does
+// not.
+struct Virt { virtual void f(); };
+union NU { int a; Virt v; };
+static_assert(!IC(&NU::a));
+
+// An unnamed bit-field is not a member, but the member after it is not at the
+// start of the struct; as GCC does, treat the bit-field as the first member.
+struct UB { int : 4; int x; };
+struct UB0 { int : 0; int x; };
+static_assert(!IC(&UB::x));
+static_assert(!IC(&UB0::x));
+
+struct NE { NO_UNIQUE_ADDRESS E e; int x; };
+static_assert(!IC(&NE::x));
+
+// Members of anonymous structs and unions: pointer-interconvertibility is
+// transitive.
+struct U { union { int a; float b; }; int c; };
+struct U2 { union { int a; float b; }; };
+union UU { union { int a; float b; }; int c; };
+struct Anon { struct { int a; int b; }; int c; };
+struct Nest { struct { struct { int a; }; int b; }; };
+struct S2 { int c; struct { int a; }; };
+union P1 { struct { int a; int b; }; };
+struct P2 { struct { union { int a; float f; }; int b; }; };
+struct Q4 { union { struct { int a; int b; }; float f; }; };
+struct Q7 { struct { union { int a; float b; }; }; };
+static_assert(IC(&U::a));
+static_assert(IC(&U::b));
+static_assert(!IC(&U::c));
+static_assert(IC(&U2::b));
+static_assert(IC(&UU::a));
+static_assert(IC(&UU::c));
+static_assert(IC(&Anon::a));
+static_assert(!IC(&Anon::b));
+static_assert(!IC(&Anon::c));
+static_assert(IC(&Nest::a));
+static_assert(!IC(&Nest::b));
+static_assert(!IC(&S2::a));
+static_assert(IC(&P1::a));
+static_assert(!IC(&P1::b));
+static_assert(IC(&P2::a));
+static_assert(IC(&P2::f));
+static_assert(IC(&Q4::a));
+static_assert(!IC(&Q4::b));
+static_assert(IC(&Q7::b));
+
+// Corresponding members of the common initial sequence ([class.mem.general]).
+struct Bf { int a : 3; int b; };
+struct Bf2 { int a : 3; int c; };
+struct Bf3 { int a : 4; int c; };
+struct L1 { int a; char b; double c; };
+struct L2 { int x; char y; float z; };
+static_assert(CM(&A::x, &B::p));
+static_assert(CM(&A::y, &B::q));
+static_assert(!CM(&A::x, &B::q));
+static_assert(!CM(&A::x, &A::y));
+static_assert(CM(&A::y, &A::y));
+static_assert(CM(&Bf::b, &Bf2::c));
+static_assert(!CM(&Bf::b, &Bf3::c));
+static_assert(CM(&L1::b, &L2::y));
+static_assert(!CM(&L1::c, &L2::z));
+static_assert(CM(&C1::x, &C2::x));
+static_assert(CM(&C1::y, &C2::y));
+static_assert(CM(&Arr::b, &Arr2::c));
+static_assert(!CM(&Arr::b, &Arr3::c));
+static_assert(!CM(&NSL::x, &NSL::x)); // not standard-layout
+static_assert(!CM(&NSL::x, &NSL2::x));
+static_assert(!CM(&V::a, &V::a)); // unions have no common initial
sequence
+static_assert(!CM(&V::a, &A::x));
+static_assert(!CM(&Mf::f, &Mf::f));
+static_assert(!CM(static_cast<int A::*>(nullptr), &B::p));
+static_assert(CM(&D::b1, &A::y));
+static_assert(CM(static_cast<int D::*>(&D::b1), &A::y));
+static_assert(CM(&A::x, static_cast<int D::*>(&D::b0)));
+
+// Unnamed bit-fields are part of the common initial sequence.
+struct UB1 { int a; int : 3; int b; };
+struct UB2 { int a; int : 3; int b; };
+struct UB3 { int a; int : 4; int b; };
+struct UB4 { int a; int b; };
+static_assert(CM(&UB1::b, &UB2::b));
+static_assert(!CM(&UB1::b, &UB3::b));
+static_assert(!CM(&UB1::b, &UB4::b));
+
+enum E1 : int {}; enum E2 : int {}; enum E3 : unsigned {};
+struct En1 { E1 e; int z; };
+struct En2 { E2 e; int z; };
+struct En3 { E3 e; int z; };
+struct En4 { int e; int z; };
+static_assert(CM(&En1::e, &En2::e));
+static_assert(CM(&En1::z, &En2::z));
+static_assert(!CM(&En1::z, &En3::z));
+static_assert(!CM(&En1::z, &En4::z));
+
+struct X1 { int i; };
+struct X2 { int i; };
+struct H1 { X1 m; int n; };
+struct H2 { X2 m; int n; };
+static_assert(CM(&H1::m, &H2::m));
+static_assert(CM(&H1::n, &H2::n));
+
+// Corresponding entities have the same alignment (C++23 [class.mem.general]).
+struct AL1 { int a; alignas(8) int b; int c; };
+struct AL2 { int a; int b; int c; };
+static_assert(CM(&AL1::a, &AL2::a));
+static_assert(!CM(&AL1::b, &AL2::b));
+static_assert(!CM(&AL1::c, &AL2::c));
+
+// Both or neither have [[no_unique_address]].
+struct NU1 { int a; NO_UNIQUE_ADDRESS E e; int b; };
+struct NU2 { int a; NO_UNIQUE_ADDRESS E e; int b; };
+struct NU3 { int a; E e; int b; };
+static_assert(CM(&NU1::b, &NU2::b));
+static_assert(CM(&NU1::a, &NU3::a));
+static_assert(!CM(&NU1::b, &NU3::b));
+
+struct Emp1 : E { int a; int b; };
+struct Emp2 { int a; int b; };
+static_assert(IC(&Emp1::a));
+static_assert(CM(&Emp1::b, &Emp2::b));
+
+// As in GCC, members of anonymous structs at the same position correspond if
+// they are in the common initial sequence of those structs.
+struct Anon2 { struct { int a; int b; }; int c; };
+struct Anon3 { struct { int a; float b; }; int c; };
+struct P6 { int x; struct { int a; int b; }; };
+struct P7 { int x; struct { int a; int b; }; };
+struct Deep1 { int a; struct { int b; struct { int c; int d; }; }; };
+struct Deep2 { int a; struct { int b; struct { int c; int d; }; }; };
+struct Deep3 { int a; struct { int b; struct { int c; float d; }; }; };
+static_assert(CM(&Anon::a, &Anon2::a));
+static_assert(CM(&Anon::b, &Anon2::b));
+static_assert(CM(&Anon::c, &Anon2::c));
+static_assert(CM(&Anon::a, &Anon3::a));
+static_assert(!CM(&Anon::b, &Anon3::b));
+static_assert(!CM(&Anon::c, &Anon3::c));
+static_assert(CM(&P6::a, &P7::a));
+static_assert(CM(&P6::b, &P7::b));
+static_assert(CM(&Deep1::d, &Deep2::d));
+static_assert(CM(&Deep1::c, &Deep3::c));
+static_assert(!CM(&Deep1::d, &Deep3::d));
+static_assert(!CM(&Anon::a, &Anon::c));
+
+// Members of anonymous unions have no defined correspondence (GCC rejects
+// these); an anonymous union as a whole can be part of the sequence.
+struct P4 { int x; union { int a; float f; }; };
+struct P5 { int x; union { int a; float f; }; };
+struct P8 { union { int a; float f; }; int y; };
+struct P9 { union { int a; float f; }; int y; };
+static_assert(!CM(&P4::a, &P5::a));
+static_assert(!CM(&P8::a, &P8::a));
+static_assert(CM(&P8::y, &P9::y));
+
+// The shape of the standard library's function templates.
+template <class S, class M>
+constexpr bool is_pointer_interconvertible_with_class(M S::*m) noexcept {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+template <class S1, class S2, class M1, class M2>
+constexpr bool is_corresponding_member(M1 S1::*m1, M2 S2::*m2) noexcept {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+static_assert(is_pointer_interconvertible_with_class(&A::x));
+static_assert(!is_pointer_interconvertible_with_class(&A::y));
+static_assert(is_pointer_interconvertible_with_class<D, int>(&D::b0));
+static_assert(!is_pointer_interconvertible_with_class<D, int>(&D::b1));
+static_assert(is_pointer_interconvertible_with_class<A, const int>(&A::x));
+static_assert(is_corresponding_member(&A::y, &B::q));
+static_assert(!is_corresponding_member(&A::y, &B::p));
+static_assert(is_corresponding_member<D, A, int, int>(&D::b1, &A::y));
+
+// Pointers that are not constants are allowed; they are compared at run time.
+bool runtime(int A::*m1, int B::*m2) {
+ return IC(m1) && CM(m1, m2);
+}
+int A::*Mutable = &A::x; // expected-note {{declared here}}
+static_assert(IC(Mutable)); // expected-error {{static assertion expression is
not an integral constant expression}} \
+ // expected-note {{read of non-constexpr variable
'Mutable' is not allowed in a constant expression}}
+
+struct Incomplete; // expected-note 2 {{forward declaration of 'Incomplete'}}
+template <class T> struct Template { T t; };
+static_assert(IC(&Template<int>::t));
+
+void errors(int *p, int Incomplete::*ip) {
+ (void)IC(p); // expected-error {{argument to
'__builtin_is_pointer_interconvertible_with_class' must be a pointer to member,
not 'int *'}}
+ (void)CM(&A::x, 0); // expected-error {{argument to
'__builtin_is_corresponding_member' must be a pointer to member, not 'int'}}
+ (void)__builtin_is_pointer_interconvertible_with_class(&A::x, &A::y); //
expected-error {{too many arguments to function call, expected 1, have 2}}
+ (void)__builtin_is_corresponding_member(&A::x); // expected-error {{too few
arguments to function call, expected 2, have 1}}
+ (void)IC(ip); // expected-error {{incomplete type 'Incomplete' where a
complete type is required}}
+ (void)CM(&A::x, ip); // expected-error {{incomplete type 'Incomplete' where
a complete type is required}}
+}
+
+template <class T> bool dependent(T m) {
+ return __builtin_is_pointer_interconvertible_with_class(m); //
expected-error {{argument to '__builtin_is_pointer_interconvertible_with_class'
must be a pointer to member, not 'int'}}
+}
+template bool dependent(int A::*);
+template bool dependent(int); // expected-note {{in instantiation of function
template specialization 'dependent<int>' requested here}}
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits