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