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