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
1
vote
1 answer

Are Ada function arguments evaluated if the body is empty?

According to this statement : Trace.Debug("My String" & Integer'Image(x) & "is evaluated" & "or not" & "if my logger is disabled ?" & Boolean'Image(YesOrNo) ); And this implementation of Trace.Debug: procedure Debug (Message : in String) is begin…
LnlB
  • 180
  • 2
  • 11
1
vote
0 answers

Using cmov to convert conditional branches into indirect causes branch misses to increase

I have a program written in NASM 64 with seven "for" loops and one conditional branch from an if statement. Valgrind shows the following branch miss stats: ==22040== Branches: 23,608,086 (23,606,080 cond + 2,006 ind) ==22040==…
RTC222
  • 2,025
  • 1
  • 20
  • 53
1
vote
0 answers

Is there a way to implement ReLU without if statements?

I'm performing this operation a lot, and I want to avoid branch-prediction problems, so I'm asking here. For signed integer values, using only integer or bitwise arithmetic, can I implement the following statement without an IF clause, or other…
tuskiomi
  • 190
  • 1
  • 15
1
vote
0 answers

How to enable Visual Studio C++ branch optimization?

I have two functions below which in terms of execution should be identical. The only difference is that in the second function, funcB(), I moved the branch on (decobj == NULL) outside the loop which is always NULL anyway. I thought that the…
1
vote
1 answer

Mathematically find the value that is closest to 0

Is there a way to determine mathematically if a value is closer to 0 than another? For example closerToZero(-2, 3) would return -2. I tried by removing the sign and then compared the values for the minimum, but I would then be assigning the…
1
vote
3 answers

Is there a performance difference between cascading if-else statements and nested if statements

Is there a performance difference between cascading if-else statements like if (i > c20) { // ... } else if (i > c19) { // ... } else if (i > c18) { // ... } else if (i > c17) { // ... } else if (i > c16) { // ... } else if (i > c15) { // ... } else…
1
vote
1 answer

In C++, does the branch predictor predict implicit conditional statements?

In this code, it is written, result += runs[i] > runs[i-1];, an implicit conditional statement. In C++, does the branch predictor make predictions for this statement? Or do I have to explicitly use the if keyword to get branch prediction…
1
vote
1 answer

Viewing the parameters of the branch predictor in gem5

part question. First, how do I configure the size of a branch predictor? I can see that I can set the type using the se.py config script and the --bp-type argument. (In my case I'm setting it to LTAGE), but how do I change the size of the tables?…
KenArrari
  • 321
  • 1
  • 2
  • 7
1
vote
0 answers

How exactly static taken prediction work? and what are delay slots?

I know that not taken prediction is always assuming the branch isnt taken so PC keep working normal unless proven wrong that branch is taken so flush all the instructions behind branch in pipeline (assuming the branch is resolved in MEM stage) but…
Mostfa shma
  • 193
  • 1
  • 6
1
vote
1 answer

Do memory barriers prevent branch prediction?

This question does not assume any specific architecture. Assume that we have a multicore processor with cache coherence, out-of-order execution, and branch prediction logic. We also assume that stores to memory are strictly in program order. We have…
Daniel Nitzan
  • 1,582
  • 3
  • 19
  • 36
1
vote
0 answers

Removing CMOV Instructions using GCC-9.2.0 (x86)

I am looking to compile a set of benchmark suites using traditional GCC optimizations (as in using -O2/3) and comparing this with the same benchmark using no cmov instructions. I have seen several posts/websites addressing this issue (all from…
Matt
  • 11
  • 2
1
vote
1 answer

std::shared_ptr vs std::make_shared: unexpected cache misses and branch prediction

I'm trying to measure the efficiency of pointers created by std::shared_ptr and std::make_shared. I have the next testing code: #include #include #include struct TestClass { TestClass(int _i) : i(_i) {} int i =…
fsquirrel
  • 800
  • 8
  • 18
1
vote
1 answer

States of a 2-bit Branch Predictor

I was reading the dynamic branch prediction section in Chapter 5 of Computer Organization and Design: The Hardware/Software Interface 5th Edition by Patterson and Hennessy when I came across the following diagram for the states of the 2-bit…
Rijul Ganguly
  • 125
  • 1
  • 10
1
vote
1 answer

How to disable branch prediction C++/Mac/Intel

I am working on an assignment for school. Essentially, we are analyzing sorting algorithms and their costs on large sets of numbers. We have a best case (in order already), worst case (reverse order), and average case (random order). However, for…
1
vote
1 answer

How much impact does branch prediction have on Haskell program?

I am benchmarking insertion sort on worst case input (reverse ordered list) and random input. import Control.Monad import Data.List import System.Random import Control.Exception import Control.DeepSeq import Criterion.Main --- Sorting…
sqd
  • 1,485
  • 13
  • 23