Hacker News new | ask | show | jobs
by josephg 21 days ago
You've got it the wrong way around. If the branch predictor was 100% accurate, branchless code would have no performance benefit compared to branching code.

> X86 should support no-branch-predict-if

It almost does. You can use __builtin_expect to hint if the branch is predictable - like assertions. Don't annotate conditionals if they're truly unpredictable. The branch predictor will run, but it's not expensive.

2 comments

I'm not sure if you mean to imply so, but the __builtin_expect() hint is not embedded in the instruction stream in any way. It mostly affects basic block layout (and not always in a good way).
Newer Intel CPUs (Raptor Lake?) are "adding back" the "branch hint" prefixes. On the Pentium P4, the segment prefixes were repurposed on conditional branches to be branch hints, but then ditched because branch prediction got good. I guess as cores have gotten deeper and deeper it makes sense to bring them back?
Do you have a source? And is there any current compiler that will emit these hints?
Redwood Cove*. It's in the optimization manual (vol 1)[0], section 2.1.1.1. It explicitly references the "SSE2" branch hints (2E and 3E).

[0]: https://cdrdv2.intel.com/v1/dl/getContent/671488

So, it basically says:

  - Do not use them in hot code
  - Use them only if you have PGO (which ignores static hints like __builtin_expect)
  - Use them only if you cannot do it by basic block layout
So it seems very narrow. On top of that, it's only for the P-cores, whose design seems to be on their way out. But thanks, it's good to know nevertheless :-)
You should prefer using the standardized likely/unlikely attributes instead.
Branchless programming is a thing because those don't work, and branch prediction hurts performance on many cases
I think -- I know -- that you have misunderstood what branch prediction is.

Maybe you are asking for way to do static branch prediction for selected conditional branches instead of dynamic branch prediction (or as a supplement)? That's the most charitable way I can interpret your comments.

That is already part of the x86 architecture. Intel introduced it back in the Pentium 4 days. It takes the form of an extra prefix byte that hints the branch as "taken" or "not taken". The trick to doing it in a backwards compatible way is that they reuse the segment override prefixes (CS and DS). These hints are ignored on modern CPUs -- except maybe on some very new Intel CPUs? They are ignored because the dynamic branch predictor works better.