| Issue |
240049
|
| Summary |
`x.saturating_add(x)` gives better assembly than `x.saturating_mul(2)`
|
| Labels |
backend:AArch64,
backend:X86,
missed-optimization
|
| Assignees |
|
| Reporter |
Kmeakin
|
Instead of shifting left by 1 and comparing `x` against a constant, add `x` to itself and use `adds` instruction to detect overflow:
# Rust example
https://godbolt.org/z/E3Mjv3Te7
```rs
#[unsafe(no_mangle)]
pub fn src1(x: u32) -> u32 {
x.saturating_mul(2)
}
#[unsafe(no_mangle)]
pub fn tgt1(x: u32) -> u32 {
x.saturating_add(x)
}
#[unsafe(no_mangle)]
pub fn src2(x: i32) -> i32 {
x.saturating_mul(2)
}
#[unsafe(no_mangle)]
pub fn tgt2(x: i32) -> i32 {
x.saturating_add(x)
}
```
# AArch64 assembly
```asm
src1:
lsl w9, w0, #1
mov w8, #-1
tst w0, #0x80000000
csel w0, w9, w8, eq
ret
tgt1:
adds w8, w0, w0
csinv w0, w8, wzr, lo
ret
src2:
asr w9, w0, #31
mov w8, #1073741824
lsl w10, w0, #1
cmn w0, w8
eor w8, w9, #0x7fffffff
csel w0, w10, w8, pl
ret
tgt2:
adds w8, w0, w0
asr w9, w8, #31
eor w9, w9, #0x80000000
csel w0, w9, w8, vs
ret
```
# x86_64 assembly:
```asm
src1:
test edi, edi
js .LBB0_2
mov eax, edi
add eax, edi
ret
.LBB0_2:
mov eax, -1
ret
src2:
mov eax, edi
mov ecx, edi
add ecx, 1073741824
js .LBB1_2
add eax, eax
ret
.LBB1_2:
shr eax, 31
add eax, 2147483647
ret
tgt1:
add edi, edi
mov eax, -1
cmovae eax, edi
ret
tgt2:
lea eax, [rdi + rdi]
sar eax, 31
add eax, -2147483648
add edi, edi
cmovno eax, edi
ret
```
# Alive proof
https://alive2.llvm.org/ce/z/W8iZ7v
```llvm
----------------------------------------
define i32 @src1(i32 noundef %x1) noundef {
start:
%_3.0 = shl nuw i32 noundef %x1, 1
%_3.1 = icmp slt i32 noundef %x1, 0
br i1 %_3.1, label %bb2, label %bb1
bb2:
br label %bb1
bb1:
%x.sroa.0.0 = phi i32 [ 4294967295, %bb2 ], [ %_3.0, %start ]
ret i32 %x.sroa.0.0
}
=>
define i32 @tgt1(i32 noundef %x) noundef {
start:
%_0 = uadd_sat i32 noundef %x, noundef %x
ret i32 %_0
}
Transformation seems to be correct!
----------------------------------------
define i32 @src2(i32 noundef %x1) noundef {
start:
%_5.0 = shl nsw i32 noundef %x1, 1
%#0 = add i32 noundef %x1, 1073741824
%_5.1 = icmp slt i32 %#0, 0
br i1 %_5.1, label %bb5, label %bb4
bb5:
%_3 = icmp sgt i32 noundef %x1, 4294967295
%. = select i1 %_3, i32 2147483647, i32 2147483648
br label %bb4
bb4:
%x.sroa.0.0 = phi i32 [ %_5.0, %start ], [ %., %bb5 ]
ret i32 %x.sroa.0.0
}
=>
define i32 @tgt2(i32 noundef %x) noundef {
start:
%_0 = sadd_sat i32 noundef %x, noundef %x
ret i32 %_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