Hacker News new | ask | show | jobs
by teddyh 971 days ago
In GCC you can already use (both on functions¹ and labels²)

  __attribute__(hot)
and

  __attribute(cold)
1. <https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gcc/Common-Functio...>; Since GCC 4.3, released March 5, 2008

2. <https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gcc/Label-Attribut...>; Since GCC 4.8, released March 3, 2013

1 comments

The typical expansion of pre attribute likely/unlikely macros (for example from the linux kernel) is buitin_expected. Hot/cold should also work if a bit extreme.
Note that those are ultimately dealing with different concepts:

likely/unlikely are ultimately about branches - predict that a likely branch is taken and an unlikely branch is not taken. Note that there is some default logic in GCC even if the branches aren't tagged (for example, pointers are assumed to usually not be NULL). Failing that it usually generates the code in the order the source was laid out, but I don't think there's any "probability" weight here, just inertia, so it's easy for the optimizer to change it even by accident.

Note that the default probabilities are 90% and 10% (I've seen other software use 93.75% = 15/16); you can specify other probabilities if meaningful. Notably, choosing 50% encourages the generation of `cmov`.

hot/cold is ultimately about code size and section layout. Keep the hot code sections in cache, keep the cold code sections out of cache (and optimize it for size more than speed). Branches from non-cold to cold code are automatically tagged unlikely (not sure about hot to non-hot, or cold to anything), which is what makes people think they're related.