xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision cf7d6b7a1a781c73aeb87de112de2e7fe5ea3b7c)
109c6f1ddSLingrui98/***************************************************************************************
209c6f1ddSLingrui98* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
309c6f1ddSLingrui98* Copyright (c) 2020-2021 Peng Cheng Laboratory
409c6f1ddSLingrui98*
509c6f1ddSLingrui98* XiangShan is licensed under Mulan PSL v2.
609c6f1ddSLingrui98* You can use this software according to the terms and conditions of the Mulan PSL v2.
709c6f1ddSLingrui98* You may obtain a copy of Mulan PSL v2 at:
809c6f1ddSLingrui98*          http://license.coscl.org.cn/MulanPSL2
909c6f1ddSLingrui98*
1009c6f1ddSLingrui98* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
1109c6f1ddSLingrui98* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
1209c6f1ddSLingrui98* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
1309c6f1ddSLingrui98*
1409c6f1ddSLingrui98* See the Mulan PSL v2 for more details.
1509c6f1ddSLingrui98***************************************************************************************/
1609c6f1ddSLingrui98
1709c6f1ddSLingrui98package xiangshan.frontend
1809c6f1ddSLingrui98
1909c6f1ddSLingrui98import chisel3._
2009c6f1ddSLingrui98import chisel3.util._
21*cf7d6b7aSMuziimport org.chipsalliance.cde.config.Parameters
22adc0b8dfSGuokai Chenimport scala.{Tuple2 => &}
23*cf7d6b7aSMuziimport scala.math.min
24*cf7d6b7aSMuziimport utility._
25*cf7d6b7aSMuziimport utils._
26*cf7d6b7aSMuziimport xiangshan._
2709c6f1ddSLingrui98
28*cf7d6b7aSMuzitrait HasSCParameter extends TageParams {}
2909c6f1ddSLingrui98
3009c6f1ddSLingrui98class SCReq(implicit p: Parameters) extends TageReq
3109c6f1ddSLingrui98
3209c6f1ddSLingrui98abstract class SCBundle(implicit p: Parameters) extends TageBundle with HasSCParameter {}
3309c6f1ddSLingrui98abstract class SCModule(implicit p: Parameters) extends TageModule with HasSCParameter {}
3409c6f1ddSLingrui98
3534ed6fbcSLingrui98class SCMeta(val ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter {
3634ed6fbcSLingrui98  val scPreds = Vec(numBr, Bool())
3709c6f1ddSLingrui98  // Suppose ctrbits of all tables are identical
3834ed6fbcSLingrui98  val ctrs = Vec(numBr, Vec(ntables, SInt(SCCtrBits.W)))
3909c6f1ddSLingrui98}
4009c6f1ddSLingrui98
4109c6f1ddSLingrui98class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
4234ed6fbcSLingrui98  val ctrs = Vec(numBr, Vec(2, SInt(ctrBits.W)))
4309c6f1ddSLingrui98}
4409c6f1ddSLingrui98
4509c6f1ddSLingrui98class SCUpdate(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
4609c6f1ddSLingrui98  val pc        = UInt(VAddrBits.W)
47a72b131fSGao-Zeyu  val ghist     = UInt(HistoryLength.W)
4834ed6fbcSLingrui98  val mask      = Vec(numBr, Bool())
4934ed6fbcSLingrui98  val oldCtrs   = Vec(numBr, SInt(ctrBits.W))
5034ed6fbcSLingrui98  val tagePreds = Vec(numBr, Bool())
5134ed6fbcSLingrui98  val takens    = Vec(numBr, Bool())
5209c6f1ddSLingrui98}
5309c6f1ddSLingrui98
5409c6f1ddSLingrui98class SCTableIO(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
5509c6f1ddSLingrui98  val req    = Input(Valid(new SCReq))
5609c6f1ddSLingrui98  val resp   = Output(new SCResp(ctrBits))
5709c6f1ddSLingrui98  val update = Input(new SCUpdate(ctrBits))
5809c6f1ddSLingrui98}
5909c6f1ddSLingrui98
6009c6f1ddSLingrui98class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)(implicit p: Parameters)
6109c6f1ddSLingrui98    extends SCModule with HasFoldedHistory {
6209c6f1ddSLingrui98  val io = IO(new SCTableIO(ctrBits))
6309c6f1ddSLingrui98
6409c6f1ddSLingrui98  // val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false))
65*cf7d6b7aSMuzi  val table = Module(new SRAMTemplate(
66*cf7d6b7aSMuzi    SInt(ctrBits.W),
67*cf7d6b7aSMuzi    set = nRows,
68*cf7d6b7aSMuzi    way = 2 * TageBanks,
69*cf7d6b7aSMuzi    shouldReset = true,
70*cf7d6b7aSMuzi    holdRead = true,
71*cf7d6b7aSMuzi    singlePort = false,
72*cf7d6b7aSMuzi    bypassWrite = true
73*cf7d6b7aSMuzi  ))
7409c6f1ddSLingrui98
75dd6c0695SLingrui98  // def getIdx(hist: UInt, pc: UInt) = {
76dd6c0695SLingrui98  //   (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0)
77dd6c0695SLingrui98  // }
78dd6c0695SLingrui98
79dd6c0695SLingrui98  val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen))
80dd6c0695SLingrui98
81dd6c0695SLingrui98  def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0)
82dd6c0695SLingrui98
83*cf7d6b7aSMuzi  def getIdx(pc: UInt, allFh: AllFoldedHistories) =
84dd6c0695SLingrui98    if (histLen > 0) {
85dd6c0695SLingrui98      val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist
86dd6c0695SLingrui98      // require(idx_fh.getWidth == log2Ceil(nRows))
87dd6c0695SLingrui98      ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows) - 1, 0)
88*cf7d6b7aSMuzi    } else {
8934ed6fbcSLingrui98      (pc >> instOffsetBits)(log2Ceil(nRows) - 1, 0)
90dd6c0695SLingrui98    }
9181d86739SLingrui98
9209c6f1ddSLingrui98  def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond)
9309c6f1ddSLingrui98
94dd6c0695SLingrui98  val s0_idx = getIdx(io.req.bits.pc, io.req.bits.folded_hist)
95005e809bSJiuyang Liu  val s1_idx = RegEnable(s0_idx, io.req.valid)
9609c6f1ddSLingrui98
97935edac4STang Haojin  val s1_pc           = RegEnable(io.req.bits.pc, io.req.fire)
9881d86739SLingrui98  val s1_unhashed_idx = s1_pc >> instOffsetBits
9981d86739SLingrui98
10009c6f1ddSLingrui98  table.io.r.req.valid       := io.req.valid
10109c6f1ddSLingrui98  table.io.r.req.bits.setIdx := s0_idx
10209c6f1ddSLingrui98
10381d86739SLingrui98  val update_wdata        = Wire(Vec(numBr, SInt(ctrBits.W))) // correspond to physical bridx
10434ed6fbcSLingrui98  val update_wdata_packed = VecInit(update_wdata.map(Seq.fill(2)(_)).reduce(_ ++ _))
10581d86739SLingrui98  val updateWayMask       = Wire(Vec(2 * numBr, Bool()))      // correspond to physical bridx
10634ed6fbcSLingrui98
10781d86739SLingrui98  val update_unhashed_idx = io.update.pc >> instOffsetBits
10881d86739SLingrui98  for (pi <- 0 until numBr) {
10981d86739SLingrui98    updateWayMask(2 * pi) := Seq.tabulate(numBr)(li =>
11081d86739SLingrui98      io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && !io.update.tagePreds(li)
11181d86739SLingrui98    ).reduce(_ || _)
11281d86739SLingrui98    updateWayMask(2 * pi + 1) := Seq.tabulate(numBr)(li =>
11381d86739SLingrui98      io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && io.update.tagePreds(li)
11481d86739SLingrui98    ).reduce(_ || _)
11534ed6fbcSLingrui98  }
11609c6f1ddSLingrui98
117a72b131fSGao-Zeyu  val update_folded_hist = WireInit(0.U.asTypeOf(new AllFoldedHistories(foldedGHistInfos)))
118a72b131fSGao-Zeyu  if (histLen > 0) {
119a72b131fSGao-Zeyu    update_folded_hist.getHistWithInfo(idxFhInfo).folded_hist := compute_folded_ghist(io.update.ghist, log2Ceil(nRows))
120a72b131fSGao-Zeyu  }
121a72b131fSGao-Zeyu  val update_idx = getIdx(io.update.pc, update_folded_hist)
12209c6f1ddSLingrui98
123b2564f6cSYuandongliang  // SCTable dual port SRAM reads and writes to the same address processing
124b2564f6cSYuandongliang  val conflict_buffer_valid   = RegInit(false.B)
125b2564f6cSYuandongliang  val conflict_buffer_data    = RegInit(0.U.asTypeOf(update_wdata_packed))
126b2564f6cSYuandongliang  val conflict_buffer_idx     = RegInit(0.U.asTypeOf(update_idx))
127b2564f6cSYuandongliang  val conflict_buffer_waymask = RegInit(0.U.asTypeOf(updateWayMask))
128b2564f6cSYuandongliang
129b2564f6cSYuandongliang  val write_conflict = update_idx === s0_idx && io.update.mask.reduce(_ || _) && io.req.valid
130b2564f6cSYuandongliang  val can_write      = (conflict_buffer_idx =/= s0_idx || !io.req.valid) && conflict_buffer_valid
131b2564f6cSYuandongliang
132b2564f6cSYuandongliang  when(write_conflict) {
133b2564f6cSYuandongliang    conflict_buffer_valid   := true.B
134b2564f6cSYuandongliang    conflict_buffer_data    := update_wdata_packed
135b2564f6cSYuandongliang    conflict_buffer_idx     := update_idx
136b2564f6cSYuandongliang    conflict_buffer_waymask := updateWayMask
137b2564f6cSYuandongliang  }
138b2564f6cSYuandongliang  when(can_write) {
139b2564f6cSYuandongliang    conflict_buffer_valid := false.B
140b2564f6cSYuandongliang  }
141b2564f6cSYuandongliang
142b2564f6cSYuandongliang  // Using buffer data for prediction
143b2564f6cSYuandongliang  val use_conflict_data = conflict_buffer_valid && conflict_buffer_idx === s1_idx
144*cf7d6b7aSMuzi  val conflict_data_bypass = conflict_buffer_data.zip(conflict_buffer_waymask).map { case (data, mask) =>
145*cf7d6b7aSMuzi    Mux(mask, data, 0.U.asTypeOf(data))
146*cf7d6b7aSMuzi  }
147b2564f6cSYuandongliang  val conflict_prediction_data = conflict_data_bypass.sliding(2, 2).toSeq.map(VecInit(_))
148b2564f6cSYuandongliang  val per_br_ctrs_unshuffled   = table.io.r.resp.data.sliding(2, 2).toSeq.map(VecInit(_))
149*cf7d6b7aSMuzi  val per_br_ctrs = VecInit((0 until numBr).map(i =>
150*cf7d6b7aSMuzi    Mux1H(
151b2564f6cSYuandongliang      UIntToOH(get_phy_br_idx(s1_unhashed_idx, i), numBr),
152b2564f6cSYuandongliang      per_br_ctrs_unshuffled
153*cf7d6b7aSMuzi    )
154*cf7d6b7aSMuzi  ))
155*cf7d6b7aSMuzi  val conflict_br_ctrs = VecInit((0 until numBr).map(i =>
156*cf7d6b7aSMuzi    Mux1H(
157b2564f6cSYuandongliang      UIntToOH(get_phy_br_idx(s1_unhashed_idx, i), numBr),
158b2564f6cSYuandongliang      conflict_prediction_data
159*cf7d6b7aSMuzi    )
160*cf7d6b7aSMuzi  ))
161b2564f6cSYuandongliang
162b2564f6cSYuandongliang  io.resp.ctrs := Mux(use_conflict_data, conflict_br_ctrs, per_br_ctrs)
163b2564f6cSYuandongliang
16409c6f1ddSLingrui98  table.io.w.apply(
165b2564f6cSYuandongliang    valid = (io.update.mask.reduce(_ || _) && !write_conflict) || can_write,
166b2564f6cSYuandongliang    data = Mux(can_write, conflict_buffer_data, update_wdata_packed),
167b2564f6cSYuandongliang    setIdx = Mux(can_write, conflict_buffer_idx, update_idx),
168b2564f6cSYuandongliang    waymask = Mux(can_write, conflict_buffer_waymask.asUInt, updateWayMask.asUInt)
16909c6f1ddSLingrui98  )
17009c6f1ddSLingrui98
17112cedb6fSLingrui98  val wrBypassEntries = 16
17209c6f1ddSLingrui98
17381d86739SLingrui98  // let it corresponds to logical brIdx
17412cedb6fSLingrui98  val wrbypasses = Seq.fill(numBr)(Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays = 2)))
17509c6f1ddSLingrui98
17681d86739SLingrui98  for (pi <- 0 until numBr) {
17781d86739SLingrui98    val br_lidx = get_lgc_br_idx(update_unhashed_idx, pi.U(log2Ceil(numBr).W))
17812cedb6fSLingrui98
17981d86739SLingrui98    val wrbypass_io = Mux1H(UIntToOH(br_lidx, numBr), wrbypasses.map(_.io))
18081d86739SLingrui98
18181d86739SLingrui98    val ctrPos        = Mux1H(UIntToOH(br_lidx, numBr), io.update.tagePreds)
18281d86739SLingrui98    val bypass_ctr    = wrbypass_io.hit_data(ctrPos)
18381d86739SLingrui98    val previous_ctr  = Mux1H(UIntToOH(br_lidx, numBr), io.update.oldCtrs)
18481d86739SLingrui98    val hit_and_valid = wrbypass_io.hit && bypass_ctr.valid
18581d86739SLingrui98    val oldCtr        = Mux(hit_and_valid, bypass_ctr.bits, previous_ctr)
18681d86739SLingrui98    val taken         = Mux1H(UIntToOH(br_lidx, numBr), io.update.takens)
18781d86739SLingrui98    update_wdata(pi) := ctrUpdate(oldCtr, taken)
18881d86739SLingrui98  }
18981d86739SLingrui98
19081d86739SLingrui98  val per_br_update_wdata_packed = update_wdata_packed.sliding(2, 2).map(VecInit(_)).toSeq
19181d86739SLingrui98  val per_br_update_way_mask     = updateWayMask.sliding(2, 2).map(VecInit(_)).toSeq
19281d86739SLingrui98  for (li <- 0 until numBr) {
19381d86739SLingrui98    val wrbypass = wrbypasses(li)
19481d86739SLingrui98    val br_pidx  = get_phy_br_idx(update_unhashed_idx, li)
19581d86739SLingrui98    wrbypass.io.wen        := io.update.mask(li)
19612cedb6fSLingrui98    wrbypass.io.write_idx  := update_idx
19781d86739SLingrui98    wrbypass.io.write_data := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_wdata_packed)
19881d86739SLingrui98    wrbypass.io.write_way_mask.map(_ := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_way_mask))
19934ed6fbcSLingrui98  }
20009c6f1ddSLingrui98
20109c6f1ddSLingrui98  val u = io.update
202*cf7d6b7aSMuzi  XSDebug(
203*cf7d6b7aSMuzi    io.req.valid,
20409c6f1ddSLingrui98    p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
205*cf7d6b7aSMuzi      p"s0_idx=${s0_idx}\n"
206*cf7d6b7aSMuzi  )
207*cf7d6b7aSMuzi  XSDebug(
208*cf7d6b7aSMuzi    RegNext(io.req.valid),
20909c6f1ddSLingrui98    p"scTableResp: s1_idx=${s1_idx}," +
210*cf7d6b7aSMuzi      p"ctr:${io.resp.ctrs}\n"
211*cf7d6b7aSMuzi  )
212*cf7d6b7aSMuzi  XSDebug(
213*cf7d6b7aSMuzi    io.update.mask.reduce(_ || _),
214e69b7315SLingrui98    p"update Table: pc:${Hexadecimal(u.pc)}, " +
215*cf7d6b7aSMuzi      p"tageTakens:${u.tagePreds}, taken:${u.takens}, oldCtr:${u.oldCtrs}\n"
216*cf7d6b7aSMuzi  )
21709c6f1ddSLingrui98}
21809c6f1ddSLingrui98
21909c6f1ddSLingrui98class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
22009c6f1ddSLingrui98  val ctr = UInt(ctrBits.W)
22109c6f1ddSLingrui98  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
22209c6f1ddSLingrui98  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
22367ba96b4SYinan Xu  def neutralVal = (1 << (ctrBits - 1)).U
22409c6f1ddSLingrui98  val thres      = UInt(8.W)
22509c6f1ddSLingrui98  def initVal    = 6.U
22609c6f1ddSLingrui98  def minThres   = 6.U
22709c6f1ddSLingrui98  def maxThres   = 31.U
22809c6f1ddSLingrui98  def update(cause: Bool): SCThreshold = {
22909c6f1ddSLingrui98    val res    = Wire(new SCThreshold(this.ctrBits))
23009c6f1ddSLingrui98    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
231*cf7d6b7aSMuzi    val newThres = Mux(
232*cf7d6b7aSMuzi      res.satPos(newCtr) && this.thres <= maxThres,
233*cf7d6b7aSMuzi      this.thres + 2.U,
234*cf7d6b7aSMuzi      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U, this.thres)
235*cf7d6b7aSMuzi    )
23609c6f1ddSLingrui98    res.thres := newThres
23709c6f1ddSLingrui98    res.ctr   := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
23809c6f1ddSLingrui98    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
23909c6f1ddSLingrui98    res
24009c6f1ddSLingrui98  }
24109c6f1ddSLingrui98}
24209c6f1ddSLingrui98
24309c6f1ddSLingrui98object SCThreshold {
24409c6f1ddSLingrui98  def apply(bits: Int)(implicit p: Parameters) = {
24509c6f1ddSLingrui98    val t = Wire(new SCThreshold(ctrBits = bits))
24609c6f1ddSLingrui98    t.ctr   := t.neutralVal
24709c6f1ddSLingrui98    t.thres := t.initVal
24809c6f1ddSLingrui98    t
24909c6f1ddSLingrui98  }
25009c6f1ddSLingrui98}
25109c6f1ddSLingrui98
2521ca0e4f3SYinan Xutrait HasSC extends HasSCParameter with HasPerfEvents { this: Tage =>
253efe3f3bbSSteve Gou  val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
254dd6c0695SLingrui98  var sc_fh_info                          = Set[FoldedHistoryInfo]()
255bf358e08SLingrui98  if (EnableSC) {
25634ed6fbcSLingrui98    val scTables = SCTableInfos.map {
25709c6f1ddSLingrui98      case (nRows, ctrBits, histLen) => {
25809c6f1ddSLingrui98        val t   = Module(new SCTable(nRows / TageBanks, ctrBits, histLen))
25909c6f1ddSLingrui98        val req = t.io.req
260adc0b8dfSGuokai Chen        req.valid            := io.s0_fire(3)
261adc0b8dfSGuokai Chen        req.bits.pc          := s0_pc_dup(3)
262adc0b8dfSGuokai Chen        req.bits.folded_hist := io.in.bits.folded_hist(3)
26386d9c530SLingrui98        req.bits.ghist       := DontCare
26409c6f1ddSLingrui98        if (!EnableSC) { t.io.update := DontCare }
26509c6f1ddSLingrui98        t
26609c6f1ddSLingrui98      }
26709c6f1ddSLingrui98    }
26834ed6fbcSLingrui98    sc_fh_info = scTables.map(_.getFoldedHistoryInfo).reduce(_ ++ _).toSet
26909c6f1ddSLingrui98
27009c6f1ddSLingrui98    val scThresholds  = List.fill(TageBanks)(RegInit(SCThreshold(5)))
27109c6f1ddSLingrui98    val useThresholds = VecInit(scThresholds map (_.thres))
2727e8b966aSLingrui98
273d71e9942SLingrui98    def sign(x: SInt) = x(x.getWidth - 1)
274d71e9942SLingrui98    def pos(x:  SInt) = !sign(x)
275d71e9942SLingrui98    def neg(x:  SInt) = sign(x)
2767e8b966aSLingrui98
2777e8b966aSLingrui98    def aboveThreshold(scSum: SInt, tagePvdr: SInt, threshold: UInt): Bool = {
278d71e9942SLingrui98      val signedThres = threshold.zext
2797e8b966aSLingrui98      val totalSum    = scSum +& tagePvdr
2807e8b966aSLingrui98      (scSum > signedThres - tagePvdr) && pos(totalSum) ||
2817e8b966aSLingrui98      (scSum < -signedThres - tagePvdr) && neg(totalSum)
282d71e9942SLingrui98    }
28309c6f1ddSLingrui98    val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
28409c6f1ddSLingrui98
28534ed6fbcSLingrui98    val s1_scResps = VecInit(scTables.map(t => t.io.resp))
28609c6f1ddSLingrui98
28734ed6fbcSLingrui98    val scUpdateMask      = WireInit(0.U.asTypeOf(Vec(numBr, Vec(SCNTables, Bool()))))
28809c6f1ddSLingrui98    val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
28909c6f1ddSLingrui98    val scUpdateTakens    = Wire(Vec(TageBanks, Bool()))
29034ed6fbcSLingrui98    val scUpdateOldCtrs   = Wire(Vec(numBr, Vec(SCNTables, SInt(SCCtrBits.W))))
29109c6f1ddSLingrui98    scUpdateTagePreds := DontCare
29209c6f1ddSLingrui98    scUpdateTakens    := DontCare
29309c6f1ddSLingrui98    scUpdateOldCtrs   := DontCare
29409c6f1ddSLingrui98
29534ed6fbcSLingrui98    val updateSCMeta = updateMeta.scMeta.get
29609c6f1ddSLingrui98
29709c6f1ddSLingrui98    val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree =
298ff1cd593SLingrui98      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
29909c6f1ddSLingrui98    val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
300ff1cd593SLingrui98      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
301efe3f3bbSSteve Gou    val sc_misp_tage_corr, sc_corr_tage_misp =
302ff1cd593SLingrui98      WireInit(0.U.asTypeOf(Vec(TageBanks, Bool())))
30309c6f1ddSLingrui98
30409c6f1ddSLingrui98    // for sc ctrs
305238c84b9SLingrui98    def getCentered(ctr: SInt): SInt = Cat(ctr, 1.U(1.W)).asSInt
306238c84b9SLingrui98    // for tage ctrs, (2*(ctr-4)+1)*8
307238c84b9SLingrui98    def getPvdrCentered(ctr: UInt): SInt = Cat(ctr ^ (1 << (TageCtrBits - 1)).U, 1.U(1.W), 0.U(3.W)).asSInt
30809c6f1ddSLingrui98
30934ed6fbcSLingrui98    val scMeta = resp_meta.scMeta.get
31009c6f1ddSLingrui98    scMeta := DontCare
31134ed6fbcSLingrui98    for (w <- 0 until TageBanks) {
31209c6f1ddSLingrui98      // do summation in s2
31309c6f1ddSLingrui98      val s1_scTableSums = VecInit(
31409c6f1ddSLingrui98        (0 to 1) map { i =>
31534ed6fbcSLingrui98          ParallelSingedExpandingAdd(s1_scResps map (r => getCentered(r.ctrs(w)(i)))) // TODO: rewrite with wallace tree
31609c6f1ddSLingrui98        }
31709c6f1ddSLingrui98      )
318adc0b8dfSGuokai Chen      val s2_scTableSums         = RegEnable(s1_scTableSums, io.s1_fire(3))
319adc0b8dfSGuokai Chen      val s2_tagePrvdCtrCentered = getPvdrCentered(RegEnable(s1_providerResps(w).ctr, io.s1_fire(3)))
320cb4f77ceSLingrui98      val s2_totalSums           = s2_scTableSums.map(_ +& s2_tagePrvdCtrCentered)
321*cf7d6b7aSMuzi      val s2_sumAboveThresholds =
322*cf7d6b7aSMuzi        VecInit((0 to 1).map(i => aboveThreshold(s2_scTableSums(i), s2_tagePrvdCtrCentered, useThresholds(w))))
323cb4f77ceSLingrui98      val s2_scPreds = VecInit(s2_totalSums.map(_ >= 0.S))
32409c6f1ddSLingrui98
325adc0b8dfSGuokai Chen      val s2_scResps   = VecInit(RegEnable(s1_scResps, io.s1_fire(3)).map(_.ctrs(w)))
326adc0b8dfSGuokai Chen      val s2_scCtrs    = VecInit(s2_scResps.map(_(s2_tageTakens_dup(3)(w).asUInt)))
327adc0b8dfSGuokai Chen      val s2_chooseBit = s2_tageTakens_dup(3)(w)
32809c6f1ddSLingrui98
329cb4f77ceSLingrui98      val s2_pred =
330*cf7d6b7aSMuzi        Mux(s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit), s2_scPreds(s2_chooseBit), s2_tageTakens_dup(3)(w))
331cb4f77ceSLingrui98
332adc0b8dfSGuokai Chen      val s3_disagree = RegEnable(s2_disagree, io.s2_fire(3))
333abdc3a32Sxu_zh      io.out.last_stage_spec_info.sc_disagree.map(_ := s3_disagree)
334d2b20d1aSTang Haojin
335adc0b8dfSGuokai Chen      scMeta.scPreds(w) := RegEnable(s2_scPreds(s2_chooseBit), io.s2_fire(3))
336adc0b8dfSGuokai Chen      scMeta.ctrs(w)    := RegEnable(s2_scCtrs, io.s2_fire(3))
33734ed6fbcSLingrui98
3384813e060SLingrui98      when(s2_provideds(w)) {
33909c6f1ddSLingrui98        s2_sc_used(w) := true.B
340b30c10d6SLingrui98        s2_unconf(w)  := !s2_sumAboveThresholds(s2_chooseBit)
341b30c10d6SLingrui98        s2_conf(w)    := s2_sumAboveThresholds(s2_chooseBit)
34209c6f1ddSLingrui98        // Use prediction from Statistical Corrector
34309c6f1ddSLingrui98        XSDebug(p"---------tage_bank_${w} provided so that sc used---------\n")
344b30c10d6SLingrui98        when(s2_sumAboveThresholds(s2_chooseBit)) {
34509c6f1ddSLingrui98          val pred     = s2_scPreds(s2_chooseBit)
34609c6f1ddSLingrui98          val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W))
347adc0b8dfSGuokai Chen          s2_agree(w)    := s2_tageTakens_dup(3)(w) === pred
348adc0b8dfSGuokai Chen          s2_disagree(w) := s2_tageTakens_dup(3)(w) =/= pred
34909c6f1ddSLingrui98          // fit to always-taken condition
350c2d1ec7dSLingrui98          // io.out.s2.full_pred.br_taken_mask(w) := pred
35109c6f1ddSLingrui98          XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n")
35209c6f1ddSLingrui98        }
35309c6f1ddSLingrui98      }
35409c6f1ddSLingrui98
355adc0b8dfSGuokai Chen      val s3_pred_dup   = io.s2_fire.map(f => RegEnable(s2_pred, f))
356adc0b8dfSGuokai Chen      val sc_enable_dup = dup(RegNext(io.ctrl.sc_enable))
357*cf7d6b7aSMuzi      for (
358*cf7d6b7aSMuzi        sc_enable & fp & s3_pred <-
359*cf7d6b7aSMuzi          sc_enable_dup zip io.out.s3.full_pred zip s3_pred_dup
360*cf7d6b7aSMuzi      ) {
361adc0b8dfSGuokai Chen        when(sc_enable) {
362adc0b8dfSGuokai Chen          fp.br_taken_mask(w) := s3_pred
363adc0b8dfSGuokai Chen        }
3646ee06c7aSSteve Gou      }
365b30c10d6SLingrui98
36634ed6fbcSLingrui98      val updateTageMeta = updateMeta
367deb3a97eSGao-Zeyu      when(updateValids(w) && updateTageMeta.providers(w).valid) {
36834ed6fbcSLingrui98        val scPred            = updateSCMeta.scPreds(w)
369deb3a97eSGao-Zeyu        val tagePred          = updateTageMeta.takens(w)
370803124a6SLingrui98        val taken             = update.br_taken_mask(w)
37134ed6fbcSLingrui98        val scOldCtrs         = updateSCMeta.ctrs(w)
3724813e060SLingrui98        val pvdrCtr           = updateTageMeta.providerResps(w).ctr
373ffa09ba7SEaston Man        val tableSum          = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered))
374ffa09ba7SEaston Man        val totalSumAbs       = (tableSum +& getPvdrCentered(pvdrCtr)).abs.asUInt
375ff1cd593SLingrui98        val updateThres       = updateThresholds(w)
376ffa09ba7SEaston Man        val sumAboveThreshold = aboveThreshold(tableSum, getPvdrCentered(pvdrCtr), updateThres)
37709c6f1ddSLingrui98        scUpdateTagePreds(w) := tagePred
37809c6f1ddSLingrui98        scUpdateTakens(w)    := taken
37909c6f1ddSLingrui98        (scUpdateOldCtrs(w) zip scOldCtrs).foreach { case (t, c) => t := c }
38009c6f1ddSLingrui98
38109c6f1ddSLingrui98        update_sc_used(w)    := true.B
382b30c10d6SLingrui98        update_unconf(w)     := !sumAboveThreshold
383b30c10d6SLingrui98        update_conf(w)       := sumAboveThreshold
38409c6f1ddSLingrui98        update_agree(w)      := scPred === tagePred
38509c6f1ddSLingrui98        update_disagree(w)   := scPred =/= tagePred
38609c6f1ddSLingrui98        sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
38709c6f1ddSLingrui98        sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
38809c6f1ddSLingrui98
38909c6f1ddSLingrui98        val thres = useThresholds(w)
390ffa09ba7SEaston Man        when(scPred =/= tagePred && totalSumAbs >= thres - 4.U && totalSumAbs <= thres - 2.U) {
39109c6f1ddSLingrui98          val newThres = scThresholds(w).update(scPred =/= taken)
39209c6f1ddSLingrui98          scThresholds(w) := newThres
39309c6f1ddSLingrui98          XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n")
39409c6f1ddSLingrui98        }
39509c6f1ddSLingrui98
396b30c10d6SLingrui98        when(scPred =/= taken || !sumAboveThreshold) {
39709c6f1ddSLingrui98          scUpdateMask(w).foreach(_ := true.B)
398*cf7d6b7aSMuzi          XSDebug(
399*cf7d6b7aSMuzi            tableSum < 0.S,
40009c6f1ddSLingrui98            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
401ffa09ba7SEaston Man              p"scSum(-${tableSum.abs}), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
40209c6f1ddSLingrui98          )
403*cf7d6b7aSMuzi          XSDebug(
404*cf7d6b7aSMuzi            tableSum >= 0.S,
40509c6f1ddSLingrui98            p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
406ffa09ba7SEaston Man              p"scSum(+${tableSum.abs}), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n"
40709c6f1ddSLingrui98          )
40809c6f1ddSLingrui98          XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n")
40909c6f1ddSLingrui98          update_on_mispred(w) := scPred =/= taken
41009c6f1ddSLingrui98          update_on_unconf(w)  := scPred === taken
41109c6f1ddSLingrui98        }
41209c6f1ddSLingrui98      }
41309c6f1ddSLingrui98    }
41409c6f1ddSLingrui98
4157af6acb0SEaston Man    val realWens = scUpdateMask.transpose.map(v => v.reduce(_ | _))
41609c6f1ddSLingrui98    for (b <- 0 until TageBanks) {
41734ed6fbcSLingrui98      for (i <- 0 until SCNTables) {
4187af6acb0SEaston Man        val realWen = realWens(i)
41934ed6fbcSLingrui98        scTables(i).io.update.mask(b)      := RegNext(scUpdateMask(b)(i))
4207af6acb0SEaston Man        scTables(i).io.update.tagePreds(b) := RegEnable(scUpdateTagePreds(b), realWen)
4217af6acb0SEaston Man        scTables(i).io.update.takens(b)    := RegEnable(scUpdateTakens(b), realWen)
4227af6acb0SEaston Man        scTables(i).io.update.oldCtrs(b)   := RegEnable(scUpdateOldCtrs(b)(i), realWen)
4237af6acb0SEaston Man        scTables(i).io.update.pc           := RegEnable(update.pc, realWen)
424a72b131fSGao-Zeyu        scTables(i).io.update.ghist        := RegEnable(io.update.bits.ghist, realWen)
42509c6f1ddSLingrui98      }
42609c6f1ddSLingrui98    }
42709c6f1ddSLingrui98
42809c6f1ddSLingrui98    tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf))
42909c6f1ddSLingrui98    tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf))
43009c6f1ddSLingrui98    tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree))
43109c6f1ddSLingrui98    tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree))
43209c6f1ddSLingrui98    tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used))
43309c6f1ddSLingrui98    XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
43409c6f1ddSLingrui98    XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
43509c6f1ddSLingrui98    XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
43609c6f1ddSLingrui98    XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
437cd365d4cSrvcoresjw
438efe3f3bbSSteve Gou  }
439efe3f3bbSSteve Gou
440dd6c0695SLingrui98  override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info)
441dd6c0695SLingrui98
4424813e060SLingrui98  override val perfEvents = Seq(
4434813e060SLingrui98    ("tage_tht_hit                  ", PopCount(updateMeta.providers.map(_.valid))),
444cd365d4cSrvcoresjw    ("sc_update_on_mispred          ", PopCount(update_on_mispred)),
445*cf7d6b7aSMuzi    ("sc_update_on_unconf           ", PopCount(update_on_unconf))
446cd365d4cSrvcoresjw  )
4471ca0e4f3SYinan Xu  generatePerfEvent()
448bf358e08SLingrui98}
449