Issue 241904
Summary [PowerPC] wrong code at -O3: a 32-bit right shift by a constant becomes a left shift on big-endian powerpc64
Labels generated by fuzzer
Assignees
Reporter hazohelet
    Live Reproducer: https://godbolt.org/z/WhKvzd5Gz

Compiling the following C code for `powerpc64` with `clang -O3` and running it prints the wrong result.

```c
#include <stdio.h>
long g;
static volatile unsigned A = 1, B = 0;
int main(void) {
  if (B)
    return 1;
  int y = B;
  long s = A >> (g ? 2 / g : 1);
  g = y ? 2 : 0;
  printf("%ld\n", s);
}
```

clang command:

```sh
clang --target=powerpc64-linux-gnu -static -O3 repro.c && qemu-ppc64 ./a.out
```

Output (wrong):

```text
2
```

Expected (what -O0 prints, and what powerpc64le and x86-64 print):

```text
0
```

`g` is 0, so the shift count is 1 and `s` is `1 >> 1`, which is 0. In the block for `g == 0` the generated code shifts left instead, with `rlwinm 4, 5, 1, 0, 30`:

```asm
.LBB0_5:
        cmpwi   4, 0
        rlwinm 4, 5, 1, 0, 30
        li 5, 0
```

With `-mllvm -ppc-late-peephole=false` the same block has the right shift:

```asm
.LBB0_5:
        li 6, 1
 cmpwi   4, 0
        srw 4, 5, 6
        li 5, 0
```

Notes:

* Correct at -O0, -O1, -O2 and -Os, and for `powerpc64le`
* Correct with `-mcpu=pwr7`, `-mcpu=pwr8` or `-mllvm -ppc-late-peephole=false`
* The link adds `-mcpu=ppc64`, the default CPU for `powerpc64-linux-gnu` b/c without it Compiler Explorer's compiler emits the right shift

clang version:

```text
clang version 24.0.0git (https://github.com/llvm/llvm-project 7d25e4f9cd72686727beaf0b661ce3e910ee1349)
```

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

Reply via email to