Day 1 of Advent of Compiler Optimisations!

Why do compilers love `xor eax, eax` for zeroing registers? It's brilliant: saves bytes compared to `mov eax, 0`, AND x86 CPUs recognise this "zeroing idiom" early in the pipeline—breaking register dependencies and removing it from execution entirely. Even better: writing to `eax` zeroes the top 32 bits of `rax` for free, handling 64-bit longs in one instruction.

Read more: https://xania.org/202512/01-xor-eax-eax
Watch: https://youtu.be/eLjZ48gqbyg

#AoCO2025

Why xor eax, eax? — Matt Godbolt’s blog

Why do compilers love xor-ing registers so much?

@mattgodbolt wait xor eax, eax clears the top of rax?

I never knew that, and also that seems pretty bad. Does xor ax, ax also clear ALL of eax and rax?

@hp @mattgodbolt The point was that half-writes (like "mov ax, 0x42") creates a dependency chain, where that instruction itself depends on the old version of eax, and the next instruction then depends on this one, even if it only uses the ax part of it.

Clearing the top halves makes these things more intuitive, where it breaks dependencies. Then also "xor eax, eax" isn't really trying to xor something - it's trying to flag to the register allocator that the register is now free from the previous value of that register, and that it can be seen as equivalent to the zero register. This is *very* nice for the register renamer.

If they'd kept it only clearing the bottom 32 bits you would make the register allocator numb, and require an extra prefix for every time you do want to have the register allocator signal... is a bad idea.