-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathdecoupled_bpred.hh
More file actions
934 lines (794 loc) · 31.6 KB
/
decoupled_bpred.hh
File metadata and controls
934 lines (794 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
#ifndef __CPU_PRED_BTB_DECOUPLED_BPRED_HH__
#define __CPU_PRED_BTB_DECOUPLED_BPRED_HH__
#include <array>
#include <cstdint>
#include <deque>
#include <queue>
#include <stack>
#include <utility>
#include <vector>
#include "arch/generic/pcstate.hh"
#include "base/types.hh"
#include "cpu/o3/cpu_def.hh"
#include "cpu/o3/dyn_inst_ptr.hh"
#include "cpu/pred/bpred_unit.hh"
#include "cpu/pred/btb/abtb.hh"
#include "cpu/pred/btb/btb_ittage.hh"
#include "cpu/pred/btb/btb_mgsc.hh"
#include "cpu/pred/btb/btb_tage.hh"
#include "cpu/pred/btb/btb_ubtb.hh"
#include "cpu/pred/btb/mbtb.hh"
#include "cpu/pred/btb/microtage.hh"
#include "cpu/pred/btb/ras.hh"
#include "cpu/pred/general_arch_db.hh"
// #include "cpu/pred/btb/uras.hh"
#include "cpu/pred/btb/common.hh"
#include "cpu/pred/btb/history_manager.hh"
#include "cpu/pred/btb/timed_base_pred.hh"
#include "debug/DBPBTBStats.hh"
#include "debug/DecoupleBP.hh"
#include "debug/DecoupleBPProbe.hh"
#include "params/DecoupledBPUWithBTB.hh"
namespace gem5
{
namespace branch_prediction
{
namespace btb_pred
{
using DynInstPtr = o3::DynInstPtr;
using CPU = o3::CPU;
/**
* @class DecoupledBPUWithBTB
* @brief A decoupled branch predictor implementation using BTB-based design
*
* This predictor implements a decoupled front-end with:
* - Multiple prediction stages (UBTB -> BTB/TAGE/ITTAGE)
* - Fetch Target Queue (FTQ) for managing predicted targets
* - Support for loop prediction and jump-ahead prediction
*/
class DecoupledBPUWithBTB : public BPredUnit
{
public:
typedef DecoupledBPUWithBTBParams Params;
DecoupledBPUWithBTB(const Params ¶ms);
private:
// FSQ storage: a simple FIFO queue with implicit IDs (baseId + index),
// which is closer to RTL than std::map and makes "head" explicit.
unsigned fetchTargetQueueSize;
std::deque<FetchTarget> fetchTargetQueue;
FetchTargetId fetchTargetBaseId{1}; // ID of fetchTargetQueue.front()
FetchTargetId ftqId{1}; // next FSQ id to allocate (monotonic)
FetchTargetId fetchHeadFtqId{1}; // next FSQ id to be consumed by fetch
CPU *cpu;
unsigned predictWidth; // max predict width, default 64
unsigned maxInstsNum;
const unsigned historyBits{488}; // will be overridden later by the constructor
const Addr MaxAddr{~(0ULL)};
UBTB *ubtb{};
AheadBTB *abtb{};
MBTB *mbtb{};
MicroTAGE *microtage{};
BTBTAGE *tage{};
BTBITTAGE *ittage{};
BTBMGSC *mgsc{};
btb_pred::BTBRAS *ras{};
// btb_pred::BTBuRAS *uras{};
// bool enableDB;
std::vector<std::string> bpDBSwitches;
bool someDBenabled{false};
bool enableBranchTrace{false};
bool enablePredFSQTrace{false};
bool checkGivenSwitch(std::vector<std::string> switches, std::string switchName) {
for (auto &sw : switches) {
if (sw == switchName) {
return true;
}
}
return false;
}
void removeGivenSwitch(std::vector<std::string> &switches, std::string switchName) {
auto it = std::remove(switches.begin(), switches.end(), switchName);
switches.erase(it, switches.end());
}
DataBase bpdb;
TraceManager *bptrace;
TraceManager *predTraceManager; // Trace manager for prediction-time events
void initDB();
std::vector<TimedBaseBTBPredictor*> components{};
std::vector<FullBTBPrediction> predsOfEachStage{};
unsigned numComponents{};
unsigned numStages{};
enum class BpuState
{
IDLE, // Waiting to start a prediction.
PREDICTOR_DONE, // Prediction in progress (conceptually replaces `predictorFinished`).
PREDICTION_OUTSTANDING, // Prediction is ready to be enqueued (replaces `receivedPred`).
};
BpuState bpuState;
Addr s0PC; ///< Current PC
// Addr s0targetStartPC;
boost::dynamic_bitset<> s0History; ///< global History bits
boost::dynamic_bitset<> s0PHistory; ///< path History bits
boost::dynamic_bitset<> s0BwHistory; ///< global backward History bits
std::vector<boost::dynamic_bitset<>> s0LHistory; ///< local History bits
FullBTBPrediction finalPred; ///< Final prediction
boost::dynamic_bitset<> commitHistory;
bool squashing{false};
HistoryManager historyManager;
bool blockPredictionPending{false};
unsigned resolveDequeueFailCounter{0};
const unsigned resolveBlockThreshold;
unsigned numOverrideBubbles{0};
bool validateFSQEnqueue();
void processNewPrediction();
FetchTarget createFetchTargetEntry();
void updateHistoryForPrediction(FetchTarget &entry);
void fillAheadPipeline(FetchTarget &entry);
// Tick helper functions
void requestNewPrediction();
// TODO: compare phr and ghr
void histShiftIn(int shamt, bool taken, boost::dynamic_bitset<> &history);
void pHistShiftIn(int shamt, bool taken, boost::dynamic_bitset<> &history, Addr pc, Addr target);
void printTarget(const FetchTarget &e)
{
if (!e.resolved) {
DPRINTFR(DecoupleBPProbe, "FSQ Predicted target: ");
} else {
DPRINTFR(DecoupleBPProbe, "FSQ Resolved target: ");
}
// TODO:fix this
DPRINTFR(DecoupleBPProbe,
"%#lx-[%#lx, %#lx) --> %#lx, taken: %lu\n",
e.startPC, e.getBranchInfo().pc, e.getEndPC(),
e.getTakenTarget(), e.getTaken());
}
void printTargetFull(const FetchTarget &e)
{
// TODO: fix this
// DPRINTFR(
// DecoupleBP,
// "FSQ prediction:: %#lx-[%#lx, %#lx) --> %#lx\n",
// e.startPC, e.predBranchPC, e.predEndPC, e.predTarget);
// DPRINTFR(
// DecoupleBP,
// "Resolved: %i, resolved target:: %#lx-[%#lx, %#lx) --> %#lx\n",
// e.exeEnded, e.startPC, e.exeBranchPC, e.exeEndPC,
// e.exeTarget);
}
bool targetQueueFull() const
{
return fetchTargetQueue.size() >= fetchTargetQueueSize;
}
bool
hasTarget(FetchTargetId id) const
{
return !fetchTargetQueue.empty() &&
id >= fetchTargetBaseId &&
id < fetchTargetBaseId + fetchTargetQueue.size();
}
FetchTarget&
getTarget(FetchTargetId id)
{
assert(hasTarget(id));
return fetchTargetQueue[id - fetchTargetBaseId];
}
FetchTargetId
frontTargetId() const
{
assert(!fetchTargetQueue.empty());
return fetchTargetBaseId;
}
FetchTargetId
backTargetId() const
{
assert(!fetchTargetQueue.empty());
return fetchTargetBaseId + fetchTargetQueue.size() - 1;
}
/**
* @brief Generate final prediction from all stages
*
* Collects predictions from all stages and:
* - Selects most accurate prediction
* - Generates necessary bubbles
* - Updates prediction state
*/
unsigned generateFinalPredAndCreateBubbles();
void clearPreds() {
for (auto &stagePred : predsOfEachStage) {
stagePred.condTakens.clear();
stagePred.indirectTargets.clear();
stagePred.btbEntries.clear();
}
}
// const bool dumpLoopPred;
void printBTBEntry(const BTBEntry &e) {
DPRINTF(BTB, "BTB entry: valid %d, pc:%#lx, tag: %#lx, size:%d, target:%#lx, cond:%d, indirect:%d, call:%d, return:%d, always_taken:%d\n",
e.valid, e.pc, e.tag, e.size, e.target, e.isCond, e.isIndirect, e.isCall, e.isReturn, e.alwaysTaken);
}
void printFullBTBPrediction(const FullBTBPrediction &pred) {
DPRINTF(DecoupleBP, "dumping FullBTBPrediction\n");
DPRINTF(DecoupleBP, "bbStart: %#lx, btbEntry:\n", pred.bbStart);
for (auto &e: pred.btbEntries) {
printBTBEntry(e);
}
DPRINTF(DecoupleBP, "condTakens: ");
for (auto pair : pred.condTakens) {
DPRINTFR(DecoupleBP, "%#lx %d ,", pair.first, pair.second);
}
DPRINTFR(DecoupleBP, "\n");
for (auto pair : pred.indirectTargets) {
DPRINTF(DecoupleBP, "indirectTarget of %#lx: %#lx\n",
pair.first, pair.second);
}
DPRINTF(DecoupleBP, "returnTarget %#lx\n", pred.returnTarget);
}
/**
* @brief Statistics collection for branch prediction
*
* Tracks detailed statistics about:
* - Branch types and mispredictions
* - Predictor component usage
* - Queue utilization
* - Loop and jump-ahead prediction performance
*/
struct DBPBTBStats : public statistics::Group {
// Branch type statistics
statistics::Scalar condNum; ///< Number of conditional branches
statistics::Scalar uncondNum; ///< Number of unconditional branches
statistics::Scalar returnNum; ///< Number of return instructions
statistics::Scalar otherNum; ///< Number of other control instructions
// Misprediction statistics
statistics::Scalar condMiss; ///< Conditional branch mispredictions
statistics::Scalar uncondMiss; ///< Unconditional branch mispredictions
statistics::Scalar returnMiss; ///< Return mispredictions
statistics::Scalar otherMiss; ///< Other control mispredictions
// Fine-grained branch classification statistics
statistics::Vector branchClassCounts; ///< Classified branch occurrences
statistics::Vector branchClassMisses; ///< Mispredictions per class
statistics::Scalar branchClassCountsTotal; ///< Total classified branches
statistics::Vector controlSquashByClass; ///< Commit/Resolve-path squashes per class
// Branch coverage statistics
statistics::Scalar staticBranchNum; ///< Total static branches seen
statistics::Scalar staticBranchNumEverTaken; ///< Static branches ever taken
statistics::Vector predsOfEachStage;
statistics::Scalar overrideBubbleNum;
statistics::Scalar overrideCount;
statistics::Vector commitPredsFromEachStage;
statistics::Formula commitOverrideBubbleNum;
statistics::Formula commitOverrideCount;
// Track override reasons
statistics::Scalar overrideFallThruMismatch;
statistics::Scalar overrideControlAddrMismatch;
statistics::Scalar overrideTargetMismatch;
statistics::Scalar overrideEndMismatch;
statistics::Scalar overrideHistInfoMismatch;
statistics::Distribution fsqEntryDist;
statistics::Scalar fsqEntryEnqueued;
statistics::Scalar fsqEntryCommitted;
// statistics::Distribution ftqEntryDist;
statistics::Scalar controlSquashFromDecode;
statistics::Scalar controlSquashFromCommit;
statistics::Scalar nonControlSquash;
statistics::Scalar trapSquash;
statistics::Scalar ftqNotValid;
statistics::Scalar fsqNotValid;
statistics::Scalar fsqFullCannotEnq;
statistics::Scalar ftqFullCannotEnq;
statistics::Scalar fsqFullFetchHungry;
statistics::Scalar fsqEmpty;
//
statistics::Distribution commitFsqEntryHasInsts;
// write back once an fsq entry finishes fetch
statistics::Distribution commitFsqEntryFetchedInsts;
statistics::Scalar commitFsqEntryOnlyHasOneJump;
statistics::Scalar btbHit;
statistics::Scalar btbMiss;
statistics::Scalar btbEntriesWithDifferentStart;
statistics::Scalar btbEntriesWithOnlyOneJump;
statistics::Scalar predFalseHit;
statistics::Scalar commitFalseHit;
// Window blocking statistics
statistics::Scalar predictionBlockedForUpdate; // Times prediction was blocked for update priority
statistics::Scalar s1PredWrongFallthrough;
statistics::Scalar s1PredWrongUbtb;
statistics::Scalar s1PredWrongAbtb;
statistics::Scalar s3PredWrongMbtb;
statistics::Scalar s3PredWrongTage;
statistics::Scalar s3PredWrongIttage;
statistics::Scalar s3PredWrongRas;
DBPBTBStats(statistics::Group* parent, unsigned numStages, unsigned fsqSize, unsigned maxInstsNum);
} dbpBtbStats;
public:
/**
* @brief Main prediction cycle function
*
* This function handles:
* - FSQ/FTQ management
* - Prediction generation
* - Loop buffer management
* - Statistics collection
*/
void tick();
void squash(const InstSeqNum &squashed_sn, ThreadID tid)
{
panic("Squashing decoupled BP with tightly coupled API\n");
}
void squash(const InstSeqNum &squashed_sn, const PCStateBase &corr_target,
bool actually_taken, ThreadID tid)
{
panic("Squashing decoupled BP with tightly coupled API\n");
}
void setCpu(CPU *_cpu) { cpu = _cpu; }
void consumeFetchTarget(unsigned fetched_inst_num);
struct BpTrace : public Record
{
void set(uint64_t fsqId, uint64_t startPC, uint64_t controlPC, uint64_t controlType,
uint64_t taken, uint64_t mispred, uint64_t fallThruPC,
uint64_t source, uint64_t target) {
_uint64_data["fsqId"] = fsqId;
_uint64_data["startPC"] = startPC;
_uint64_data["controlPC"] = controlPC;
_uint64_data["controlType"] = controlType;
_uint64_data["taken"] = taken;
_uint64_data["mispred"] = mispred;
_uint64_data["fallThruPC"] = fallThruPC;
_uint64_data["source"] = source;
_uint64_data["target"] = target;
}
BpTrace(uint64_t fsqId, FetchTarget &target, const DynInstPtr &inst, bool mispred);
};
// Prediction trace record for tracking prediction-time information
struct PredictionTrace : public Record
{
void set(uint64_t fsqId, uint64_t startPC, uint64_t predTaken, uint64_t predEndPC,
uint64_t controlPC, uint64_t target,
uint64_t predSource, uint64_t btbHit) {
_uint64_data["fsqId"] = fsqId;
_uint64_data["startPC"] = startPC;
_uint64_data["predTaken"] = predTaken;
_uint64_data["predEndPC"] = predEndPC;
_uint64_data["controlPC"] = controlPC;
_uint64_data["target"] = target;
_uint64_data["predSource"] = predSource;
_uint64_data["btbHit"] = btbHit;
}
PredictionTrace(uint64_t id, const FetchTarget &entry) {
_tick = curTick();
set(id, entry.startPC, entry.predTaken, entry.predEndPC,
entry.getControlPC(), entry.getTakenTarget(),
entry.predSource, entry.isHit ? 1 : 0);
}
};
// redirect the target
void controlSquash(unsigned fsq_id,
const PCStateBase &control_pc,
const PCStateBase &target_pc,
const StaticInstPtr &static_inst, unsigned inst_bytes,
bool actually_taken, const InstSeqNum &squashed_sn,
ThreadID tid, const unsigned ¤tLoopIter,
const bool fromCommit);
// keep the target: original prediction might be right
// For memory violation, target continues after squashing
void nonControlSquash(unsigned fsq_id,
const PCStateBase &inst_pc, const InstSeqNum seq,
ThreadID tid, const unsigned ¤tLoopIter);
// Not a control. But target is actually disturbed
void trapSquash(unsigned fsq_id, Addr last_committed_pc,
const PCStateBase &inst_pc, ThreadID tid, const unsigned ¤tLoopIter);
void update(unsigned fsqID, ThreadID tid);
void squashTargetAfter(unsigned squash_target_id);
// Fetch-facing interface: consume FSQ head directly (RTL-like single queue).
bool ftqHasHead() const { return hasTarget(fetchHeadFtqId); }
FetchTargetId ftqHeadId() const { assert(ftqHasHead()); return fetchHeadFtqId; }
const FetchTarget &ftqHead() { assert(ftqHasHead()); return getTarget(fetchHeadFtqId); }
void dumpFsq(const char *when);
// Dummy overriding
void uncondBranch(ThreadID tid, Addr pc, void *&bp_history) override {}
void squash(ThreadID tid, void *bp_history) override {}
void btbUpdate(ThreadID tid, Addr instPC, void *&bp_history) override {}
void update(ThreadID tid, Addr instPC, bool taken, void *bp_history,
bool squashed, const StaticInstPtr &inst,
Addr corrTarget) override
{
}
bool lookup(ThreadID tid, Addr instPC, void *&bp_history) override { return false; }
// end Dummy overriding
void overrideStats(OverrideReason overrideReason);
void checkHistory(const boost::dynamic_bitset<> &history);
Addr getPreservedReturnAddr(const DynInstPtr &dynInst);
std::unordered_map<Addr, int> takenBranches; // branch address -> taken count
std::unordered_map<Addr, int> currentPhaseTakenBranches;
std::unordered_map<Addr, int> currentSubPhaseTakenBranches;
/**
* @brief Types of control flow instruction mispredictions
*/
enum MispredType {
DIR_WRONG, ///< Direction prediction error (predicted taken when not taken or vice versa)
TARGET_WRONG, ///< Target address prediction was wrong (branch taken but to the wrong address)
NO_PRED, ///< No prediction was made (branch wasn't predicted at all)
FAKE_LAST ///< Sentinel value
};
/**
* @brief Branch statistics structure holding detailed misprediction data
*
* This structure captures comprehensive statistics about a specific branch,
* tracking both execution counts and various types of mispredictions.
* It allows for detailed analysis of predictor performance for each branch.
*/
struct BranchStats
{
Addr pc; ///< Branch PC address
int branchType; ///< Branch type (0=cond, 1=uncond, 2=call, 3=ind, etc.)
int totalCount; ///< Total number of times branch was executed
int mispredCount; ///< Total number of mispredictions for this branch
int dirWrongCount; ///< Number of times direction was mispredicted
int targetWrongCount; ///< Number of times target address was mispredicted
int noPredCount; ///< Number of times no prediction was made
/**
* @brief Default constructor
*/
BranchStats()
: pc(0), branchType(0), totalCount(0), mispredCount(0),
dirWrongCount(0), targetWrongCount(0), noPredCount(0) {}
/**
* @brief Create branch stats with initial values
*/
BranchStats(Addr _pc, int _type)
: pc(_pc), branchType(_type), totalCount(0), mispredCount(0),
dirWrongCount(0), targetWrongCount(0), noPredCount(0) {}
/**
* @brief Increment total execution count
*/
void incrementTotal() { totalCount++; }
/**
* @brief Increment misprediction count for a specific type
*/
void incrementMispred(MispredType type) {
mispredCount++;
switch(type) {
case DIR_WRONG: dirWrongCount++; break;
case TARGET_WRONG: targetWrongCount++; break;
case NO_PRED: noPredCount++; break;
default: break;
}
}
/**
* @brief Calculate misprediction rate (per 1000 executions)
*
* @return Misprediction rate scaled to per-mille (0-1000)
*/
double getMispredRate() const {
return totalCount > 0 ? (double)(mispredCount * 1000) / totalCount : 0;
}
};
/**
* @brief Index type for branch statistics maps
*/
using BranchKey = std::pair<Addr, int>;
/**
* @brief Map type for branch statistics
*/
using BranchStatsMap = std::map<BranchKey, BranchStats>;
// Branch statistics maps
/**
* @brief Maps (startPC, controlPC) pairs to misprediction counts
*
* This tracks mispredictions based on the starting address of a basic block
* and the address of the control instruction that was mispredicted.
*/
std::map<std::pair<Addr, Addr>, int> topMispredicts;
/**
* @brief Maps branch keys (PC, type) to detailed branch statistics
*
* Main container for branch prediction statistics, storing information about
* each branch's execution count, mispredictions, and error types.
*/
BranchStatsMap topMispredictsByBranch;
/**
* @brief Maps branch history patterns to misprediction counts
*
* Tracks which history patterns tend to cause more mispredictions.
* Key: History pattern value
* Value: Count of mispredictions with this pattern
*/
std::map<uint64_t, uint64_t> topMispredHist;
// Phase-based statistics
/**
* @brief Stores branch statistics from the previous phase
*
* Used to calculate delta statistics between phases.
*/
BranchStatsMap lastPhaseTopMispredictsByBranch;
/**
* @brief Vector of branch statistics for each phase
*
* Each entry contains the branch statistics for a complete phase.
*/
std::vector<BranchStatsMap> topMispredictsByBranchByPhase;
/**
* @brief Vector of branch statistics for each sub-phase
*
* Similar to topMispredictsByBranchByPhase but with finer granularity.
*/
std::vector<BranchStatsMap> topMispredictsByBranchBySubPhase;
/**
* @brief Vector of taken branches for each phase
*
* Each entry maps branch addresses to execution counts for a phase.
*/
std::vector<std::unordered_map<Addr, int>> takenBranchesByPhase;
/**
* @brief Vector of taken branches for each sub-phase
*
* Each entry maps branch addresses to execution counts for a sub-phase.
*/
std::vector<std::unordered_map<Addr, int>> takenBranchesBySubPhase;
// BTB entry tracking
/**
* @brief BTB entries from the previous phase
*
* Maps start address to (BTBEntry, visit count) to track BTB entry usage.
*/
std::unordered_map<Addr, std::pair<BTBEntry, int>> lastPhaseBTBEntries;
/**
* @brief Cumulative BTB entries seen so far
*
* Maps start address to (BTBEntry, visit count) with total usage.
*/
std::unordered_map<Addr, std::pair<BTBEntry, int>> totalBTBEntries;
/**
* @brief Vector of BTB entries for each phase
*
* Each entry contains the BTB entries used during a phase.
*/
std::vector<std::unordered_map<Addr, std::pair<BTBEntry, int>>> BTBEntriesByPhase;
/**
* @brief Next phase ID to dump statistics for
*/
int phaseIdToDump{1};
/**
* @brief Total number of instructions committed
*/
int numInstCommitted{0};
/**
* @brief Number of instructions per phase
*/
int phaseSizeByInst{100000};
/**
* @brief Next sub-phase ID to dump statistics for
*/
int subPhaseIdToDump{1};
/**
* @brief Ratio between phase and sub-phase sizes
*/
int subPhaseRatio{10};
/**
* @brief Calculate sub-phase size in instructions
* @return Number of instructions per sub-phase
*/
int subPhaseSizeByInst() { return phaseSizeByInst/subPhaseRatio; }
/**
* @brief Distribution of committed instructions from previous phase
*
* Vector indexed by instruction count, values are frequency.
*/
std::vector<int> lastPhaseFsqEntryNumCommittedInstDist;
/**
* @brief Total committed instruction count distribution
*
* Tracks how many FSQ entries have each number of committed instructions.
*/
std::vector<int> commitFsqEntryHasInstsVector;
/**
* @brief Committed instruction distributions by phase
*
* Each entry contains the distribution of committed instructions for a phase.
*/
std::vector<std::vector<int>> fsqEntryNumCommittedInstDistByPhase;
/**
* @brief Distribution of fetched instructions from previous phase
*
* Vector indexed by instruction count, values are frequency.
*/
std::vector<int> lastPhaseFsqEntryNumFetchedInstDist;
/**
* @brief Total fetched instruction count distribution
*
* Tracks how many FSQ entries have each number of fetched instructions.
*/
std::vector<int> commitFsqEntryFetchedInstsVector;
/**
* @brief Fetched instruction distributions by phase
*
* Each entry contains the distribution of fetched instructions for a phase.
*/
std::vector<std::vector<int>> fsqEntryNumFetchedInstDistByPhase;
/**
* @brief Total branch misprediction count
*/
unsigned int missCount{0};
/**
* @brief Branch statistics from the previous sub-phase
*
* Used to calculate delta statistics between sub-phases.
*/
BranchStatsMap lastSubPhaseTopMispredictsByBranch;
// These are already declared above, so no need to redeclare
// std::vector<BranchStatsMap> topMispredictsByBranchBySubPhase;
// std::vector<std::map<Addr, int>> takenBranchesBySubPhase;
void recoverHistoryForSquash(
FetchTarget &target,
unsigned target_id,
const PCStateBase &squash_pc,
bool is_conditional,
bool actually_taken,
SquashType squash_type,
Addr redirect_pc);
// Common logic for squash handling
void handleSquash(unsigned target_id,
SquashType squash_type,
const PCStateBase &squash_pc,
Addr redirect_pc,
bool is_conditional = false,
bool actually_taken = false,
const StaticInstPtr &static_inst = nullptr,
unsigned control_inst_size = 0);
void resetPC(Addr new_pc);
// Helper functions for update
bool resolveUpdate(unsigned &target_id);
void prepareResolveUpdateEntries(unsigned &target_id);
void markCFIResolved(unsigned &target, uint64_t resolvedInstPC);
void updatePredictorComponents(FetchTarget &target);
void updateStatistics(const FetchTarget &target);
void notifyResolveSuccess();
void notifyResolveFailure();
void blockPredictionOnce();
/**
* @brief Types of control flow instructions for misprediction tracking
*/
enum CfiType
{
COND, ///< Conditional branch
UNCOND, ///< Unconditional branch
RETURN, ///< Return instruction
OTHER ///< Other control flow instruction
};
/**
* @brief Fine-grained branch classes used to tie stats to predictors
*/
enum class BranchClass : uint8_t
{
CondBranch = 0, ///< Conditional direct branches (TAGE focus)
DirectCall, ///< Direct call instructions (RAS + BTB)
IndirectCall, ///< Indirect call instructions (ITTAGE + RAS)
Return, ///< Return instructions (RAS)
DirectJump, ///< Direct, non-call control transfers (BTB)
IndirectJump, ///< Indirect jumps that are not calls/returns (ITTAGE)
Unknown, ///< Fallback for unexpected classifications
NumClasses ///< Sentinel used for sizing stat containers
};
static constexpr size_t NumBranchClasses =
static_cast<size_t>(BranchClass::NumClasses);
void addCfi(CfiType type, bool mispred) {
switch (type) {
case COND:
dbpBtbStats.condNum++;
if (mispred)
dbpBtbStats.condMiss++;
break;
case UNCOND:
dbpBtbStats.uncondNum++;
if (mispred)
dbpBtbStats.uncondMiss++;
break;
case RETURN:
dbpBtbStats.returnNum++;
if (mispred)
dbpBtbStats.returnMiss++;
break;
case OTHER:
dbpBtbStats.otherNum++;
if (mispred)
dbpBtbStats.otherMiss++;
break;
}
DPRINTF(DBPBTBStats, "Miss type: %d\n", type);
}
BranchClass classifyBranch(const DynInstPtr &inst) const;
BranchClass classifyBranch(const StaticInstPtr &inst) const;
static const char *branchClassName(BranchClass cls);
void addBranchClassStat(BranchClass cls, bool mispred);
void addControlSquashCommitStat(BranchClass cls);
void addFtqNotValid() {
dbpBtbStats.ftqNotValid++;
}
/**
* @brief Process a branch instruction during commit
*
* Updates branch prediction statistics and trains predictor components.
*
* @param inst Dynamic instruction pointer
* @param miss Whether the branch was mispredicted
*/
void commitBranch(const DynInstPtr &inst, bool miss);
void commitPredWrongSource(const FetchTarget &entry);
/**
* @brief Process branch misprediction, determine type and update statistics
*
* @param entry The fetch target entry
* @param branchAddr Branch instruction address
* @param info Branch information
* @param taken Whether the branch was taken
* @param mispred Whether the branch was mispredicted
*/
void processMisprediction(
const FetchTarget &entry,
Addr branchAddr,
const BranchInfo &info,
bool taken,
bool mispred);
/**
* @brief Track statistics for taken branches
*
* @param branchAddr Branch instruction address
*/
void trackTakenBranch(Addr branchAddr);
/**
* @brief Process phase-based statistics at phase boundaries
*
* @param isSubPhase Whether this is a sub-phase or main phase
* @param phaseID Current phase ID
* @param phaseToDump Phase ID to be processed
* @param lastPhaseStats Last phase branch statistics map
* @param phaseStatsList List of all phases branch statistics
* @param currentPhaseBranches Current phase taken branches map
* @param phaseBranchesList List of all phases taken branches
* @return true If the phase was processed
*/
bool processPhase(bool isSubPhase, int phaseID, int &phaseToDump,
BranchStatsMap &lastPhaseStats,
std::vector<BranchStatsMap> &phaseStatsList,
std::unordered_map<Addr, int> ¤tPhaseBranches,
std::vector<std::unordered_map<Addr, int>> &phaseBranchesList);
/**
* @brief Process fetch instruction distributions for a phase
*
* @param currentPhaseCommittedDist Output vector for committed instruction distribution
* @param currentPhaseFetchedDist Output vector for fetched instruction distribution
*/
void processFetchDistributions(std::vector<int> ¤tPhaseCommittedDist,
std::vector<int> ¤tPhaseFetchedDist);
/**
* @brief Process BTB entries for a phase
*
* @return std::map<Addr, std::pair<BTBEntry, int>> Map of BTB entries for the phase
*/
std::unordered_map<Addr, std::pair<BTBEntry, int>> processBTBEntries();
/**
* @brief Process instruction commit and update phase-based statistics
*
* Called whenever an instruction is committed, updating instruction counts
* and phase-based statistics when phase boundaries are reached.
*
* @param inst Dynamic instruction pointer of the committed instruction
*/
void notifyInstCommit(const DynInstPtr &inst);
/**
* @brief Tracks mispredictions of indirect branches
*
* Maps indirect branch addresses to misprediction counts.
*/
std::map<Addr, unsigned> topMispredIndirect;
/**
* @brief Dump statistics on program exit
*
* This method dumps various predictor statistics to output files when
* the simulation ends. It tracks mispredictions by branch type,
* phase information, and other metrics.
*/
void dumpStats();
};
} // namespace btb_pred
} // namespace branch_prediction
} // namespace gem5
#endif // __CPU_PRED_BTB_DECOUPLED_BPRED_HH__