| Issue |
241274
|
| Summary |
[clang][CodeGen] Member-pointer call claims align/deref of the derived class on base `this` (miscompile at -O3)
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
jeffchen006
|
`(p->*pm)()` with `pm = &A::clr` converted to `void (D::*)()` adjusts `this` to the A subobject (offset 8), but clang still marks the argument `nonnull align 16 dereferenceable(sizeof(D))`. At -O3 the alignment reaches the stores in `A::clr` and X86 uses `movaps` on an 8-aligned address.
**Reproducer** (`repro.cpp`)
```cpp
// D is 16-byte aligned; its base A is at offset 8. (p->*pm)() calls A::clr on the A part of d.
// Correct output: 0 (clr sets d.a[0] to 0). clang++ -O3: SIGSEGV. Clang marks the adjusted
// `this` (d + 8) "align 16", as if it pointed to a D, and the inlined loop uses movaps.
extern "C" int printf(const char *, ...);
struct A { unsigned a[4]; void clr() { for (int i = 0; i < 4; i++) a[i] = 0; } };
struct B { long b; };
struct alignas(16) D : B, A {};
void run(D *p) {
void (D::*pm)() = &A::clr;
(p->*pm)();
}
void (*volatile g)(D *) = run; // keep run out of line
int main() {
D d{};
d.a[0] = 1;
g(&d);
printf("%u\n", d.a[0]);
}
```
**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 repro.cpp -o ./o0
$ ./o0
0
O0 rc=0
$ clang++ -O3 repro.cpp -o ./o3
$ ./o3
Segmentation fault
O3 rc=139
```
Expected (as `-O0`): `0`. `-O3` crashes with SIGSEGV.
**Why the expected output is right**
`&A::clr` converted to `void (D::*)()` is valid ([conv.mem]/2, A is an unambiguous non-virtual base); `(p->*pm)()` on a live `D` calls `A::clr` with `this` = the A subobject. UBSan/ASan at -O0 are clean.
**Potential Root cause**
`clang/lib/CodeGen/CGExprCXX.cpp`, `CodeGenFunction::EmitCXXMemberPointerCallExpr`: after `EmitLoadOfMemberFunctionPointer` adjusts `this` (+8), it still passes it with `ThisType = pointer to RD` (RD = D). `ConstructAttributeList` (CGCall.cpp) then adds `nonnull dereferenceable(sizeof D) align alignof(D)`. FE IR: `call void %19(ptr noundef nonnull align 16 dereferenceable(28) %7)` with `%7 = p+8`.
**Possible Proposed fix**
```diff
- QualType ThisType = getContext().getPointerType(ClassType);
+ // The ABI may adjust 'this' to a base subobject of RD; do not claim RD's
+ // alignment or size for it.
+ QualType ThisType = getContext().VoidPtrTy;
```
(A finer fix keeps the attributes only for a constant member pointer with zero adjustment.)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs