Re:Push ifs up and fors down
by RenThraysk on Thursday November 16, 2023 @11:58AM
(#38292023)
That code shouldn't generate any branching (unless on an odd cpu). A serious compiler should recognise it can be done with a conditional move.
A conditional move is not guaranteed to be faster than a predictable branch. It varies a lot by microarchitecture. It was just an example. Imagine if you had a store in the else branch. Now optimizing away a store means that load elimination may kick in. Folding branches in the compiler unlocks tons of downstream benefits.
"If the branch condition is not volatile, compilers will usually lift it."
E.g.
If the compiler (or programmer) knows foo is greater than zero (even if we don't know what it actually is), then the whole thing folds into: That also means that foo is not even used, so it might get dead-code eliminated.If that gets inlined, then the optimizations just keep stacking up.
(not that the article was about that, it's just one implication of removing branches: downstream code can be optimized knowing more).
So, in summary, compilers matter.