Skip to content

__builtin_bit_cast to bool diverges from GCC's behavior #120211

@tbaederr

Description

@tbaederr

This is the specific case:

constexpr bool A = __builtin_bit_cast(bool, 'A');
static_assert(A);

GCC happily compiles this while clang prints an error:

array.cpp:128:16: error: constexpr variable 'a' must be initialized by a constant expression
  128 | constexpr bool a = __builtin_bit_cast(bool, 'A');
      |                ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
array.cpp:128:20: note: value 65 cannot be represented in type 'bool'
  128 | constexpr bool a = __builtin_bit_cast(bool, 'A');
      |                    ^

This specific diagnostic is tested exactly once, in SemaCXX/constexpr-builtin-bit-cast.cpp. It's an edge case which clang checks for all integral types though:

if (T->isIntegralOrEnumerationType()) {
Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
if (IntWidth != Val.getBitWidth()) {
APSInt Truncated = Val.trunc(IntWidth);
if (Truncated.extend(Val.getBitWidth()) != Val)
return unrepresentableValue(QualType(T, 0), Val);
Val = Truncated;
}
return APValue(Val);
}

I think the relevant part from https://eel.is/c++draft/bit.cast is

For the result and each object created within it, if there is no value of the object's type corresponding to the value representation produced, the behavior is undefined.
If there are multiple such values, which value is produced is unspecified.

Does the first sentence apply here or the second?

CC @zygoloid

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"constexprAnything related to constant evaluationdiverges-from:edgDoes the clang frontend diverge from edg compiler on this issuediverges-from:gccDoes the clang frontend diverge from gcc on this issuediverges-from:msvcDoes the clang frontend diverge from msvc on this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions