Anch Prediction
Anch Prediction
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
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?
6
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.
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
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
+
ResultW
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
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?
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
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
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
taken?
Address of the
current branch
target address
26
More Sophisticated Branch Direction Prediction
Global branch
history PC + inst size Next Fetch
XOR Address
Program
hit?
Counter
Address of the
current branch
target address
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)
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 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
33
Digital Design & Computer Arch.
Lecture 16b: Branch Prediction
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
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)) { … }
38
Static Branch Prediction
n All previous techniques can be combined
q Profile based
q Program based
q Programmer based
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 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
taken?
Address of the
current branch
target address
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
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
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
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
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
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
….
}
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)
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
11 …. 11
Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 60
How Does the Global Predictor Work?
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
62
Intel Pentium Pro (1995)
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
taken?
Address of the
current instruction
target address
66
Two-Level Global History Branch Predictor
Global branch
history PC + inst size Next Fetch
Address
Program
hit?
Counter
Address of the
current instruction
target address
67
Two-Level Gshare Branch Predictor
Global branch
history PC + inst size Next Fetch
XOR Address
Program
hit?
Counter
Address of the
current instruction
target address
68
Can We Do Better: Two-Level Prediction
n Last-time and 2BC predictors exploit only “last-time”
predictability for a given branch
Yeh and Patt, “Two-Level Adaptive Training Branch Prediction,” MICRO 1991. 69
Local Branch Correlation
70
More Motivation for Local History
Loop closing branch’s history
n To predict a loop PHT
11101110111011101110 0000
branch “perfectly”, we 0001
1101 11
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
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?
Address of the
current instruction
target address
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)
76
Can We Do Even Better?
n Predictability of branches varies
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
80
Are We Done w/ Branch Prediction?
n Hybrid branch predictors work well
q E.g., 90-97% prediction accuracy on average
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
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
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
See, e.g., Grayson+, “Evolution of the Samsung Exynos CPU Microarchitecture,” ISCA 2020.
89
Recommended Reading
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
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
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 …
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.
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
https://www.youtube.com/onurmutlulectures 111
Lectures on Static Instruction Scheduling
https://www.youtube.com/onurmutlulectures 112
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.
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
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
https://www.youtube.com/onurmutlulectures 118
How to Handle Control Dependences
n Critical to keep the pipeline full with correct sequence of
dynamic instructions.
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)
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
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
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 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
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)
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
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
+ 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
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)
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
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
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
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)
163
Fetching Multiple Instructions Per Cycle
n Two problems
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
165
Split Line Fetch
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
A A A A
99% T NT 1%
B C B
B C D D C
D
D C B
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
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
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 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
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
x86 Decoder
183