Issue 241277
Summary [clang][CodeGen] Under-aligned packed member used directly as sret slot (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    `q.b = make();` where `q.b` is a member of a packed struct (offset 1). Clang passes `&q.b` as the sret pointer and marks it `sret align 16`. The callee stores with `movdqa` at -O3 and faults.

**Reproducer** (`repro.c`)
```c
/* make() returns a struct B into the packed member q.b (offset 1).
   Correct output: 4 (q.b.a[3]).  clang -O3: SIGSEGV. The caller passes &q.b
   (align 1) as the sret pointer marked "align 16"; make() stores with movaps. */
int printf(const char *, ...);
struct B { _Alignas(16) long a[4]; };
struct __attribute__((packed)) P { char c; struct B b; };
struct B make(void) { struct B r = {{1, 2, 3, 4}}; return r; }
struct B (*volatile mk)(void) = make;   /* keep make out of line */
int main(void) {
  struct P q = { 0, mk() };
  printf("%ld\n", q.b.a[3]);
 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
4
O0 rc=0
$ clang -O3 repro.c -o ./o3
$ ./o3
Segmentation fault
O3 rc=139
```
Expected (as `-O0`): `4`. `-O3` crashes with SIGSEGV.

**Why the expected output is right**
The program forms no pointer to the packed member; `q.b` is initialized by value from a call (C11 6.7.9) and read by member access. UBSan/ASan/MSan at -O0 are clean. (gcc -O2 has the same problem.)

**Potential Root cause**
`clang/lib/CodeGen/CGExprAgg.cpp`, `AggExprEmitter::withReturnValueSlot`: `UseTemp` is true only for aliasing, GC, destruction or address-space mismatch. It does not check that the destination is aligned enough for the return type, so `RetAddr = Dest.getAddress()` (the packed member, align 1) is used. `EmitCall` uses it as `SRetPtr` and `ConstructAttributeList` marks it `sret align 16` (`RetAI.getIndirectAlign()`).

**Possible Proposed fix**
```diff
   bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
- (RequiresDestruction && Dest.isIgnored()) || DestASMismatch;
+ (RequiresDestruction && Dest.isIgnored()) || DestASMismatch ||
+                 (!Dest.isIgnored() &&
+ Dest.getAlignment() < CGF.getContext().getTypeAlignInChars(RetTy));
```
More general: the same check in `EmitCall` where `SRetPtr = ReturnValue.getAddress()`.

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

Reply via email to