Issue 241271
Summary [clang] requiresBuiltinLaunder ignores base classes; std::launder emits no launder (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    With `-fstrict-vtable-pointers`, `std::launder` on a class whose non-dynamic base has a dynamic member emits no `llvm.launder.invariant.group`. EarlyCSE then reuses the vptr of the old object in the same storage.

**Reproducer** (`repro.cpp`)
```cpp
// Correct output: 1 2 (r2 calls B::f of the new TB object, found through std::launder).
// clang++ -O3 -fstrict-vtable-pointers prints 1 1: std::launder(TB*) emits no launder.invariant.group,
// because Clang checks the fields of TB but not its base MB (which holds the dynamic member b).
#include <new>
extern "C" int printf(const char *, ...);
struct A { virtual int f() { return 1; } };
struct B : A { int f() override { return 2; } };
struct MA { A a; };
struct TA : MA {};
struct MB { B b; };
struct TB : MB {};
int main() {
  alignas(TB) unsigned char buf[sizeof(TB)];
  new (buf) TA;
  A *p1 = &std::launder(reinterpret_cast<TA *>(buf))->a;
  int r1 = p1->f();
  new (buf) TB;  // reuses the storage: the TA object ends (trivial destructor)
 A *p2 = &std::launder(reinterpret_cast<TB *>(buf))->b;
  int r2 = p2->f();
 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++ -std=c++17 -fstrict-vtable-pointers -O0 repro.cpp -o ./o0
$ ./o0
1 2
$ clang++ -std=c++17 -fstrict-vtable-pointers -O3 repro.cpp -o ./o3
$ ./o3
1 1
```
Expected (as `-O0`): `1 2`. `-O3` prints `1 1`.

**Why the expected output is right**
`new (buf) TB` reuses the storage of the `TA` object (trivial destructor). The old pointer is not used; `std::launder(reinterpret_cast<TB*>(buf))` is the correct way to reach the new object ([ptr.launder]). UBSan/ASan/MSan (libc++) at -O0 are clean.

**Potential Root cause**
`clang/lib/AST/Type.cpp`, `requiresBuiltinLaunderImpl` (used by `TypeRequiresBuiltinLaunder` in CGBuiltin.cpp): it strips arrays, returns true for a dynamic class, then recurses into `Record->fields()` only. It does not visit `Record->bases()`. `isDynamicClass()` covers a dynamic base, but not a non-dynamic base with a dynamic member (`TB : MB`, `MB` has `B b`).

**Possible Proposed fix**
```diff
   if (Record->isDynamicClass())
     return true;

+  for (const CXXBaseSpecifier &B : Record->bases())
+    if (requiresBuiltinLaunderImpl(Context, B.getType(), Seen))
+      return true;
+
   for (FieldDecl *F : Record->fields()) {
```

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to