| Issue |
242266
|
| Summary |
[PowerPC] `cmpwi` folded into a record-form `or.` relies on a sign extension that a 4-byte spill (`stw`/`lwz`) does not keep
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
hazohelet
|
Live Reproducer: [https://godbolt.org/z/EKjsa8fcY](<https://godbolt.org/z/EKjsa8fcY>)
Compiling the following C code for `powerpc64le` with `clang -O2` (or -O3) and running it prints the wrong result.
```c
#include <stdio.h>
static volatile short A = -1;
static volatile signed char B = 1;
int G;
__attribute__((noinline)) long f(int n) {
short x = A;
long v[30];
for (int i = 0; i < 30; i++)
v[i] = n + i;
while (n--)
for (int i = 0; i < 30; i++)
v[i] += v[(i + 1) % 30];
G = (x | B) < 0 ? x : 1;
return v[0];
}
int main(void) {
f(2);
printf("%d\n", G);
}
```
clang command:
```sh
clang --target=powerpc64le-linux-gnu -O2 repro.c && qemu-ppc64le ./a.out
```
Output (wrong):
```text
1
```
Expected (what -O0 prints):
```text
-1
```
`x` is -1 and `B` is 1, so `x | B` is -1, and `G` should be `x`.
The loop keeps the 30 elements of `v` in registers, so `x`, which the loop does not use, is spilled around it. The compare of `x | B` with 0 is folded into a record-form `or.`, whose CR0 compares all 64 bits of the result with 0. `x` comes from a sign-extending `lha`, but it is spilled with a 4-byte `stw` and reloaded with a `lwz`, which zero-extends. After the reload the register holds 0x00000000ffffffff, the 64-bit `or.` result is positive, and `isellt` picks 1:
```asm
lha 4, 2(4)
stw 4, 36(1) # 4-byte Folded Spill
...
lwz 5, 36(1) # 4-byte Folded Reload
...
extsb 4, 4
...
or. 4, 4, 5
li 4, 1
isellt 4, 5, 4
```
Notes:
* `-O2` and `-O3` are wrong; `-O0`, `-O1`, `-Os` and `-Oz` are correct, and so are `-mcpu=pwr9`, `-mcpu=pwr10` and `powerpc64` (big-endian)
* Correct with `-mllvm -ppc-cmp-opt=false` and with `-mllvm -disable-peephole`
* Clang 21.1.8 to 23.1.2 are wrong too; 18.1.8 to 20.1.8 print the right result, but they also fold the compare into `or.` and only do not spill `x` in this program
clang version:
```text
clang version 24.0.0git (https://github.com/llvm/llvm-project 4e8f741d81620d640c4d25b9e78f327772e60ed7)
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs