https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129139
Bug ID: 129139
Summary: [14/15/16/17 Regression] wrong code at -O1:
end-of-object clobber of an explicit destructor call
on a base subobject uses the full class size and kills
a derived member stored there, since r9-84
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Keywords: wrong-code
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: jeffchen006 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
extern "C" int printf(const char *, ...);
struct A {};
struct D : A { char d; };
char *w[2];
int i = 1;
int main() {
D *q = new D;
w[0] = w[1] = &q->d;
q->d = 44;
A *p = q;
p->~A();
printf("%d\n", *w[i]);
}
$ g++ -O0 t.cc && ./a.out
44
$ g++ -O1 t.cc && ./a.out
0
-O2, -O3, -Os too; -fno-lifetime-dse gives 44. clang gives 44.
A is an empty base, so D::d is at offset 0, in the same byte as the A
subobject. Calling the destructor on the base subobject ends only the lifetime
of that subobject; d is a different object and still alive.
build_trivial_dtor_call (cp/call.cc) clobbers with the full class type of A (1
byte), which covers d, so DSE removes q->d = 44. Bisected to r9-84-gcdc184174ce
(PR c++/61982, dead stores to destroyed objects); its parent prints 44.
The same happens with a non-trivial destructor through build_clobber_this
(cp/decl.cc), where a class with a virtual base is a potentially-overlapping
member:
extern "C" int printf(const char *, ...);
struct V {};
struct A : virtual V { int x = 1; ~A() {} };
struct B { [[no_unique_address]] A a; int d; };
int *where[2];
int idx = 1;
int main() {
B *b = new B;
where[0] = where[1] = &b->d;
b->d = 42;
b->a.~A();
printf("%d %d\n", (int)sizeof(B), *where[idx]);
}
$ g++ -O0 t2.cc && ./a.out
16 42
$ g++ -O1 t2.cc && ./a.out
16 0
(The read goes through w[i] only because a direct read of q->d also gives a
bogus -Wuninitialized from the same clobber.)
gcc version 17.0.0 20261128 (experimental), r17-6781-gd10e6c3818a,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release