xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision 5c5bd416ce761d956348a8e2fbbf268922371d8b)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import xiangshan._
6import utils._
7import chisel3.experimental.chiselName
8
9import scala.math.min
10
11trait HasSCParameter extends HasTageParameter {
12  val SCHistLens = 0 :: TableInfo.map{ case (_,h,_) => h}.toList
13  val SCNTables = 6
14  val SCCtrBits = 6
15  val SCNRows = 1024
16  val SCTableInfo = Seq.fill(SCNTables)((SCNRows, SCCtrBits)) zip SCHistLens map {case ((n, cb), h) => (n, cb, h)}
17}
18
19class SCReq extends TageReq
20
21abstract class SCBundle extends TageBundle with HasSCParameter {}
22abstract class SCModule extends TageModule with HasSCParameter {}
23
24class SCResp(val ctrBits: Int = 6) extends SCBundle {
25  val ctr = Vec(2, SInt(ctrBits.W))
26}
27
28class SCUpdate(val ctrBits: Int = 6) extends SCBundle {
29  val pc = UInt(VAddrBits.W)
30  val hist = UInt(HistoryLength.W)
31  val mask = Vec(TageBanks, Bool())
32  val oldCtrs = Vec(TageBanks, SInt(ctrBits.W))
33  val tagePreds = Vec(TageBanks, Bool())
34  val takens = Vec(TageBanks, Bool())
35}
36
37class SCTableIO(val ctrBits: Int = 6) extends SCBundle {
38  val req = Input(Valid(new SCReq))
39  val resp = Output(Vec(TageBanks, new SCResp(ctrBits)))
40  val update = Input(new SCUpdate(ctrBits))
41}
42
43@chiselName
44class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)
45  extends SCModule with HasFoldedHistory {
46  val io = IO(new SCTableIO(ctrBits))
47
48  val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false))
49
50  def getIdx(hist: UInt, pc: UInt) = {
51    (compute_folded_hist(hist, log2Ceil(nRows)) ^ (pc >> (instOffsetBits+log2Ceil(TageBanks))))(log2Ceil(nRows)-1,0)
52  }
53
54  def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond)
55
56  val if2_idx = getIdx(io.req.bits.hist, io.req.bits.pc)
57  val if3_idx = RegEnable(if2_idx, enable=io.req.valid)
58
59  val table_r =
60    VecInit((0 until TageBanks).map(b => VecInit((0 to 1).map(i => table.io.r.resp.data(b*2+i)))))
61
62
63  val if2_mask = io.req.bits.mask
64  val if3_mask = RegEnable(if2_mask, enable=io.req.valid)
65
66  val update_idx = getIdx(io.update.hist, io.update.pc)
67  val update_wdatas =
68    VecInit((0 until TageBanks).map(w =>
69      ctrUpdate(io.update.oldCtrs(w), io.update.takens(w))))
70
71  table.io.r.req.valid := io.req.valid
72  table.io.r.req.bits.setIdx := if2_idx
73
74  val updateWayMask =
75    VecInit((0 until TageBanks).map(b =>
76      VecInit((0 to 1).map(i =>
77        (io.update.mask(b) && i.U === io.update.tagePreds(b).asUInt))))).asUInt
78
79  table.io.w.apply(
80    valid = io.update.mask.asUInt.orR,
81    data = VecInit((0 until TageBanks*2).map(i => update_wdatas(i/2))),
82    setIdx = update_idx,
83    waymask = updateWayMask
84  )
85
86  (0 until TageBanks).map(b => {
87    io.resp(b).ctr := table_r(b)
88  })
89
90  val wrBypassEntries = 4
91
92  val wrbypass_idxs = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, UInt(log2Ceil(nRows).W))))
93  val wrbypass_ctrs = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, Vec(2*TageBanks, SInt(ctrBits.W)))))
94  val wrbypass_ctr_valids = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, Vec(2*TageBanks, Bool()))))
95  val wrbypass_enq_idx = RegInit(0.U(log2Ceil(wrBypassEntries).W))
96
97  when (reset.asBool) {
98    wrbypass_ctr_valids := 0.U.asTypeOf(Vec(wrBypassEntries, Vec(2*TageBanks, Bool())))
99  }
100
101  val wrbypass_hits = VecInit((0 until wrBypassEntries) map (i => wrbypass_idxs(i) === update_idx))
102  val wrbypass_hit = wrbypass_hits.asUInt.orR
103  val wrbypass_hit_idx = ParallelPriorityEncoder(wrbypass_hits)
104
105  for (w <- 0 until TageBanks) {
106    val ctrPos = (w << 1).U | io.update.tagePreds(w).asUInt
107    val altPos = (w << 1).U | ~io.update.tagePreds(w).asUInt
108    val bypass_ctr = wrbypass_ctrs(wrbypass_hit_idx)(ctrPos)
109    val hit_and_valid = wrbypass_hit && wrbypass_ctr_valids(wrbypass_hit_idx)(ctrPos)
110    val oldCtr = Mux(hit_and_valid, wrbypass_ctrs(wrbypass_hit_idx)(ctrPos), io.update.oldCtrs(w))
111    update_wdatas(w) := ctrUpdate(oldCtr, io.update.takens(w))
112
113    when (io.update.mask.reduce(_||_)) {
114      when (wrbypass_hit) {
115        when (io.update.mask(w)) {
116          wrbypass_ctrs(wrbypass_hit_idx)(ctrPos) := update_wdatas(w)
117          wrbypass_ctr_valids(wrbypass_hit_idx)(ctrPos) := true.B
118        }
119      }.otherwise {
120        // reset valid bit first
121        wrbypass_ctr_valids(wrbypass_enq_idx)(ctrPos) := false.B
122        wrbypass_ctr_valids(wrbypass_enq_idx)(altPos) := false.B
123        when (io.update.mask(w)) {
124          wrbypass_ctr_valids(wrbypass_enq_idx)(ctrPos) := true.B
125          wrbypass_ctrs(wrbypass_enq_idx)(w) := update_wdatas(w)
126        }
127      }
128    }
129  }
130
131  when (io.update.mask.reduce(_||_) && !wrbypass_hit) {
132    wrbypass_idxs(wrbypass_enq_idx) := update_idx
133    wrbypass_enq_idx := (wrbypass_enq_idx + 1.U)(log2Ceil(wrBypassEntries)-1,0)
134  }
135
136
137  if (BPUDebug && debug) {
138    val u = io.update
139    XSDebug(io.req.valid,
140      p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
141      p"if2_idx=${if2_idx}, hist=${Hexadecimal(io.req.bits.hist)}, " +
142      p"if2_mask=${Binary(if2_mask)}\n")
143    for (i <- 0 until TageBanks) {
144      XSDebug(RegNext(io.req.valid),
145        p"scTableResp[${i.U}]: if3_idx=${if3_idx}," +
146        p"ctr:${io.resp(i).ctr}, if3_mask=${Binary(if3_mask)}\n")
147      XSDebug(io.update.mask(i),
148        p"update Table: pc:${Hexadecimal(u.pc)}, hist:${Hexadecimal(u.hist)}, " +
149        p"bank:${i}, tageTaken:${u.tagePreds(i)}, taken:${u.takens(i)}, oldCtr:${u.oldCtrs(i)}\n")
150      val ctrPos = (i << 1).U | io.update.tagePreds(i).asUInt
151      val hitCtr = wrbypass_ctrs(wrbypass_hit_idx)(ctrPos)
152      XSDebug(wrbypass_hit && wrbypass_ctr_valids(wrbypass_hit_idx)(ctrPos) && io.update.mask(i),
153        p"bank $i wrbypass hit wridx:$wrbypass_hit_idx, idx:$update_idx, ctr:$hitCtr" +
154        p"taken:${io.update.takens(i)} newCtr:${update_wdatas(i)}\n")
155    }
156  }
157
158}
159
160class SCThreshold(val ctrBits: Int = 6) extends SCBundle {
161  val ctr = UInt(ctrBits.W)
162  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
163  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
164  def neutralVal = (1.U << (ctrBits - 1))
165  val thres = UInt(8.W)
166  def initVal = 6.U
167  def minThres = 6.U
168  def maxThres = 31.U
169  def update(cause: Bool): SCThreshold = {
170    val res = Wire(new SCThreshold(this.ctrBits))
171    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
172    val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U,
173                      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U,
174                      this.thres))
175    res.thres := newThres
176    res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
177    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
178    res
179  }
180}
181
182object SCThreshold {
183  def apply(bits: Int) = {
184    val t = Wire(new SCThreshold(ctrBits=bits))
185    t.ctr := t.neutralVal
186    t.thres := t.initVal
187    t
188  }
189}
190
191
192trait HasSC extends HasSCParameter { this: Tage =>
193  val scTables = SCTableInfo.map {
194    case (nRows, ctrBits, histLen) => {
195      val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen))
196      val req = t.io.req
197      req.valid := io.pc.valid
198      req.bits.pc := io.pc.bits
199      req.bits.hist := io.hist
200      req.bits.mask := io.inMask
201      if (!EnableSC) {t.io.update := DontCare}
202      t
203    }
204  }
205
206  val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5)))
207  val useThresholds = VecInit(scThresholds map (_.thres))
208  val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
209
210  val if3_scResps = VecInit(scTables.map(t => t.io.resp))
211
212  val scUpdateMask = WireInit(0.U.asTypeOf(Vec(SCNTables, Vec(TageBanks, Bool()))))
213  val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
214  val scUpdateTakens = Wire(Vec(TageBanks, Bool()))
215  val scUpdateOldCtrs = Wire(Vec(TageBanks, Vec(SCNTables, SInt(SCCtrBits.W))))
216  scUpdateTagePreds := DontCare
217  scUpdateTakens := DontCare
218  scUpdateOldCtrs := DontCare
219
220  val updateSCMetas = VecInit(u.metas.map(_.tageMeta.scMeta))
221
222  val if4_sc_used, if4_conf, if4_unconf, if4_agree, if4_disagree =
223    0.U.asTypeOf(Vec(TageBanks, Bool()))
224  val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
225    0.U.asTypeOf(Vec(TageBanks, Bool()))
226  val update_on_mispred, update_on_unconf, sc_misp_tage_corr, sc_corr_tage_misp =
227    0.U.asTypeOf(Vec(TageBanks, Bool()))
228
229  // for sc ctrs
230  def getCentered(ctr: SInt): SInt = (ctr << 1).asSInt + 1.S
231  // for tage ctrs
232  def getPvdrCentered(ctr: UInt): SInt = ((((ctr.zext -& 4.S) << 1).asSInt + 1.S) << 3).asSInt
233
234  for (w <- 0 until TageBanks) {
235    val scMeta = io.meta(w).scMeta
236    scMeta := DontCare
237    // do summation in if3
238    val if3_scTableSums = VecInit(
239      (0 to 1) map { i =>
240        ParallelSingedExpandingAdd(if3_scResps map (r => getCentered(r(w).ctr(i)))) // TODO: rewrite with wallace tree
241      }
242    )
243
244    val providerCtr = if3_providerCtrs(w)
245    val if3_pvdrCtrCentered = getPvdrCentered(providerCtr)
246    val if3_totalSums = VecInit(if3_scTableSums.map(_  +& if3_pvdrCtrCentered))
247    val if3_sumAbs = VecInit(if3_totalSums.map(_.abs.asUInt))
248    val if3_sumBelowThresholds = VecInit(if3_sumAbs map (_ <= useThresholds(w)))
249    val if3_scPreds = VecInit(if3_totalSums.map (_ >= 0.S))
250
251    val if4_sumBelowThresholds = RegEnable(if3_sumBelowThresholds, s3_fire)
252    val if4_scPreds = RegEnable(if3_scPreds, s3_fire)
253    val if4_sumAbs = RegEnable(if3_sumAbs, s3_fire)
254
255    val if4_scCtrs = RegEnable(VecInit(if3_scResps.map(r => r(w).ctr(if3_tageTakens(w).asUInt))), s3_fire)
256    val if4_chooseBit = if4_tageTakens(w)
257    scMeta.tageTaken := if4_tageTakens(w)
258    scMeta.scUsed := if4_provideds(w)
259    scMeta.scPred := if4_scPreds(if4_chooseBit)
260    scMeta.ctrs   := if4_scCtrs
261
262    when (if4_provideds(w)) {
263      if4_sc_used(w) := true.B
264      if4_unconf(w) := if4_sumBelowThresholds(if4_chooseBit)
265      if4_conf(w) := !if4_sumBelowThresholds(if4_chooseBit)
266      // Use prediction from Statistical Corrector
267      XSDebug(p"---------tage${w} provided so that sc used---------\n")
268      XSDebug(p"scCtrs:$if4_scCtrs, prdrCtr:${if4_providerCtrs(w)}, sumAbs:$if4_sumAbs, tageTaken:${if4_chooseBit}\n")
269      when (!if4_sumBelowThresholds(if4_chooseBit)) {
270        when (ctrl.sc_enable) {
271          val pred = if4_scPreds(if4_chooseBit)
272          val debug_pc = Cat(packetIdx(debug_pc_s3), w.U, 0.U(instOffsetBits.W))
273          XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n")
274          if4_agree(w) := if4_tageTakens(w) === pred
275          if4_disagree(w) := if4_tageTakens(w) =/= pred
276          io.resp.takens(w) := pred
277        }
278      }
279    }
280
281    val updateSCMeta = updateSCMetas(w)
282    val updateTageMeta = updateMetas(w)
283    when (updateValids(w) && updateSCMeta.scUsed.asBool) {
284      val scPred = updateSCMeta.scPred
285      val tagePred = updateSCMeta.tageTaken
286      val taken = u.takens(w)
287      val scOldCtrs = updateSCMeta.ctrs
288      val pvdrCtr = updateTageMeta.providerCtr
289      val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr)
290      val sumAbs = sum.abs.asUInt
291      scUpdateTagePreds(w) := tagePred
292      scUpdateTakens(w) := taken
293      (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c}
294
295      update_sc_used(w) := true.B
296      update_unconf(w) := sumAbs < useThresholds(w)
297      update_conf(w) := sumAbs >= useThresholds(w)
298      update_agree(w) := scPred === tagePred
299      update_disagree(w) := scPred =/= tagePred
300      sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
301      sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
302
303      val thres = useThresholds(w)
304      when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) {
305        val newThres = scThresholds(w).update(scPred =/= taken)
306        scThresholds(w) := newThres
307        XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n")
308      }
309
310      val updateThres = updateThresholds(w)
311      when (scPred =/= taken || sumAbs < updateThres) {
312        scUpdateMask.foreach(t => t(w) := true.B)
313        XSDebug(sum < 0.S,
314        p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
315        p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateTageMisPreds(w)})\n"
316        )
317        XSDebug(sum >= 0.S,
318        p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
319        p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateTageMisPreds(w)})\n"
320        )
321        XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n")
322        update_on_mispred(w) := scPred =/= taken
323        update_on_unconf(w) := scPred === taken
324      }
325    }
326  }
327
328  tage_perf("sc_conf", PopCount(if4_conf), PopCount(update_conf))
329  tage_perf("sc_unconf", PopCount(if4_unconf), PopCount(update_unconf))
330  tage_perf("sc_agree", PopCount(if4_agree), PopCount(update_agree))
331  tage_perf("sc_disagree", PopCount(if4_disagree), PopCount(update_disagree))
332  tage_perf("sc_used", PopCount(if4_sc_used), PopCount(update_sc_used))
333  XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
334  XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
335  XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
336  XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
337
338  for (i <- 0 until SCNTables) {
339    scTables(i).io.update.mask := RegNext(scUpdateMask(i))
340    scTables(i).io.update.tagePreds := RegNext(scUpdateTagePreds)
341    scTables(i).io.update.takens    := RegNext(scUpdateTakens)
342    scTables(i).io.update.oldCtrs   := RegNext(VecInit(scUpdateOldCtrs.map(_(i))))
343    scTables(i).io.update.pc := RegNext(u.ftqPC)
344    scTables(i).io.update.hist := RegNext(updateHist)
345  }
346}
347