0% found this document useful (0 votes)
14 views183 pages

Anch Prediction

Uploaded by

6cc6nqjdzn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views183 pages

Anch Prediction

Uploaded by

6cc6nqjdzn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 183

Digital Design & Computer Arch.

Lecture 16b: Branch Prediction

Prof. Onur Mutlu

ETH Zürich
Spring 2023
27 April 2023
Roadmap for Today (and Past 2-3 Weeks)
n Microarchitecture Fundamentals
q Single-cycle Microarchitectures Problem
q Multi-cycle Microarchitectures Algorithm
Program/Language
n Pipelining & Precise Exceptions System Software
SW/HW Interface
q Pipelining
Micro-architecture
q Pipelined Processor Design
Logic
n Control & Data Dependence Handling
Devices
n Precise Exceptions: State Maintenance & Recovery
Electrons

n Last+this week: Out-of-Order & Superscalar Execution


q Out-of-Order Execution
q Dataflow & Superscalar Execution
q Branch Prediction
2
Readings
n This week

q Smith and Sohi, “The Microarchitecture of Superscalar


Processors,” Proceedings of the IEEE, 1995

q H&H Chapters 7.8 and 7.9

q McFarling, “Combining Branch Predictors,” DEC WRL Technical


Report, 1993.

q Optional: Kessler, “The Alpha 21264 Microprocessor,” IEEE


Micro 1999.

3
Control Dependence Handling

4
Recall: Control Dependence
n Question: What should the fetch PC be in the next cycle?
n Answer: The address of the next instruction
q All instructions are control dependent on previous ones. Why?

n If the fetched instruction is a non-control-flow instruction:


q Next Fetch PC is the address of the next-sequential instruction
q Easy to determine if we know the size of the fetched instruction

n If the instruction that is fetched is a control-flow instruction:


q How do we determine the next Fetch PC?

n In fact, how do we even know whether or not the fetched


instruction is a control-flow instruction?
Lecture 13, DDCA Spring 2023 https://www.youtube.com/watch?v=523JOL6jck0&list=PL5Q2soXY2Zi-EImKxYYY1SZuGiOAOBKaf&index=16
Branch Types
Type Direction at Number of When is next
fetch time possible next fetch address
fetch addresses? resolved?
Conditional Unknown 2 Execution (register
dependent)
Unconditional Always taken 1 Decode (PC +
offset)
Call Always taken 1 Decode (PC +
offset)
Return Always taken Many Execution (register
dependent)
Indirect Always taken Many Execution (register
dependent)

Different branch types are handled differently

6
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
7
Stall Fetch Until Next PC is Known: Good Idea?

t0 t1 t2 t3 t4 t5
Insth IF ID ALU MEM WB
Insti IF IF ID ALU MEM WB
Instj IF IF ID ALU
Instk IF IF
Instl

Stall for 50% of the cycles!


This is the case with non-control-flow and unconditional br instructions
Much worse stalling for conditional branch instructions! 8
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
Lecture 13, DDCA Spring 2023 https://www.youtube.com/watch?v=523JOL6jck0&list=PL5Q2soXY2Zi-EImKxYYY1SZuGiOAOBKaf&index=16 9
Recall: Fine-Grained Multithreading: Basic Idea
CLK CLK CLK

RegWriteD RegWriteE RegWriteM RegWriteW


Control MemtoRegE MemtoRegM MemtoRegW
MemtoRegD
Unit
MemWriteD MemWriteE MemWriteM
BranchD BranchE BranchM
31:26 PCSrcM
Op ALUControlD ALUControlE2:0
5:0
Funct ALUSrcD ALUSrcE
RegDstD RegDstE
ALUOutW
CLK CLK CLK
CLK
25:21 WE3 SrcAE ZeroM WE
0 PC' PCF InstrD A1 RD1 0
A RD ReadDataW
1 ALUOutM
A RD 1
Instruction 20:16

ALU
A2 RD2 0 SrcBE Data
Memory
A3 1 Memory
Register WriteDataE WriteDataM
WD3 WD
File
20:16
RtE
0 WriteRegE4:0 WriteRegM4:0 WriteRegW 4:0
15:11
RdE
1

+
15:0
<<2
Sign Extend SignImmE
4 PCBranchM
+

PCPlus4F PCPlus4D PCPlus4E

ResultW

Each pipeline stage has an instruction from a different, completely-independent thread

No need to perform any control and data dependence handling


How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
11
The Branch Problem
n Control flow instructions (branches) are frequent
q 15-25% of all instructions

n Problem: Next fetch address after a control-flow instruction


is not determined after N cycles in a pipelined processor
q N cycles: (minimum) branch resolution latency

n If we are fetching W instructions per cycle (i.e., if the


pipeline is W wide superscalar)
q A branch misprediction leads to N x W wasted instruction slots

12
Importance of The Branch Problem
n Assume N = 20 (20 pipeline stages), W = 5 (5 wide superscalar fetch)
n Assume: 1 out of 5 instructions is a branch
n Assume: Each 5 instruction-block ends with a branch

n How long does it take to fetch 500 instructions?


q 100% accuracy
n 100 cycles (all instructions fetched on the correct path)
n No wasted work; IPC = 500/100
q 99% accuracy
n 100 (correct path) + 20 * 1 (wrong path) = 120 cycles
n 20% extra instructions fetched; IPC = 500/120
q 90% accuracy
n 100 (correct path) + 20 * 10 (wrong path) = 300 cycles
n 200% extra instructions fetched; IPC = 500/300
q 60% accuracy
n 100 (correct path) + 20 * 40 (wrong path) = 900 cycles
n 800% extra instructions fetched; IPC = 500/900
13
Branch Prediction

14
Branch Prediction: Guess the Next Instruction to Fetch

PC 0x0008
0x0007
0x0006
0x0005
0x0004
??

I-$ DEC RF WB
0x0001
LD R1, MEM[R0]
0x0002 D-$
ADD R2, R2, #1 Stall fetch
0x0003
BRZERO 0x0001
0x0004
ADD R3, R2, #1 12 cycles
0x0005
MUL R1, R2, R3
0x0006
LD R2, MEM[R2] Branch prediction
0x0007
LD R0, MEM[R2]
8 cycles
Misprediction Penalty

PC !!
Flush
I-$ DEC RF WB
0x0001
LD R1, MEM[R0] 0x0007 0x0006 0x0005 0x0004 0x0003
0x0002 D-$
ADD R2, R2, #1
0x0003
BRZERO 0x0001
0x0004
ADD R3, R2, #1
0x0005
MUL R1, R2, R3
0x0006
LD R2, MEM[R2]
0x0007
LD R0, MEM[R2]
Simplest: Always Guess NextPC = PC + 4
n Always predict the next sequential instruction is the next
instruction to be executed
n This is a form of next fetch address prediction (and branch
prediction)

n How can you make this more effective?

n Idea: Maximize the chances that the next sequential


instruction is the next instruction to be executed
q Software: Lay out the control flow graph such that the “likely
next instruction” is on the not-taken path of a branch
n Profile guided code positioning à Pettis & Hansen, PLDI 1990.
q Hardware: ??? (how can you do this in hardware…)
n Cache traces of executed instructions à Trace cache
17
Guessing NextPC = PC + 4
n How else can you make this more effective?

n Idea: Get rid of control flow instructions (or minimize their


occurrence)

n How?
1. Get rid of unnecessary control flow instructions à
combine predicates (predicate combining) and test only once
2. Convert control dependences into data dependences à
predicated execution (aka if-conversion)

18
Branch Prediction: Always PC+4

t0 t1 t2 t3 t4 t5
Insth IFPC ID ALU MEM
Insti IFPC+4 ID ALU
Instj IFPC+8 ID
Instk IFtarget
Instl Insth branch condition and target
evaluated in ALU
When a branch resolves
- branch target (Instk) is fetched
- all instructions fetched since
insth (i.e., “wrong-path”
Insth is a branch instructions) must be flushed 19
Pipeline Flush on a Misprediction

t0 t1 t2 t3 t4 t5
Insth IFPC ID ALU MEM WB
Insti IFPC+4 ID flushed
Instj IFPC+8 flushed
Instk IFtarget ID ALU WB
Instl IF ID ALU
IF ID
IF

Insth is a branch 20
Performance Analysis
n correct guess Þ no penalty ~86% of the time
n incorrect guess Þ 2 bubbles
n Assume
q no data dependency related stalls
q 20% control flow instructions
q 70% of control flow instructions are taken
q CPI = [ 1 + (0.20*0.7) * 2 ] =
= [ 1 + 0.14 * 2 ] = 1.28

probability of penalty for


a wrong guess a wrong guess

Can we reduce either of the two penalty terms?


21
Reducing the Branch Misprediction Penalty
n Resolve branch condition and target address early
IF.Flush

Hazard
detection
unit
M ID/EX
u
x
WB
EX/MEM
M
Control u M WB
x MEM/WB
0

IF/ID EX M WB

4 Shift
left 2
M
u
x
Registers =
Instruction Data
PC ALU
memory memory M
u
M x
u
x

Sign
extend Is this a good idea?
M
u
x
Forwarding
unit

[Based on original figure from P&H CO&D, COPYRIGHT 2004 Elsevier. ALL RIGHTS RESERVED.]
CPI = [ 1 + (0.2*0.7) * 1 ] = 1.14 22
Carnegie Mellon

Recall: Pipeline with Early Branch Resolution


Idea: Calculate branch target and condition in the Decode Stage

Dependence Detection Logic

23
Lecture 13, DDCA Spring 2023 https://www.youtube.com/watch?v=523JOL6jck0&list=PL5Q2soXY2Zi-EImKxYYY1SZuGiOAOBKaf&index=16
(Enhanced) Branch Prediction

24
Branch Prediction (A Bit More Enhanced)
n Idea: Predict the next fetch address (to be used in the
next cycle) à no wasted cycle(s) on correct prediction

n Requires three things to be predicted at fetch stage:


q Whether the fetched instruction is a branch
q (Conditional) branch direction
q Branch target address (if taken)

n Observation: Target address remains the same for a


conditional direct branch across dynamic instances
q Idea: Store the target address from previous instance and access
it with the PC
q Called Branch Target Buffer (BTB) or Branch Target Address
Cache
25
Fetch Stage with BTB and Direction Prediction
Direction predictor (taken?)

taken?

PC + inst size Next Fetch


Address
Program
hit?
Counter

Address of the
current branch

target address

Cache of Target Addresses (BTB: Branch Target Buffer)

26
More Sophisticated Branch Direction Prediction

Which direction earlier Direction predictor (taken?)


branches went
taken?

Global branch
history PC + inst size Next Fetch
XOR Address
Program
hit?
Counter

Address of the
current branch

target address

Cache of Target Addresses (BTB: Branch Target Buffer)

27
Three Things to Be Predicted
n Requires three things to be predicted at fetch stage:
1. Whether the fetched instruction is a branch
2. (Conditional) branch direction
3. Branch target address (if taken)

n Third (3.) can be accomplished using a BTB


q Remember target address computed last time branch was
executed
n First (1.) can be accomplished using a BTB
q If BTB provides a target address for the program counter, then it
must be a branch
q Or, we can store “branch metadata” bits in instruction

cache/memory à partially decoded instruction


n Second (2.): How do we predict the direction?
28
Simple Branch Direction Prediction Schemes
n Compile time (static)
q Always not taken
q Always taken
q BTFN (Backward taken, forward not taken)
q Profile based (likely direction)

n Run time (dynamic)


q Last time prediction (single-bit)

29
More Sophisticated Direction Prediction
n Compile time (static)
q Always not taken
q Always taken
q BTFN (Backward taken, forward not taken)
q Profile based (likely direction)
q Program analysis based (likely direction)

n Run time (dynamic)


q Last time prediction (single-bit)
q Two-bit counter based prediction
q Two-level prediction (global vs. local)
q Hybrid
q Advanced algorithms (e.g., using perceptrons, geometric history)
30
Static Branch Prediction (I)
n Always not-taken
q Simple to implement: no need for BTB, no direction prediction
q Low accuracy: ~30-40% (for conditional branches)
q Remember: Compiler can layout code such that the likely path
is the “not-taken” path à more effective prediction

n Always taken
q No direction prediction
q Better accuracy: ~60-70% (for conditional branches)
n Backward branches (i.e., loop branches) are usually taken
n Backward branch: target address lower than branch PC

n Backward taken, forward not taken (BTFN)


q Predict backward (loop) branches as taken, others not-taken
31
Static Branch Prediction (II)
n Profile-based
q Idea: Compiler determines likely direction for each branch using
a profile run. Encodes that direction as a hint bit in the branch
instruction format.

+ Per branch prediction (more accurate than schemes in


previous slide) à accurate if profile is representative!
-- Requires hint bits in the branch instruction format
-- Accuracy depends on dynamic branch behavior:
TTTTTTTTTTNNNNNNNNNN à 50% accuracy
TNTNTNTNTNTNTNTNTNTN à 50% accuracy
-- Accuracy depends on representativeness of profile input set
TTTTTTTTTTTTTTTTTTNN à 90% accuracy (or 10%?)
32
We Covered
Until This Point
in Lecture

33
Digital Design & Computer Arch.
Lecture 16b: Branch Prediction

Prof. Onur Mutlu

ETH Zürich
Spring 2023
27 April 2023
Slides for Future Lectures

35
Static Branch Prediction (III)
n Program-based (or, program analysis based)
q Idea: Use heuristics based on program analysis to determine statically-
predicted direction
q Example opcode heuristic: Predict BLEZ as NT (negative integers used
as error values in many programs)
q Example loop heuristic: Predict a branch guarding a loop execution as
taken (i.e., execute the loop)
q Pointer and FP comparisons: Predict not equal

+ Does not require profiling


-- Heuristics might be not representative or good
-- Requires compiler analysis and ISA support (ditto for other static methods)

n Ball and Larus, ”Branch prediction for free,” PLDI 1993.


q 20% misprediction rate
36
Static Branch Prediction (IV)
n Programmer-based
q Idea: Programmer provides the statically-predicted direction
q Via pragmas in the programming language that qualify a branch as
likely-taken versus likely-not-taken

+ Does not require profiling or program analysis


+ Programmer may know some branches and their program better than
other analysis techniques
-- Requires programming language, compiler, ISA support
-- Burdens the programmer

37
Pragmas
n Idea: Keywords that enable a programmer to convey hints
to lower levels of the transformation hierarchy

n if (likely(x)) { ... }
n if (unlikely(error)) { … }

n Many other hints and optimizations can be enabled with


pragmas
q E.g., whether a loop can be parallelized
q #pragma omp parallel
q Description
n The omp parallel directive explicitly instructs the compiler to
parallelize the chosen segment of code.

38
Static Branch Prediction
n All previous techniques can be combined
q Profile based
q Program based
q Programmer based

n How would you do that?

n What is the common disadvantage of all three techniques?


q Cannot adapt to dynamic changes in branch behavior
n This can be mitigated by a dynamic compiler, but not at a fine
granularity (and a dynamic compiler has its overheads…)
n What is a Dynamic Compiler?
q A compiler that generates code at runtime
q Java JIT (just in time) compiler, Microsoft CLR (common lang. runtime)
39
Recall: Rosetta 2 Binary Translator

https://en.wikipedia.org/wiki/Rosetta_(software)#Rosetta_2 40
Recall: NVIDIA Denver Dynamic Code Optimizer

https://www.anandtech.com/show/8701/the-google-nexus-9-review/4
https://www.toradex.com/computer-on-modules/apalis-arm-family/nvidia-tegra-k1
41
More Sophisticated Direction Prediction
n Compile time (static)
q Always not taken
q Always taken
q BTFN (Backward taken, forward not taken)
q Profile based (likely direction)
q Program analysis based (likely direction)

n Run time (dynamic)


q Last time prediction (single-bit)
q Two-bit counter based prediction
q Two-level prediction (global vs. local)
q Hybrid
q Advanced algorithms (e.g., using perceptrons, geometric history)
42
Dynamic Branch Prediction
n Idea: Predict branches based on dynamic information
(collected at run-time)

n Advantages
+ Prediction based on history of the execution of branches
+ It can adapt to dynamic changes in branch behavior
+ No need for static profiling: input set representativeness
problem goes away

n Disadvantages
-- More complex (requires additional hardware)

43
Last Time Predictor
n Last time predictor
q Idea: Guess branch will take the same direction as its last instance
q Single bit per branch (stored in BTB)
n Indicates which direction branch went last time it executed
TTTTTTTTTTNNNNNNNNNN à 90% accuracy

n Always mispredicts the last iteration and the first iteration of a


loop branch
q Accuracy for a loop with N iterations = (N-2)/N

+ Loop branches for loops with large N (number of iterations)


~100% accuracy
-- Loop branches for loops will small N (number of iterations)
TNTNTNTNTNTNTNTNTNTN à 0% accuracy
44
Implementing the Last-Time Predictor (I)
Direction predictor (taken last time?)

taken?

PC + inst size Next Fetch


Address
Program
hit?
Counter

Address of the
current branch

target address

Cache of Target Addresses (BTB: Branch Target Buffer)


Implementing the Last-Time Predictor (II)
tag BTB index Program Counter

N-bit BHT:
One
tag BTB: one target
Bit
table address per entry
per
entry

taken? PC+4
1 0
=

nextPC
The 1-bit BHT (Branch History Table) entry is updated with
the correct outcome after each execution of a branch
46
State Machine for Last-Time Prediction

actually
taken

actually predict predict actually


not taken not taken taken
taken

actually
not taken

47
Improving the Last Time Predictor
n Problem: A last-time predictor changes its prediction from
TàNT or NTàT too quickly
q even though the branch may be mostly taken or mostly not
taken

n Solution Idea: Add hysteresis to the predictor so that


prediction does not change on a single different outcome
q Use two bits to track the history of predictions for a branch
instead of a single bit
q Can have 2 states each for T or NT instead of 1 state for each

n Smith, “A Study of Branch Prediction Strategies,” ISCA 1981.


48
Two-Bit Counter Based Prediction
n Each branch associated with a two-bit counter (2BC)
n One more bit provides hysteresis
n A strong prediction does not change with one single
different outcome

n Also called bimodal prediction

49
State Machine for 2-bit Saturating Counter
n Counter using saturating arithmetic
q Arithmetic with maximum and minimum values

actually actually
taken pred !taken pred
taken taken
11 actually 10
taken
actually actually
taken !taken

actually
pred !taken pred
!taken !taken
actually actually
01 00
!taken 50
taken
Hysteresis Using a 2-bit Counter
actually actually “weakly
taken !taken taken”
“strongly pred pred
taken” taken actually taken
taken
actually actually
taken !taken
“strongly
actually !taken”
pred !taken pred
“weakly !taken !taken actually
!taken” actually !taken
taken

Change “strong” prediction only after 2 consecutive mistakes 51


Two-Bit Counter Based Prediction
n Each branch associated with a two-bit counter (stored in BTB)
n One more bit provides hysteresis
n A strong prediction does not change with one single different
outcome

n Accuracy for a loop with N iterations = (N-1)/N


TTTTTTTTTTTTTTTTTTTN à 95% accuracy
TNTNTNTNTNTNTNTNTNTN à 50% accuracy
(assuming counter initialized to weakly taken)

+ Better prediction accuracy


-- More hardware cost (but counter can be part of a BTB entry)
52
Is This Good Enough?
n ~85-90% accuracy for many programs with 2-bit counter
based prediction (also called bimodal prediction)

n Is this good enough?

n How big is the branch problem?

53
Let’s Do the Exercise Again
n Assume N = 20 (20 pipe stages), W = 5 (5 wide fetch)
n Assume: 1 out of 5 instructions is a branch
n Assume: Each 5 instruction-block ends with a branch

n How long does it take to fetch 500 instructions?


q 100% accuracy
n 100 cycles (all instructions fetched on the correct path)
n No wasted work; IPC = 500/100
q 90% accuracy
n 100 (correct path) + 20 * 10 (wrong path) = 300 cycles
n 200% extra instructions fetched; IPC = 500/300
q 85% accuracy
n 100 (correct path) + 20 * 15 (wrong path) = 400 cycles
n 300% extra instructions fetched; IPC = 500/400
q 80% accuracy
n 100 (correct path) + 20 * 20 (wrong path) = 500 cycles
n 400% extra instructions fetched; IPC = 500/500
54
Can We Do Better: Two-Level Prediction
n Last-time and 2BC predictors exploit “last-time”
predictability

n Realization 1: A branch’s outcome can be correlated with


other branches’ outcomes
q Global branch correlation

n Realization 2: A branch’s outcome can be correlated with


past outcomes of the same branch (other than the outcome
of the branch “last-time” it was executed)
q Local branch correlation

Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 55
Global Branch Correlation (I)
n Recently executed branch outcomes in the execution path
are correlated with the outcome of the next branch

n If first branch not taken, second also not taken

n If first branch taken, second definitely not taken


56
Global Branch Correlation (II)

n If Y and Z both taken, then X also taken


n If Y or Z not taken, then X also not taken

57
Global Branch Correlation (III)
n Eqntott, SPEC’92 workload
q Generates truth table from Boolean expression

if (aa==2) ;; B1
aa=0;
if (bb==2) ;; B2
bb=0;
if (aa!=bb) { ;; B3
….
}

If B1 is taken (i.e., aa=0@B3) and B2 is taken (i.e. bb=0@B3)


then B3 is not taken
58
Capturing Global Branch Correlation
n Idea: Associate branch outcomes with “global T/NT history”
of all branches
n Make a prediction based on the outcome of the branch the
last time the same global branch history was encountered

n Implementation:
q Keep track of the “global T/NT history” of all branches in a
register à Global History Register (GHR)
q Use GHR to index into a table that recorded the outcome that
was seen for each GHR value in the recent past à Pattern
History Table (table of 2-bit counters)

n Global history/branch predictor


n Uses two levels of history (GHR + history at that GHR)

Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 59
Two Level Global Branch Prediction
n First level: Global branch history register (N bits)
q The direction of last N branches

n Second level: Table of saturating counters for each history entry


q The direction the branch took the last time the same history was
seen
Pattern History Table (PHT)
00 …. 00
1 1 ….. 1 0 00 …. 01
2 3
GHR
previous 00 …. 10
(global
branch’s
history
direction
register)
index
0 1

11 …. 11

Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 60
How Does the Global Predictor Work?

This branch tests i


Last 3 branches test j
History: TTTN
Predict taken for i
Next history: TTNT
(shift in last outcome)

n McFarling, “Combining Branch Predictors,” DEC WRL TR 1993.

61
Intel Pentium Pro Branch Predictor
n Two-level global branch predictor
n 4-bit global history register
n Multiple pattern history tables (of 2-bit counters)
q Which pattern history table to use is determined by lower
order bits of the branch address

n First widely commercially successful out-of-order execution


machine
q Out-of-order + superscalar + 2-level branch prediction +
precise exceptions using reorder buffer

62
Intel Pentium Pro (1995)

Processor chip Level 2 cache chip

Multi-chip module package

By Moshen - http://en.wikipedia.org/wiki/Image:Pentiumpro_moshen.jpg, CC BY-SA 2.5, https://commons.wikimedia.org/w/index.php?curid=2262471


63
Aside: Global Branch Correlation Analysis

n If Y and Z both taken, then X also taken


n If Y or Z not taken, then X also not taken

n Only 3 past branches’ directions


*really* matter
n Evers et al., “An Analysis of
Correlation and Predictability:
What Makes Two-Level Branch
Predictors Work,” ISCA 1998.

64
Improving Global Predictor Accuracy
n Idea: Add more context information to the global predictor to take into
account which branch is being predicted
q Gshare predictor: GHR hashed with the Branch PC

+ More context information used for prediction


+ Better utilization of the two-bit counter array
-- Increases access latency

n McFarling, “Combining Branch Predictors,” DEC WRL Tech Report, 1993.


65
Review: One-Level Branch Predictor
Direction predictor (2-bit counters)

taken?

PC + inst size Next Fetch


Address
Program
hit?
Counter

Address of the
current instruction

target address

Cache of Target Addresses (BTB: Branch Target Buffer)

66
Two-Level Global History Branch Predictor

Which direction earlier Direction predictor (2-bit counters)


branches went
taken?

Global branch
history PC + inst size Next Fetch
Address
Program
hit?
Counter

Address of the
current instruction

target address

Cache of Target Addresses (BTB: Branch Target Buffer)

67
Two-Level Gshare Branch Predictor

Which direction earlier Direction predictor (2-bit counters)


branches went
taken?

Global branch
history PC + inst size Next Fetch
XOR Address
Program
hit?
Counter

Address of the
current instruction

target address

Cache of Target Addresses (BTB: Branch Target Buffer)

68
Can We Do Better: Two-Level Prediction
n Last-time and 2BC predictors exploit only “last-time”
predictability for a given branch

n Realization 1: A branch’s outcome can be correlated with


other branches’ outcomes
q Global branch correlation

n Realization 2: A branch’s outcome can be correlated with


past outcomes of the same branch (in addition to the
outcome of the branch “last-time” it was executed)
q Local branch correlation

Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 69
Local Branch Correlation

n McFarling, “Combining Branch Predictors,” DEC WRL TR 1993.

70
More Motivation for Local History
Loop closing branch’s history
n To predict a loop PHT
11101110111011101110 0000
branch “perfectly”, we 0001

want to identify the 0010

last iteration of the 0011


0100
loop
0101
0110
n By having a separate 0111 00

PHT entry for each 1000

local history, we can 1001


1010
distinguish different
1011 11
iterations of a loop
1100

1101 11

n Works for “short” 1110 11


1111
loops
71
Capturing Local Branch Correlation
n Idea: Have a per-branch history register
q Associate the predicted outcome of a branch with “T/NT history”
of the same branch
n Make a prediction based on the outcome of the branch the
last time the same local branch history was encountered

n Called the local history/branch predictor


n Uses two levels of history
q per-branch history register + history at that history register value

72
Two Level Local Branch Prediction
n First level: A set of local history registers (N bits each)
q Select the history register based on the PC of the branch

n Second level: Table of saturating counters for each history entry


q The direction the branch took the last time the same history was
seen
Pattern History Table (PHT)
00 …. 00
1 1 ….. 1 0 00 …. 01
2 3
00 …. 10

index
0 1

Local history
11 …. 11
registers
Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 73
Two-Level Local History Branch Predictor
Which directions earlier instances of *this branch* went
Direction predictor (2-bit counters)

taken?

PC + inst size Next Fetch


Address
Program
hit?
Counter

Address of the
current instruction

target address

Cache of Target Addresses (BTB: Branch Target Buffer)

74
Aside: Two-Level Predictor Taxonomy
n BHR can be global (G), per set of branches (S), or per branch (P)
n PHT counters can be adaptive (A) or static (S)
n PHT can be global (g), per set of branches (s), or per branch (p)

n Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,”


MICRO 1991.
75
Can We Do Better?

76
Can We Do Even Better?
n Predictability of branches varies

n Some branches are more predictable using local history


n Some branches are more predictable using global
n For others, a simple two-bit counter is enough
n Yet for others, a single bit is enough

n Observation: There is heterogeneity in predictability


behavior of branches
q No one-size fits all branch prediction algorithm for all branches

n Idea: Exploit that heterogeneity by designing


heterogeneous (hybrid) branch predictors
77
Hybrid Branch Predictors
n Idea: Use more than one type of predictor (i.e., multiple
algorithms) and select the “best” prediction
q E.g., hybrid of 2-bit counters and global predictor

n Advantages:
+ Better accuracy: different predictors are better for different branches
+ Reduced warmup time (faster-warmup predictor used until the
slower-warmup predictor warms up)

n Disadvantages:
-- Need “meta-predictor” or “selector” to decide which predictor to use
-- Longer access latency
-- More hardware & complexity

McFarling, “Combining Branch Predictors,” DEC WRL Tech Report, 1993. 78


Alpha 21264 Tournament Predictor

n Minimum branch penalty: 7 cycles


n Typical branch penalty: 11+ cycles
n 48K bits of target addresses stored in I-cache
n Predictor tables are reset on a context switch

n Kessler, “The Alpha 21264 Microprocessor,” IEEE Micro 1999.


79
Biased Branches and Branch Filtering
n Observation: Many branches are biased in one direction
(e.g., 99% taken)

n Problem: These branches pollute the branch prediction


structures à make the prediction of other branches difficult
by causing “interference” in branch prediction tables and
history registers

n Solution: Detect such biased branches, and predict them


with a simpler predictor (e.g., last time, static, …)

n Chang et al., “Branch classification: a new mechanism for improving


branch predictor performance,” MICRO 1994.

80
Are We Done w/ Branch Prediction?
n Hybrid branch predictors work well
q E.g., 90-97% prediction accuracy on average

n Some “difficult” workloads still suffer a lot, though!


q E.g., gcc
q Max IPC with tournament prediction: 9
q Max IPC with perfect prediction: 35

81
Some Other Branch Predictor Types
n Loop branch detector and predictor
q Loop iteration count detector/predictor
q Works well for loops with small number of iterations, where
iteration count is predictable
q Used in Intel Pentium M
n Perceptron branch predictor
q Learns the direction correlations between individual branches

q Assigns weights to correlations using simple machine learning


q Jimenez and Lin, “Dynamic Branch Prediction with Perceptrons,”
HPCA 2001.
n Hybrid history-length based predictor
q Uses different tables with different history lengths
q Seznec, “Analysis of the O-Geometric History Length Branch
Predictor,” ISCA 2005.
82
Intel Pentium M Predictors: Loop and Jump

Gochman et al.,
“The Intel Pentium M Processor: Microarchitecture and Performance,”
Intel Technology Journal, May 2003.
83
Intel Pentium M (2003)

https://www.anandtech.com/show/1083/3 84
More Advanced Branch Prediction

85
Perceptrons for Learning Linear Functions
n A perceptron is a simplified model of a biological neuron
n It is also a simple binary classifier

n A perceptron maps an input vector X to a 0 or 1


q Input = Vector X
q Perceptron learns the linear function (if one exists) of how
each element of the vector affects the output (stored in an
internal Weight vector)
q Output = Weight.X + Bias > 0

n In the branch prediction context


q Vector X: Branch history register bits
q Output: Prediction for the current branch
Rosenblatt, “Principles of Neurodynamics: Perceptrons and the Theory of Brain Mechanisms,” 1962
Perceptron Branch Predictor (I)
n Idea: Use a perceptron to learn the correlations between branch history
register bits and branch outcome
n A perceptron learns a target Boolean function of N inputs
Each branch associated with a perceptron

A perceptron contains a set of weights wi


à Each weight corresponds to a bit in
the GHR
à Represents how much the bit is correlated
with the direction of the branch
à Positive correlation: large positive + weight
à Negative correlation: large negative - weight

Prediction:
à Express GHR bits as 1 (T) and -1 (NT)
à Take dot product of GHR and weights
à If output > 0, predict taken

n Jimenez and Lin, “Dynamic Branch Prediction with Perceptrons,” HPCA 2001.
n Rosenblatt, “Principles of Neurodynamics: Perceptrons and the Theory of Brain Mechanisms,” 1962
Perceptron Branch Predictor (II)
Prediction function:
Dot product of GHR
and perceptron weights

Output
compared Bias weight
to 0 (bias of branch, independent of
the history)

Training function:

88
Perceptron Branch Predictor (III)
n Advantages
+ More sophisticated learning mechanism à better accuracy
+ Enables long branch history lengths à better accuracy

n Disadvantages
-- Complexity (adder tree to compute perceptron output)
-- Can learn only linearly-separable functions
e.g., cannot learn XOR type of correlation between 2 history
bits and branch outcome

A successful example of use of machine learning in processor design

See, e.g., Grayson+, “Evolution of the Samsung Exynos CPU Microarchitecture,” ISCA 2020.
89
Recommended Reading

Grayson+, “Evolution of the Samsung Exynos CPU Microarchitecture,” ISCA 2020. 90


AMD Piledriver/Zen/Zen2 (2012-Present)
n These processors employ a perceptron branch predictor

https://fuse.wikichip.org/news/2458/a-look-at-the-amd-zen-2-core/
91
AMD Zen2 Perceptron Predictor (2019)

92
https://fuse.wikichip.org/news/2458/a-look-at-the-amd-zen-2-core/
Another Idea: TAGE

93
Prediction Using Multiple History Lengths
n Observation: Different
branches require
different history lengths
for better prediction
accuracy

n Idea: Have multiple


PHTs indexed with
GHRs with different
history lengths and
intelligently allocate
PHT entries to different
branches
Seznec and Michaud, “A case for (partially) tagged Geometric History Length
Branch Prediction,” JILP 2006.
94
Different Branches: Different History Lengths

https://fuse.wikichip.org/news/2458/a-look-at-the-amd-zen-2-core/ 95
TAGE Branch Predictor
n Advantages
+ Chooses the “best” history length to predict each branch à
better accuracy
+ Enables long branch history lengths à better accuracy

n Disadvantages
-- Hardware (design) complexity is not low
-- Need to choose good hash functions and table sizes to
maximize accuracy and minimize latency

A successful recent idea that is used in many modern processor designs

96
AMD Zen2 Perceptron + TAGE (2019)
n A multi-level branch predictor
q Perceptron (L1)
q TAGE (L2)

https://fuse.wikichip.org/news/2458/a-look-at-the-amd-zen-2-core/ 97
https://www.amd.com/en/technologies/zen-core
AMD Zen2 TAGE Predictor (2019)

https://fuse.wikichip.org/news/2458/a-look-at-the-amd-zen-2-core/ 98
Can We Do Better?

99
State of the Art in Branch Prediction
n See the Branch Prediction Championship
q https://www.jilp.org/cbp2016/program.html

Andre Seznec,
“TAGE-SC-L branch predictors,”
CBP 2014.

100
Branch Confidence Estimation
n Idea: Estimate if the prediction is likely to be correct
q i.e., estimate how “confident” you are in the prediction

n Why?
q Could be very useful in deciding how to speculate:
n What predictor/PHT/table to choose/use
n Whether to keep fetching on this path
n Whether to switch to some other way of handling the branch,
e.g. dual-path execution (eager execution) or predicated
execution
n …

n Jacobsen et al., “Assigning Confidence to Conditional Branch


Predictions,” MICRO 1996.
101
How to Estimate Confidence
n An example estimator:
q Keep a record of correct/incorrect outcomes for the past N
instances of the “branch”
q Based on the correct/incorrect patterns, guess if the curent
prediction will likely be correct/incorrect

Jacobsen et al., “Assigning Confidence to Conditional Branch Predictions,” MICRO 1996.102


What to Do With Confidence Estimation?
n An example application: Pipeline Gating

Manne et al., “Pipeline Gating: Speculation Control for Energy Reduction,” ISCA 1998.

103
Other Ways of Handling
Branches

104
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
105
Delayed Branching (I)
n Change the semantics of a branch instruction
q Branch after N instructions
q Branch after N cycles
n Idea: Delay the execution of a branch. N instructions (delay
slots) that come after the branch are always executed
regardless of branch direction.

n Problem: How do you find instructions to fill the delay


slots?
q Branch must be independent of delay slot instructions

n Unconditional branch: Easier to find instructions to fill the delay slot


n Conditional branch: Condition computation should not depend on
instructions in delay slots à difficult to fill the delay slot
106
Delayed Branching (II)

Normal code: Timeline: Delayed branch code: Timeline:

A ex A if ex
if
B C
C A BC X A
BC X B A B C A
D C B D BC C
E BC C E B BC
F -- BC F G B
X: G G -- X: G

6 cycles 5 cycles

107
Fancy Delayed Branching (III)
n Delayed branch with squashing
q In SPARC ISA
q Semantics: If the branch falls through (i.e., it is not taken),
the delay slot instruction is not executed
q Why could this help?
Normal code: Delayed branch code: Delayed branch w/ squashing:

X: A X: A A
B B X: B
C C C
BC X BC X BC X
D NOP A
E D D
E E

108
Delayed Branching (IV)
n Advantages:
+ Keeps the pipeline full with useful instructions in a simple way assuming
1. Number of delay slots == number of instructions to keep the pipeline
full before the branch resolves
2. All delay slots can be filled with useful instructions

n Disadvantages:
-- Not easy to fill the delay slots (even with a 2-stage pipeline)
1. Number of delay slots increases with pipeline depth, superscalar
execution width
2. Number of delay slots should be variable with variable latency
operations. Why?
-- Ties ISA semantics to hardware implementation
-- SPARC, MIPS, HP-PA: 1 delay slot
-- What if pipeline implementation changes with the next design?
109
An Aside: Filling the Delay Slot
a. From before b. From target c. From fall through
sub $t4, $t5, $t6
add $s1, $s2, $s3 add $s1, $s2, $s3

if $s2 = 0 then if $s1 = 0 then
reordering add $s1, $s2, $s3
independent Delay slot Delay slot
if $s1 = 0 then
instructions
Delay slot sub $t4, $t5, $t6
does not change
program semantics
Becomes Becomes Becomes

add $s1, $s2, $s3

if $s2 = 0 then if $s1 = 0 then


add $s1, $s2, $s3
add $s1, $s2, $s3 sub $t4, $t5, $t6
if $s1 = 0 then

sub $t4, $t5, $t6 Safe?

within same For correctness: For correctness:


basic block add a new instruction add a new instruction
to the not-taken path? to the taken path?

[Based on original figure from P&H CO&D, COPYRIGHT 110


2004 Elsevier. ALL RIGHTS RESERVED.]
Lecture on Static Instruction Scheduling

https://www.youtube.com/onurmutlulectures 111
Lectures on Static Instruction Scheduling

n Computer Architecture, Spring 2015, Lecture 16


q Static Instruction Scheduling (CMU, Spring 2015)
q https://www.youtube.com/watch?v=isBEVkIjgGA&list=PL5PHm2jkkXmi5CxxI7b3JC
L1TWybTDtKq&index=18

n Computer Architecture, Spring 2013, Lecture 21


q Static Instruction Scheduling (CMU, Spring 2013)
q https://www.youtube.com/watch?v=XdDUn2WtkRg&list=PL5PHm2jkkXmidJOd59RE
og9jDnPDTG6IJ&index=21

https://www.youtube.com/onurmutlulectures 112
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
113
Other Branch Solutions Covered in This Lecture…

https://www.youtube.com/onurmutlulectures 114
Other Branch Solutions Covered in This Lecture…
n Computer Architecture, Spring 2015, Lecture 5
q Advanced Branch Prediction (CMU, Spring 2015)
q https://www.youtube.com/watch?v=yDjsr-
jTOtk&list=PL5PHm2jkkXmgVhh8CHAu9N76TShJqfYDt&index=4

n See Backup Slides

https://www.youtube.com/onurmutlulectures 115
Backup Slides
(These are for Your Further Study)

116
Other Branch Solutions Covered in This Lecture…

https://www.youtube.com/onurmutlulectures 117
Other Branch Solutions Covered in This Lecture…
n Computer Architecture, Spring 2015, Lecture 5
q Advanced Branch Prediction (CMU, Spring 2015)
q https://www.youtube.com/watch?v=yDjsr-
jTOtk&list=PL5PHm2jkkXmgVhh8CHAu9N76TShJqfYDt&index=4

n See Backup Slides

https://www.youtube.com/onurmutlulectures 118
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
119
Predicate Combining (not Predicated Execution)
n Complex predicates are converted into multiple branches
q if ((a == b) && (c < d) && (a > 5000)) { … }
n 3 conditional branches
n Problem: This increases the number of control
dependencies
n Idea: Combine predicate operations to feed a single branch
instruction instead of having one branch for each
q Predicates stored and operated on using condition registers
q A single branch checks the value of the combined predicate
+ Fewer branches in code à fewer mipredictions/stalls
-- Possibly unnecessary work
-- If the first predicate is false, no need to compute other predicates
n Condition registers exist in IBM RS6000 and the POWER architecture
120
Predication (Predicated Execution)
n Idea: Convert control dependence to data dependence

n Simple example: Suppose we had a Conditional Move


instruction…
q CMOV condition, R1 ß R2
q R1 = (condition == true) ? R2 : R1
q Employed in most modern ISAs (x86, Alpha)

n Code example with branches vs. CMOVs


if (a == 5) {b = 4;} else {b = 3;}

CMPEQ condition, a, 5;
CMOV condition, b ß 4;
CMOV !condition, b ß 3;
121
Predication (Predicated Execution)
n Idea: Compiler converts control dependence into data dependence
à branch is eliminated
q Each instruction has a predicate bit set based on the predicate computation
q Only instructions with TRUE predicates are committed (others become NOPs)

(normal branch code) (predicated code)


A
T N A
if (cond) {
b = 0; C B B
} C
else { D D
b = 1; A
p1 = (cond) A
} branch p1, TARGET p1 = (cond)
B
mov b, 1 B
jmp JOIN (!p1) mov b, 1
C C
TARGET:
mov b, 0
(p1) mov b, 0
D D
add x, b, 1 add x, b, 1 122
Predicated Execution References
n Allen et al., “Conversion of control dependence to data
dependence,” POPL 1983.

n Kim et al., “Wish Branches: Combining Conditional


Branching and Predication for Adaptive Predicated
Execution,” MICRO 2005.
n Kim et al., “Diverge-Merge Processor (DMP): Dynamic
Predicated Execution of Complex Control-Flow Graphs
Based on Frequently Executed Paths,” MICRO 2006.

123
Conditional Move Operations
n Very limited form of predicated execution

n CMOV R1 ß R2
q R1 = (ConditionCode == true) ? R2 : R1
q Employed in most modern ISAs (x86, Alpha)

124
Predicated Execution (II)
n Predicated execution can be high performance and energy-
efficient

Predicated Execution
A Fetch Decode Rename Schedule RegisterRead Execute

F
E
A
D
B
C F
D
E
C
A
B F
E
C
D
B
A A
B
C
D
E
F A
B
C
D
E
F B
A
D
C
E
F A
E
F
C
D
B D
E
B
C
A
F C
D
A
B
E B
C
A
D A
B
C B A
A
C B nop
Branch Prediction
D Fetch Decode Rename Schedule RegisterRead Execute

F E D B A
E
Pipeline flush!!
F

125
Predicated Execution
n Eliminates branches à enables straight line code (i.e.,
larger basic blocks in code)

n Advantages
q Eliminates hard-to-predict branches
q Always-not-taken prediction works better (no branches)
q Compiler has more freedom to optimize code (no branches)
n control flow does not hinder inst. reordering optimizations
n code optimizations hindered only by data dependencies

n Disadvantages
q Useless work: some instructions fetched/executed but
discarded (especially bad for easy-to-predict branches)
q Requires additional ISA (and hardware) support
q Can we eliminate all branches this way?
126
Predicated Execution vs. Branch Prediction
+ Eliminates mispredictions for hard-to-predict branches
+ No need for branch prediction for some branches
+ Good if misprediction cost > useless work due to predication

-- Causes useless work for branches that are easy to predict


-- Reduces performance if misprediction cost < useless work
-- Adaptivity: Static predication is not adaptive to run-time branch
behavior. Branch behavior changes based on input set, program
phase, control-flow path.

127
Predicated Execution in Intel Itanium
n Each instruction can be separately predicated
n 64 one-bit predicate registers
each instruction carries a 6-bit predicate field
n An instruction is effectively a NOP if its predicate is false

cmp p1 p2 ¬cmp
br p2 else1
else1 p1 then1
join1
else2
p1 then2
br
p2 else2
then1
join2
then2
join1
join2
128
Conditional Execution in the ARM ISA
n Almost all ARM instructions could include an optional
condition code
q Prior to ARM v8

n An instruction with a condition code is executed only if


q the condition code flags in the CPSR (Current Program Status
Register) meet the specified condition

129
Conditional Execution in ARM ISA

130
Conditional Execution in ARM ISA

131
Conditional Execution in ARM ISA

132
Conditional Execution in ARM ISA

133
Conditional Execution in ARM ISA

134
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.

n Potential solutions if the instruction is a control-flow


instruction:

n Stall the pipeline until we know the next fetch address


n Guess the next fetch address (branch prediction)
n Employ delayed branching (branch delay slot)
n Do something else (fine-grained multithreading)
n Eliminate control-flow instructions (predicated execution)
n Fetch from both possible paths (if you know the addresses
of both possible paths) (multipath execution)
135
Multi-Path Execution
n Idea: Execute both paths after a conditional branch
q For all branches: Riseman and Foster, “The inhibition of potential parallelism
by conditional jumps,” IEEE Transactions on Computers, 1972.
q For a hard-to-predict branch: Use dynamic confidence estimation

n Advantages:
+ Improves performance if misprediction cost > useless work
+ No ISA change needed

n Disadvantages:
-- What happens when the machine encounters another hard-to-predict
branch? Execute both paths again?
-- Paths followed quickly become exponential
-- Each followed path requires its own context (registers, PC, GHR)
-- Wasted work (and reduced performance) if paths merge
136
Dual-Path Execution versus Predication

Dual-path Predicated Execution

A Hard to predict path 1 path 2 path 1 path 2

C B C B C B

D D D CFMerge CFMerge

D
E E E

E
F F F

137
Handling Other Types of
Branches

138
Remember: Branch Types
Type Direction at Number of When is next
fetch time possible next fetch address
fetch addresses? resolved?
Conditional Unknown 2 Execution (register
dependent)
Unconditional Always taken 1 Decode (PC +
offset)
Call Always taken 1 Decode (PC +
offset)
Return Always taken Many Execution (register
dependent)
Indirect Always taken Many Execution (register
dependent)

How can we predict an indirect branch with many target addresses?

139
Call and Return Prediction
Call X
n Direct calls are easy to predict …
Call X
q Always taken, single target

q Call marked in BTB, target predicted by BTB Call X

Return
n Returns are indirect branches Return
Return
q A function can be called from many points in code
q A return instruction can have many target addresses
n Next instruction after each call point for the same function
q Observation: Usually a return matches a call
q Idea: Use a stack to predict return addresses (Return Address Stack)
n A fetched call: pushes the return (next instruction) address on the stack
n A fetched return: pops the stack and uses the address as its predicted
target
n Accurate most of the time: 8-entry stack à > 95% accuracy

140
Indirect Branch Prediction (I)
n Register-indirect branches have multiple targets
A br.cond TARGET A R1 = MEM[R2]
T N ? branch R1

TARG A+1
a b d r

Conditional (Direct) Branch Indirect Jump

n Used to implement
q Switch-case statements
q Virtual function calls
q Jump tables (of function pointers)
q Interface calls

141
Indirect Branch Prediction (II)
n No direction prediction needed
n Idea 1: Predict the last resolved target as the next fetch address
+ Simple: Use the BTB to store the target address
-- Inaccurate: 50% accuracy (empirical). Many indirect branches switch
between different targets

n Idea 2: Use history based target prediction


q E.g., Index the BTB with GHR XORed with Indirect Branch PC
q Chang et al., “Target Prediction for Indirect Jumps,” ISCA 1997.

+ More accurate
-- An indirect branch maps to (too) many entries in BTB
-- Conflict misses with other branches (direct or indirect)
-- Inefficient use of space if branch has few target addresses

142
Intel Pentium M Indirect Branch Predictor

Gochman et al.,
“The Intel Pentium M Processor: Microarchitecture and Performance,”
Intel Technology Journal, May 2003.
143
Issues in Branch Prediction (I)
n Need to identify a branch before it is fetched

n How do we do this?
q BTB hit à indicates that the fetched instruction is a branch
q BTB entry contains the “type” of the branch
q Pre-decoded “branch type” information stored in the
instruction cache identifies type of branch

n What if no BTB?
q Bubble in the pipeline until target address is computed
q E.g., IBM POWER4

144
Latency of Branch Prediction
n Latency: Prediction is latency critical
q Need to generate next fetch address for the next cycle
q Bigger, more complex predictors are more accurate but slower

PC + inst size
BTB target Next Fetch
Return Address Stack target Address
Indirect Branch Predictor target
Resolved target from Backend

???

145
Issues in Fast & Wide Fetch
Engines

146
These Issues Covered in This Lecture…

https://www.youtube.com/onurmutlulectures 147
These Issues Covered in This Lecture…
n Computer Architecture, Spring 2015, Lecture 5
q Advanced Branch Prediction (CMU, Spring 2015)
q https://www.youtube.com/watch?v=yDjsr-
jTOtk&list=PL5PHm2jkkXmgVhh8CHAu9N76TShJqfYDt&index=4

https://www.youtube.com/onurmutlulectures 148
Interference in Branch Predictors

149
An Issue: Interference in the PHTs
n Sharing the PHTs between histories/branches leads to interference
q Different branches map to the same PHT entry and modify it

q Interference can be positive, negative, or neutral

n Interference can be eliminated by dedicating a PHT per branch


-- Too much hardware cost
n How else can you eliminate or reduce interference?
150
Reducing Interference in PHTs (I)
n Increase size of PHT

n Branch filtering
q Predict highly-biased branches separately so that they do not
consume PHT entries
q E.g., static prediction or BTB based prediction

n Hashing/index-randomization
q Gshare
q Gskew

n Agree prediction

151
Biased Branches and Branch Filtering
n Observation: Many branches are biased in one direction
(e.g., 99% taken)

n Problem: These branches pollute the branch prediction


structures à make the prediction of other branches difficult
by causing “interference” in branch prediction tables and
history registers

n Solution: Detect such biased branches, and predict them


with a simpler predictor (e.g., last time, static, …)

n Chang et al., “Branch classification: a new mechanism for improving


branch predictor performance,” MICRO 1994.

152
Reducing Interference: Gshare
n Idea 1: Randomize the indexing function into the PHT such that
probability of two branches mapping to the same entry reduces
q Gshare predictor: GHR hashed with the Branch PC

+ Better utilization of PHT + More context information


- Increases access latency

q McFarling, “Combining Branch Predictors,” DEC WRL Tech Report, 1993.


153
Reducing Interference: Agree Predictor
n Idea 2: Agree prediction
q Each branch has a “bias” bit associated with it in BTB

n Ideally, most likely outcome for the branch


q High bit of the PHT counter indicates whether or not the prediction
agrees with the bias bit (not whether or not prediction is taken)
+ Reduces negative interference (Why???)
-- Requires determining bias bits (compiler vs. hardware)

Sprangle et al., “The Agree Predictor:


A Mechanism for Reducing Negative
Branch History Interference,” ISCA
1997.

154
Why Does Agree Prediction Make Sense?
n Assume two branches have taken rates of 85% and 15%.
n Assume they conflict in the PHT

n Let’s compute the probability they have opposite outcomes


q Baseline predictor:
n P (b1 T, b2 NT) + P (b1 NT, b2 T)
= (85%*85%) + (15%*15%) = 74.5%
q Agree predictor:
n Assume bias bits are set to T (b1) and NT (b2)
n P (b1 agree, b2 disagree) + P (b1 disagree, b2 agree)
= (85%*15%) + (15%*85%) = 25.5%

n Works because most branches are biased (not 50% taken)


155
Reducing Interference: Gskew
n Idea 3: Gskew predictor
q Multiple PHTs

q Each indexed with a different type of hash function

q Final prediction is a majority vote

+ Distributes interference patterns in a more randomized way


(interfering patterns less likely in different PHTs at the same time)
-- More complexity (due to multiple PHTs, hash functions)
Branch Address
PHT0 PHT1 PHT2
Seznec, “An optimized
f0
Global BHR
2bcgskew branch
f1 predictor,” IRISA Tech
Report 1993.
f2

Michaud, “Trading conflict


and capacity aliasing in
M a jority conditional branch
Final Prediction
predictors,” ISCA 1997
156
More Techniques to Reduce PHT Interference
n The bi-mode predictor
q Separate PHTs for mostly-taken and mostly-not-taken branches
q Reduces negative aliasing between them
q Lee et al., “The bi-mode branch predictor,” MICRO 1997.

n The YAGS predictor


q Use a small tagged “cache” to predict branches that have experienced
interference
q Aims to not to mispredict them again
q Eden and Mudge, “The YAGS branch prediction scheme,” MICRO 1998.

n Alpha EV8 (21464) branch predictor


q Seznec et al., “Design tradeoffs for the Alpha EV8 conditional
branch predictor,” ISCA 2002.
157
Another Direction: Helper Threading
n Idea: Pre-compute the outcome of the branch with a
separate, customized thread (i.e., a helper thread)

n Chappell et al., “Difficult-Path Branch Prediction Using Subordinate


Microthreads,” ISCA 2002.
n Chappell et al., “Simultaneous Subordinate Microthreading,” ISCA 1999.
158
Issues in Wide & Fast Fetch

159
I-Cache Line and Way Prediction
n Problem: Complex branch prediction can take too long (many
cycles)
n Goal
q Quickly generate (a reasonably accurate) next fetch address
q Enable the fetch engine to run at high frequencies
q Override the quick prediction with more sophisticated prediction
n Idea: Get the predicted next cache line and way at the time
you fetch the current cache line

n Example Mechanism (e.g., Alpha 21264)


q Each cache line tells which line/way to fetch next (prediction)
q On a fill, line/way predictor points to next sequential line
q On branch resolution, line/way predictor is updated
q If line/way prediction is incorrect, one cycle is wasted
160
Alpha 21264 Line & Way Prediction

Kessler, “The Alpha 21264 Microprocessor,” IEEE Micro, March-April 1999. 161
Alpha 21264 Line & Way Prediction

Kessler, “The Alpha 21264 Microprocessor,” IEEE Micro, March-April 1999. 162
Issues in Wide Fetch Engines
n Wide Fetch: Fetch multiple instructions per cycle

n Superscalar
n VLIW
n SIMT (GPUs’ single-instruction multiple thread model)

n Wide fetch engines suffer from the branch problem:


q How do you feed the wide pipeline with useful instructions in a
single cycle?
q What if there is a taken branch in the “fetch packet”?
q What is there are “multiple (taken) branches” in the “fetch
packet”?

163
Fetching Multiple Instructions Per Cycle
n Two problems

1. Alignment of instructions in I-cache


q What if there are not enough (N) instructions in the cache line
to supply the fetch width?

2. Fetch break: Branches present in the fetch block


q Fetching sequential instructions in a single cycle is easy
q What if there is a control flow instruction in the N instructions?
q Problem: The direction of the branch is not known but we
need to fetch more instructions

n These can cause effective fetch width < peak fetch width

164
Wide Fetch Solutions: Alignment
n Large cache blocks: Hope N instructions contained in the
block

n Split-line fetch: If address falls into second half of the


cache block, fetch the first half of next cache block as well
q Enabled by banking of the cache
q Allows sequential fetch across cache blocks in one cycle
q Intel Pentium and AMD K5

165
Split Line Fetch

Need alignment logic:


166
Short Distance Predicted-Taken Branches

167
Techniques to Reduce Fetch Breaks
n Compiler
q Code reordering (basic block reordering)
q Superblock

n Hardware
q Trace cache

n Hardware/software cooperative
q Block structured ISA

168
Basic Block Reordering
n Not-taken control flow instructions not a problem: no fetch
break: make the likely path the not-taken path
n Idea: Convert taken branches to not-taken ones
q i.e., reorder basic blocks (after profiling)
q Basic block: code with a single entry and single exit point

Control Flow Graph Code Layout 1 Code Layout 2 Code Layout 3

A A A A
99% T NT 1%
B C B
B C D D C
D
D C B

n Code Layout 1 leads to the fewest fetch breaks

169
Basic Block Reordering
n Pettis and Hansen, “Profile Guided Code Positioning,” PLDI
1990.

n Advantages:
+ Reduced fetch breaks (assuming profile behavior matches
runtime behavior of branches)
+ Increased I-cache hit rate
+ Reduced page faults

n Disadvantages:
-- Dependent on compile-time profiling
-- Does not help if branches are not biased
-- Requires recompilation
170
Superblock
n Idea: Combine frequently executed basic blocks such that they form a
single-entry multiple exit larger block, which is likely executed as
straight-line code

+ Helps wide fetch


+ Enables aggressive
compiler optimizations
and code reordering
within the superblock

-- Increased code size


-- Profile dependent
-- Requires recompilation

n Hwu et al. “The Superblock: An effective technique for VLIW


and superscalar compilation,” Journal of Supercomputing, 1993.
171
Superblock Formation (I)
Is this a superblock?
Y Y
1
1
A A
100 100
90 10 10
90
B C B C
90 10 90 10
0 90 0 90
D E D E
0 90 10 0 90 10
99
90 90
0 0
F F
100 100 99
1 1
Z Z

172
Superblock Formation (II)
Y

1
A Tail duplication:
100
90 10 duplication of basic blocks
B after a side entrance to
90 C
0 90 10 eliminate side entrances
D E 10 à transforms
0 90
90 a trace into a superblock.
89.1
F
9.9 0 90
0.9
Z 10

F’ 0.1
10

173
Superblock Code Optimization Example

opA: mul r1<-r2,3 opA: mul r1<-r2,3


1 1
99 opB: add r2<-r2,1 99 opB: add r2<-r2,1
1 opC’: mul r3<-r2,3
opC: mul r3<-r2,3 opC: mul r3<-r2,3
Original Code Code After Superblock Formation

opA: mul r1<-r2,3


1
99 opB: add r2<-r2,1
opC’: mul r3<-r2,3
opC: mov r3<-r1
Code After Common
Subexpression Elimination
174
Techniques to Reduce Fetch Breaks
n Compiler
q Code reordering (basic block reordering)
q Superblock

n Hardware
q Trace cache

n Hardware/software cooperative
q Block structured ISA

175
Trace Cache: Basic Idea
n A trace is a sequence of executed instructions.
n It is specified by a start address and the branch outcomes
of control transfer instructions.
n Traces repeat: programs have frequently executed paths
n Trace cache idea: Store the dynamic instruction sequence
in the same physical location.

176
Reducing Fetch Breaks: Trace Cache
n Dynamically determine the basic blocks that are executed consecutively
n Trace: Consecutively executed basic blocks
n Idea: Store consecutively-executed basic blocks in physically-contiguous
internal storage (called trace cache)

n Basic trace cache operation:


q Fetch from consecutively-stored basic blocks (predict next trace or branches)
q Verify the executed branch directions with the stored ones
q If mismatch, flush the remaining portion of the trace

n Rotenberg et al., “Trace Cache: a Low Latency Approach to High Bandwidth Instruction
Fetching,” MICRO 1996.
n Patel et al., “Critical Issues Regarding the Trace Cache Fetch Mechanism,” Umich TR, 1997.
177
Trace Cache: Example

178
An Example Trace Cache Based Processor

n From Patel’s PhD Thesis: “Trace Cache Design for Wide Issue Superscalar
Processors,” University of Michigan, 1999.
179
Multiple Branch Predictor
n S. Patel, “Trace Cache Design for Wide Issue Superscalar Processors,” PhD
Thesis, University of Michigan, 1999.

180
What Does A Trace Cache Line Store?

n Patel et al., “Critical Issues Regarding the Trace Cache Fetch Mechanism,” Umich TR,
1997.
181
Trace Cache: Advantages/Disadvantages

+ Reduces fetch breaks (assuming branches are biased)


+ No need for decoding (instructions can be stored in decoded form)
+ Can enable dynamic optimizations within a trace
-- Requires hardware to form traces (more complexity) à called fill unit
-- Results in duplication of the same basic blocks in the cache
-- Can require the prediction of multiple branches per cycle
-- If multiple cached traces have the same start address
-- What if XYZ and XYT are both likely traces?

182
Intel Pentium 4 Trace Cache
n A 12K-uop trace cache replaces the L1 I-cache
n Trace cache stores decoded and cracked instructions
q Micro-operations (uops): returns 6 uops every other cycle
n x86 decoder can be simpler and slower
n A. Peleg, U. Weiser; "Dynamic Flow Instruction Cache Memory Organized
Around Trace Segments Independent of Virtual Address Line", United States
Patent No. 5,381,533, Jan 10, 1995

Front End BTB ITLB &


L2 Interface
4K Entries Prefetcher

x86 Decoder

Trace Cache BTB Trace Cache


512 Entries 12K uop’s

183

You might also like