xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision dd6c0695f1cf59980dc2882dce3874535d6d6e49)
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 hist = UInt(HistoryLength.W)
53  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
54  val mask = Bool()
55  val oldCtr = SInt(ctrBits.W)
56  val tagePred = Bool()
57  val taken = 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, shouldReset=true, holdRead=true, singlePort=false))
73
74  val phistLen = PathHistoryLength
75  // def getIdx(hist: UInt, pc: UInt) = {
76  //   (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0)
77  // }
78
79
80  val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen))
81
82  def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0)
83
84  def getIdx(pc: UInt, allFh: AllFoldedHistories) = {
85    if (histLen > 0) {
86      val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist
87      // require(idx_fh.getWidth == log2Ceil(nRows))
88      ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows)-1,0)
89    }
90    else {
91      pc(log2Ceil(nRows)-1,0)
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, enable=io.req.valid)
99
100  table.io.r.req.valid := io.req.valid
101  table.io.r.req.bits.setIdx := s0_idx
102
103  io.resp.ctr := table.io.r.resp.data
104
105  val update_wdata = Wire(SInt(ctrBits.W))
106  val updateWayMask =
107      VecInit((0 to 1).map(io.update.mask && _.U === io.update.tagePred.asUInt)).asUInt
108
109  val update_idx = getIdx(io.update.pc, io.update.folded_hist)
110
111  table.io.w.apply(
112    valid = io.update.mask,
113    data = VecInit(Seq.fill(2)(update_wdata)),
114    setIdx = update_idx,
115    waymask = updateWayMask
116  )
117
118  val wrBypassEntries = 4
119
120  class SCWrBypass extends XSModule {
121    val io = IO(new Bundle {
122      val wen = Input(Bool())
123      val update_idx  = Input(UInt(log2Ceil(nRows).W))
124      val update_ctrs  = Flipped(ValidIO(SInt(ctrBits.W)))
125      val update_ctrPos = Input(UInt(log2Ceil(2).W))
126      val update_altPos = Input(UInt(log2Ceil(2).W))
127
128      val hit   = Output(Bool())
129      val ctrs  = Vec(2, ValidIO(SInt(ctrBits.W)))
130    })
131
132    val idxes       = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, UInt(log2Ceil(nRows).W))))
133    val ctrs        = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, Vec(2, SInt(ctrBits.W)))))
134    val ctr_valids  = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, Vec(2, Bool()))))
135    val enq_idx     = RegInit(0.U(log2Ceil(wrBypassEntries).W))
136
137    val hits = VecInit((0 until wrBypassEntries).map { i => idxes(i) === io.update_idx })
138
139    val hit = hits.reduce(_||_)
140    val hit_idx = ParallelPriorityEncoder(hits)
141
142    io.hit := hit
143
144    for (i <- 0 until 2) {
145      io.ctrs(i).valid := ctr_valids(hit_idx)(i)
146      io.ctrs(i).bits := ctrs(hit_idx)(i)
147    }
148
149    when (io.wen) {
150      when (hit) {
151        ctrs(hit_idx)(io.update_ctrPos) := io.update_ctrs.bits
152        ctr_valids(hit_idx)(io.update_ctrPos) := io.update_ctrs.valid
153      }.otherwise {
154        ctr_valids(enq_idx)(io.update_altPos) := false.B
155        ctr_valids(enq_idx)(io.update_ctrPos) := io.update_ctrs.valid
156        ctrs(enq_idx)(io.update_ctrPos) := io.update_ctrs.bits
157      }
158    }
159
160    when(io.wen && !hit) {
161      idxes(enq_idx) := io.update_idx
162      enq_idx := (enq_idx + 1.U)(log2Ceil(wrBypassEntries)-1, 0)
163    }
164  }
165
166  val wrbypass = Module(new SCWrBypass)
167
168  val ctrPos = io.update.tagePred
169  val altPos = !io.update.tagePred
170  val bypass_ctr = wrbypass.io.ctrs(ctrPos)
171  val hit_and_valid = wrbypass.io.hit && bypass_ctr.valid
172  val oldCtr = Mux(hit_and_valid, bypass_ctr.bits, io.update.oldCtr)
173  update_wdata := ctrUpdate(oldCtr, io.update.taken)
174
175  wrbypass.io.wen := io.update.mask
176  wrbypass.io.update_ctrs.valid := io.update.mask
177  wrbypass.io.update_ctrs.bits := update_wdata
178  wrbypass.io.update_idx := update_idx
179  wrbypass.io.update_ctrPos := ctrPos
180  wrbypass.io.update_altPos := altPos
181
182  val u = io.update
183  XSDebug(io.req.valid,
184    p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
185    p"s0_idx=${s0_idx}, hist=${Hexadecimal(io.req.bits.hist)}\n")
186  XSDebug(RegNext(io.req.valid),
187    p"scTableResp: s1_idx=${s1_idx}," +
188    p"ctr:${io.resp.ctr}\n")
189  XSDebug(io.update.mask,
190    p"update Table: pc:${Hexadecimal(u.pc)}, hist:${Hexadecimal(u.hist)}, " +
191    p"tageTaken:${u.tagePred}, taken:${u.taken}, oldCtr:${u.oldCtr}\n")
192  val updateCtrPos = io.update.tagePred
193  val hitCtr = wrbypass.io.ctrs(updateCtrPos).bits
194  XSDebug(wrbypass.io.hit && wrbypass.io.ctrs(updateCtrPos).valid && io.update.mask,
195    p"wrbypass hit idx:$update_idx, ctr:$hitCtr, " +
196    p"taken:${io.update.taken} newCtr:${update_wdata}\n")
197
198}
199
200class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
201  val ctr = UInt(ctrBits.W)
202  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
203  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
204  def neutralVal = (1.U << (ctrBits - 1))
205  val thres = UInt(8.W)
206  def initVal = 6.U
207  def minThres = 6.U
208  def maxThres = 31.U
209  def update(cause: Bool): SCThreshold = {
210    val res = Wire(new SCThreshold(this.ctrBits))
211    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
212    val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U,
213                      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U,
214                      this.thres))
215    res.thres := newThres
216    res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
217    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
218    res
219  }
220}
221
222object SCThreshold {
223  def apply(bits: Int)(implicit p: Parameters) = {
224    val t = Wire(new SCThreshold(ctrBits=bits))
225    t.ctr := t.neutralVal
226    t.thres := t.initVal
227    t
228  }
229}
230
231
232trait HasSC extends HasSCParameter { this: Tage =>
233  val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
234  var sc_fh_info = Set[FoldedHistoryInfo]()
235  if (EnableSC) {
236    val bank_scTables = BankSCTableInfos.zipWithIndex.map {
237      case (info, b) =>
238        val tables = info.map {
239          case (nRows, ctrBits, histLen) => {
240            val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen))
241            val req = t.io.req
242            req.valid := io.s0_fire
243            req.bits.pc := s0_pc
244            req.bits.hist := io.in.bits.ghist
245            req.bits.folded_hist := io.in.bits.folded_hist
246            req.bits.phist := DontCare
247            if (!EnableSC) {t.io.update := DontCare}
248            t
249          }
250        }
251        tables
252    }
253    sc_fh_info = bank_scTables.flatMap(_.map(_.getFoldedHistoryInfo).reduce(_++_)).toSet
254
255    val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5)))
256    val useThresholds = VecInit(scThresholds map (_.thres))
257    val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
258
259    val s1_scResps = MixedVecInit(bank_scTables.map(b => VecInit(b.map(t => t.io.resp))))
260
261    val scUpdateMask = WireInit(0.U.asTypeOf(MixedVec(BankSCNTables.map(Vec(_, Bool())))))
262    val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
263    val scUpdateTakens = Wire(Vec(TageBanks, Bool()))
264    val scUpdateOldCtrs = Wire(MixedVec(BankSCNTables.map(Vec(_, SInt(SCCtrBits.W)))))
265    scUpdateTagePreds := DontCare
266    scUpdateTakens := DontCare
267    scUpdateOldCtrs := DontCare
268
269    val updateSCMetas = VecInit(updateMetas.map(_.scMeta))
270
271    val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree =
272      0.U.asTypeOf(Vec(TageBanks, Bool()))
273    val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
274      0.U.asTypeOf(Vec(TageBanks, Bool()))
275    val sc_misp_tage_corr, sc_corr_tage_misp =
276      0.U.asTypeOf(Vec(TageBanks, Bool()))
277
278    // for sc ctrs
279    def getCentered(ctr: SInt): SInt = (ctr << 1).asSInt + 1.S
280    // for tage ctrs
281    def getPvdrCentered(ctr: UInt): SInt = ((((ctr.zext -& 4.S) << 1).asSInt + 1.S) << 3).asSInt
282
283    for (w <- 0 until TageBanks) {
284      val scMeta = resp_meta(w).scMeta
285      scMeta := DontCare
286      // do summation in s2
287      val s1_scTableSums = VecInit(
288        (0 to 1) map { i =>
289          ParallelSingedExpandingAdd(s1_scResps(w) map (r => getCentered(r.ctr(i)))) // TODO: rewrite with wallace tree
290        }
291      )
292
293      val providerCtr = s1_providerCtrs(w)
294      val s1_pvdrCtrCentered = getPvdrCentered(providerCtr)
295      val s1_totalSums = VecInit(s1_scTableSums.map(_  +& s1_pvdrCtrCentered))
296      val s1_sumAbs = VecInit(s1_totalSums.map(_.abs.asUInt))
297      val s1_sumBelowThresholds = VecInit(s1_sumAbs map (_ <= useThresholds(w)))
298      val s1_scPreds = VecInit(s1_totalSums.map (_ >= 0.S))
299
300      val s2_sumBelowThresholds = RegEnable(s1_sumBelowThresholds, io.s1_fire)
301      val s2_scPreds = RegEnable(s1_scPreds, io.s1_fire)
302      val s2_sumAbs = RegEnable(s1_sumAbs, io.s1_fire)
303
304      val s2_scCtrs = RegEnable(VecInit(s1_scResps(w).map(r => r.ctr(s1_tageTakens(w).asUInt))), io.s1_fire)
305      val s2_chooseBit = s2_tageTakens(w)
306      scMeta.tageTaken := s2_tageTakens(w)
307      scMeta.scUsed := s2_provideds(w)
308      scMeta.scPred := s2_scPreds(s2_chooseBit)
309      scMeta.ctrs   := s2_scCtrs
310
311      when (s2_provideds(w)) {
312        s2_sc_used(w) := true.B
313        s2_unconf(w) := s2_sumBelowThresholds(s2_chooseBit)
314        s2_conf(w) := !s2_sumBelowThresholds(s2_chooseBit)
315        // Use prediction from Statistical Corrector
316        XSDebug(p"---------tage_bank_${w} provided so that sc used---------\n")
317        XSDebug(p"scCtrs:$s2_scCtrs, prdrCtr:${s2_providerCtrs(w)}, sumAbs:$s2_sumAbs, tageTaken:${s2_chooseBit}\n")
318        when (!s2_sumBelowThresholds(s2_chooseBit)) {
319          val pred = s2_scPreds(s2_chooseBit)
320          val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W))
321          s2_agree(w) := s2_tageTakens(w) === pred
322          s2_disagree(w) := s2_tageTakens(w) =/= pred
323          // fit to always-taken condition
324          io.out.resp.s2.preds.br_taken_mask(w) := pred
325          XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n")
326        }
327      }
328
329      val updateSCMeta = updateSCMetas(w)
330      val updateTageMeta = updateMetas(w)
331      when (updateValids(w) && updateSCMeta.scUsed.asBool) {
332        val scPred = updateSCMeta.scPred
333        val tagePred = updateSCMeta.tageTaken
334        val taken = update.preds.br_taken_mask(w)
335        val scOldCtrs = updateSCMeta.ctrs
336        val pvdrCtr = updateTageMeta.providerCtr
337        val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr)
338        val sumAbs = sum.abs.asUInt
339        scUpdateTagePreds(w) := tagePred
340        scUpdateTakens(w) := taken
341        (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c}
342
343        update_sc_used(w) := true.B
344        update_unconf(w) := sumAbs < useThresholds(w)
345        update_conf(w) := sumAbs >= useThresholds(w)
346        update_agree(w) := scPred === tagePred
347        update_disagree(w) := scPred =/= tagePred
348        sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
349        sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
350
351        val thres = useThresholds(w)
352        when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) {
353          val newThres = scThresholds(w).update(scPred =/= taken)
354          scThresholds(w) := newThres
355          XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n")
356        }
357
358        val updateThres = updateThresholds(w)
359        when (scPred =/= taken || sumAbs < updateThres) {
360          scUpdateMask(w).foreach(_ := true.B)
361          XSDebug(sum < 0.S,
362            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
363            p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
364          )
365          XSDebug(sum >= 0.S,
366            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
367            p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
368          )
369          XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n")
370          update_on_mispred(w) := scPred =/= taken
371          update_on_unconf(w) := scPred === taken
372        }
373      }
374    }
375
376
377    for (b <- 0 until TageBanks) {
378      for (i <- 0 until BankSCNTables(b)) {
379        bank_scTables(b)(i).io.update.mask := RegNext(scUpdateMask(b)(i))
380        bank_scTables(b)(i).io.update.tagePred := RegNext(scUpdateTagePreds(b))
381        bank_scTables(b)(i).io.update.taken    := RegNext(scUpdateTakens(b))
382        bank_scTables(b)(i).io.update.oldCtr   := RegNext(scUpdateOldCtrs(b)(i))
383        bank_scTables(b)(i).io.update.pc := RegNext(update.pc)
384        bank_scTables(b)(i).io.update.hist := RegNext(updateHist.predHist)
385        bank_scTables(b)(i).io.update.folded_hist := RegNext(updateFHist)
386      }
387    }
388
389    tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf))
390    tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf))
391    tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree))
392    tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree))
393    tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used))
394    XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
395    XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
396    XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
397    XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
398
399  }
400
401  override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info)
402
403
404  val perfinfo = IO(new Bundle(){
405    val perfEvents = Output(new PerfEventsBundle(3))
406  })
407  val perfEvents = Seq(
408    ("tage_tht_hit                  ", updateMetas(1).provider.valid + updateMetas(0).provider.valid),
409    ("sc_update_on_mispred          ", PopCount(update_on_mispred) ),
410    ("sc_update_on_unconf           ", PopCount(update_on_unconf)  ),
411  )
412  for (((perf_out,(perf_name,perf)),i) <- perfinfo.perfEvents.perf_events.zip(perfEvents).zipWithIndex) {
413    perf_out.incr_step := RegNext(perf)
414  }
415}
416