All Topics
All Topics
Technology
Technology
Design
Design
Programming
Programming
Science
Science
News
News
Gaming
Gaming
Entertainment
Entertainment
Business
Business
Finance
Finance
Sports
Sports
Health
Health
Food
Food
Travel
Travel
Art
Art
Music
Music
Books
Books
Education
Education
Politics
Politics
Personal
Personal
No algorithm. No AI slop. No ads. Just RSS. Pro-human. Indie writers. Real journalism. Open web. Chronological. Hand toasted.

Compiler Optimization: Why XOR Instructions Are Used to Zero Registers in x86 Assembly

By

hasheddan

6mo ago· 3 min readenInsight

Summary

The article explores why the XOR instruction appears so frequently in compiled x86 code, explaining that compilers use 'xor eax, eax' as an efficient way to zero registers. The author, Matt Godbolt, discusses how this optimization technique became common practice among compiler writers and how it's more efficient than using 'mov eax, 0' due to smaller instruction size and better performance characteristics. The article provides technical insights into compiler optimization strategies and assembly language patterns.

Key quotes

· 4 pulled
In one of my talks on assembly, I show a list of the 20 most executed instructions on an average x86 Linux desktop. All the usual culprits are there, mov, add, lea, sub, jmp, call and so on, but the surprise interloper is xor - 'eXclusive OR'.
In my 6502 hacking days, the presence of an exclusive OR was a sure-fire indicator you'd either found the encryption part of the code, or some kind of sprite routine. It's surprising then, that a Linux machine just minding its own business, would be executing so many.
That is, until you realize that compilers love to use xor to zero registers. 'xor eax, eax' is the canonical way to set eax to zero, and it's used all over the place in compiled code.
The reason is simple: it's smaller and faster than 'mov eax, 0'. The xor instruction is only two bytes, while the mov instruction is five. And on modern processors, xor has special handling that makes it even faster.
Snippet from the RSS feed
Why do compilers love xor-ing registers so much?

You might also wanna read