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 ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter { 38 val tageTakens = Vec(numBr, Bool()) 39 val scUsed = Bool() 40 val scPreds = Vec(numBr, Bool()) 41 // Suppose ctrbits of all tables are identical 42 val ctrs = Vec(numBr, Vec(ntables, SInt(SCCtrBits.W))) 43} 44 45 46class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 47 val ctrs = Vec(numBr, 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 = Vec(numBr, Bool()) 54 val oldCtrs = Vec(numBr, SInt(ctrBits.W)) 55 val tagePreds = Vec(numBr, Bool()) 56 val takens = Vec(numBr, 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*TageBanks, shouldReset=true, holdRead=true, singlePort=false)) 72 73 // def getIdx(hist: UInt, pc: UInt) = { 74 // (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0) 75 // } 76 77 78 val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen)) 79 80 def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0) 81 82 def getIdx(pc: UInt, allFh: AllFoldedHistories) = { 83 if (histLen > 0) { 84 val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist 85 // require(idx_fh.getWidth == log2Ceil(nRows)) 86 ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows)-1,0) 87 } 88 else { 89 (pc >> instOffsetBits)(log2Ceil(nRows)-1,0) 90 } 91 } 92 93 def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond) 94 95 val s0_idx = getIdx(io.req.bits.pc, io.req.bits.folded_hist) 96 val s1_idx = RegEnable(s0_idx, enable=io.req.valid) 97 98 table.io.r.req.valid := io.req.valid 99 table.io.r.req.bits.setIdx := s0_idx 100 101 for (i <- 0 until numBr) { 102 io.resp.ctrs(i)(0) := table.io.r.resp.data(2*i) 103 io.resp.ctrs(i)(1) := table.io.r.resp.data(2*i+1) 104 } 105 106 val update_wdata = Wire(Vec(numBr, SInt(ctrBits.W))) 107 val update_wdata_packed = VecInit(update_wdata.map(Seq.fill(2)(_)).reduce(_++_)) 108 val updateWayMask = Wire(Vec(2*numBr, Bool())) 109 110 for (i <- 0 until numBr) { 111 updateWayMask(2*i) := io.update.mask(i) && !io.update.tagePreds(i) 112 updateWayMask(2*i+1) := io.update.mask(i) && io.update.tagePreds(i) 113 } 114 115 val update_idx = getIdx(io.update.pc, io.update.folded_hist) 116 117 table.io.w.apply( 118 valid = io.update.mask.reduce(_||_), 119 data = update_wdata_packed, 120 setIdx = update_idx, 121 waymask = updateWayMask.asUInt 122 ) 123 124 val wrBypassEntries = 4 125 126 val wrbypass = Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays=2*numBr)) 127 128 for (i <- 0 until numBr) { 129 val ctrPos = io.update.tagePreds(i) 130 val altPos = !io.update.tagePreds(i) 131 val bypass_ctr = wrbypass.io.hit_data((i << 1).U | ctrPos) 132 val hit_and_valid = wrbypass.io.hit && bypass_ctr.valid 133 val oldCtr = Mux(hit_and_valid, bypass_ctr.bits, io.update.oldCtrs(i)) 134 update_wdata(i) := ctrUpdate(oldCtr, io.update.takens(i)) 135 } 136 137 wrbypass.io.wen := io.update.mask.reduce(_||_) 138 wrbypass.io.write_data := update_wdata_packed // only one of them are used 139 wrbypass.io.write_idx := update_idx 140 wrbypass.io.write_way_mask.map(_ := updateWayMask) 141 142 val u = io.update 143 XSDebug(io.req.valid, 144 p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " + 145 p"s0_idx=${s0_idx}\n") 146 XSDebug(RegNext(io.req.valid), 147 p"scTableResp: s1_idx=${s1_idx}," + 148 p"ctr:${io.resp.ctrs}\n") 149 XSDebug(io.update.mask.reduce(_||_), 150 p"update Table: pc:${Hexadecimal(u.pc)}, " + 151 p"tageTakens:${u.tagePreds}, taken:${u.takens}, oldCtr:${u.oldCtrs}\n") 152} 153 154class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 155 val ctr = UInt(ctrBits.W) 156 def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U) 157 def satNeg(ctr: UInt = this.ctr) = ctr === 0.U 158 def neutralVal = (1.U << (ctrBits - 1)) 159 val thres = UInt(8.W) 160 def initVal = 6.U 161 def minThres = 6.U 162 def maxThres = 31.U 163 def update(cause: Bool): SCThreshold = { 164 val res = Wire(new SCThreshold(this.ctrBits)) 165 val newCtr = satUpdate(this.ctr, this.ctrBits, cause) 166 val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U, 167 Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U, 168 this.thres)) 169 res.thres := newThres 170 res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr) 171 // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n") 172 res 173 } 174} 175 176object SCThreshold { 177 def apply(bits: Int)(implicit p: Parameters) = { 178 val t = Wire(new SCThreshold(ctrBits=bits)) 179 t.ctr := t.neutralVal 180 t.thres := t.initVal 181 t 182 } 183} 184 185 186trait HasSC extends HasSCParameter with HasPerfEvents { this: Tage => 187 val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool()))) 188 var sc_fh_info = Set[FoldedHistoryInfo]() 189 if (EnableSC) { 190 val scTables = SCTableInfos.map { 191 case (nRows, ctrBits, histLen) => { 192 val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen)) 193 val req = t.io.req 194 req.valid := io.s0_fire 195 req.bits.pc := s0_pc 196 req.bits.folded_hist := io.in.bits.folded_hist 197 req.bits.ghist := DontCare 198 if (!EnableSC) {t.io.update := DontCare} 199 t 200 } 201 } 202 sc_fh_info = scTables.map(_.getFoldedHistoryInfo).reduce(_++_).toSet 203 204 val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5))) 205 val useThresholds = VecInit(scThresholds map (_.thres)) 206 207 def sign(x: SInt) = x(x.getWidth-1) 208 def pos(x: SInt) = !sign(x) 209 def neg(x: SInt) = sign(x) 210 211 def aboveThreshold(scSum: SInt, tagePvdr: SInt, threshold: UInt): Bool = { 212 val signedThres = threshold.zext 213 val totalSum = scSum +& tagePvdr 214 (scSum > signedThres - tagePvdr) && pos(totalSum) || 215 (scSum < -signedThres - tagePvdr) && neg(totalSum) 216 } 217 val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U)) 218 219 val s1_scResps = VecInit(scTables.map(t => t.io.resp)) 220 221 val scUpdateMask = WireInit(0.U.asTypeOf(Vec(numBr, Vec(SCNTables, Bool())))) 222 val scUpdateTagePreds = Wire(Vec(TageBanks, Bool())) 223 val scUpdateTakens = Wire(Vec(TageBanks, Bool())) 224 val scUpdateOldCtrs = Wire(Vec(numBr, Vec(SCNTables, SInt(SCCtrBits.W)))) 225 scUpdateTagePreds := DontCare 226 scUpdateTakens := DontCare 227 scUpdateOldCtrs := DontCare 228 229 val updateSCMeta = updateMeta.scMeta.get 230 231 val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree = 232 0.U.asTypeOf(Vec(TageBanks, Bool())) 233 val update_sc_used, update_conf, update_unconf, update_agree, update_disagree = 234 0.U.asTypeOf(Vec(TageBanks, Bool())) 235 val sc_misp_tage_corr, sc_corr_tage_misp = 236 0.U.asTypeOf(Vec(TageBanks, Bool())) 237 238 // for sc ctrs 239 def getCentered(ctr: SInt): SInt = Cat(ctr, 1.U(1.W)).asSInt 240 // for tage ctrs, (2*(ctr-4)+1)*8 241 def getPvdrCentered(ctr: UInt): SInt = Cat(ctr ^ (1 << (TageCtrBits-1)).U, 1.U(1.W), 0.U(3.W)).asSInt 242 243 val scMeta = resp_meta.scMeta.get 244 scMeta := DontCare 245 for (w <- 0 until TageBanks) { 246 // do summation in s2 247 val s1_scTableSums = VecInit( 248 (0 to 1) map { i => 249 ParallelSingedExpandingAdd(s1_scResps map (r => getCentered(r.ctrs(w)(i)))) // TODO: rewrite with wallace tree 250 } 251 ) 252 253 val tage_hit_vec = VecInit(s1_resps.map(_.valid)) 254 val tage_pvdr_oh = VecInit((0 until TageNTables).map(i => 255 tage_hit_vec(i) && !tage_hit_vec.drop(i+1).reduceOption(_||_).getOrElse(false.B) 256 )) 257 val tage_table_centered_ctrs = s1_resps.map(r => getPvdrCentered(r.bits.ctrs(w))) 258 259 val s1_sumAboveThresholdsForAllTageCtrs = 260 VecInit(s1_scTableSums.map(s => 261 VecInit(tage_table_centered_ctrs.map(tctr => 262 aboveThreshold(s, tctr, useThresholds(w)) 263 )) 264 )) 265 val s1_totalSumsForAllTageCtrs = 266 VecInit(s1_scTableSums.map(s => 267 VecInit(tage_table_centered_ctrs.map(tctr => 268 s +& tctr 269 )) 270 )) 271 val s1_totalSums = VecInit(s1_totalSumsForAllTageCtrs.map(i => Mux1H(tage_pvdr_oh, i))) 272 val s1_sumAboveThresholds = VecInit(s1_sumAboveThresholdsForAllTageCtrs.map(i => Mux1H(tage_pvdr_oh, i))) 273 val s1_scPreds = VecInit(s1_totalSums.map (_ >= 0.S)) 274 275 val s2_sumAboveThresholds = RegEnable(s1_sumAboveThresholds, io.s1_fire) 276 val s2_scPreds = RegEnable(s1_scPreds, io.s1_fire) 277 val s2_scResps = VecInit(RegEnable(s1_scResps, io.s1_fire).map(_.ctrs(w))) 278 val s2_scCtrs = VecInit(s2_scResps.map(_(s2_tageTakens(w).asUInt))) 279 val s2_chooseBit = s2_tageTakens(w) 280 281 scMeta.tageTakens(w) := s2_tageTakens(w) 282 scMeta.scUsed := s2_provided 283 scMeta.scPreds(w) := s2_scPreds(s2_chooseBit) 284 scMeta.ctrs(w) := s2_scCtrs 285 286 when (s2_provided) { 287 s2_sc_used(w) := true.B 288 s2_unconf(w) := !s2_sumAboveThresholds(s2_chooseBit) 289 s2_conf(w) := s2_sumAboveThresholds(s2_chooseBit) 290 // Use prediction from Statistical Corrector 291 XSDebug(p"---------tage_bank_${w} provided so that sc used---------\n") 292 when (s2_sumAboveThresholds(s2_chooseBit)) { 293 val pred = s2_scPreds(s2_chooseBit) 294 val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W)) 295 s2_agree(w) := s2_tageTakens(w) === pred 296 s2_disagree(w) := s2_tageTakens(w) =/= pred 297 // fit to always-taken condition 298 // io.out.resp.s2.full_pred.br_taken_mask(w) := pred 299 XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n") 300 } 301 } 302 303 io.out.resp.s2.full_pred.br_taken_mask(w) := 304 Mux(s2_provided && s2_sumAboveThresholds(s2_chooseBit), 305 s2_scPreds(s2_chooseBit), s2_tageTakens(w)) 306 307 val updateTageMeta = updateMeta 308 when (updateValids(w) && updateSCMeta.scUsed.asBool) { 309 val scPred = updateSCMeta.scPreds(w) 310 val tagePred = updateSCMeta.tageTakens(w) 311 val taken = update.full_pred.br_taken_mask(w) 312 val scOldCtrs = updateSCMeta.ctrs(w) 313 val pvdrCtr = updateTageMeta.providerResp.ctrs(w) 314 val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr) 315 val sumAbs = sum.abs.asUInt 316 val sumAboveThreshold = aboveThreshold(sum, getPvdrCentered(pvdrCtr), useThresholds(w)) 317 scUpdateTagePreds(w) := tagePred 318 scUpdateTakens(w) := taken 319 (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c} 320 321 update_sc_used(w) := true.B 322 update_unconf(w) := !sumAboveThreshold 323 update_conf(w) := sumAboveThreshold 324 update_agree(w) := scPred === tagePred 325 update_disagree(w) := scPred =/= tagePred 326 sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w) 327 sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w) 328 329 val thres = useThresholds(w) 330 when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) { 331 val newThres = scThresholds(w).update(scPred =/= taken) 332 scThresholds(w) := newThres 333 XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n") 334 } 335 336 val updateThres = updateThresholds(w) 337 when (scPred =/= taken || !sumAboveThreshold) { 338 scUpdateMask(w).foreach(_ := true.B) 339 XSDebug(sum < 0.S, 340 p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " + 341 p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n" 342 ) 343 XSDebug(sum >= 0.S, 344 p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " + 345 p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n" 346 ) 347 XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n") 348 update_on_mispred(w) := scPred =/= taken 349 update_on_unconf(w) := scPred === taken 350 } 351 } 352 } 353 354 355 for (b <- 0 until TageBanks) { 356 for (i <- 0 until SCNTables) { 357 scTables(i).io.update.mask(b) := RegNext(scUpdateMask(b)(i)) 358 scTables(i).io.update.tagePreds(b) := RegNext(scUpdateTagePreds(b)) 359 scTables(i).io.update.takens(b) := RegNext(scUpdateTakens(b)) 360 scTables(i).io.update.oldCtrs(b) := RegNext(scUpdateOldCtrs(b)(i)) 361 scTables(i).io.update.pc := RegNext(update.pc) 362 scTables(i).io.update.folded_hist := RegNext(updateFHist) 363 } 364 } 365 366 tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf)) 367 tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf)) 368 tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree)) 369 tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree)) 370 tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used)) 371 XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred)) 372 XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf)) 373 XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr)) 374 XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp)) 375 376 } 377 378 override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info) 379 380 val perfEvents = Seq( 381 ("tage_tht_hit ", updateMeta.provider.valid), 382 ("sc_update_on_mispred ", PopCount(update_on_mispred) ), 383 ("sc_update_on_unconf ", PopCount(update_on_unconf) ), 384 ) 385 generatePerfEvent() 386} 387