| Issue |
240651
|
| Summary |
[clang][CodeGen] Compound `>>=`, `/=` and `%=` on a signed `_Atomic char`/`_Atomic short` zero-extend the old value
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
20000419
|
For a compound assignment on a signed `_Atomic` integer narrower than `int`, clang promotes the loaded old value with a zero extension instead of a sign extension. Operators whose result depends on the sign of the promoted value then compute the wrong thing: `>>=`, `/=` and `%=`. `+=`, `-=`, `&=`, `|=` and `^=` are unaffected because the low bits are the same either way. The same code without `_Atomic` is correct.
```c
#include <stdio.h>
#include <stdatomic.h>
volatile int _one_ = 1, three = 3;
int main(void) {
_Atomic char a = -1; a >>= one; /* -1 >> 1 */
_Atomic signed char b = -8; b >>= one; /* -8 >> 1 */
_Atomic short c = -100; c /= three; /* -100 / 3 */
_Atomic short d = -100; d %= three; /* -100 % 3 */
printf("a=%d b=%d c=%d d=%d\n", (int)a, (int)b, (int)c, (int)d);
return 0;
}
```
`clang -O0 t.c && ./a.out` (x86-64)
Expected `a=-1 b=-4 c=-33 d=-1`. clang prints `a=127 b=124 c=21812 d=0` at every optimization level. gcc 14 prints the expected values at `-O0` and `-O2`.
Godbolt: https://godbolt.org/z/G387vssq5
C11 6.5.16.2p3: `E1 op= E2` is equivalent to `E1 = E1 op (E2)` except that `E1` is evaluated once, and for an atomic object it is a read-modify-write with these semantics. The usual arithmetic conversions promote the `signed char`/`short` old value to `int`, so `-1 >> 1` is `-1` and `-100 / 3` is `-33`.
In the `-O0` IR the old value is loaded as `i8`/`i16` and widened with `zext` before the `ashr`/`sdiv`/`srem`; the non-atomic version uses `sext`. These operators have no `atomicrmw` form, so `ScalarExprEmitter::EmitCompoundAssignLValue` (`clang/lib/CodeGen/CGExprScalar.cpp`) takes the `cmpxchg` loop path and promotes the loaded value with `EmitScalarConversion(OpInfo.LHS, LHSTy, ...)`, where `LHSTy` is the `_Atomic` type. `isSignedIntegerOrEnumerationType()` is false for an `AtomicType`, so the conversion zero-extends. The store back already converts to `atomicTy->getValueType()`. Using the value type of the atomic for the load-side conversion as well should fix it (not tested).
Versions (x86-64): wrong output at `-O0`, `-O1`, `-O2`, `-O3` and `-Os` with clang 15.0.6, 16.0.4, 17.0.6, 19, 20, 21, 22, 23 and trunk (24.0.0, 7bdabc8be443). `-O0` is also wrong with clang 3.8.0, 6.0.0, 9.0.0, 11.0.0, 14.0.0 and 18.1.0. gcc 14 (`-O0`, `-O2`) and gcc trunk (`-O2`) print the expected values.
Disclaimer: This test case was found with LLM-assisted targeted testing, and the report was written with LLM assistance.
Assisted-by: Grok
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs