| Issue |
242074
|
| Summary |
Suboptimal `saturating_mul(-1, x)`
|
| Labels |
backend:AArch64,
backend:X86,
missed-optimization
|
| Assignees |
|
| Reporter |
Kmeakin
|
https://godbolt.org/z/o6hMexvcr
# Rust example
```rs
#[unsafe(no_mangle)]
pub fn src1(x: u32) -> u32 {
(u32::MAX).saturating_mul(x)
}
#[unsafe(no_mangle)]
pub fn tgt1(x: u32) -> u32 {
if x == 0 { 0 } else { u32::MAX }
}
#[unsafe(no_mangle)]
pub fn src2(x: i32) -> i32 {
(-1i32).saturating_mul(x)
}
#[unsafe(no_mangle)]
pub fn tgt2(x: i32) -> i32 {
x.saturating_neg()
}
```
# AArch64 assembly
```asm
src1:
mov w8, #-1
cmp w0, #2
csneg w0, w8, w0, hs
ret
src2:
mov w8, #-2147483648
cmp w0, w8
mov w8, #2147483647
csneg w0, w8, w0, eq
ret
tgt1:
cmp w0, #0
csetm w0, ne
ret
tgt2:
mov w8, #2147483647
negs w9, w0
csel w0, w8, w9, vs
ret
```
# x86_64 assembly
Interestingly, `tgt2` gives worse assembly for x86_64
```asm
src1:
cmp edi, 2
jae .LBB0_2
mov eax, edi
neg eax
ret
.LBB0_2:
mov eax, -1
ret
src2:
mov eax, edi
neg eax
jo .LBB1_1
ret
.LBB1_1:
mov eax, 2147483647
ret
tgt1:
xor eax, eax
neg edi
sbb eax, eax
ret
tgt2:
xor eax, eax
mov ecx, edi
neg ecx
setns al
add eax, 2147483647
neg edi
cmovno eax, edi
ret
```
# Alive proof
https://alive2.llvm.org/ce/z/aCUAof
```llvm
----------------------------------------
define i32 @src1(i32 noundef %x) noundef {
start:
%_3.0 = sub nsw i32 0, noundef %x
%_3.1 = icmp ugt i32 noundef %x, 1
br i1 %_3.1, label %bb2, label %bb1
bb2:
br label %bb1
bb1:
%_0.sroa.0.0 = phi i32 [ 4294967295, %bb2 ], [ %_3.0, %start ]
%#range_0_%_0.sroa.0.0 = !range i32 %_0.sroa.0.0, i32 2147483649, i32 2147483648
ret i32 %#range_0_%_0.sroa.0.0
}
=>
define i32 @tgt1(i32 noundef %x) noundef {
start:
%#0 = icmp ne i32 noundef %x, 0
%. = sext i1 %#0 to i32
%#range_0_%. = !range i32 %., i32 4294967295, i32 1
ret i32 %#range_0_%.
}
Transformation seems to be correct!
----------------------------------------
define i32 @src2(i32 noundef %x) noundef {
start:
%_5.0 = sub nsw i32 0, noundef %x
%_5.1 = icmp eq i32 noundef %x, 2147483648
br i1 %_5.1, label %bb1, label %bb4
bb1:
br label %bb4
bb4:
%_0.sroa.0.0 = phi i32 [ 2147483647, %bb1 ], [ %_5.0, %start ]
%#range_0_%_0.sroa.0.0 = !range i32 %_0.sroa.0.0, i32 2147483649, i32 2147483648
ret i32 %#range_0_%_0.sroa.0.0
}
=>
define i32 @tgt2(i32 noundef %x) noundef {
start:
%_0 = ssub_sat i32 0, noundef %x
%#range_0_%_0 = !range i32 %_0, i32 2147483649, i32 2147483648
ret i32 %#range_0_%_0
}
Transformation seems to be correct!
Summary:
2 correct transformations
0 incorrect transformations
0 failed-to-prove transformations
0 Alive2 errors
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs