-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathbtb_mgsc.cc
More file actions
executable file
·1528 lines (1384 loc) · 59.2 KB
/
Copy pathbtb_mgsc.cc
File metadata and controls
executable file
·1528 lines (1384 loc) · 59.2 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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "cpu/pred/btb/btb_mgsc.hh"
#include "base/intmath.hh"
#include "base/logging.hh"
#ifdef UNIT_TEST
#include "cpu/pred/btb/test/test_dprintf.hh"
// Define debug flags for unit testing
namespace gem5 {
namespace debug {
bool MGSC = true;
}
}
#else
#include "cpu/o3/dyn_inst.hh"
#include "debug/MGSC.hh"
#endif
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <type_traits>
#include <vector>
namespace gem5
{
namespace branch_prediction
{
namespace btb_pred
{
#ifdef UNIT_TEST
namespace test
{
#endif
void
BTBMGSC::initStorage()
{
auto pow2 = [](unsigned width) -> uint64_t {
assert(width < 63);
return 1ULL << width;
};
auto allocPredTable = [&](std::vector<std::vector<std::vector<int16_t>>> &table, unsigned numTables,
unsigned idxWidth) -> uint64_t {
table.resize(numTables);
auto tableSize = pow2(idxWidth);
assert(tableSize > numCtrsPerLine);
for (unsigned int i = 0; i < numTables; ++i) {
table[i].resize(tableSize / numCtrsPerLine, std::vector<int16_t>(numCtrsPerLine, 0));
}
return tableSize;
};
assert(isPowerOf2(numCtrsPerLine));
numCtrsPerLineBits = log2i(numCtrsPerLine);
threadHistory.resize(MaxThreads);
threadMeta.resize(MaxThreads);
auto bwTableSize = allocPredTable(bwTable, bwTableNum, bwTableIdxWidth);
for (ThreadID tid = 0; tid < MaxThreads; ++tid) {
auto &state = threadHistory[tid];
for (unsigned int i = 0; i < bwTableNum; ++i) {
state.indexBwFoldedHist.emplace_back(
bwHistLen[i], bwTableIdxWidth - numCtrsPerLineBits, 16);
}
}
bwIndex.resize(bwTableNum);
auto lTableSize = allocPredTable(lTable, lTableNum, lTableIdxWidth);
for (ThreadID tid = 0; tid < MaxThreads; ++tid) {
auto &state = threadHistory[tid];
state.indexLFoldedHist.resize(numEntriesFirstLocalHistories);
for (unsigned int i = 0; i < lTableNum; ++i) {
for (unsigned int k = 0; k < numEntriesFirstLocalHistories; ++k) {
state.indexLFoldedHist[k].push_back(LocalFoldedHist(
lHistLen[i], lTableIdxWidth - numCtrsPerLineBits, 16));
}
}
}
lIndex.resize(lTableNum);
auto iTableSize = allocPredTable(iTable, iTableNum, iTableIdxWidth);
for (ThreadID tid = 0; tid < MaxThreads; ++tid) {
auto &state = threadHistory[tid];
for (unsigned int i = 0; i < iTableNum; ++i) {
assert(iHistLen[i] >= 0);
assert(static_cast<unsigned>(iHistLen[i]) < 63);
assert(pow2(static_cast<unsigned>(iHistLen[i])) <= iTableSize);
state.indexIFoldedHist.emplace_back(
iHistLen[i], iTableIdxWidth - numCtrsPerLineBits, 16);
}
}
iIndex.resize(iTableNum);
auto gTableSize = allocPredTable(gTable, gTableNum, gTableIdxWidth);
for (ThreadID tid = 0; tid < MaxThreads; ++tid) {
auto &state = threadHistory[tid];
for (unsigned int i = 0; i < gTableNum; ++i) {
assert(gTable.size() >= gTableNum);
state.indexGFoldedHist.emplace_back(
gHistLen[i], gTableIdxWidth - numCtrsPerLineBits, 16);
}
}
gIndex.resize(gTableNum);
auto pTableSize = allocPredTable(pTable, pTableNum, pTableIdxWidth);
for (ThreadID tid = 0; tid < MaxThreads; ++tid) {
auto &state = threadHistory[tid];
for (unsigned int i = 0; i < pTableNum; ++i) {
assert(pTable.size() >= pTableNum);
state.indexPFoldedHist.emplace_back(
pHistLen[i], pTableIdxWidth - numCtrsPerLineBits, 2);
}
}
pIndex.resize(pTableNum);
allocPredTable(biasTable, biasTableNum, biasTableIdxWidth);
biasIndex.resize(biasTableNum);
auto weightTableSize = pow2(weightTableIdxWidth);
bwWeightTable.resize(weightTableSize);
lWeightTable.resize(weightTableSize);
iWeightTable.resize(weightTableSize);
gWeightTable.resize(weightTableSize);
pWeightTable.resize(weightTableSize);
biasWeightTable.resize(weightTableSize);
pUpdateThreshold.resize(pow2(thresholdTablelogSize));
}
#ifdef UNIT_TEST
BTBMGSC::BTBMGSC()
: TimedBaseBTBPredictor(),
bwTableNum(1),
// Use a slightly larger idx width so foldedLen is not too small (helps pattern-learning tests).
bwTableIdxWidth(6),
bwHistLen({4}),
numEntriesFirstLocalHistories(4),
lTableNum(1),
// Use a slightly larger idx width so foldedLen is not too small (helps pattern-learning tests).
lTableIdxWidth(6),
lHistLen({4}),
iTableNum(1),
iTableIdxWidth(5),
// `ImliFoldedHist` requires foldedLen >= histLen. With `numCtrsPerLine=8` and `iTableIdxWidth=5`,
// foldedLen is small (5 - log2(8) = 2), so keep histLen=1 for unit tests.
// Also keep it >= 2 so we can build loop-trip-count tests on IMLI.
iHistLen({2}),
gTableNum(1),
// Use a slightly larger idx width so foldedLen is not too small (helps pattern-learning tests).
gTableIdxWidth(6),
gHistLen({4}),
pTableNum(1),
// Use a slightly larger idx width so foldedLen is not too small (helps pattern-learning tests).
pTableIdxWidth(6),
pHistLen({4}),
biasTableNum(1),
biasTableIdxWidth(5),
scCountersWidth(6),
thresholdTablelogSize(4),
updateThresholdWidth(12),
pUpdateThresholdWidth(8),
extraWeightsWidth(6),
weightTableIdxWidth(4),
// Keep consistent with `src/cpu/pred/BranchPredictor.py` default (8 counters per SRAM line).
// This models "read a whole SRAM line, then pick a lane" behavior in `posHash()`.
numCtrsPerLine(8),
forceUseSC(false),
allowMissingTageInfo(false),
enableBwTable(true),
enableLTable(true),
enableITable(true),
enableGTable(true),
enablePTable(true),
enableBiasTable(true),
enablePCThreshold(false),
focusBranchPC(0),
mgscStats()
{
// Test-only small config: keep tables tiny and deterministic for fast unit tests.
initStorage();
updateThreshold = 35 * 8;
}
#else
// Constructor: Initialize MGSC predictor with given parameters
BTBMGSC::BTBMGSC(const Params &p)
: TimedBaseBTBPredictor(p),
bwTableNum(p.bwTableNum),
bwTableIdxWidth(p.bwTableIdxWidth),
bwHistLen(p.bwHistLen),
numEntriesFirstLocalHistories(p.numEntriesFirstLocalHistories),
lTableNum(p.lTableNum),
lTableIdxWidth(p.lTableIdxWidth),
lHistLen(p.lHistLen),
iTableNum(p.iTableNum),
iTableIdxWidth(p.iTableIdxWidth),
iHistLen(p.iHistLen),
gTableNum(p.gTableNum),
gTableIdxWidth(p.gTableIdxWidth),
gHistLen(p.gHistLen),
pTableNum(p.pTableNum),
pTableIdxWidth(p.pTableIdxWidth),
pHistLen(p.pHistLen),
biasTableNum(p.biasTableNum),
biasTableIdxWidth(p.biasTableIdxWidth),
scCountersWidth(p.scCountersWidth),
thresholdTablelogSize(p.thresholdTablelogSize),
updateThresholdWidth(p.updateThresholdWidth),
pUpdateThresholdWidth(p.pUpdateThresholdWidth),
extraWeightsWidth(p.extraWeightsWidth),
weightTableIdxWidth(p.weightTableIdxWidth),
numCtrsPerLine(p.numCtrsPerLine),
forceUseSC(p.forceUseSC),
allowMissingTageInfo(p.allowMissingTageInfo),
enableBwTable(p.enableBwTable),
enableLTable(p.enableLTable),
enableITable(p.enableITable),
enableGTable(p.enableGTable),
enablePTable(p.enablePTable),
enableBiasTable(p.enableBiasTable),
enablePCThreshold(p.enablePCThreshold),
focusBranchPC(p.focusBranchPC),
mgscStats(this)
{
DPRINTF(MGSC, "BTBMGSC constructor\n");
initStorage();
updateThreshold = 35 * 8;
hasDB = true;
dbName = std::string("mgsc");
}
#endif
BTBMGSC::~BTBMGSC() {}
ThreadID
BTBMGSC::predictorTid(const std::vector<FullBTBPrediction> &stagePreds) const
{
assert(!stagePreds.empty());
return stagePreds.front().tid;
}
BTBMGSC::ThreadHistoryState &
BTBMGSC::historyState(ThreadID tid)
{
assert(tid < threadHistory.size());
return threadHistory[tid];
}
const BTBMGSC::ThreadHistoryState &
BTBMGSC::historyState(ThreadID tid) const
{
assert(tid < threadHistory.size());
return threadHistory[tid];
}
// Set up tracing for debugging
void
BTBMGSC::setTrace()
{
#ifndef UNIT_TEST
if (enableDB) {
std::vector<std::pair<std::string, DataType>> fields_vec = {
std::make_pair("branchPC", UINT64),
std::make_pair("bbStart", UINT64),
std::make_pair("branchOffset", UINT64),
std::make_pair("tagePred", UINT64),
std::make_pair("tageConfHigh", UINT64),
std::make_pair("tageConfMid", UINT64),
std::make_pair("tageConfLow", UINT64),
std::make_pair("bwPercsum", UINT64),
std::make_pair("lPercsum", UINT64),
std::make_pair("iPercsum", UINT64),
std::make_pair("gPercsum", UINT64),
std::make_pair("pPercsum", UINT64),
std::make_pair("biasPercsum", UINT64),
std::make_pair("totalSum", UINT64),
std::make_pair("totalThres", UINT64),
std::make_pair("effectiveGate", UINT64),
std::make_pair("margin", UINT64),
std::make_pair("bwIndexSig", UINT64),
std::make_pair("lIndexSig", UINT64),
std::make_pair("iIndexSig", UINT64),
std::make_pair("gIndexSig", UINT64),
std::make_pair("pIndexSig", UINT64),
std::make_pair("biasIndexSig", UINT64),
std::make_pair("useSc", UINT64),
std::make_pair("scPred", UINT64),
std::make_pair("actualTaken", UINT64),
};
mgscMissTrace = _db->addAndGetTrace("MGSCTRACE", fields_vec);
mgscMissTrace->init_table();
}
#endif
}
void
BTBMGSC::tick()
{
}
void
BTBMGSC::tickStart()
{
}
/**
* Calculate perceptron sum from a table for a given PC
* Counter range: [-2^(w-1), 2^(w-1)-1], e.g., [-32, 31] for w=6
* Percsum = sum of (2*counter + 1), transforms to odd numbers, e.g., [-63, 63] per entry
* @param table The table to search in
* @param tableIndices Indices to use for each table component
* @param numTables Number of tables to search
* @param pc PC to match against
* @return Calculated percsum value (positive=taken bias, negative=not-taken bias)
*/
int
BTBMGSC::calculatePercsum(const std::vector<std::vector<std::vector<int16_t>>> &table,
const std::vector<unsigned> &tableIndices, unsigned numTables, Addr pc)
{
int percsum = 0;
for (unsigned int i = 0; i < numTables; ++i) {
auto [idx1, idx2] = posHash(pc, tableIndices[i]);
auto &entry = table[i][idx1][idx2];
percsum += (2 * entry + 1); // transform to odd numbers, avoid zero
}
return percsum;
}
/**
* Find weight in a weight table for a given PC
* @param weightTable The weight table to search
* @param tableIndex Index to use for the table
* @param pc PC to match against
* @return Found weight or 0 if not found
*/
int
BTBMGSC::findWeight(const std::vector<int16_t> &weightTable, Addr pc,
uint8_t asidHash)
{
auto mask = (1 << weightTableIdxWidth) - 1;
auto pcHash = ((pc >> instShiftAmt) ^ ((pc >> instShiftAmt) >> 2)) & mask;
pcHash = xorAsidHashIntoIndex(pcHash, weightTableIdxWidth, asidHash);
auto &entry = weightTable[pcHash];
return entry;
}
int
BTBMGSC::calculateScaledPercsum(int weight, int percsum)
{
return percsum; // disable weight scaling for test
}
/**
* Find threshold in a threshold table for a given PC
* @param thresholdTable The threshold table to search
* @param tableIndex Index to use for the table
* @param pc PC to match against
* @param defaultValue Default value to return if not found
* @return Found threshold or default value if not found
*/
int
BTBMGSC::findThreshold(const std::vector<int16_t> &thresholdTable, Addr pc,
uint8_t asidHash)
{
auto mask = (1 << thresholdTablelogSize) - 1;
auto pcHash = ((pc >> instShiftAmt) ^ ((pc >> instShiftAmt) >> 2)) & mask;
pcHash = xorAsidHashIntoIndex(pcHash, thresholdTablelogSize, asidHash);
auto &entry = thresholdTable[pcHash];
return entry;
}
/**
* Calculate if weight scale causes prediction difference
* @param total_sum Total weighted sum
* @param scale_percsum Component's scaled percsum
* @param percsum Component's raw percsum
* @return True if weight scale causes prediction to change
*/
bool
BTBMGSC::calculateWeightScaleDiff(int total_sum, int scale_percsum, int percsum)
{
// First check if removing this table's contribution keeps the sum positive (predict taken)
// Then check if doubling this table's contribution keeps the sum positive
// If one is true and the other is false, the table's weight is crucial for prediction
return ((total_sum - scale_percsum) >= 0) != ((total_sum - scale_percsum + 2 * percsum) >= 0);
}
/**
* @brief Generate prediction for a single BTB entry by searching MGSC tables
*
* @param btb_entry The BTB entry to generate prediction for
* @param startPC The starting PC address for calculating indices and tags
* @return TagePrediction containing main and alternative predictions
*/
BTBMGSC::MgscPrediction
BTBMGSC::generateSinglePrediction(const BTBEntry &btb_entry, const Addr &startPC,
const TageInfoForMGSC &tage_info,
ThreadID tid, uint8_t asidHash)
{
DPRINTF(MGSC, "generateSinglePrediction for btbEntry: %#lx, always taken %d\n", btb_entry.pc,
btb_entry.alwaysTaken);
const auto &state = historyState(tid);
// Calculate indices for all tables
for (unsigned int i = 0; i < bwTableNum; ++i) {
bwIndex[i] = getHistIndex(startPC, bwTableIdxWidth - numCtrsPerLineBits,
state.indexBwFoldedHist[i].get(), asidHash);
}
const Addr localHistoryIndex =
getPcIndex(startPC, log2(numEntriesFirstLocalHistories), asidHash);
for (unsigned int i = 0; i < lTableNum; ++i) {
lIndex[i] = getHistIndex(startPC, lTableIdxWidth - numCtrsPerLineBits,
state.indexLFoldedHist[localHistoryIndex][i].get(),
asidHash);
}
// std::string buf;
// boost::to_string(indexLFoldedHist[getPcIndex(startPC, log2(numEntriesFirstLocalHistories))][0].getAsBitset(), buf);
// DPRINTF(MGSC, "startPC: %#lx, local index: %d, local_folded_hist: %s\n", startPC, lIndex[0], buf.c_str());
for (unsigned int i = 0; i < iTableNum; ++i) {
iIndex[i] = getHistIndex(startPC, iTableIdxWidth - numCtrsPerLineBits,
state.indexIFoldedHist[i].get(), asidHash);
}
for (unsigned int i = 0; i < gTableNum; ++i) {
gIndex[i] = getHistIndex(startPC, gTableIdxWidth - numCtrsPerLineBits,
state.indexGFoldedHist[i].get(), asidHash);
}
for (unsigned int i = 0; i < pTableNum; ++i) {
pIndex[i] = getHistIndex(startPC, pTableIdxWidth - numCtrsPerLineBits,
state.indexPFoldedHist[i].get(), asidHash);
}
for (unsigned int i = 0; i < biasTableNum; ++i) {
biasIndex[i] = getBiasIndex(startPC, biasTableIdxWidth - numCtrsPerLineBits, tage_info.tage_main_taken,
tage_info.tage_pred_conf_low, asidHash);
}
int bw_percsum = enableBwTable ? calculatePercsum(bwTable, bwIndex, bwTableNum, btb_entry.pc) : 0;
int bw_weight = findWeight(bwWeightTable, btb_entry.pc, asidHash);
int bw_scaled_percsum = calculateScaledPercsum(bw_weight, bw_percsum);
int l_percsum = enableLTable ? calculatePercsum(lTable, lIndex, lTableNum, btb_entry.pc) : 0;
int l_weight = findWeight(lWeightTable, btb_entry.pc, asidHash);
int l_scaled_percsum = calculateScaledPercsum(l_weight, l_percsum);
int i_percsum = enableITable ? calculatePercsum(iTable, iIndex, iTableNum, btb_entry.pc) : 0;
int i_weight = findWeight(iWeightTable, btb_entry.pc, asidHash);
int i_scaled_percsum = calculateScaledPercsum(i_weight, i_percsum);
int g_percsum = enableGTable ? calculatePercsum(gTable, gIndex, gTableNum, btb_entry.pc) : 0;
int g_weight = findWeight(gWeightTable, btb_entry.pc, asidHash);
int g_scaled_percsum = calculateScaledPercsum(g_weight, g_percsum);
int p_percsum = enablePTable ? calculatePercsum(pTable, pIndex, pTableNum, btb_entry.pc) : 0;
int p_weight = findWeight(pWeightTable, btb_entry.pc, asidHash);
int p_scaled_percsum = calculateScaledPercsum(p_weight, p_percsum);
int bias_percsum = enableBiasTable ? calculatePercsum(biasTable, biasIndex, biasTableNum, btb_entry.pc) : 0;
int bias_weight = findWeight(biasWeightTable, btb_entry.pc, asidHash);
int bias_scaled_percsum = calculateScaledPercsum(bias_weight, bias_percsum);
// Calculate total sum of all weighted percsums
int total_sum = bw_scaled_percsum + l_scaled_percsum + i_scaled_percsum + g_scaled_percsum + p_scaled_percsum +
bias_scaled_percsum;
// Find thresholds
// pc-indexed threshold table (only if enabled)
int p_update_thres =
enablePCThreshold ? findThreshold(pUpdateThreshold, btb_entry.pc, asidHash) : 0;
int total_thres = (updateThreshold / 8) + p_update_thres;
// Threshold is used as a confidence gate; avoid negative values which
// effectively disable the gate (abs(sum) > negative is almost always true).
total_thres = std::max(total_thres, 0);
bool use_sc_pred = forceUseSC; // Force use SC if configured
if (!use_sc_pred) {
if (tage_info.tage_pred_conf_high) {
if (abs(total_sum) > total_thres / 2) {
use_sc_pred = true;
}
} else if (tage_info.tage_pred_conf_mid) {
if (abs(total_sum) > total_thres / 4) {
use_sc_pred = true;
}
} else if (tage_info.tage_pred_conf_low) {
if (abs(total_sum) > total_thres / 8) {
use_sc_pred = true;
}
}
}
// Final prediction, total_sum >= 0 means taken if use_sc_pred
bool taken = use_sc_pred ? (total_sum >= 0) : tage_info.tage_pred_taken;
// DPRINTF(MGSC, "global tag_index: %d, global_percsum: %d, total_sum: %d\n", gIndex[0], g_percsum, total_sum);
// DPRINTF(MGSC, "local tag_index: %d, local_percsum: %d, total_sum: %d\n", lIndex[0], l_percsum, total_sum);
// DPRINTF(MGSC, "path tag_index: %d, path_percsum: %d, total_sum: %d\n", pIndex[0], p_percsum, total_sum);
// Calculate weight scale differences
bool bw_weight_scale_diff = calculateWeightScaleDiff(total_sum, bw_scaled_percsum, bw_percsum);
bool l_weight_scale_diff = calculateWeightScaleDiff(total_sum, l_scaled_percsum, l_percsum);
bool i_weight_scale_diff = calculateWeightScaleDiff(total_sum, i_scaled_percsum, i_percsum);
bool g_weight_scale_diff = calculateWeightScaleDiff(total_sum, g_scaled_percsum, g_percsum);
bool p_weight_scale_diff = calculateWeightScaleDiff(total_sum, p_scaled_percsum, p_percsum);
bool bias_weight_scale_diff = calculateWeightScaleDiff(total_sum, bias_scaled_percsum, bias_percsum);
DPRINTF(MGSC, "sc predict %#lx taken %d\n", btb_entry.pc, taken);
return MgscPrediction(btb_entry.pc, total_sum, use_sc_pred, taken, tage_info.tage_pred_taken,
tage_info.tage_pred_conf_high, tage_info.tage_pred_conf_mid, tage_info.tage_pred_conf_low,
total_thres, bwIndex, lIndex, iIndex, gIndex, pIndex, biasIndex, bw_weight_scale_diff,
l_weight_scale_diff, i_weight_scale_diff, g_weight_scale_diff, p_weight_scale_diff,
bias_weight_scale_diff, bw_percsum, l_percsum, i_percsum, g_percsum, p_percsum, bias_percsum);
}
/**
* @brief Look up predictions in MGSC tables for a stream of instructions
*
* @param startPC The starting PC address for the instruction stream
* @param btbEntries Vector of BTB entries to make predictions for
* @return Map of branch PC addresses to their predicted outcomes
*/
void
BTBMGSC::lookupHelper(const Addr &startPC, const std::vector<BTBEntry> &btbEntries,
const std::unordered_map<Addr, TageInfoForMGSC> &tageInfoForMgscs,
CondTakens &results, ThreadID tid, uint8_t asidHash)
{
DPRINTF(MGSC, "lookupHelper startAddr: %#lx\n", startPC);
// Process each BTB entry to make predictions
for (auto &btb_entry : btbEntries) {
// Only predict for valid conditional branches
if (btb_entry.isCond && btb_entry.valid) {
auto tage_info = tageInfoForMgscs.find(btb_entry.pc);
panic_if(tage_info == tageInfoForMgscs.end() && !allowMissingTageInfo,
"MGSC missing TAGE info for conditional branch pc %#lx "
"startPC %#lx tid %u asidHash %#x",
btb_entry.pc, startPC, static_cast<unsigned>(tid),
static_cast<unsigned>(asidHash));
const TageInfoForMGSC missing_tage_info;
const auto &info =
tage_info != tageInfoForMgscs.end() ? tage_info->second : missing_tage_info;
auto pred = generateSinglePrediction(btb_entry, startPC, info, tid, asidHash);
threadMeta[tid]->preds[btb_entry.pc] = pred;
results.push_back({btb_entry.pc, pred.taken || btb_entry.alwaysTaken});
}
}
}
/**
* @brief Makes predictions for a stream of instructions using TAGE predictor
*
* This function is called during the prediction stage and:
* 1. Uses lookupHelper to get predictions for all BTB entries
* 2. Stores predictions in the stage prediction structure
* 3. Handles multiple prediction stages with different delays
*
* @param stream_start Starting PC of the instruction stream
* @param history Current branch history
* @param stagePreds Vector of predictions for different pipeline stages
*/
void
BTBMGSC::putPCHistory(Addr stream_start, const boost::dynamic_bitset<> &history,
std::vector<FullBTBPrediction> &stagePreds)
{
const ThreadID tid = predictorTid(stagePreds);
const auto &state = historyState(tid);
const uint8_t asidHash = stagePreds.empty() ? 0 : stagePreds.front().asidHash;
DPRINTF(MGSC, "putPCHistory startAddr: %#lx\n", stream_start);
// IMPORTANT: when this function is called,
// btb entries should already be in stagePreds
// get prediction and save it
if (!isEnabled()) {
return; // Just return if MGSC is disabled
}
// Clear old prediction metadata and save current history state
threadMeta[tid] = std::make_shared<MgscMeta>();
threadMeta[tid]->indexBwFoldedHist = state.indexBwFoldedHist;
threadMeta[tid]->indexLFoldedHist = state.indexLFoldedHist;
threadMeta[tid]->indexIFoldedHist = state.indexIFoldedHist;
threadMeta[tid]->indexGFoldedHist = state.indexGFoldedHist;
threadMeta[tid]->indexPFoldedHist = state.indexPFoldedHist;
for (int s = getDelay(); s < stagePreds.size(); s++) {
// TODO: only lookup once for one btb entry in different stages
auto &stage_pred = stagePreds[s];
stage_pred.condTakens.clear();
lookupHelper(stream_start, stage_pred.btbEntries,
stage_pred.tageInfoForMgscs, stage_pred.condTakens, tid,
asidHash);
}
}
std::shared_ptr<void>
BTBMGSC::getPredictionMeta(ThreadID tid)
{
if (tid >= threadMeta.size()) {
return nullptr;
}
return threadMeta[tid];
}
/**
* @brief Prepare BTB entries for update by filtering and processing
*
* @param stream The fetch stream containing update information
* @return Vector of BTB entries that need to be updated
*/
std::vector<BTBEntry>
BTBMGSC::prepareUpdateEntries(const FetchTarget &stream)
{
auto all_entries = stream.updateBTBEntries;
// Filter out non-conditional and always-taken branches
auto remove_it = std::remove_if(all_entries.begin(), all_entries.end(),
[](const BTBEntry &e) { return !e.isCond && !e.alwaysTaken; });
all_entries.erase(remove_it, all_entries.end());
// Handle potential new BTB entry
auto &potential_new_entry = stream.updateNewBTBEntry;
if (!stream.updateIsOldEntry && potential_new_entry.isCond && !potential_new_entry.alwaysTaken) {
all_entries.push_back(potential_new_entry);
}
return all_entries;
}
/**
* Update a prediction table and allocate new entry if needed
*
* This function handles the main perceptron tables (bwTable, lTable, iTable, gTable, pTable, biasTable)
* which store counter values that contribute to the final prediction. These tables:
* - Are organized as [numTables][tableIndices][numWays]
* - Store signed counters (-32 to 31) representing branch bias
* - Are updated for each branch outcome
* - Start with 0 for taken branches and -1 for not-taken branches when newly allocated
*
* @param table The table to update (one of the six main prediction tables)
* @param tableIndices Indices for each component of the table, derived from history hashing
* @param numTables Number of tables in this category (e.g., bwnb, lnb, etc.)
* @param pc PC to match against for finding the right entry
* @param actual_taken Actual branch outcome (true=taken, false=not taken)
*/
void
BTBMGSC::updatePredTable(std::vector<std::vector<std::vector<int16_t>>> &table,
const std::vector<unsigned> &tableIndices, unsigned numTables, Addr pc, bool actual_taken)
{
for (unsigned int i = 0; i < numTables; ++i) {
auto [idx1, idx2] = posHash(pc, tableIndices[i]);
auto &entry = table[i][idx1][idx2];
updateCounter(actual_taken, scCountersWidth, entry);
}
}
/**
* Update a weight table and allocate new entry if needed
*
* This function handles the weight tables (bwWeightTable, lWeightTable, etc.) which
* determine the relative importance of each predictor type. These tables:
* - Are organized as [tableIndex][numWays]
* - Store weights that scale the importance of each predictor component
* - Are only updated when the weight could have affected the outcome (weight_scale_diff)
* - Are initialized to 0 when newly allocated
* - Allow adaptive tuning of the prediction mechanism
*
* @param weightTable The weight table to update
* @param tableIndex Index to use for the table (typically derived from PC)
* @param pc PC to match against for finding the right entry
* @param weight_scale_diff Whether weight scaling affects prediction outcome
* @param percsum_matches_actual Whether the raw percsum correctly predicted the outcome
*/
void
BTBMGSC::updateWeightTable(std::vector<int16_t> &weightTable, Addr tableIndex, Addr pc, bool weight_scale_diff,
bool percsum_matches_actual)
{
auto mask = (1 << weightTableIdxWidth) - 1;
auto pcHash = ((pc >> instShiftAmt) ^ ((pc >> instShiftAmt) >> 2)) & mask;
auto &entry = weightTable[pcHash];
// Only update if weight scale could affect prediction
if (weight_scale_diff) {
// Increase weight if percsum was correct, decrease if incorrect
updateCounter(percsum_matches_actual, extraWeightsWidth, entry);
}
}
/**
* Update a threshold table and allocate new entry if needed
*
* This function handles threshold tables (pUpdateThreshold) which determine
* when to use statistical correction over TAGE. These tables:
* - Are organized as [tableIndex][numWays]
* - Store unsigned threshold values
* - Are only updated when there's a disagreement between TAGE and SC predictions
* - Control the confidence level required to override TAGE prediction
* - Are initialized to a default value when newly allocated
*
* @param tableIndex Index to use for the table (typically derived from PC)
* @param pc PC to match against for finding the right entry
* @param update_condition Whether to update the counter (typically when TAGE and SC disagree)
* @param update_direction Direction to update (true=increment, false=decrement)
*/
void
BTBMGSC::updatePCThresholdTable(Addr pc, uint8_t asidHash, bool update_direction)
{
auto mask = (1 << thresholdTablelogSize) - 1;
auto pcHash = ((pc >> instShiftAmt) ^ ((pc >> instShiftAmt) >> 2)) & mask;
pcHash = xorAsidHashIntoIndex(pcHash, thresholdTablelogSize, asidHash);
auto &entry = pUpdateThreshold[pcHash];
updateCounter(update_direction, pUpdateThresholdWidth, entry);
}
/**
* Update the global threshold table and allocate new entry if needed
*
* This function handles the global threshold table (updateThreshold) which is
* structured differently than other threshold tables:
* - It's a one-dimensional array of entries
* - It stores a global threshold value that applies across many branches
* - It's updated when TAGE and SC predictions disagree
*
* @param pc PC to match against for finding the right entry
* @param update_condition Whether to update the counter (typically when TAGE and SC disagree)
* @param update_direction Direction to update (true=increment, false=decrement)
*/
void
BTBMGSC::updateGlobalThreshold(Addr pc, bool update_direction)
{
updateCounter(update_direction, updateThresholdWidth, updateThreshold);
// Keep global threshold non-negative; negative thresholds make SC gating
// degenerate and can cause overuse of SC.
if (updateThreshold < 0) {
updateThreshold = 0;
}
}
void
BTBMGSC::recordPredictionStats(const MgscPrediction &pred, bool actual_taken, bool sc_pred_taken,
bool tage_pred_taken)
{
auto tage_conf_high = pred.tage_conf_high;
auto tage_conf_mid = pred.tage_conf_mid;
auto tage_conf_low = pred.tage_conf_low;
// SC vs TAGE outcomes
if (pred.use_mgsc) {
mgscStats.scUsed++;
if (sc_pred_taken == actual_taken && tage_pred_taken != actual_taken) {
mgscStats.scCorrectTageWrong++;
} else if (sc_pred_taken != actual_taken && tage_pred_taken == actual_taken) {
mgscStats.scWrongTageCorrect++;
} else if (sc_pred_taken == actual_taken && tage_pred_taken == actual_taken) {
mgscStats.scCorrectTageCorrect++;
} else if (sc_pred_taken != actual_taken && tage_pred_taken != actual_taken) {
mgscStats.scWrongTageWrong++;
}
} else {
mgscStats.scNotUsed++; // sc confidence is low
}
// Record raw percsum correctness and weight criticality for each table
auto recordPercsum = [&](int percsum, auto &correct, auto &wrong) {
if ((percsum >= 0) == actual_taken) {
correct++;
} else {
wrong++;
}
};
if (pred.bw_weight_scale_diff) {
mgscStats.bwWeightScaleDiff++;
}
recordPercsum(pred.bw_percsum, mgscStats.bwPercsumCorrect, mgscStats.bwPercsumWrong);
if (pred.l_weight_scale_diff) {
mgscStats.lWeightScaleDiff++;
}
recordPercsum(pred.l_percsum, mgscStats.lPercsumCorrect, mgscStats.lPercsumWrong);
if (pred.i_weight_scale_diff) {
mgscStats.iWeightScaleDiff++;
}
recordPercsum(pred.i_percsum, mgscStats.iPercsumCorrect, mgscStats.iPercsumWrong);
if (pred.g_weight_scale_diff) {
mgscStats.gWeightScaleDiff++;
}
recordPercsum(pred.g_percsum, mgscStats.gPercsumCorrect, mgscStats.gPercsumWrong);
if (pred.p_weight_scale_diff) {
mgscStats.pWeightScaleDiff++;
}
recordPercsum(pred.p_percsum, mgscStats.pPercsumCorrect, mgscStats.pPercsumWrong);
if (pred.bias_weight_scale_diff) {
mgscStats.biasWeightScaleDiff++;
}
recordPercsum(pred.bias_percsum, mgscStats.biasPercsumCorrect, mgscStats.biasPercsumWrong);
// SC usage under TAGE confidence buckets
auto recordConfOutcome = [&](bool conf_high, bool conf_mid, bool conf_low, bool use, bool correct) {
if (conf_high) {
if (use) {
correct ? mgscStats.scHighUseCorrect++ : mgscStats.scHighUseWrong++;
} else {
mgscStats.scHighBypass++;
}
} else if (conf_mid) {
if (use) {
correct ? mgscStats.scMidUseCorrect++ : mgscStats.scMidUseWrong++;
} else {
mgscStats.scMidBypass++;
}
} else if (conf_low) {
if (use) {
correct ? mgscStats.scLowUseCorrect++ : mgscStats.scLowUseWrong++;
} else {
mgscStats.scLowBypass++;
}
}
};
recordConfOutcome(tage_conf_high, tage_conf_mid, tage_conf_low, pred.use_mgsc, sc_pred_taken == actual_taken);
}
/**
* @brief Update predictor for a single entry and allocate new entries if needed
*
* This function updates the MGSC predictor state based on the actual branch outcome
* and allocates new entries in various tables if they don't already exist.
*
* @param entry The BTB entry being updated
* @param actual_taken The actual outcome of the branch
* @param pred The prediction made for this entry
* @param stream The fetch stream containing update information
*/
void
BTBMGSC::updateSinglePredictor(const BTBEntry &entry, bool actual_taken, const MgscPrediction &pred,
const FetchTarget &stream)
{
// Extract prediction information
auto total_sum = pred.total_sum;
auto use_mgsc = pred.use_mgsc;
auto total_thres = pred.total_thres;
auto sc_pred_taken = total_sum >= 0;
auto tage_pred_taken = pred.taken_before_sc; // tage predictions
recordPredictionStats(pred, actual_taken, sc_pred_taken, tage_pred_taken);
#ifndef UNIT_TEST
// Write trace record
if (enableDB && (focusBranchPC == 0 || entry.pc == focusBranchPC)) {
auto effective_gate = pred.tage_conf_high ? (total_thres / 2)
: (pred.tage_conf_mid ? (total_thres / 4) : (total_thres / 8));
auto margin = std::abs(total_sum) - effective_gate;
auto foldIndexSig = [](const std::vector<unsigned> &indices) -> uint64_t {
uint64_t sig = 0xcbf29ce484222325ULL;
for (auto idx : indices) {
sig ^= static_cast<uint64_t>(idx) + 0x9e3779b97f4a7c15ULL + (sig << 6) + (sig >> 2);
}
return sig;
};
MgscTrace t;
t.set(entry.pc,
stream.startPC, getOffset(entry.pc),
tage_pred_taken, pred.tage_conf_high, pred.tage_conf_mid, pred.tage_conf_low,
pred.bw_percsum, pred.l_percsum, pred.i_percsum,
pred.g_percsum, pred.p_percsum, pred.bias_percsum,
total_sum, total_thres, effective_gate, margin,
foldIndexSig(pred.bwIndex), foldIndexSig(pred.lIndex), foldIndexSig(pred.iIndex),
foldIndexSig(pred.gIndex), foldIndexSig(pred.pIndex), foldIndexSig(pred.biasIndex),
use_mgsc, sc_pred_taken,
actual_taken);
mgscMissTrace->write_record(t);
}
#endif
// Only update tables if prediction was wrong or confidence was low
if (sc_pred_taken != actual_taken || abs(total_sum) < (total_thres / 2)) {
// get weight table index from startPC
Addr weightTableIdx = getPcIndex(stream.startPC, weightTableIdxWidth,
stream.asidHash);
bool threshold_inc = (sc_pred_taken != actual_taken);
if (threshold_inc) {
mgscStats.pcThresholdInc++;
mgscStats.globalThresholdInc++;
} else {
mgscStats.pcThresholdDec++;
mgscStats.globalThresholdDec++;
}
// Update BW tables
updatePredTable(bwTable, pred.bwIndex, bwTableNum, entry.pc, actual_taken);
updateWeightTable(bwWeightTable, weightTableIdx, entry.pc, pred.bw_weight_scale_diff,
(pred.bw_percsum >= 0) == actual_taken);
// Update L tables
updatePredTable(lTable, pred.lIndex, lTableNum, entry.pc, actual_taken);
updateWeightTable(lWeightTable, weightTableIdx, entry.pc, pred.l_weight_scale_diff,
(pred.l_percsum >= 0) == actual_taken);
// Update I tables
updatePredTable(iTable, pred.iIndex, iTableNum, entry.pc, actual_taken);
updateWeightTable(iWeightTable, weightTableIdx, entry.pc, pred.i_weight_scale_diff,
(pred.i_percsum >= 0) == actual_taken);
// Update G tables
updatePredTable(gTable, pred.gIndex, gTableNum, entry.pc, actual_taken);
updateWeightTable(gWeightTable, weightTableIdx, entry.pc, pred.g_weight_scale_diff,
(pred.g_percsum >= 0) == actual_taken);
// Update P tables
updatePredTable(pTable, pred.pIndex, pTableNum, entry.pc, actual_taken);
updateWeightTable(pWeightTable, weightTableIdx, entry.pc, pred.p_weight_scale_diff,
(pred.p_percsum >= 0) == actual_taken);
// Update bias tables
updatePredTable(biasTable, pred.biasIndex, biasTableNum, entry.pc, actual_taken);
updateWeightTable(biasWeightTable, weightTableIdx, entry.pc, pred.bias_weight_scale_diff,
(pred.bias_percsum >= 0) == actual_taken);
// Update PC-indexed threshold table (only if enabled)
if (enablePCThreshold) {
updatePCThresholdTable(entry.pc, stream.asidHash,
sc_pred_taken != actual_taken);
}
// Update global threshold table
updateGlobalThreshold(entry.pc, sc_pred_taken != actual_taken);
}
}
void
BTBMGSC::update(const FetchTarget &stream)
{
if (!isEnabled()) {
return; // No update if disabled
}
Addr startAddr = stream.getRealStartPC();
DPRINTF(MGSC, "update startAddr: %#lx\n", startAddr);
// Prepare BTB entries to update
auto entries_to_update = prepareUpdateEntries(stream);
// Get prediction metadata
auto meta = std::static_pointer_cast<MgscMeta>(stream.predMetas[getComponentIdx()]);
auto &preds = meta->preds;
// Process each BTB entry
for (auto &btb_entry : entries_to_update) {
bool actual_taken = stream.exeTaken && stream.exeBranchInfo == btb_entry;
auto pred_it = preds.find(btb_entry.pc);
if (pred_it == preds.end()) {
continue;
}
// Update predictor state and check if need to allocate new entry
updateSinglePredictor(btb_entry, actual_taken, pred_it->second, stream);
}
DPRINTF(MGSC, "end update\n");
}
// Update counter with saturation (template for all integer types)
template<typename T>
void
BTBMGSC::updateCounter(bool taken, unsigned width, T &counter)
{
static_assert(std::is_integral<T>::value, "Counter type must be integral");
if constexpr (std::is_signed<T>::value) {
T max = static_cast<T>((1LL << (width - 1)) - 1);
T min = static_cast<T>(-(1LL << (width - 1)));
if (taken) {
satIncrement(max, counter);
} else {
satDecrement(min, counter);
}
} else {
T max = static_cast<T>((1LL << width) - 1);
T min = static_cast<T>(0);
if (taken) {
satIncrement(max, counter);
} else {
satDecrement(min, counter);