[InstCombine] Missed scmp fold with an offset-form range
llvm.scmp(x, 0) returns -1, 0, or 1 according to the sign of x. If x is known to be one of -1, 0, and 1, the result is x itself, adjusted only to the result width by truncation or sign extension.
For the following LLVM IR:
define i64 @src(i32 %x) {
entry:
%offset = add i32 %x, 1
%range = icmp ult i32 %offset, 3
call void @llvm.assume(i1 %range)
%r = call i64 @llvm.scmp.i64.i32(i32 %x, i32 0)
ret i64 %r
}
On current LLVM trunk, opt -O3 keeps the intrinsic call (Godbolt: https://godbolt.org/z/1jThj6he3):
define i64 @src(i32 %x) {
entry:
%offset = add i32 %x, 1
%range = icmp ult i32 %offset, 3
call void @llvm.assume(i1 %range)
%r = call i64 @llvm.scmp.i64.i32(i32 %x, i32 0)
ret i64 %r
}
The condition (x + 1) <u 3 holds exactly for x in {-1, 0, 1}. Alive2 verifies that the intrinsic call can therefore be replaced with a sign extension (https://alive2.llvm.org/ce/z/bStPFD):
%r = sext i32 %x to i64
ret i64 %r
If the range is attached to %x, the input is:
define i64 @scmp_zero_range_sext(i32 range(i32 -1, 2) %x) {
%r = call i64 @llvm.scmp.i64.i32(i32 %x, i32 0)
ret i64 %r
}
O3 performs the fold:
define i64 @scmp_zero_range_sext(i32 range(i32 -1, 2) %x) {
%1 = sext i32 %x to i64
ret i64 %1
}
The scmp(x, 0) combine already calls computeConstantRange() with SQ.getWithInstruction(II), so the range query has the required context. However, when consuming the assumption, computeConstantRange() requires the first comparison operand to be %x itself and does not translate icmp ult (x + 1), 3 back to a range for %x. A possible fix is to normalize an assumed comparison involving a constant-offset form of the tracked value, preserve the comparison predicate, and subtract the offset from the resulting allowed range before intersecting it with the tracked value’s range. It might also benefit other consumers that query contextual ranges for equivalent x + C forms, beyond the scmp combine.
Hi, I would love to work on this one.