How do you recognize a conditional move (cmov) and when does it replace an if-else?
cmovCC copies its source to its destination only when the condition holds — a branchless replacement for short if-else that avoids branch-misprediction stalls.
* cmovCC replaces a short if-else with a branchless copy-if-condition, avoiding branch-misprediction stalls. *
cmp %esi, %edi
cmovl %esi, %edi
Means: "if %edi < %esi, then %edi = %esi" — i.e. whenever %edi is the smaller, replace it with %esi, so %edi ends up holding max(edi, esi).
Common uses:
| C code | Assembly |
|---|---|
x = (a < b) ? b : a |
cmp %esi, %edi + cmovl %esi, %edi |
if (a > 0) x = a |
test %edi, %edi + cmovg %edi, %eax |
max(a, b) |
cmp + cmovl |
min(a, b) |
cmp + cmovg |
Why branchless? The CPU executes cmov without a branch, avoiding branch misprediction penalties. Compilers use it for simple, short if-else where both paths are cheap.
All variants: cmove, cmovne, cmovl, cmovg, cmovle, cmovge, cmova, cmovb, etc. — same conditions as jCC jumps.
Go deeper: