Issue 240402
Summary [clang] volatile struct passed by value after longjmp gets a stale value at -O1/-O2 (clang 23.1.5)
Labels clang
Assignees
Reporter RainerXE
    With clang 23.1.5 at `-O1` and `-O2`, a `volatile` struct local that is modified between `setjmp` and `longjmp` is passed by value after the jump with a stale value: the call receives the value of the initialization, not of the last store.

C11 7.13.2.1p3 makes such an object determinate when it is volatile-qualified and changed between `setjmp` and `longjmp`, so the program below must print `length 4`.

```c
#include <setjmp.h>
#include <stdio.h>
#include <stdint.h>
typedef struct { uint8_t* bytes; int32_t length; uint32_t flags; } S;
static const S init = { (uint8_t*)"t", 1, 1 };
static jmp_buf jb;
__attribute__((noinline)) static S grow(S in, int v) { S r = in; r.length += v; return r; }
__attribute__((noinline)) static void show(S s) { printf("length %d (expected 4)\n", s.length); }
__attribute__((noinline)) static void thrower(void) { longjmp(jb, 1); }
int main(void) {
    volatile S text = init;
    if (setjmp(jb) == 0) {
        for (int v = 1; v <= 3; v++) {
            text = grow(text, v);
            if (v == 2) thrower();
        }
    } else {
 show(text);
    }
    return 0;
}
```

| Compiler (Ubuntu 24.04, x86_64) | -O0 | -O1 | -O2 |
|---|---|---|---|
| Homebrew clang 23.1.5 | length 4 | **length 1** | **length 1** |
| Ubuntu clang 18.1.3 | length 4 | length 4 | length 4 |
| clang 22.1.8 (bundled with zig 0.17.1) | | length 4 | length 4 |
| gcc 13.3.0 | length 4 | length 4 | length 4 |

**IR** (`clang -O1 -S -emit-llvm`): every store to `text` is `store volatile`, but the argument in the `else` branch is the SSA value of the initialization load, and the read of `text` for the call is gone:

```llvm
  %6 = load volatile i64, ptr getelementptr inbounds nuw (i8, ptr @__const.main.text, i64 8), align 8
  store volatile i64 %6, ptr %2, align 8
  ...
  call fastcc void @show(i64 %6)
```

With `-O0 -Xclang -disable-O0-optnone`, the front end reads `text` for the by-value argument with plain (non-volatile) loads of the coerced pieces, which the optimizer then forwards from the initialization.

Workarounds that print 4 on 23.1.5: copy first (`S c = text; show(c);`), or pass the fields (`show((S){ text.bytes, text.length, text.flags })`).

Context: found by a compiler that generates C (every local of a function with a `try` is `volatile`, and the catch path reads it after `longjmp`).

This report was prepared with an AI coding agent (Claude Code). The reproduction and the IR excerpt were re-run on the machine in the table before filing.

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

Reply via email to