Increment / Decrement (x86 - IA32, AMD64)

Make compiler generate "inc [foo]"/"dec [foo]" opcodes instead of "add [foo], 1"/"sub [foo], 1" when using "foo += 1"/"foo -= 1".

This is more an LLVM thing than a rustc thing. This is such an obvious thing that I'd assume that LLVM has a reason to not use inc. E.g.

It seems that because add updates all flags but inc only updates some flags (notably, it does not change the carry flag), inc introduces a "partial flags update stall" which is not present with add or lea.

This means that add can run at 4/clock and inc at 1/clock on many recentish x86 CPUs.

8 Likes

Indeed LLVM seems to emit inc at opt-level=0 and changes it to add 1 at opt-level=1 and above!

3 Likes

I translated

#![no_main]

#[no_mangle]
unsafe extern fn main() {
    static mut A: u8 = 0;
    A += 1;
}

to asm in rust playground and it generated add 1

According to my new info, "add [{mem}], {imm}" on Pentium is 3 tacts, which is adequate to 3 tacts of "inc [{mem}]". I understood this tread is unneccessary. Thank y'all for replying.

Erm... admins?... Can someone close this thread, please?