Reputation: 5118
Does rustc optimize such expressions?
Upvotes: 3
Views: 537
Reputation: 2863
Such trivial optimizations are in the domain of LLVM optimization passes, in fact generated assembly is even better and more correct.
2*x
is compiled to single instruction lea rax, [rdi + rdi]
, which on all modern x86 processors is single uop (relevant question)
x/2
for signed numbers is compiled to fastest and the correct way, which gives right answer in case of -1
(relevant question
mov rax, rdi
shr rax, 63
add rax, rdi
sar rax
but compiles to right shift for unsigned numbers
mov rax, rdi
shr rax
same story goes for x % 8
it compiles to long assembly for signed numbers (for negative cases)
mov rax, rdi
lea rcx, [rdi + 7]
test rdi, rdi
cmovns rcx, rdi
and rcx, -8
sub rax, rcx
ret
and to and
instruction for unsigned numbers (relevant question)
mov rax, rdi
and eax, 7
ret
Upvotes: 3