xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision 57bb43b5f11c3f1e89ac52f232fe73056b35d9bd)
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
17package xiangshan.frontend
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import utils._
24import chisel3.experimental.chiselName
25
26import scala.math.min
27
28trait HasSCParameter extends TageParams {
29}
30
31class SCReq(implicit p: Parameters) extends TageReq
32
33abstract class SCBundle(implicit p: Parameters) extends TageBundle with HasSCParameter {}
34abstract class SCModule(implicit p: Parameters) extends TageModule with HasSCParameter {}
35
36
37class SCMeta(val ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter {
38  val tageTakens = Vec(numBr, Bool())
39  val scUsed = Vec(numBr, Bool())
40  val scPreds = Vec(numBr, Bool())
41  // Suppose ctrbits of all tables are identical
42  val ctrs = Vec(numBr, Vec(ntables, SInt(SCCtrBits.W)))
43}
44
45
46class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
47  val ctrs = Vec(numBr, Vec(2, SInt(ctrBits.W)))
48}
49
50class SCUpdate(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
51  val pc = UInt(VAddrBits.W)
52  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
53  val mask = Vec(numBr, Bool())
54  val oldCtrs = Vec(numBr, SInt(ctrBits.W))
55  val tagePreds = Vec(numBr, Bool())
56  val takens = Vec(numBr, Bool())
57}
58
59class SCTableIO(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
60  val req = Input(Valid(new SCReq))
61  val resp = Output(new SCResp(ctrBits))
62  val update = Input(new SCUpdate(ctrBits))
63}
64
65@chiselName
66class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)(implicit p: Parameters)
67  extends SCModule with HasFoldedHistory {
68  val io = IO(new SCTableIO(ctrBits))
69
70  // val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false))
71  val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false))
72
73  // def getIdx(hist: UInt, pc: UInt) = {
74  //   (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0)
75  // }
76
77
78  val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen))
79
80  def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0)
81
82  def getIdx(pc: UInt, allFh: AllFoldedHistories) = {
83    if (histLen > 0) {
84      val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist
85      // require(idx_fh.getWidth == log2Ceil(nRows))
86      ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows)-1,0)
87    }
88    else {
89      (pc >> instOffsetBits)(log2Ceil(nRows)-1,0)
90    }
91  }
92
93
94  def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond)
95
96  val s0_idx = getIdx(io.req.bits.pc, io.req.bits.folded_hist)
97  val s1_idx = RegEnable(s0_idx, enable=io.req.valid)
98
99  val s1_pc = RegEnable(io.req.bits.pc, io.req.fire())
100  val s1_unhashed_idx = s1_pc >> instOffsetBits
101
102  table.io.r.req.valid := io.req.valid
103  table.io.r.req.bits.setIdx := s0_idx
104
105  val per_br_ctrs_unshuffled = table.io.r.resp.data.sliding(2,2).toSeq.map(VecInit(_))
106  val per_br_ctrs = VecInit((0 until numBr).map(i => Mux1H(
107    UIntToOH(get_phy_br_idx(s1_unhashed_idx, i), numBr),
108    per_br_ctrs_unshuffled
109  )))
110
111  io.resp.ctrs := per_br_ctrs
112
113  val update_wdata = Wire(Vec(numBr, SInt(ctrBits.W))) // correspond to physical bridx
114  val update_wdata_packed = VecInit(update_wdata.map(Seq.fill(2)(_)).reduce(_++_))
115  val updateWayMask = Wire(Vec(2*numBr, Bool())) // correspond to physical bridx
116
117  val update_unhashed_idx = io.update.pc >> instOffsetBits
118  for (pi <- 0 until numBr) {
119    updateWayMask(2*pi)   := Seq.tabulate(numBr)(li =>
120      io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && !io.update.tagePreds(li)
121    ).reduce(_||_)
122    updateWayMask(2*pi+1) := Seq.tabulate(numBr)(li =>
123      io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U &&  io.update.tagePreds(li)
124    ).reduce(_||_)
125  }
126
127  val update_idx = getIdx(io.update.pc, io.update.folded_hist)
128
129  table.io.w.apply(
130    valid = io.update.mask.reduce(_||_),
131    data = update_wdata_packed,
132    setIdx = update_idx,
133    waymask = updateWayMask.asUInt
134  )
135
136  val wrBypassEntries = 16
137
138  // let it corresponds to logical brIdx
139  val wrbypasses = Seq.fill(numBr)(Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays=2)))
140
141  for (pi <- 0 until numBr) {
142    val br_lidx = get_lgc_br_idx(update_unhashed_idx, pi.U(log2Ceil(numBr).W))
143
144    val wrbypass_io = Mux1H(UIntToOH(br_lidx, numBr), wrbypasses.map(_.io))
145
146    val ctrPos = Mux1H(UIntToOH(br_lidx, numBr), io.update.tagePreds)
147    val bypass_ctr = wrbypass_io.hit_data(ctrPos)
148    val previous_ctr = Mux1H(UIntToOH(br_lidx, numBr), io.update.oldCtrs)
149    val hit_and_valid = wrbypass_io.hit && bypass_ctr.valid
150    val oldCtr = Mux(hit_and_valid, bypass_ctr.bits, previous_ctr)
151    val taken = Mux1H(UIntToOH(br_lidx, numBr), io.update.takens)
152    update_wdata(pi) := ctrUpdate(oldCtr, taken)
153  }
154
155  val per_br_update_wdata_packed = update_wdata_packed.sliding(2,2).map(VecInit(_)).toSeq
156  val per_br_update_way_mask = updateWayMask.sliding(2,2).map(VecInit(_)).toSeq
157  for (li <- 0 until numBr) {
158    val wrbypass = wrbypasses(li)
159    val br_pidx = get_phy_br_idx(update_unhashed_idx, li)
160    wrbypass.io.wen := io.update.mask(li)
161    wrbypass.io.write_idx := update_idx
162    wrbypass.io.write_data := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_wdata_packed)
163    wrbypass.io.write_way_mask.map(_ := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_way_mask))
164  }
165
166
167  val u = io.update
168  XSDebug(io.req.valid,
169    p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
170    p"s0_idx=${s0_idx}\n")
171  XSDebug(RegNext(io.req.valid),
172    p"scTableResp: s1_idx=${s1_idx}," +
173    p"ctr:${io.resp.ctrs}\n")
174  XSDebug(io.update.mask.reduce(_||_),
175    p"update Table: pc:${Hexadecimal(u.pc)}, " +
176    p"tageTakens:${u.tagePreds}, taken:${u.takens}, oldCtr:${u.oldCtrs}\n")
177}
178
179class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
180  val ctr = UInt(ctrBits.W)
181  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
182  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
183  def neutralVal = (1.U << (ctrBits - 1))
184  val thres = UInt(8.W)
185  def initVal = 6.U
186  def minThres = 6.U
187  def maxThres = 31.U
188  def update(cause: Bool): SCThreshold = {
189    val res = Wire(new SCThreshold(this.ctrBits))
190    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
191    val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U,
192                      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U,
193                      this.thres))
194    res.thres := newThres
195    res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
196    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
197    res
198  }
199}
200
201object SCThreshold {
202  def apply(bits: Int)(implicit p: Parameters) = {
203    val t = Wire(new SCThreshold(ctrBits=bits))
204    t.ctr := t.neutralVal
205    t.thres := t.initVal
206    t
207  }
208}
209
210
211trait HasSC extends HasSCParameter with HasPerfEvents { this: Tage =>
212  val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
213  var sc_fh_info = Set[FoldedHistoryInfo]()
214  if (EnableSC) {
215    val scTables = SCTableInfos.map {
216      case (nRows, ctrBits, histLen) => {
217        val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen))
218        val req = t.io.req
219        req.valid := io.s0_fire
220        req.bits.pc := s0_pc
221        req.bits.folded_hist := io.in.bits.folded_hist
222        req.bits.ghist := DontCare
223        if (!EnableSC) {t.io.update := DontCare}
224        t
225      }
226    }
227    sc_fh_info = scTables.map(_.getFoldedHistoryInfo).reduce(_++_).toSet
228
229    val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5)))
230    val useThresholds = VecInit(scThresholds map (_.thres))
231
232    def sign(x: SInt) = x(x.getWidth-1)
233    def pos(x: SInt) = !sign(x)
234    def neg(x: SInt) = sign(x)
235
236    def aboveThreshold(scSum: SInt, tagePvdr: SInt, threshold: UInt): Bool = {
237      val signedThres = threshold.zext
238      val totalSum = scSum +& tagePvdr
239      (scSum >  signedThres - tagePvdr) && pos(totalSum) ||
240      (scSum < -signedThres - tagePvdr) && neg(totalSum)
241    }
242    val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
243
244    val s1_scResps = VecInit(scTables.map(t => t.io.resp))
245
246    val scUpdateMask = WireInit(0.U.asTypeOf(Vec(numBr, Vec(SCNTables, Bool()))))
247    val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
248    val scUpdateTakens = Wire(Vec(TageBanks, Bool()))
249    val scUpdateOldCtrs = Wire(Vec(numBr, Vec(SCNTables, SInt(SCCtrBits.W))))
250    scUpdateTagePreds := DontCare
251    scUpdateTakens := DontCare
252    scUpdateOldCtrs := DontCare
253
254    val updateSCMeta = updateMeta.scMeta.get
255
256    val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree =
257      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
258    val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
259      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
260    val sc_misp_tage_corr, sc_corr_tage_misp =
261      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
262
263    // for sc ctrs
264    def getCentered(ctr: SInt): SInt = Cat(ctr, 1.U(1.W)).asSInt
265    // for tage ctrs, (2*(ctr-4)+1)*8
266    def getPvdrCentered(ctr: UInt): SInt = Cat(ctr ^ (1 << (TageCtrBits-1)).U, 1.U(1.W), 0.U(3.W)).asSInt
267
268    val scMeta = resp_meta.scMeta.get
269    scMeta := DontCare
270    for (w <- 0 until TageBanks) {
271      // do summation in s2
272      val s1_scTableSums = VecInit(
273        (0 to 1) map { i =>
274          ParallelSingedExpandingAdd(s1_scResps map (r => getCentered(r.ctrs(w)(i)))) // TODO: rewrite with wallace tree
275        }
276      )
277      val s2_scTableSums = RegEnable(s1_scTableSums, io.s1_fire)
278      val s2_tagePrvdCtrCentered = getPvdrCentered(RegEnable(s1_providerResps(w).ctr, io.s1_fire))
279      val s2_totalSums = s2_scTableSums.map(_ +& s2_tagePrvdCtrCentered)
280      val s2_sumAboveThresholds = aboveThreshold(s2_scTableSums(w), s2_tagePrvdCtrCentered, useThresholds(w))
281      val s2_scPreds = VecInit(s2_totalSums.map(_ >= 0.S))
282
283      val s2_scResps = VecInit(RegEnable(s1_scResps, io.s1_fire).map(_.ctrs(w)))
284      val s2_scCtrs = VecInit(s2_scResps.map(_(s2_tageTakens(w).asUInt)))
285      val s2_chooseBit = s2_tageTakens(w)
286
287      val s2_pred =
288        Mux(s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit),
289          s2_scPreds(s2_chooseBit),
290          s2_tageTakens(w)
291        )
292
293      scMeta.tageTakens(w) := RegEnable(s2_tageTakens(w), io.s2_fire)
294      scMeta.scUsed(w)     := RegEnable(s2_provideds(w), io.s2_fire)
295      scMeta.scPreds(w)    := RegEnable(s2_scPreds(s2_chooseBit), io.s2_fire)
296      scMeta.ctrs(w)       := RegEnable(s2_scCtrs, io.s2_fire)
297
298      when (s2_provideds(w)) {
299        s2_sc_used(w) := true.B
300        s2_unconf(w) := !s2_sumAboveThresholds(s2_chooseBit)
301        s2_conf(w) := s2_sumAboveThresholds(s2_chooseBit)
302        // Use prediction from Statistical Corrector
303        XSDebug(p"---------tage_bank_${w} provided so that sc used---------\n")
304        when (s2_sumAboveThresholds(s2_chooseBit)) {
305          val pred = s2_scPreds(s2_chooseBit)
306          val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W))
307          s2_agree(w) := s2_tageTakens(w) === pred
308          s2_disagree(w) := s2_tageTakens(w) =/= pred
309          // fit to always-taken condition
310          // io.out.resp.s2.full_pred.br_taken_mask(w) := pred
311          XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n")
312        }
313      }
314
315      when (io.ctrl.sc_enable) {
316        io.out.resp.s3.full_pred.br_taken_mask(w) := RegEnable(s2_pred, io.s2_fire)
317      }
318
319      val updateTageMeta = updateMeta
320      when (updateValids(w) && updateSCMeta.scUsed(w)) {
321        val scPred = updateSCMeta.scPreds(w)
322        val tagePred = updateSCMeta.tageTakens(w)
323        val taken = update.full_pred.br_taken_mask(w)
324        val scOldCtrs = updateSCMeta.ctrs(w)
325        val pvdrCtr = updateTageMeta.providerResps(w).ctr
326        val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr)
327        val sumAbs = sum.abs.asUInt
328        val updateThres = updateThresholds(w)
329        val sumAboveThreshold = aboveThreshold(sum, getPvdrCentered(pvdrCtr), updateThres)
330        scUpdateTagePreds(w) := tagePred
331        scUpdateTakens(w) := taken
332        (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c}
333
334        update_sc_used(w) := true.B
335        update_unconf(w) := !sumAboveThreshold
336        update_conf(w) := sumAboveThreshold
337        update_agree(w) := scPred === tagePred
338        update_disagree(w) := scPred =/= tagePred
339        sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
340        sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
341
342        val thres = useThresholds(w)
343        when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) {
344          val newThres = scThresholds(w).update(scPred =/= taken)
345          scThresholds(w) := newThres
346          XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n")
347        }
348
349        when (scPred =/= taken || !sumAboveThreshold) {
350          scUpdateMask(w).foreach(_ := true.B)
351          XSDebug(sum < 0.S,
352            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
353            p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
354          )
355          XSDebug(sum >= 0.S,
356            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
357            p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
358          )
359          XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n")
360          update_on_mispred(w) := scPred =/= taken
361          update_on_unconf(w) := scPred === taken
362        }
363      }
364    }
365
366
367    for (b <- 0 until TageBanks) {
368      for (i <- 0 until SCNTables) {
369        scTables(i).io.update.mask(b) := RegNext(scUpdateMask(b)(i))
370        scTables(i).io.update.tagePreds(b) := RegNext(scUpdateTagePreds(b))
371        scTables(i).io.update.takens(b)    := RegNext(scUpdateTakens(b))
372        scTables(i).io.update.oldCtrs(b)   := RegNext(scUpdateOldCtrs(b)(i))
373        scTables(i).io.update.pc := RegNext(update.pc)
374        scTables(i).io.update.folded_hist := RegNext(updateFHist)
375      }
376    }
377
378    tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf))
379    tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf))
380    tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree))
381    tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree))
382    tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used))
383    XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
384    XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
385    XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
386    XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
387
388  }
389
390  override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info)
391
392  override val perfEvents = Seq(
393    ("tage_tht_hit                  ", PopCount(updateMeta.providers.map(_.valid))),
394    ("sc_update_on_mispred          ", PopCount(update_on_mispred) ),
395    ("sc_update_on_unconf           ", PopCount(update_on_unconf)  ),
396  )
397  generatePerfEvent()
398}
399