xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision 30f35717e23156cb95b30a36db530384545b48a4)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15*
16*
17* Acknowledgement
18*
19* This implementation is inspired by several key papers:
20* [1] André Seznec. "[Tage-sc-l branch predictors.](https://inria.hal.science/hal-01086920)" The Journal of
21* Instruction-Level Parallelism (JILP) 4th JILP Workshop on Computer Architecture Competitions (JWAC): Championship
22* Branch Prediction (CBP). 2014.
23* [2] André Seznec. "[Tage-sc-l branch predictors again.](https://inria.hal.science/hal-01354253)" The Journal of
24* Instruction-Level Parallelism (JILP) 5th JILP Workshop on Computer Architecture Competitions (JWAC): Championship
25* Branch Prediction (CBP). 2016.
26***************************************************************************************/
27
28package xiangshan.frontend
29
30import chisel3._
31import chisel3.util._
32import org.chipsalliance.cde.config.Parameters
33import scala.{Tuple2 => &}
34import scala.math.min
35import utility._
36import utility.mbist.MbistPipeline
37import utility.sram.SRAMConflictBehavior
38import utility.sram.SRAMTemplate
39import xiangshan._
40
41trait HasSCParameter extends TageParams {}
42
43class SCReq(implicit p: Parameters) extends TageReq
44
45abstract class SCBundle(implicit p: Parameters) extends TageBundle with HasSCParameter {}
46abstract class SCModule(implicit p: Parameters) extends TageModule with HasSCParameter {}
47
48class SCMeta(val ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter {
49  val scPreds = Vec(numBr, Bool())
50  // Suppose ctrbits of all tables are identical
51  val ctrs = Vec(numBr, Vec(ntables, SInt(SCCtrBits.W)))
52}
53
54class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
55  val ctrs = Vec(numBr, Vec(2, SInt(ctrBits.W)))
56}
57
58class SCUpdate(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
59  val pc        = UInt(VAddrBits.W)
60  val ghist     = UInt(HistoryLength.W)
61  val mask      = Vec(numBr, Bool())
62  val oldCtrs   = Vec(numBr, SInt(ctrBits.W))
63  val tagePreds = Vec(numBr, Bool())
64  val takens    = Vec(numBr, Bool())
65}
66
67class SCTableIO(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
68  val req    = Input(Valid(new SCReq))
69  val resp   = Output(new SCResp(ctrBits))
70  val update = Input(new SCUpdate(ctrBits))
71}
72
73class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)(implicit p: Parameters)
74    extends SCModule with HasFoldedHistory {
75  val io = IO(new SCTableIO(ctrBits))
76
77  // val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false))
78  val table = Module(new SRAMTemplate(
79    SInt(ctrBits.W),
80    set = nRows,
81    way = 2 * TageBanks,
82    shouldReset = true,
83    holdRead = true,
84    singlePort = false,
85    conflictBehavior = SRAMConflictBehavior.BufferWriteLossy,
86    withClockGate = true,
87    hasMbist = hasMbist,
88    hasSramCtl = hasSramCtl
89  ))
90  private val mbistPl = MbistPipeline.PlaceMbistPipeline(1, "MbistPipeSc", hasMbist)
91  // def getIdx(hist: UInt, pc: UInt) = {
92  //   (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0)
93  // }
94
95  val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen))
96
97  def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0)
98
99  def getIdx(pc: UInt, allFh: AllFoldedHistories) =
100    if (histLen > 0) {
101      val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist
102      // require(idx_fh.getWidth == log2Ceil(nRows))
103      ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows) - 1, 0)
104    } else {
105      (pc >> instOffsetBits)(log2Ceil(nRows) - 1, 0)
106    }
107
108  def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond)
109
110  val s0_idx = getIdx(io.req.bits.pc, io.req.bits.folded_hist)
111  val s1_idx = RegEnable(s0_idx, io.req.valid)
112
113  val s1_pc           = RegEnable(io.req.bits.pc, io.req.fire)
114  val s1_unhashed_idx = s1_pc >> instOffsetBits
115
116  table.io.r.req.valid       := io.req.valid
117  table.io.r.req.bits.setIdx := s0_idx
118
119  val per_br_ctrs_unshuffled = table.io.r.resp.data.sliding(2, 2).toSeq.map(VecInit(_))
120  val per_br_ctrs = VecInit((0 until numBr).map(i =>
121    Mux1H(
122      UIntToOH(get_phy_br_idx(s1_unhashed_idx, i), numBr),
123      per_br_ctrs_unshuffled
124    )
125  ))
126
127  io.resp.ctrs := per_br_ctrs
128
129  val update_wdata        = Wire(Vec(numBr, SInt(ctrBits.W))) // correspond to physical bridx
130  val update_wdata_packed = VecInit(update_wdata.map(Seq.fill(2)(_)).reduce(_ ++ _))
131  val updateWayMask       = Wire(Vec(2 * numBr, Bool()))      // correspond to physical bridx
132
133  val update_unhashed_idx = io.update.pc >> instOffsetBits
134  for (pi <- 0 until numBr) {
135    updateWayMask(2 * pi) := Seq.tabulate(numBr)(li =>
136      io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && !io.update.tagePreds(li)
137    ).reduce(_ || _)
138    updateWayMask(2 * pi + 1) := Seq.tabulate(numBr)(li =>
139      io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && io.update.tagePreds(li)
140    ).reduce(_ || _)
141  }
142
143  val update_folded_hist = WireInit(0.U.asTypeOf(new AllFoldedHistories(foldedGHistInfos)))
144  if (histLen > 0) {
145    update_folded_hist.getHistWithInfo(idxFhInfo).folded_hist := compute_folded_ghist(io.update.ghist, log2Ceil(nRows))
146  }
147  val update_idx = getIdx(io.update.pc, update_folded_hist)
148
149  table.io.w.apply(
150    valid = io.update.mask.reduce(_ || _),
151    data = update_wdata_packed,
152    setIdx = update_idx,
153    waymask = updateWayMask.asUInt
154  )
155
156  val wrBypassEntries = 16
157
158  // let it corresponds to logical brIdx
159  val wrbypasses = Seq.fill(numBr)(Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays = 2)))
160
161  for (pi <- 0 until numBr) {
162    val br_lidx = get_lgc_br_idx(update_unhashed_idx, pi.U(log2Ceil(numBr).W))
163
164    val wrbypass_io = Mux1H(UIntToOH(br_lidx, numBr), wrbypasses.map(_.io))
165
166    val ctrPos        = Mux1H(UIntToOH(br_lidx, numBr), io.update.tagePreds)
167    val bypass_ctr    = wrbypass_io.hit_data(ctrPos)
168    val previous_ctr  = Mux1H(UIntToOH(br_lidx, numBr), io.update.oldCtrs)
169    val hit_and_valid = wrbypass_io.hit && bypass_ctr.valid
170    val oldCtr        = Mux(hit_and_valid, bypass_ctr.bits, previous_ctr)
171    val taken         = Mux1H(UIntToOH(br_lidx, numBr), io.update.takens)
172    update_wdata(pi) := ctrUpdate(oldCtr, taken)
173  }
174
175  val per_br_update_wdata_packed = update_wdata_packed.sliding(2, 2).map(VecInit(_)).toSeq
176  val per_br_update_way_mask     = updateWayMask.sliding(2, 2).map(VecInit(_)).toSeq
177  for (li <- 0 until numBr) {
178    val wrbypass = wrbypasses(li)
179    val br_pidx  = get_phy_br_idx(update_unhashed_idx, li)
180    wrbypass.io.wen        := io.update.mask(li)
181    wrbypass.io.write_idx  := update_idx
182    wrbypass.io.write_data := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_wdata_packed)
183    wrbypass.io.write_way_mask.map(_ := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_way_mask))
184  }
185
186  val u = io.update
187  XSDebug(
188    io.req.valid,
189    p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
190      p"s0_idx=${s0_idx}\n"
191  )
192  XSDebug(
193    RegNext(io.req.valid),
194    p"scTableResp: s1_idx=${s1_idx}," +
195      p"ctr:${io.resp.ctrs}\n"
196  )
197  XSDebug(
198    io.update.mask.reduce(_ || _),
199    p"update Table: pc:${Hexadecimal(u.pc)}, " +
200      p"tageTakens:${u.tagePreds}, taken:${u.takens}, oldCtr:${u.oldCtrs}\n"
201  )
202}
203
204class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
205  val ctr = UInt(ctrBits.W)
206  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
207  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
208  def neutralVal = (1 << (ctrBits - 1)).U
209  val thres      = UInt(8.W)
210  def initVal    = 6.U
211  def minThres   = 6.U
212  def maxThres   = 31.U
213  def update(cause: Bool): SCThreshold = {
214    val res    = Wire(new SCThreshold(this.ctrBits))
215    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
216    val newThres = Mux(
217      res.satPos(newCtr) && this.thres <= maxThres,
218      this.thres + 2.U,
219      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U, this.thres)
220    )
221    res.thres := newThres
222    res.ctr   := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
223    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
224    res
225  }
226}
227
228object SCThreshold {
229  def apply(bits: Int)(implicit p: Parameters) = {
230    val t = Wire(new SCThreshold(ctrBits = bits))
231    t.ctr   := t.neutralVal
232    t.thres := t.initVal
233    t
234  }
235}
236
237trait HasSC extends HasSCParameter with HasPerfEvents { this: Tage =>
238  val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
239  var sc_fh_info                          = Set[FoldedHistoryInfo]()
240  if (EnableSC) {
241    val scTables = SCTableInfos.map {
242      case (nRows, ctrBits, histLen) => {
243        val t   = Module(new SCTable(nRows / TageBanks, ctrBits, histLen))
244        val req = t.io.req
245        req.valid            := io.s0_fire(3)
246        req.bits.pc          := s0_pc_dup(3)
247        req.bits.folded_hist := io.in.bits.folded_hist(3)
248        req.bits.ghist       := DontCare
249        if (!EnableSC) { t.io.update := DontCare }
250        t
251      }
252    }
253    sc_fh_info = scTables.map(_.getFoldedHistoryInfo).reduce(_ ++ _).toSet
254
255    val scThresholds  = List.fill(TageBanks)(RegInit(SCThreshold(5)))
256    val useThresholds = VecInit(scThresholds map (_.thres))
257
258    def sign(x: SInt) = x(x.getWidth - 1)
259    def pos(x:  SInt) = !sign(x)
260    def neg(x:  SInt) = sign(x)
261
262    def aboveThreshold(scSum: SInt, tagePvdr: SInt, threshold: UInt): Bool = {
263      val signedThres = threshold.zext
264      val totalSum    = scSum +& tagePvdr
265      (scSum > signedThres - tagePvdr) && pos(totalSum) ||
266      (scSum < -signedThres - tagePvdr) && neg(totalSum)
267    }
268    val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
269
270    val s1_scResps = VecInit(scTables.map(t => t.io.resp))
271
272    val scUpdateMask      = WireInit(0.U.asTypeOf(Vec(numBr, Vec(SCNTables, Bool()))))
273    val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
274    val scUpdateTakens    = Wire(Vec(TageBanks, Bool()))
275    val scUpdateOldCtrs   = Wire(Vec(numBr, Vec(SCNTables, SInt(SCCtrBits.W))))
276    scUpdateTagePreds := DontCare
277    scUpdateTakens    := DontCare
278    scUpdateOldCtrs   := DontCare
279
280    val updateSCMeta = updateMeta.scMeta.get
281
282    val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree =
283      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
284    val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
285      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
286    val sc_misp_tage_corr, sc_corr_tage_misp =
287      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
288
289    // for sc ctrs
290    def getCentered(ctr: SInt): SInt = Cat(ctr, 1.U(1.W)).asSInt
291    // for tage ctrs, (2*(ctr-4)+1)*8
292    def getPvdrCentered(ctr: UInt): SInt = Cat(ctr ^ (1 << (TageCtrBits - 1)).U, 1.U(1.W), 0.U(3.W)).asSInt
293
294    val scMeta = resp_meta.scMeta.get
295    scMeta := DontCare
296    for (w <- 0 until TageBanks) {
297      // do summation in s2
298      val s1_scTableSums = VecInit(
299        (0 to 1) map { i =>
300          ParallelSingedExpandingAdd(s1_scResps map (r => getCentered(r.ctrs(w)(i)))) // TODO: rewrite with wallace tree
301        }
302      )
303      val s2_scTableSums         = RegEnable(s1_scTableSums, io.s1_fire(3))
304      val s2_tagePrvdCtrCentered = getPvdrCentered(RegEnable(s1_providerResps(w).ctr, io.s1_fire(3)))
305      val s2_totalSums           = s2_scTableSums.map(_ +& s2_tagePrvdCtrCentered)
306      val s2_sumAboveThresholds =
307        VecInit((0 to 1).map(i => aboveThreshold(s2_scTableSums(i), s2_tagePrvdCtrCentered, useThresholds(w))))
308      val s2_scPreds = VecInit(s2_totalSums.map(_ >= 0.S))
309
310      val s2_scResps   = VecInit(RegEnable(s1_scResps, io.s1_fire(3)).map(_.ctrs(w)))
311      val s2_scCtrs    = VecInit(s2_scResps.map(_(s2_tageTakens_dup(3)(w).asUInt)))
312      val s2_chooseBit = s2_tageTakens_dup(3)(w)
313
314      val s2_pred =
315        Mux(s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit), s2_scPreds(s2_chooseBit), s2_tageTakens_dup(3)(w))
316
317      val s3_disagree = RegEnable(s2_disagree, io.s2_fire(3))
318      io.out.last_stage_spec_info.sc_disagree.map(_ := s3_disagree)
319
320      scMeta.scPreds(w) := RegEnable(s2_scPreds(s2_chooseBit), io.s2_fire(3))
321      scMeta.ctrs(w)    := RegEnable(s2_scCtrs, io.s2_fire(3))
322
323      val pred     = s2_scPreds(s2_chooseBit)
324      val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W))
325      when(s2_provideds(w)) {
326        s2_sc_used(w) := true.B
327        s2_unconf(w)  := !s2_sumAboveThresholds(s2_chooseBit)
328        s2_conf(w)    := s2_sumAboveThresholds(s2_chooseBit)
329        // Use prediction from Statistical Corrector
330        when(s2_sumAboveThresholds(s2_chooseBit)) {
331          s2_agree(w)    := s2_tageTakens_dup(3)(w) === pred
332          s2_disagree(w) := s2_tageTakens_dup(3)(w) =/= pred
333          // fit to always-taken condition
334          // io.out.s2.full_pred.br_taken_mask(w) := pred
335        }
336      }
337      XSDebug(s2_provideds(w), p"---------tage_bank_${w} provided so that sc used---------\n")
338      XSDebug(
339        s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit),
340        p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n"
341      )
342
343      val s3_pred_dup   = io.s2_fire.map(f => RegEnable(s2_pred, f))
344      val sc_enable_dup = dup(RegNext(io.ctrl.sc_enable))
345      for (
346        sc_enable & fp & s3_pred <-
347          sc_enable_dup zip io.out.s3.full_pred zip s3_pred_dup
348      ) {
349        when(sc_enable) {
350          fp.br_taken_mask(w) := s3_pred
351        }
352      }
353
354      val updateTageMeta    = updateMeta
355      val scPred            = updateSCMeta.scPreds(w)
356      val tagePred          = updateTageMeta.takens(w)
357      val taken             = update.br_taken_mask(w)
358      val scOldCtrs         = updateSCMeta.ctrs(w)
359      val pvdrCtr           = updateTageMeta.providerResps(w).ctr
360      val tableSum          = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered))
361      val totalSumAbs       = (tableSum +& getPvdrCentered(pvdrCtr)).abs.asUInt
362      val updateThres       = updateThresholds(w)
363      val sumAboveThreshold = aboveThreshold(tableSum, getPvdrCentered(pvdrCtr), updateThres)
364      val thres             = useThresholds(w)
365      val newThres          = scThresholds(w).update(scPred =/= taken)
366      when(updateValids(w) && updateTageMeta.providers(w).valid) {
367        scUpdateTagePreds(w) := tagePred
368        scUpdateTakens(w)    := taken
369        (scUpdateOldCtrs(w) zip scOldCtrs).foreach { case (t, c) => t := c }
370
371        update_sc_used(w)    := true.B
372        update_unconf(w)     := !sumAboveThreshold
373        update_conf(w)       := sumAboveThreshold
374        update_agree(w)      := scPred === tagePred
375        update_disagree(w)   := scPred =/= tagePred
376        sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
377        sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
378
379        when(scPred =/= tagePred && totalSumAbs >= thres - 4.U && totalSumAbs <= thres - 2.U) {
380          scThresholds(w) := newThres
381        }
382
383        when(scPred =/= taken || !sumAboveThreshold) {
384          scUpdateMask(w).foreach(_ := true.B)
385          update_on_mispred(w) := scPred =/= taken
386          update_on_unconf(w)  := scPred === taken
387        }
388      }
389      XSDebug(
390        updateValids(w) && updateTageMeta.providers(w).valid &&
391          scPred =/= tagePred && totalSumAbs >= thres - 4.U && totalSumAbs <= thres - 2.U,
392        p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n"
393      )
394      XSDebug(
395        updateValids(w) && updateTageMeta.providers(w).valid &&
396          (scPred =/= taken || !sumAboveThreshold) &&
397          tableSum < 0.S,
398        p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
399          p"scSum(-${tableSum.abs}), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
400      )
401      XSDebug(
402        updateValids(w) && updateTageMeta.providers(w).valid &&
403          (scPred =/= taken || !sumAboveThreshold) &&
404          tableSum >= 0.S,
405        p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
406          p"scSum(+${tableSum.abs}), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
407      )
408      XSDebug(
409        updateValids(w) && updateTageMeta.providers(w).valid &&
410          (scPred =/= taken || !sumAboveThreshold),
411        p"bank(${w}), update: sc: ${updateSCMeta}\n"
412      )
413    }
414
415    val realWens = scUpdateMask.transpose.map(v => v.reduce(_ | _))
416    for (b <- 0 until TageBanks) {
417      for (i <- 0 until SCNTables) {
418        val realWen = realWens(i)
419        scTables(i).io.update.mask(b)      := RegNext(scUpdateMask(b)(i))
420        scTables(i).io.update.tagePreds(b) := RegEnable(scUpdateTagePreds(b), realWen)
421        scTables(i).io.update.takens(b)    := RegEnable(scUpdateTakens(b), realWen)
422        scTables(i).io.update.oldCtrs(b)   := RegEnable(scUpdateOldCtrs(b)(i), realWen)
423        scTables(i).io.update.pc           := RegEnable(update_pc, realWen)
424        scTables(i).io.update.ghist        := RegEnable(update.ghist, realWen)
425      }
426    }
427
428    tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf))
429    tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf))
430    tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree))
431    tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree))
432    tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used))
433    XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
434    XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
435    XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
436    XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
437
438  }
439
440  override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info)
441
442  override val perfEvents = Seq(
443    ("tage_tht_hit                  ", PopCount(updateMeta.providers.map(_.valid))),
444    ("sc_update_on_mispred          ", PopCount(update_on_mispred)),
445    ("sc_update_on_unconf           ", PopCount(update_on_unconf))
446  )
447  generatePerfEvent()
448}
449