r/programming • • Aug 22 '26

The unlikely Linux macro

https://rushed-reflections.bearblog.dev/an-unlikely-experiment/

Wrote a bit about the `unlikely` and `likely` macros in the Linux codebase. Great little exploration into tiny optimizations that everyone should know more about 😄

188 Upvotes

61 comments sorted by

View all comments

24

u/yanitrix Aug 23 '26

ah, branch prediction, my favourite thing about compilers

27

u/UnrealHallucinator Aug 23 '26

This isn't branch prediction. It's just a compiler hint that places the likely basic block immediately below the existing basic block as a fall through, thus allowing efficient cpu pipelining (which could lead to better branch prediction and speculative execution). Branch predictors and pre fetchers work more with patterns (strided access for eg) and are hardware optimisations.

17

u/LeeHide Aug 23 '26

Isn't that a processor feature, not a compiler one? A compiler can emit it such that it's convenient for the processor to predict a specific way, but the prediction is in the processor.

8

u/theangeryemacsshibe Aug 23 '26

Compilers can branch predict too, for the sake of working out code layout (as in OP) or deciding if optimisations are profitable by spotting hot/cold variables/control flow. Here's some branch prediction heuristics for compilers for example.

1

u/yanitrix Aug 23 '26

i think it can be both, actually