| Issue |
241252
|
| Summary |
[clang][TBAA] C23 compatible structs in different scopes get different pointer TBAA names (miscompile at -O3)
|
| Labels |
|
| Assignees |
|
| Reporter |
jeffchen006
|
In C23 a block-scope `struct foo` with the same tag and members is compatible with the file-scope `struct foo`. Clang names pointer TBAA nodes with the Itanium mangled name, which includes the enclosing function for the block-scope type, so stores through the two compatible pointer types are treated as NoAlias.
**Reproducer** (`repro.c`)
```c
/* C23 6.2.7p1: the block-scope struct foo in f (same tag, same members) is
compatible with the file-scope struct foo, so *pl is the object gp.
Correct output: 2 (clang -O0). clang -O3: 1. */
int printf(const char *, ...);
struct foo { int a; } x = {1}, y = {2}, *gp;
int f(struct foo **pp) {
struct foo { int a; } **pl = (void *)pp;
gp = &x;
*pl = &y; /* pp == &gp, so now gp == &y */
return gp->a; /* 2 */
}
int main(void) {
printf("%d\n", f(&gp));
return 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 -std=c23 -O0 repro.c -o ./o0
$ ./o0
2
$ clang -std=c23 -O3 repro.c -o ./o3
$ ./o3
1
```
Expected (as `-O0`): `2`. `-O3` prints `1`.
**Why the expected output is right**
C23 6.2.7p1 (N3037): same tag and same members -> compatible in the same TU; 6.7.6.1p2: pointers to compatible types are compatible. The program writes `gp` through a compatible lvalue type (6.5p7). Clang accepts it in C23 without a warning. UBSan/ASan/MSan at -O0 are clean. Only `-fno-strict-aliasing` / `-fno-pointer-tbaa` remove the difference.
**Potential Root cause**
`clang/lib/CodeGen/CodeGenTBAA.cpp`, `CodeGenTBAA::getTypeInfoHelper`, pointer branch: for a named record pointee the node name is `"p<depth> " + mangleCanonicalTypeName(pointee)`. The block-scope type mangles to `_ZTSZ1fE3foo`, the file-scope type to `_ZTS3foo`, so they get two sibling nodes under "any pointer". InstCombine then forwards `@x` to the load of `gp`. Only unnamed records are guarded (#116596).
**Possible Proposed fix**
In C, do not use the mangler for record pointees; use the plain tag name (as `getBaseTypeInfoHelper` already does for C struct-path names):
```diff
- llvm::raw_svector_ostream TyOut(TyName);
- MangleCtx->mangleCanonicalTypeName(QualType(Ty, 0), TyOut);
+ if (!Features.CPlusPlus) {
+ TyName = "struct "; // or "union "
+ TyName += RT->getDecl()->getName();
+ } else {
+ llvm::raw_svector_ostream TyOut(TyName);
+ MangleCtx->mangleCanonicalTypeName(QualType(Ty, 0), TyOut);
+ }
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs