| Issue |
241257
|
| Summary |
[clang][CodeGen] hasAnyVptr ignores arrays: union member not laundered (strict vtable ptrs) (miscompile at -O3)
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
jeffchen006
|
With `-fstrict-vtable-pointers`, clang launders the address of a union member that has a vptr. `hasAnyVptr` does not look through array types, so a member `B b[1]` gets no launder, and EarlyCSE reuses the vptr of the old active member.
**Reproducer** (`repro.cpp`)
```cpp
// The union U changes its active member from s to t by placement new, so
// u.t.b[0] is a B and u.t.b[0].f() calls B::f ([basic.life]/8).
// Correct output: 1 2 (clang++ -O0, g++). clang++ -O3 -fstrict-vtable-pointers: 1 1.
void *operator new(decltype(sizeof 0), void *) noexcept; // as in <new>
extern "C" int printf(const char *, ...);
struct A { virtual int f() { return 1; } };
struct B : A { int f() override { return 2; } };
struct S { A a[1]; };
struct T { B b[1]; };
union U { S s; T t; U() : s() {} };
int main() {
U u;
int r1 = u.s.a[0].f(); // 1
new (&u.t) T; // ends the lifetime of u.s; u.t is now active
int r2 = u.t.b[0].f(); // 2
printf("%d %d\n", r1, r2);
}
```
**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang++ -O0 -fstrict-vtable-pointers repro.cpp -o ./o0
$ ./o0
1 2
$ clang++ -O3 -fstrict-vtable-pointers repro.cpp -o ./o3
$ ./o3
1 1
```
Expected (as `-O0`, g++ -O0/-O2): `1 2`. `-O3` prints `1 1`.
**Why the expected output is right**
`new (&u.t) T` ends the lifetime of `u.s` (trivial destructor) and starts `u.t` ([class.union]/6 allows a change of active member by placement new). `u.t.b[0].f()` names the new object through the union member. UBSan/ASan/MSan (libc++) at -O0 are clean.
**Potential Root cause**
`clang/lib/CodeGen/CGExpr.cpp`, static `hasAnyVptr`, used in `CodeGenFunction::EmitLValueForField` for union members: clang emits `llvm.launder.invariant.group` only if `hasAnyVptr(FieldType)`. `hasAnyVptr` uses `getAsCXXRecordDecl()`, which is null for an array type, so a field `B b[1]` gives false. Both vptr loads use `&u` with `!invariant.group`, and early-cse reuses the first one.
**Possible Proposed fix**
```diff
static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
- const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
+ const auto *RD =
+ Context.getBaseElementType(Type).getTypePtr()->getAsCXXRecordDecl();
```
Better: use `FieldType.requiresBuiltinLaunder(getContext())` here (after it also visits base classes) and delete `hasAnyVptr`.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs