| Issue |
241272
|
| Summary |
[X86] insert of -1 lowered as OR blend without freeze; or(poison, -1) is poison (miscompile at -O3)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
jeffchen006
|
Without SSE4.1, inserting `-1` into a `v16i8` is lowered as `or(V, <0,..,-1,..,0>)`. If lane i of V is poison, the OR is poison, not -1. A later constant fold then gives a wrong lane value.
**Reproducer** (`repro.c`)
```c
/* Correct output: 2 130 0. r = g | -1 = 255; k = r + {2, 130, 0, ...} = {1, 129, 255, ...};
k[11] = 255; w = 1 + k = {2, 130, ..., w[11] = 0}.
clang -O3 prints 2 130 1 (x86 lowers "insert -1 into lane 11" as an OR with a poison lane). */
int printf(const char *, ...);
typedef unsigned char v16 __attribute__((vector_size(16)));
typedef long v2 __attribute__((vector_size(16)));
long g;
int main(void) {
unsigned char r = __builtin_reduce_or((v2){g, -1});
v16 k = r + (v16){2, 130};
k[11] = 255;
v16 w = 1 + k;
printf("%d %d %d\n", w[0], w[1], w[11]);
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
$ ./o0
2 130 0
$ clang -O3 repro.c -o ./o3
$ ./o3
2 130 1
```
Expected (as `-O0`): `2 130 0`. `-O3` prints `2 130 1`.
**Why the expected output is right**
`unsigned char` / `unsigned long long` arithmetic only (wraps); constant lane indices < 16; lanes that are never printed are computed but unused. The -O3 IR is correct (`insertelement` overwrites the poison lane). UBSan/ASan/MSan at -O0 are clean.
**Potential Root cause**
`llvm/lib/Target/X86/X86ISelLowering.cpp`, `X86TargetLowering::LowerINSERT_VECTOR_ELT`, "Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend": `return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);`. `insert(V, -1, i) == or(V, mask)` only if lane i of V is not poison. Dagcombine #84 constant-folds the OR with the poison lane. `combineOr` already has "We must freeze the result to prevent OR(poison,-1) -> poison"; this lowering has no freeze.
**Possible Proposed fix**
```diff
SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
- return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
+ APInt DemandedElts = APInt::getOneBitSet(NumElts, IdxVal);
+ if (!DAG.isGuaranteedNotToBePoison(N0, DemandedElts))
+ N0 = DAG.getFreeze(N0);
+ return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs