[libc++] Use __datasizeof for __libcpp_datasizeof if available (#72104)

This avoids the UB and makes things a bit cheaper in terms of
compile-times.
This commit is contained in:
Nikolas Klauser 2023-12-24 08:45:25 +01:00 committed by GitHub
parent 0f1721c480
commit eeeb963841
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -28,13 +28,17 @@ _LIBCPP_BEGIN_NAMESPACE_STD
template <class _Tp> template <class _Tp>
struct __libcpp_datasizeof { struct __libcpp_datasizeof {
#if __has_cpp_attribute(__no_unique_address__) #if __has_extension(datasizeof)
static const size_t value = __datasizeof(_Tp);
#else
// NOLINTNEXTLINE(readability-redundant-preprocessor) This is https://llvm.org/PR64825
# if __has_cpp_attribute(__no_unique_address__)
template <class = char> template <class = char>
struct _FirstPaddingByte { struct _FirstPaddingByte {
[[__no_unique_address__]] _Tp __v_; [[__no_unique_address__]] _Tp __v_;
char __first_padding_byte_; char __first_padding_byte_;
}; };
#else # else
template <bool = __libcpp_is_final<_Tp>::value || !is_class<_Tp>::value> template <bool = __libcpp_is_final<_Tp>::value || !is_class<_Tp>::value>
struct _FirstPaddingByte : _Tp { struct _FirstPaddingByte : _Tp {
char __first_padding_byte_; char __first_padding_byte_;
@ -45,7 +49,7 @@ struct __libcpp_datasizeof {
_Tp __v_; _Tp __v_;
char __first_padding_byte_; char __first_padding_byte_;
}; };
#endif # endif // __has_cpp_attribute(__no_unique_address__)
// _FirstPaddingByte<> is sometimes non-standard layout. Using `offsetof` is UB in that case, but GCC and Clang allow // _FirstPaddingByte<> is sometimes non-standard layout. Using `offsetof` is UB in that case, but GCC and Clang allow
// the use as an extension. // the use as an extension.
@ -53,6 +57,7 @@ struct __libcpp_datasizeof {
_LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Winvalid-offsetof") _LIBCPP_CLANG_DIAGNOSTIC_IGNORED("-Winvalid-offsetof")
static const size_t value = offsetof(_FirstPaddingByte<>, __first_padding_byte_); static const size_t value = offsetof(_FirstPaddingByte<>, __first_padding_byte_);
_LIBCPP_DIAGNOSTIC_POP _LIBCPP_DIAGNOSTIC_POP
#endif // __has_extension(datasizeof)
}; };
_LIBCPP_END_NAMESPACE_STD _LIBCPP_END_NAMESPACE_STD