Issue 241292
Summary [X86] combineOr keeps `disjoint` after it simplifies operand 0 (miscompile at -O3)
Labels new issue
Assignees
Reporter jeffchen006
    `or disjoint %3, <-1, 2>`: lane 0 of the constant is all-ones, so `combineOr` simplifies operand 0 in that lane (removes `insertelement 0`). The OR keeps `disjoint`, which is now false, and a later fold turns `or disjoint` into `sub`.

**Reproducer** (`repro.c`)
```c
int printf(const char *, ...);
typedef unsigned long long v4 __attribute__((vector_size(32)));
v4 g = {1, 3, 5, 7};
unsigned long long out[4];
volatile int zero = 0;
int main(void) {
  v4 m = g * 0xff80000000000000ULL; /* low 55 bits of every lane are 0 */
  m[0] = -3; /* lane 0: ...11101 */
  m = m | 2; /* lane 0 becomes -3 | 2 = -1 */
  for (int i = 0; i < 4; i++) out[i] = m[i];
  printf("%llx\n", out[zero]);      /* correct: ffffffffffffffff */
  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 repro.c -o O0.out
$ ./O0.out
ffffffffffffffff
$ clang -O3 repro.c -o O3.out
$ ./O3.out
ff7fffffffffffff
```
Expected (as `-O0`): `ffffffffffffffff`. `-O3` prints `ff7fffffffffffff`.

**Why the expected output is right**
`unsigned long long` vector arithmetic (wraps); a `volatile int zero` only selects lane 0; lane writes by constant index. The `disjoint` flag is true in the IR. UBSan/ASan/MSan at -O0 are clean.

**Potential Root cause**
`llvm/lib/Target/X86/X86ISelLowering.cpp`, `combineOr` ("If second operand is a constant mask, then only the elements that aren't allones are actually demanded by the first operand"): `TLI.SimplifyDemandedVectorElts(N0, DemandedElts, DCI)` removes the insert of 0 into lane 0, then `DAG.UpdateNodeOperands(N, F0, N->getOperand(1))` keeps all flags of N, also `disjoint`. Lane 0 of N0 is now `x0 * C`, not 0. A later fold `or disjoint (sub 0, y), C -> sub C, y` uses the false flag.

**Possible Proposed fix**
```diff
         SDValue F0 = DAG.getFreeze(N->getOperand(0), ~DemandedElts);
+ N->dropFlags(SDNodeFlags::Disjoint);
         DAG.UpdateNodeOperands(N, F0, N->getOperand(1));
```
(If `UpdateNodeOperands` CSEs into an existing node, drop the flag there too.)

**Reduced IR**
```llvm
define <2 x i64> @f(<2 x i64> %0) {
  %2 = mul <2 x i64> %0, <i64 poison, i64 -36028797018963968>
 %3 = insertelement <2 x i64> %2, i64 0, i64 0
  %4 = or disjoint <2 x i64> %3, <i64 -1, i64 2>
  ret <2 x i64> %4
}
```
`llc -O2` on this IR: for x = <1, 0> lane 0 of the result must be -1; it is `-1 - (x0 << 55)`.

Related: PR #230700 (fb2596089e9d) drops `Disjoint` when generic TargetLowering demanded-bits code rewrites an OR operand. This X86 `combineOr` call site was not changed and still keeps the flag.

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

Reply via email to