x.abs() vs negation (-x) performance in Rust, when x is a known negative number

Solution 1:

Checking these two cases in the playground, we get the following assembly:

playground::abs:
    movl    %edi, %eax
    negl    %eax
    cmovll  %edi, %eax
    retq

playground::negate:
    movl    %edi, %eax
    negl    %eax
    retq

However, if it's known to optimizer that the value of x is indeed negative, these two versions became equivalent. For example, these two functions are both semantically no-ops:

pub fn extending_abs(x: u8) -> u32 {
    abs(-(x as i32))
}

pub fn extending_negate(x: u8) -> u32 {
    negate(-(x as i32))
}

And the assembly for both of them indeed consists only of the zero-extension:

playground::extending_abs:
    movzbl  %dil, %eax
    retq

playground::extending_negate:
    movzbl  %dil, %eax
    retq