Skip to main content

Module optimize

Module optimize 

Source
Expand description

Peephole optimizations for instruction encoding. Peephole optimizations for x86/x86-64 instructions.

These optimizations transform instructions into shorter or more efficient encodings. Which ones run is governed by OptLevel: the default OptLevel::Size is restricted to transforms that leave all architectural state (registers, memory, FLAGS) observably unchanged.

§Optimizations

State-preserving (applied at OptLevel::Size, the default):

  • Immediate narrowing: mov r64, imm where imm fits u32mov r32, imm32 (writes to a 32-bit register zero-extend, so the 64-bit result is unchanged); saves the REX.W byte.
  • REX elimination: and r64, imm where imm fits u32and r32, imm32 (the result’s upper 32 bits are zero either way).
  • Test conversion: and reg, regtest reg, reg (r & r == r, so the destination is unchanged, and both set FLAGS identically).

FLAGS-clobbering (requires OptLevel::Aggressive):

  • Zero idiom: mov reg, 0xor reg, reg (saves 3–5 bytes and is recognised as a dependency-breaking idiom by modern CPUs, but writes FLAGS).

Functions§

optimize_instruction
Apply peephole optimizations to an instruction (mutates in place).