xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision dcbc69cb2a7ea07707ede3d8f7c74421ef450202)
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 useSC: Boolean, val ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter {
38  val tageTaken = if (useSC) Bool() else UInt(0.W)
39  val scUsed = if (useSC) Bool() else UInt(0.W)
40  val scPred = if (useSC) Bool() else UInt(0.W)
41  // Suppose ctrbits of all tables are identical
42  val ctrs = if (useSC) Vec(ntables, SInt(SCCtrBits.W)) else Vec(ntables, SInt(0.W))
43}
44
45
46class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
47  val ctr = 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 = Bool()
54  val oldCtr = SInt(ctrBits.W)
55  val tagePred = Bool()
56  val taken = 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, shouldReset=true, holdRead=true, singlePort=false))
72
73  val phistLen = PathHistoryLength
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(log2Ceil(nRows)-1,0)
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  table.io.r.req.valid := io.req.valid
100  table.io.r.req.bits.setIdx := s0_idx
101
102  io.resp.ctr := table.io.r.resp.data
103
104  val update_wdata = Wire(SInt(ctrBits.W))
105  val updateWayMask =
106      VecInit((0 to 1).map(io.update.mask && _.U === io.update.tagePred.asUInt)).asUInt
107
108  val update_idx = getIdx(io.update.pc, io.update.folded_hist)
109
110  table.io.w.apply(
111    valid = io.update.mask,
112    data = VecInit(Seq.fill(2)(update_wdata)),
113    setIdx = update_idx,
114    waymask = updateWayMask
115  )
116
117  val wrBypassEntries = 4
118
119  val wrbypass = Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays=2))
120
121  val ctrPos = io.update.tagePred
122  val altPos = !io.update.tagePred
123  val bypass_ctr = wrbypass.io.hit_data(ctrPos)
124  val hit_and_valid = wrbypass.io.hit && bypass_ctr.valid
125  val oldCtr = Mux(hit_and_valid, bypass_ctr.bits, io.update.oldCtr)
126  update_wdata := ctrUpdate(oldCtr, io.update.taken)
127
128  wrbypass.io.wen := io.update.mask
129  wrbypass.io.write_data.map(_ := update_wdata) // only one of them are used
130  wrbypass.io.write_idx := update_idx
131  wrbypass.io.write_way_mask.map(_ := UIntToOH(ctrPos).asTypeOf(Vec(2, Bool())))
132
133  val u = io.update
134  XSDebug(io.req.valid,
135    p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
136    p"s0_idx=${s0_idx}\n")
137  XSDebug(RegNext(io.req.valid),
138    p"scTableResp: s1_idx=${s1_idx}," +
139    p"ctr:${io.resp.ctr}\n")
140  XSDebug(io.update.mask,
141    p"update Table: pc:${Hexadecimal(u.pc)}, " +
142    p"tageTaken:${u.tagePred}, taken:${u.taken}, oldCtr:${u.oldCtr}\n")
143}
144
145class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
146  val ctr = UInt(ctrBits.W)
147  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
148  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
149  def neutralVal = (1.U << (ctrBits - 1))
150  val thres = UInt(8.W)
151  def initVal = 6.U
152  def minThres = 6.U
153  def maxThres = 31.U
154  def update(cause: Bool): SCThreshold = {
155    val res = Wire(new SCThreshold(this.ctrBits))
156    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
157    val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U,
158                      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U,
159                      this.thres))
160    res.thres := newThres
161    res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
162    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
163    res
164  }
165}
166
167object SCThreshold {
168  def apply(bits: Int)(implicit p: Parameters) = {
169    val t = Wire(new SCThreshold(ctrBits=bits))
170    t.ctr := t.neutralVal
171    t.thres := t.initVal
172    t
173  }
174}
175
176
177trait HasSC extends HasSCParameter { this: Tage =>
178  val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
179  var sc_fh_info = Set[FoldedHistoryInfo]()
180  if (EnableSC) {
181    val bank_scTables = BankSCTableInfos.zipWithIndex.map {
182      case (info, b) =>
183        val tables = info.map {
184          case (nRows, ctrBits, histLen) => {
185            val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen))
186            val req = t.io.req
187            req.valid := io.s0_fire
188            req.bits.pc := s0_pc
189            req.bits.folded_hist := io.in.bits.folded_hist
190            req.bits.phist := DontCare
191            if (!EnableSC) {t.io.update := DontCare}
192            t
193          }
194        }
195        tables
196    }
197    sc_fh_info = bank_scTables.flatMap(_.map(_.getFoldedHistoryInfo).reduce(_++_)).toSet
198
199    val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5)))
200    val useThresholds = VecInit(scThresholds map (_.thres))
201    val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
202
203    val s1_scResps = MixedVecInit(bank_scTables.map(b => VecInit(b.map(t => t.io.resp))))
204
205    val scUpdateMask = WireInit(0.U.asTypeOf(MixedVec(BankSCNTables.map(Vec(_, Bool())))))
206    val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
207    val scUpdateTakens = Wire(Vec(TageBanks, Bool()))
208    val scUpdateOldCtrs = Wire(MixedVec(BankSCNTables.map(Vec(_, SInt(SCCtrBits.W)))))
209    scUpdateTagePreds := DontCare
210    scUpdateTakens := DontCare
211    scUpdateOldCtrs := DontCare
212
213    val updateSCMetas = VecInit(updateMetas.map(_.scMeta))
214
215    val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree =
216      0.U.asTypeOf(Vec(TageBanks, Bool()))
217    val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
218      0.U.asTypeOf(Vec(TageBanks, Bool()))
219    val sc_misp_tage_corr, sc_corr_tage_misp =
220      0.U.asTypeOf(Vec(TageBanks, Bool()))
221
222    // for sc ctrs
223    def getCentered(ctr: SInt): SInt = (ctr << 1).asSInt + 1.S
224    // for tage ctrs
225    def getPvdrCentered(ctr: UInt): SInt = ((((ctr.zext -& 4.S) << 1).asSInt + 1.S) << 3).asSInt
226
227    for (w <- 0 until TageBanks) {
228      val scMeta = resp_meta(w).scMeta
229      scMeta := DontCare
230      // do summation in s2
231      val s1_scTableSums = VecInit(
232        (0 to 1) map { i =>
233          ParallelSingedExpandingAdd(s1_scResps(w) map (r => getCentered(r.ctr(i)))) // TODO: rewrite with wallace tree
234        }
235      )
236
237      val providerCtr = s1_providerCtrs(w)
238      val s1_pvdrCtrCentered = getPvdrCentered(providerCtr)
239      val s1_totalSums = VecInit(s1_scTableSums.map(_  +& s1_pvdrCtrCentered))
240      val s1_sumAbs = VecInit(s1_totalSums.map(_.abs.asUInt))
241      val s1_sumBelowThresholds = VecInit(s1_sumAbs map (_ <= useThresholds(w)))
242      val s1_scPreds = VecInit(s1_totalSums.map (_ >= 0.S))
243
244      val s2_sumBelowThresholds = RegEnable(s1_sumBelowThresholds, io.s1_fire)
245      val s2_scPreds = RegEnable(s1_scPreds, io.s1_fire)
246      val s2_sumAbs = RegEnable(s1_sumAbs, io.s1_fire)
247
248      val s2_scCtrs = RegEnable(VecInit(s1_scResps(w).map(r => r.ctr(s1_tageTakens(w).asUInt))), io.s1_fire)
249      val s2_chooseBit = s2_tageTakens(w)
250      scMeta.tageTaken := s2_tageTakens(w)
251      scMeta.scUsed := s2_provideds(w)
252      scMeta.scPred := s2_scPreds(s2_chooseBit)
253      scMeta.ctrs   := s2_scCtrs
254
255      when (s2_provideds(w)) {
256        s2_sc_used(w) := true.B
257        s2_unconf(w) := s2_sumBelowThresholds(s2_chooseBit)
258        s2_conf(w) := !s2_sumBelowThresholds(s2_chooseBit)
259        // Use prediction from Statistical Corrector
260        XSDebug(p"---------tage_bank_${w} provided so that sc used---------\n")
261        XSDebug(p"scCtrs:$s2_scCtrs, prdrCtr:${s2_providerCtrs(w)}, sumAbs:$s2_sumAbs, tageTaken:${s2_chooseBit}\n")
262        when (!s2_sumBelowThresholds(s2_chooseBit)) {
263          val pred = s2_scPreds(s2_chooseBit)
264          val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W))
265          s2_agree(w) := s2_tageTakens(w) === pred
266          s2_disagree(w) := s2_tageTakens(w) =/= pred
267          // fit to always-taken condition
268          io.out.resp.s2.preds.br_taken_mask(w) := pred
269          XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n")
270        }
271      }
272
273      val updateSCMeta = updateSCMetas(w)
274      val updateTageMeta = updateMetas(w)
275      when (updateValids(w) && updateSCMeta.scUsed.asBool) {
276        val scPred = updateSCMeta.scPred
277        val tagePred = updateSCMeta.tageTaken
278        val taken = update.preds.br_taken_mask(w)
279        val scOldCtrs = updateSCMeta.ctrs
280        val pvdrCtr = updateTageMeta.providerCtr
281        val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr)
282        val sumAbs = sum.abs.asUInt
283        scUpdateTagePreds(w) := tagePred
284        scUpdateTakens(w) := taken
285        (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c}
286
287        update_sc_used(w) := true.B
288        update_unconf(w) := sumAbs < useThresholds(w)
289        update_conf(w) := sumAbs >= useThresholds(w)
290        update_agree(w) := scPred === tagePred
291        update_disagree(w) := scPred =/= tagePred
292        sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
293        sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
294
295        val thres = useThresholds(w)
296        when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) {
297          val newThres = scThresholds(w).update(scPred =/= taken)
298          scThresholds(w) := newThres
299          XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n")
300        }
301
302        val updateThres = updateThresholds(w)
303        when (scPred =/= taken || sumAbs < updateThres) {
304          scUpdateMask(w).foreach(_ := true.B)
305          XSDebug(sum < 0.S,
306            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
307            p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
308          )
309          XSDebug(sum >= 0.S,
310            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
311            p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
312          )
313          XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n")
314          update_on_mispred(w) := scPred =/= taken
315          update_on_unconf(w) := scPred === taken
316        }
317      }
318    }
319
320
321    for (b <- 0 until TageBanks) {
322      for (i <- 0 until BankSCNTables(b)) {
323        bank_scTables(b)(i).io.update.mask := RegNext(scUpdateMask(b)(i))
324        bank_scTables(b)(i).io.update.tagePred := RegNext(scUpdateTagePreds(b))
325        bank_scTables(b)(i).io.update.taken    := RegNext(scUpdateTakens(b))
326        bank_scTables(b)(i).io.update.oldCtr   := RegNext(scUpdateOldCtrs(b)(i))
327        bank_scTables(b)(i).io.update.pc := RegNext(update.pc)
328        bank_scTables(b)(i).io.update.folded_hist := RegNext(updateFHist)
329      }
330    }
331
332    tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf))
333    tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf))
334    tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree))
335    tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree))
336    tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used))
337    XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
338    XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
339    XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
340    XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
341
342  }
343
344  override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info)
345
346
347  val perfinfo = IO(new Bundle(){
348    val perfEvents = Output(new PerfEventsBundle(3))
349  })
350  val perfEvents = Seq(
351    ("tage_tht_hit                  ", updateMetas(1).provider.valid + updateMetas(0).provider.valid),
352    ("sc_update_on_mispred          ", PopCount(update_on_mispred) ),
353    ("sc_update_on_unconf           ", PopCount(update_on_unconf)  ),
354  )
355  for (((perf_out,(perf_name,perf)),i) <- perfinfo.perfEvents.perf_events.zip(perfEvents).zipWithIndex) {
356    perf_out.incr_step := RegNext(perf)
357  }
358}
359