Questions tagged [branch-prediction]

In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Why is it faster to process a sorted array than an unsorted array? Stack Overflow's highest-voted question and answer is a good introduction to the subject.


In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g. an if-then-else structure) will go before this is known for sure. The purpose of the branch predictor is to improve the flow in the instruction pipeline.

Branch predictors play a critical role in achieving high effective performance in many modern pipelined microprocessor architectures such as x86.

Two-way branching is usually implemented with a conditional jump instruction. A conditional jump can either be "not taken" and continue execution with the first branch of code which follows immediately after the conditional jump - or it can be "taken" and jump to a different place in program memory where the second branch of code is stored.

It is not known for certain whether a conditional jump will be taken or not taken until the condition has been calculated and the conditional jump has passed the execution stage in the instruction pipeline.

Without branch prediction, the processor would have to wait until the conditional jump instruction has passed the execute stage before the next instruction can enter the fetch stage in the pipeline. The branch predictor attempts to avoid this waste of time by trying to guess whether the conditional jump is most likely to be taken or not taken. The branch that is guessed to be the most likely is then fetched and speculatively executed. If it is later detected that the guess was wrong then the speculatively executed or partially executed instructions are discarded and the pipeline starts over with the correct branch, incurring a delay.

The time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. The longer the pipeline the greater the need for a good branch predictor.

Source: http://en.wikipedia.org/wiki/Branch_predictor


The Spectre security vulnerability revolves around branch prediction:


Other resources

Special-purpose predictors: Return Address Stack for call/ret. ret is effectively an indirect branch, setting program-counter = return address. This would be hard to predict on its own, but calls are normally made with a special instruction so modern CPUs can match call/ret pairs with an internal stack.

Computer architecture details about branch prediction / speculative execution, and its effects on pipelined CPUs

  • Why is it faster to process a sorted array than an unsorted array?
  • Branch prediction - Dan Luu's article on branch prediction, adapted from a talk. With diagrams. Good introduction to why it's needed, and some basic implementations used in early CPUs, building up to more complicated predictors. And at the end, a link to TAGE branch predictors used on modern Intel CPUs. (Too complicated for that article to explain, though!)
  • Slow jmp-instruction - even unconditional direct jumps (like x86's jmp) need to be predicted, to avoid stalls in the very first stage of the pipeline: fetching blocks of machine code from I-cache. After fetching one block, you need to know which block to fetch next, before (or at best in parallel with) decoding the block you just fetched. A large sequence of jmp next_instruction will overwhelm branch prediction and expose the cost of misprediction in this part of the pipeline. (Many high-end modern CPUs have a queue after fetch before decode, to hide bubbles, so some blocks of non-branchy code can allow the queue to refill.)
  • Branch target prediction in conjunction with branch prediction?
  • What branch misprediction does the Branch Target Buffer detect?

Cost of a branch miss


Modern TAGE predictors (in Intel CPUs for example) can "learn" amazingly long patterns, because they index based on past branch history. (So the same branch can get different predictions depending on the path leading up to it. A single branch can have its prediction data scattered over many bits in the branch predictor table). This goes a long way to solving the problem of indirect branches in an interpreter almost always mispredicting (X86 prefetching optimizations: "computed goto" threaded code and Branch prediction and the performance of interpreters — Don't trust folklore), or for example a binary search on the same data with the same input can be really efficient.

Static branch prediction on newer Intel processors - according to experimental evidence, it appears Nehalem and earlier do sometimes use static prediction at some point in the pipeline (backwards branches default to predicted-taken, forward to not-taken.) But Sandybridge and newer seem to be always dynamic based on some history, whether it's from this branch or one that aliases it. Why did Intel change the static branch prediction mechanism over these years?

Cases where TAGE does "amazingly" well


Assembly code layout: not so much for branch prediction, but because not-taken branches are easier on the front-end than taken branches. Better I-cache code density if the fast-path is just a straight line, and taken branches mean the part of a fetch block after the branch isn't useful.

Superscalar CPUs fetch code in blocks, e.g. aligned 16 byte blocks, containing multiple instructions. In non-branching code, including not-taken conditional branches, all of those bytes are useful instruction bytes.


Branchless code: using cmov or other tricks to avoid branches

This is the asm equivalent of replacing if (c) a=b; with a = c ? b : a;. If b doesn't have side-effects, and a isn't a potentially-shared memory location, compilers can do "if-conversion" to do the conditional with a data dependency on c instead of a control dependency.

(C compilers can't introduce a non-atomic read/write: that could step on another thread's modification of the variable. Writing your code as always rewriting a value tells compilers that it's safe, which sometimes enables auto-vectorization: AVX-512 and Branching)

Potential downside to cmov in scalar code: the data dependency can become part of a loop-carried dependency chain and become a bottleneck, while branch prediction + speculative execution hide the latency of control dependencies. The branchless data dependency isn't predicted or speculated, which makes it good for unpredictable cases, but potentially bad otherwise.

363 questions
12
votes
4 answers

What can a compiler do with branching information?

On a modern Pentium it is no longer possible to give branching hints to the processor it seems. Assuming that a profiling compiler such as gcc with profile-guided optimization gains information about likely branching behavior, what can it do to…
12
votes
3 answers

Micro-optimizing a c++ comparison function

I have a Compare() function that looks like this: inline bool Compare(bool greater, int p1, int p2) { if (greater) return p1>=p2; else return p1<=p2; } I decided to optimize to avoid branching: inline bool Compare2(bool greater, int p1, int p2)…
dshin
  • 2,354
  • 19
  • 29
11
votes
2 answers

Performance of "conditional call" on amd64

When considering a conditional function call in a critical section of code I found that both gcc and clang will branch around the call. For example, for the following (admittedly trivial) code: int32_t __attribute__((noinline)) negate(int32_t num)…
Bailey Parker
  • 15,599
  • 5
  • 53
  • 91
11
votes
1 answer

Will Speculative Execution Follow Into an Expensive Operation?

If I understand branching correctly (x86), the processor will sometimes speculatively take a code path and perform the instructions and 'cancel' the results of the wrong path. What if the operation in the wrong codepath is very expensive, like a…
user1043761
  • 696
  • 6
  • 22
11
votes
2 answers

Where/how is branch prediction data stored?

I have always wondered where/how the prediction data is stored? Is there a limit? Is it only recent branches? I am mostly concerned about Intel architecture, but anything I can learn about any architecture is appreciated.
johnnycrash
  • 5,184
  • 5
  • 34
  • 58
11
votes
3 answers

Can branch prediction cause illegal instruction?

In the following pseudo-code: if (rdtscp supported by hardware) { Invoke "rdtscp" instruction } else { Invoke "rdtsc" instruction } Let's say the CPU does not support the rdtscp instruction and so we fallback to the else statement. If CPU…
mtoossi
  • 937
  • 8
  • 14
11
votes
1 answer

Can I use GCC's __builtin_expect() with ternary operator in C

The GCC manual only shows examples where __builtin_expect() is placed around the entire condition of an 'if' statement. I also noticed that GCC does not complain if I use it, for example, with a ternary operator, or in any arbitrary integral…
Kristian Spangsege
  • 2,903
  • 1
  • 20
  • 43
10
votes
1 answer

Any reason to use BX R over MOV pc, R except thumb interwork pre ARMv7?

Linux defines an assembler macro to use BX on CPUs that support it, which makes me suspect there is some performance reason. This answer and the Cortex-A7 MPCore Technical Reference Manual also states that it helps with branch prediction. However my…
10
votes
2 answers

Performance difference between branch prediction and branch target prediction?

I'm writing some audio code where basically everything is a tiny loop. Branch prediction failures as I understand them is a big enough performance issue that I struggle to keep the code branch free. But there is only so far that can take me, which…
porgarmingduod
  • 7,668
  • 10
  • 50
  • 83
10
votes
1 answer

branch prediction vs branch target prediction

Have I understood this right, if statements are more dependent on branch prediction and v-table look-up is more dependent on branch target prediction? Regarding v-tables, there is no "branch prediction", just the target prediction? Trying to…
user997112
  • 29,025
  • 43
  • 182
  • 361
10
votes
1 answer

Return stack buffer?

As I understood, Return Stack Buffer only supports 4 to 16 entries (from wiki: http://en.wikipedia.org/wiki/Branch_predictor#Prediction_of_function_returns) and is not pair of key-value(based on indexing by position of ret instruction). Is it…
9
votes
1 answer

How does Branch Prediction affect performance in R?

Some references: This is a follow-up on this Why is processing a sorted array faster than processing an unsorted array? The only post in r tag that I found somewhat related to branch prediction was this Why sampling matrix row is very…
M--
  • 25,431
  • 8
  • 61
  • 93
9
votes
1 answer

C++20: difference between [[likely]], [[unlikely]] and __builtin_expect?

Preliminary information: according to the recent ISO C++ Committee Trip Report, the [[ likely ]] and [[ unlikely ]] attributes for conditional branching will be added in C++20 and is available in the newest version of GNU GCC (you can play with it…
Chan Kha Vu
  • 9,834
  • 6
  • 32
  • 64
9
votes
1 answer

Why not just predict both branches?

CPU's use branch prediction to speed up code, but only if the first branch is actually taken. Why not simply take both branches? That is, assume both branches will be hit, cache both sides, and the take the proper one when necessary. The cache does…
9
votes
3 answers

Branch prediction and branch target prediction optimization

My code makes frequent calls to a function with multiple (unpredictable) branches. When I profiled, I found that it is a minor bottleneck, with the majority of CPU time used on the conditional JMPs. Consider the following two functions, where the…
frank90
  • 129
  • 5