llvm / llvm/llvm-project

[clang] Clarify constexpr active union member change diagnostic

Open
#207,913 9 comments 0 reactions 0 assignees View on GitHub
clang:frontend constexpr diverges-from:edg diverges-from:gcc diverges-from:msvc
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

This is specifically about this test from `test/Sema/constant-expression-cxx2a.cpp`:
```c++
template struct X {};
union V {
int a, b;
constexpr V(X<1>) : a(b = 1) {} // expected-note {{assignment would change active union member during the initialization of a different member}}
constexpr V(X<3>) : a((b = 1, a = 1)) {} // expected-note {{assignment would change active union member during the initialization of a different member}}
};
constinit V v1 = X<1>(); // expected-error {{constant init}} expected-note {{constinit}} expected-note {{in call}}
constinit V v3 = X<3>(); // expected-error {{constant init}} expected-note {{constinit}} expected-note {{in call}}
```

Clang is the only compiler diagnosing this: https://godbolt.org/z/WvP1PsG6W

Is this really invalid?

By contrast, initializing (and activating) the union members via normal assignments does _not_ diagnose:
```c++
union U {
int a;
int b;
constexpr U() {
a = b = 10;
}
};

constexpr U u;
static_assert(u.a == 10);
```
https://godbolt.org/z/rqP9n9766

Which makes sense, I guess? We're first activating `b` and then `a` by reading from `b`.
Is the constructor field initializer case really different?

CC @zygoloid @frederick-vs-ja @Endilll

Contributor guide

Open the contributing guide

Research direction

Start with test/Sema/constant-expression-cxx2a.cpp and the two constructor cases shown in the issue, then compare their diagnostics with the normal-assignment example. Determine whether the constructor field-initializer cases are valid under the relevant constant-expression rules; done means the diagnostic behavior and test expectations match that conclusion.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.