Issue 241249
Summary [clang][TBAA] Copy of a union member gets typed !tbaa.struct (ignores may-alias) (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    A struct member of a union is copied with `memcpy` + `!tbaa.struct` that names the struct field types. Clang treats a scalar read of the same union member as may-alias, but the copy is typed, so GVN forwards an old value past an `int` store to the same bytes.

**Reproducer** (`repro.c`)
```c
/* u.a and u.b share storage. get() stores the bits of 1.0f through the int
 member, then copies the struct member b (type punning through a union is
 allowed, C11 6.5.2.3p3). Correct output: 1 (clang -O0, gcc). clang -O3: 2. */
int printf(const char *, ...);

struct A { int x; };
struct B { float f; };
union U { struct A a; struct B b; };

float old;

float get(union U *u, struct A *pa) {
  old = u->b.f;          /* 2.0f */
  pa->x = 0x3f800000;    /* bit pattern of 1.0f */
  struct B y = u->b;     /* aggregate copy of the union member */
  return y.f;            /* 1.0f */
}

int main(void) {
  union U u;
  u.b.f = 2.0f;
  printf("%g\n", get(&u, &u.a));
  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 -O0 repro.c -o ./o0
$ ./o0
1
$ clang -O3 repro.c -o ./o3
$ ./o3
2
```
Expected (as `-O0`, gcc -O0/-O2): `1`. `-O3` prints `2`.

**Why the expected output is right**
The program stores an `int` through `pa->x` and then reads the union through a member access (`u->b`), which is type punning allowed by C11 6.5.2.3p3 and footnote 95. `0x3f800000` is a valid float. Clang itself treats the scalar read `u->b.f` as may-alias. UBSan/ASan/MSan at -O0 are clean.

**Possible Root cause**
`clang/lib/CodeGen/CGExprAgg.cpp`, `CodeGenFunction::EmitAggregateCopy`: `if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty)) Inst->setMetadata(MD_tbaa_struct, ...)`. The `!tbaa.struct` comes from the type only. For a union member, `EmitLValueForField` sets `TBAAAccessInfo::getMayAliasInfo()` on the lvalue, but `EmitAggregateCopy` does not look at it. InstCombine turns the memcpy into `load float !tbaa float`; GVN sees the earlier `store i32 !tbaa (A,int)` as NoAlias. (PR #84370 fixed whole-union copies only.)

**Possible Proposed fix**
```diff
-  if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
- Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
+  if (!Dest.getTBAAInfo().isMayAlias() && !Src.getTBAAInfo().isMayAlias())
+ if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
+ Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
```

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

Reply via email to