Issue 235315
Summary [SelectionDAG] Store merging fuses `p[sext(x + 1)]` and `p[sext(x + 2)]` into one i16 store although the i8 add wraps
Labels miscompilation, llvm:SelectionDAG, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/764a4rc3r

```llvm
define void @f(ptr %p, i8 %x) {
 %a = add i8 %x, 1
  %ea = sext i8 %a to i64
  %pa = getelementptr i8, ptr %p, i64 %ea
  store i8 1, ptr %pa
  %b = add i8 %x, 2
  %eb = sext i8 %b to i64
  %pb = getelementptr i8, ptr %p, i64 %eb
  store i8 2, ptr %pb
 ret void
}

define i32 @main() {
  %buf = alloca [512 x i8]
  store i8 0, ptr %buf
  %p = getelementptr i8, ptr %buf, i64 128
  call void @f(ptr %p, i8 126)
  %v = load i8, ptr %buf
  %r = zext i8 %v to i32
  ret i32 %r
}
```

```console
$ llc -O2 repro.ll -o -
...
f: # @f
	.cfi_startproc
# %bb.0:
	incb	%sil
	movsbq	%sil, %rax
	movw	$513, (%rdi,%rax) # imm = 0x201
	retq
...

$ llubi repro.ll; echo $?
2
$ llc -O2 -filetype=obj repro.ll -o r.o && clang r.o -o r && ./r; echo $?
0
$ llc -O2 -combiner-store-merging=false -filetype=obj repro.ll -o r.o && clang r.o -o r && ./r; echo $?
2
```

### suggested fix
`matchLSNode` (SelectionDAGAddressAnalysis.cpp) skips a `SIGN_EXTEND` of the index and then folds the inner add's constant into `Offset`, i.e. it treats `sext(add iN x, C)` as `sext(x) + C`, which is wrong when the narrow add wraps.
Here both addresses decompose to index `x` (with `IsIndexSignExt` reset to false) and offsets 1 and 2, so `mergeConsecutiveStores` emits one i16 store at `p + sext(x + 1)`, although for x = 126 the second store is at `p - 128`.
After skipping a sign extension, fold the constant only if the add has `nsw` (`Index->getFlags().hasNoSignedWrap()`); otherwise keep the add as the index.

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

Reply via email to