Issue 244613
Summary Wrong code at -O1 and above: `lshr (xor (vector.reduce.or V), (vector.reduce.umax V)), 7` lowered to a single MOVMSK "any sign bit" test
Labels new issue
Assignees
Reporter haoxintu
    ## Description

```c
typedef unsigned char v4 __attribute__((ext_vector_type(4)));

__attribute__((noinline)) unsigned char
f (unsigned char x)
{
  v4 v = x; /* splat */
  return (__builtin_reduce_or (v) ^ __builtin_reduce_max (v)) >> 7;   /* (x ^ x) >> 7 == 0 */
}

int main (void)
{
  if (f (128) != 0)
    __builtin_abort ();
  return 0;
}
```

```
$ clang -O1 repro.c && ./a.out      # Aborted (also -O2, -O3, -Os); -O0 is fine
```

The IR after the middle end is correct. `llc -O2` alone miscompiles it:

```llvm
define i8 @f(i8 %x) {
  %ins = insertelement <4 x i8> poison, i8 %x, i64 0
  %v = shufflevector <4 x i8> %ins, <4 x i8> poison, <4 x i32> zeroinitializer
  %or = call i8 @llvm.vector.reduce.or.v4i8(<4 x i8> %v)
  %max = call i8 @llvm.vector.reduce.umax.v4i8(<4 x i8> %v)
  %xor = xor i8 %or, %max
  %r = lshr i8 %xor, 7
  ret i8 %r
}
```

```
	pmovmskb	%xmm0, %eax
	testl	%eax, %eax
	setne	%al
```

The `xor` of the two reductions followed by `lshr 7` is compiled as "is the sign bit of any lane set". So for `x = 128` it returns 1 instead of `(128 ^ 128) >> 7 = 0`.

- Each reduction on its own is correct, and so are `or ^ and`, `max ^ min` and `or ^ or`. Only the `or ^ umax` pair fails.
- It fails the same way with 4, 6, 8 and 16 lanes.
- Sanitizers (ASan, UBSan) are clean.

Reproduced in Godbolt (x86-64 clang assertions trunk, -O2): https://godbolt.org/z/dqKrGe6Mj

## Checked Versions

- Wrong at -O1/-O2/-O3/-Os with clang trunk 2012344e5da8 (2026-11-19); -O0 is correct.

Thanks.

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

Reply via email to