Issue 233693
Summary [FastISel] `sdiv exact i64 %x, INT64_MIN` is selected as `sar %x, 63`
Labels llvm:codegen, miscompilation, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/nMs1ocj41

```llvm
target triple = "x86_64-unknown-linux-gnu"

@fmt = private constant [5 x i8] c"%ld\0A\00"
declare i32 @printf(ptr, ...)

define i64 @f(i64 %x) noinline {
  %q = sdiv exact i64 %x, -9223372036854775808
  ret i64 %q
}

define i32 @main() {
  %q = call i64 @f(i64 -9223372036854775808)
 call i32 (ptr, ...) @printf(ptr @fmt, i64 %q)
  ret i32 0
}
```

```console
$ llc -O0 -mtriple=x86_64-unknown-linux-gnu repro.ll -o -
f:
	movq	%rdi, %rax
	sarq	$63, %rax
	retq

$ llubi repro.ll
1
$ clang -O0 repro.ll && ./a.out
-1
$ clang -O0 -mllvm -fast-isel=false repro.ll && ./a.out
1
```

### suggested fix
`FastISel::selectBinaryOp` (FastISel.cpp) turns `sdiv exact X, C` into `sra X, log2(C)` when `isPowerOf2_64(CI->getSExtValue())`. For an i64 `INT64_MIN` the sign-extended value `0x8000000000000000` passes that check, but a negative divisor would also need a negation, so `INT64_MIN / INT64_MIN` yields -1 instead of 1.
Require a positive divisor (e.g. `!CI->isNegative()`) before the transform.

> Disclaimer: This test case was generated by a fuzzer, and the report was written with LLM assistance.

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

Reply via email to