Hi! Since r14-4771 the FE tries to differentiate between cases where the lhs of a store allows changing the current union member and cases where it doesn't, and cases where it doesn't includes everything that has gone through the cxx_eval_constant_expression path on the lhs. As the testcase shows, DECL_ANON_UNION_VAR_P vars were handled like that too, even when stores to them are the only way how to change the current union member in the sources.
So, the following patch just handles that case manually without calling cxx_eval_constant_expression and without setting evaluated to true. Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk? 2024-12-11 Jakub Jelinek <ja...@redhat.com> PR c++/117614 * constexpr.cc (cxx_eval_store_expression): For stores to DECL_ANON_UNION_VAR_P vars just continue with DECL_VALUE_EXPR of it, without setting evaluated to true or full cxx_eval_constant_expression. * g++.dg/cpp2a/constexpr-union8.C: New test. --- gcc/cp/constexpr.cc.jj 2024-12-06 09:08:20.977872404 +0100 +++ gcc/cp/constexpr.cc 2024-12-09 16:57:23.682959311 +0100 @@ -6418,6 +6418,14 @@ cxx_eval_store_expression (const constex object = probe; else { + tree pvar = tree_strip_any_location_wrapper (probe); + if (VAR_P (pvar) && DECL_ANON_UNION_VAR_P (pvar)) + { + /* Stores to DECL_ANON_UNION_VAR_P var are allowed to change + active union member. */ + probe = DECL_VALUE_EXPR (pvar); + break; + } probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue, non_constant_p, overflow_p); evaluated = true; --- gcc/testsuite/g++.dg/cpp2a/constexpr-union8.C.jj 2024-12-09 17:06:02.876721019 +0100 +++ gcc/testsuite/g++.dg/cpp2a/constexpr-union8.C 2024-12-09 17:05:01.832572060 +0100 @@ -0,0 +1,31 @@ +// PR c++/117614 +// { dg-do compile { target c++20 } } + +constexpr int +foo () +{ + union { + int x{0}; + char y; + }; + y = 1; + return y; +} + +constexpr int +bar () +{ + union { + union { + int x{0}; + char y; + }; + long long z; + }; + y = 1; + z = 2; + return z; +} + +static_assert (foo () == 1); +static_assert (bar () == 2); Jakub