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