Issue 241253
Summary [X86] matchBinaryShuffle turns a blend into OR using known-zero of poison lanes (miscompile at -O3)
Labels new issue
Assignees
Reporter jeffchen006
    A blend of `ashr exact` (lane 1 is poison: shift by 255) and an `and` is turned into an OR. `computeKnownBits` says the poison lane is zero, so the OR keeps it, and `vpsravq` with count 255 gives the sign fill.

**Reproducer** (`repro.c`)
```c
/* All a[k] are -2. For i = 1, f stores d[14] = e[11] + (unsigned char)p[11]
   = -2 + 254 = 252: the program must print 252. Clang -O3 -march=znver4
   prints -3 (the value 254 is ORed with a poison lane, which is -1). */
int printf(const char *, ...);
double d[16];
long long a[16] = {-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2};
void f(const long long *e, const long long *p, double *g, long n) {
  for (long i = 0; i < n; i++) {
    g[8 * i + 1] = e[8 * i + 1] + (char)p[i & 255] + 562949953421312;
    g[8 * i + 5] = (char)e[8 * i + 5] + p[8 * i + 2];
    g[8 * i + 6] = e[8 * i + 3] + (unsigned char)p[8 * i + 3];
  }
}
void (*volatile fp)(const long long *, const long long *, double *, long) = f;
int main(void) {
  fp(a, a, d, 2);
  printf("%g\n", d[14]);
  return 0;
}
```

**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 -march=znver4 repro.c -o o0
$ ./o0
252
$ clang -O3 -march=znver4 repro.c -o o3
$ ./o3
-3
```
Expected (as `-O0`): `252`. `-O3` prints `-3`.

**Why the expected output is right**
All values are small integers and convert exactly to `double`; the `(char)` conversion is implementation-defined (the same at all -O levels). The IR before the back end is correct (it selects the lane from the `and`). UBSan/ASan/MSan at -O0 are clean.

**Potential Root cause**
`llvm/lib/Target/X86/X86ISelLowering.cpp`, `matchBinaryShuffle` (from `combineX86ShuffleChain`): "blend -> OR if the non-blended source element is zero" uses `DAG.MaskedVectorIsZero` / per-element `computeKnownBits`. For an always-poison `SRA`, `KnownBits::ashr` returns zero ("Always poison. Return zero"), so the poison lane counts as known zero and the blend becomes an OR. The OR keeps the poison lane (`vpternlogq $248`).

**Possible Proposed fix**
Before the two `Shuffle = ISD::OR` returns, require the zero lanes to be not poison:
```diff
+      if (!DAG.isGuaranteedNotToBePoison(V1, DemandedZeroV1) ||
+ !DAG.isGuaranteedNotToBePoison(V2, DemandedZeroV2))
+        <skip the OR match>
```
(or freeze the operand).

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

Reply via email to