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.stage.{ChiselGeneratorAnnotation, ChiselStage} 22import chisel3.util._ 23import xiangshan._ 24import utils._ 25import chisel3.experimental.chiselName 26 27import scala.math.min 28import os.copy 29 30 31trait FTBParams extends HasXSParameter with HasBPUConst { 32 val numEntries = 4096 33 val numWays = 4 34 val numSets = numEntries/numWays // 512 35 val tagSize = 20 36 37 38 39 val TAR_STAT_SZ = 2 40 def TAR_FIT = 0.U(TAR_STAT_SZ.W) 41 def TAR_OVF = 1.U(TAR_STAT_SZ.W) 42 def TAR_UDF = 2.U(TAR_STAT_SZ.W) 43 44 def BR_OFFSET_LEN = 12 45 def JMP_OFFSET_LEN = 20 46} 47 48class FtbSlot(val offsetLen: Int, val subOffsetLen: Int = 0)(implicit p: Parameters) extends XSBundle with FTBParams { 49 require(subOffsetLen <= offsetLen) 50 val offset = UInt(log2Ceil(PredictWidth).W) 51 val lower = UInt(offsetLen.W) 52 val tarStat = UInt(TAR_STAT_SZ.W) 53 val sharing = Bool() 54 val valid = Bool() 55 56 def setLowerStatByTarget(pc: UInt, target: UInt, isShare: Boolean) = { 57 def getTargetStatByHigher(pc_higher: UInt, target_higher: UInt) = 58 Mux(target_higher > pc_higher, TAR_OVF, 59 Mux(target_higher < pc_higher, TAR_UDF, TAR_FIT)) 60 def getLowerByTarget(target: UInt, offsetLen: Int) = target(offsetLen, 1) 61 val offLen = if (isShare) this.subOffsetLen else this.offsetLen 62 val pc_higher = pc(VAddrBits-1, offLen+1) 63 val target_higher = target(VAddrBits-1, offLen+1) 64 val stat = getTargetStatByHigher(pc_higher, target_higher) 65 val lower = ZeroExt(getLowerByTarget(target, offLen), this.offsetLen) 66 this.lower := lower 67 this.tarStat := stat 68 this.sharing := isShare.B 69 } 70 71 def getTarget(pc: UInt) = { 72 def getTarget(offLen: Int)(pc: UInt, lower: UInt, stat: UInt) = { 73 val higher = pc(VAddrBits-1, offLen+1) 74 val target = 75 Cat( 76 Mux(stat === TAR_OVF, higher+1.U, 77 Mux(stat === TAR_UDF, higher-1.U, higher)), 78 lower(offLen-1, 0), 0.U(1.W) 79 ) 80 require(target.getWidth == VAddrBits) 81 require(offLen != 0) 82 target 83 } 84 if (subOffsetLen != 0) 85 Mux(sharing, 86 getTarget(subOffsetLen)(pc, lower, tarStat), 87 getTarget(offsetLen)(pc, lower, tarStat) 88 ) 89 else 90 getTarget(offsetLen)(pc, lower, tarStat) 91 } 92 def fromAnotherSlot(that: FtbSlot) = { 93 require( 94 this.offsetLen > that.offsetLen && that.offsetLen == this.subOffsetLen || 95 this.offsetLen == that.offsetLen 96 ) 97 this.offset := that.offset 98 this.tarStat := that.tarStat 99 this.sharing := (this.offsetLen > that.offsetLen && that.offsetLen == this.subOffsetLen).B 100 this.valid := that.valid 101 this.lower := ZeroExt(that.lower, this.offsetLen) 102 } 103 104} 105 106class FTBEntry(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils { 107 108 109 val valid = Bool() 110 111 val brSlots = Vec(numBrSlot, new FtbSlot(BR_OFFSET_LEN)) 112 113 // if shareTailSlot is set, this slot can hold a branch or a jal/jalr 114 // else this slot holds only jal/jalr 115 val tailSlot = new FtbSlot(JMP_OFFSET_LEN, BR_OFFSET_LEN) 116 117 // Partial Fall-Through Address 118 val pftAddr = UInt((log2Up(PredictWidth)+1).W) 119 val carry = Bool() 120 121 val isCall = Bool() 122 val isRet = Bool() 123 val isJalr = Bool() 124 125 // 126 val oversize = Bool() 127 128 val last_is_rvc = Bool() 129 130 val always_taken = Vec(numBr, Bool()) 131 132 def getSlotForBr(idx: Int): FtbSlot = { 133 require( 134 idx < numBr-1 || idx == numBr-1 && !shareTailSlot || 135 idx == numBr-1 && shareTailSlot 136 ) 137 (idx, numBr, shareTailSlot) match { 138 case (i, n, true) if i == n-1 => this.tailSlot 139 case _ => this.brSlots(idx) 140 } 141 } 142 def allSlotsForBr = { 143 (0 until numBr).map(getSlotForBr(_)) 144 } 145 def setByBrTarget(brIdx: Int, pc: UInt, target: UInt) = { 146 val slot = getSlotForBr(brIdx) 147 slot.setLowerStatByTarget(pc, target, shareTailSlot && brIdx == numBr-1) 148 } 149 def setByJmpTarget(pc: UInt, target: UInt) = { 150 this.tailSlot.setLowerStatByTarget(pc, target, false) 151 } 152 153 def getTargetVec(pc: UInt) = { 154 VecInit((brSlots :+ tailSlot).map(_.getTarget(pc))) 155 } 156 157 def getOffsetVec = VecInit(brSlots.map(_.offset) :+ tailSlot.offset) 158 def isJal = !isJalr 159 def getFallThrough(pc: UInt) = getFallThroughAddr(pc, carry, pftAddr) 160 def hasBr(offset: UInt) = 161 brSlots.map{ s => s.valid && s.offset <= offset}.reduce(_||_) || 162 (shareTailSlot.B && tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing) 163 164 def getBrMaskByOffset(offset: UInt) = 165 brSlots.map{ s => s.valid && s.offset <= offset } ++ 166 (if (shareTailSlot) Seq(tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing) else Nil) 167 168 def getBrRecordedVec(offset: UInt) = { 169 VecInit( 170 brSlots.map(s => s.valid && s.offset === offset) ++ 171 (if (shareTailSlot) Seq(tailSlot.valid && tailSlot.offset === offset && tailSlot.sharing) else Nil) 172 ) 173 } 174 175 def brIsSaved(offset: UInt) = getBrRecordedVec(offset).reduce(_||_) 176 177 def onNotHit(pc: UInt) = { 178 pftAddr := pc(instOffsetBits + log2Ceil(PredictWidth), instOffsetBits) ^ (1 << log2Ceil(PredictWidth)).U 179 carry := pc(instOffsetBits + log2Ceil(PredictWidth)).asBool 180 oversize := false.B 181 } 182 183 def brValids = { 184 VecInit( 185 brSlots.map(_.valid) ++ 186 (if (shareTailSlot) Seq(tailSlot.valid && tailSlot.sharing) else Nil) 187 ) 188 } 189 190 def noEmptySlotForNewBr = { 191 VecInit( 192 brSlots.map(_.valid) ++ 193 (if (shareTailSlot) Seq(tailSlot.valid) else Nil) 194 ).reduce(_&&_) 195 } 196 197 def newBrCanNotInsert(offset: UInt) = { 198 val lastSlotForBr = if (shareTailSlot) tailSlot else brSlots.last 199 lastSlotForBr.valid && lastSlotForBr.offset < offset 200 } 201 202 def jmpValid = { 203 tailSlot.valid && (!shareTailSlot.B || !tailSlot.sharing) 204 } 205 206 def brOffset = { 207 VecInit( 208 brSlots.map(_.offset) ++ 209 (if (shareTailSlot) Seq(tailSlot.offset) else Nil) 210 ) 211 } 212 213 214 def display(cond: Bool): Unit = { 215 XSDebug(cond, p"-----------FTB entry----------- \n") 216 XSDebug(cond, p"v=${valid}\n") 217 for(i <- 0 until numBr) { 218 XSDebug(cond, p"[br$i]: v=${allSlotsForBr(i).valid}, offset=${allSlotsForBr(i).offset}," + 219 p"lower=${Hexadecimal(allSlotsForBr(i).lower)}\n") 220 } 221 XSDebug(cond, p"[tailSlot]: v=${tailSlot.valid}, offset=${tailSlot.offset}," + 222 p"lower=${Hexadecimal(tailSlot.lower)}, sharing=${tailSlot.sharing}}\n") 223 XSDebug(cond, p"pftAddr=${Hexadecimal(pftAddr)}, carry=$carry\n") 224 XSDebug(cond, p"isCall=$isCall, isRet=$isRet, isjalr=$isJalr\n") 225 XSDebug(cond, p"oversize=$oversize, last_is_rvc=$last_is_rvc\n") 226 XSDebug(cond, p"------------------------------- \n") 227 } 228 229} 230 231class FTBEntryWithTag(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils { 232 val entry = new FTBEntry 233 val tag = UInt(tagSize.W) 234 def display(cond: Bool): Unit = { 235 entry.display(cond) 236 XSDebug(cond, p"tag is ${Hexadecimal(tag)}\n------------------------------- \n") 237 } 238} 239 240class FTBMeta(implicit p: Parameters) extends XSBundle with FTBParams { 241 val writeWay = UInt(numWays.W) 242 val hit = Bool() 243 val pred_cycle = UInt(64.W) // TODO: Use Option 244} 245 246object FTBMeta { 247 def apply(writeWay: UInt, hit: Bool, pred_cycle: UInt)(implicit p: Parameters): FTBMeta = { 248 val e = Wire(new FTBMeta) 249 e.writeWay := writeWay 250 e.hit := hit 251 e.pred_cycle := pred_cycle 252 e 253 } 254} 255 256class FTB(implicit p: Parameters) extends BasePredictor with FTBParams with BPUUtils { 257 override val meta_size = WireInit(0.U.asTypeOf(new FTBMeta)).getWidth 258 259 val ftbAddr = new TableAddr(log2Up(numSets), 1) 260 261 class FTBBank(val numSets: Int, val nWays: Int) extends XSModule with BPUUtils { 262 val io = IO(new Bundle { 263 val req_pc = Flipped(DecoupledIO(UInt(VAddrBits.W))) 264 val read_resp = Output(new FTBEntry) 265 266 // when ftb hit, read_hits.valid is true, and read_hits.bits is OH of hit way 267 // when ftb not hit, read_hits.valid is false, and read_hits is OH of allocWay 268 val read_hits = Valid(Vec(numWays, Bool())) 269 270 val update_pc = Input(UInt(VAddrBits.W)) 271 val update_write_data = Flipped(Valid(new FTBEntryWithTag)) 272 val update_write_mask = Input(UInt(numWays.W)) 273 }) 274 275 val ftb = Module(new SRAMTemplate(new FTBEntryWithTag, set = numSets, way = numWays, shouldReset = true, holdRead = true, singlePort = true)) 276 277 ftb.io.r.req.valid := io.req_pc.valid // io.s0_fire 278 ftb.io.r.req.bits.setIdx := ftbAddr.getIdx(io.req_pc.bits) // s0_idx 279 280 io.req_pc.ready := ftb.io.r.req.ready 281 282 val req_tag = RegEnable(ftbAddr.getTag(io.req_pc.bits)(tagSize-1, 0), io.req_pc.valid) 283 284 val read_entries = ftb.io.r.resp.data.map(_.entry) 285 val read_tags = ftb.io.r.resp.data.map(_.tag) 286 287 val total_hits = VecInit((0 until numWays).map(b => read_tags(b) === req_tag && read_entries(b).valid)) 288 val hit = total_hits.reduce(_||_) 289 val hit_way_1h = VecInit(PriorityEncoderOH(total_hits)) 290 291 def allocWay(valids: UInt, meta_tags: UInt, req_tag: UInt) = { 292 val randomAlloc = false 293 if (numWays > 1) { 294 val w = Wire(UInt(log2Up(numWays).W)) 295 val valid = WireInit(valids.andR) 296 val tags = Cat(meta_tags, req_tag) 297 val l = log2Up(numWays) 298 val nChunks = (tags.getWidth + l - 1) / l 299 val chunks = (0 until nChunks).map( i => 300 tags(min((i+1)*l, tags.getWidth)-1, i*l) 301 ) 302 w := Mux(valid, if (randomAlloc) {LFSR64()(log2Up(numWays)-1,0)} else {chunks.reduce(_^_)}, PriorityEncoder(~valids)) 303 w 304 } else { 305 val w = WireInit(0.U) 306 w 307 } 308 } 309 310 val allocWriteWay = allocWay( 311 VecInit(read_entries.map(_.valid)).asUInt, 312 VecInit(read_tags).asUInt, 313 req_tag 314 ) 315 316 io.read_resp := PriorityMux(total_hits, read_entries) // Mux1H 317 io.read_hits.valid := hit 318 io.read_hits.bits := Mux(hit, hit_way_1h, VecInit(UIntToOH(allocWriteWay).asBools())) 319 320 // Update logic 321 val u_valid = io.update_write_data.valid 322 val u_data = io.update_write_data.bits 323 val u_idx = ftbAddr.getIdx(io.update_pc) 324 val u_mask = io.update_write_mask 325 326 ftb.io.w.apply(u_valid, u_data, u_idx, u_mask) 327 328 // print hit entry info 329 PriorityMux(total_hits, ftb.io.r.resp.data).display(true.B) 330 } // FTBBank 331 332 val ftbBank = Module(new FTBBank(numSets, numWays)) 333 334 ftbBank.io.req_pc.valid := io.s0_fire 335 ftbBank.io.req_pc.bits := s0_pc 336 337 io.s1_ready := ftbBank.io.req_pc.ready // && !io.redirect.valid 338 339 val ftb_entry = RegEnable(ftbBank.io.read_resp, io.s1_fire) 340 val s1_hit = ftbBank.io.read_hits.valid 341 val s2_hit = RegEnable(s1_hit, io.s1_fire) 342 val writeWay = ftbBank.io.read_hits.bits 343 344 val fallThruAddr = getFallThroughAddr(s2_pc, ftb_entry.carry, ftb_entry.pftAddr) 345 346 // io.out.bits.resp := RegEnable(io.in.bits.resp_in(0), 0.U.asTypeOf(new BranchPredictionResp), io.s1_fire) 347 io.out.resp := io.in.bits.resp_in(0) 348 349 val s1_latch_call_is_rvc = DontCare // TODO: modify when add RAS 350 351 io.out.resp.s2.preds.hit := s2_hit 352 io.out.resp.s2.pc := s2_pc 353 io.out.resp.s2.ftb_entry := ftb_entry 354 io.out.resp.s2.preds.fromFtbEntry(ftb_entry, s2_pc) 355 356 io.out.s3_meta := RegEnable(RegEnable(FTBMeta(writeWay.asUInt(), s1_hit, GTimer()).asUInt(), io.s1_fire), io.s2_fire) 357 358 when(!s2_hit) { 359 io.out.resp.s2.ftb_entry.onNotHit(s2_pc) 360 } 361 362 // always taken logic 363 when (s2_hit) { 364 for (i <- 0 until numBr) { 365 when (ftb_entry.always_taken(i)) { 366 io.out.resp.s2.preds.br_taken_mask(i) := true.B 367 } 368 } 369 } 370 371 // Update logic 372 val has_update = RegInit(VecInit(Seq.fill(64)(0.U(VAddrBits.W)))) 373 val has_update_ptr = RegInit(0.U(log2Up(64))) 374 375 val update = RegNext(io.update.bits) 376 377 val u_meta = update.meta.asTypeOf(new FTBMeta) 378 val u_valid = RegNext(io.update.valid && !io.update.bits.old_entry) 379 val u_way_mask = u_meta.writeWay 380 381 val ftb_write = Wire(new FTBEntryWithTag) 382 ftb_write.entry := update.ftb_entry 383 ftb_write.tag := ftbAddr.getTag(update.pc)(tagSize-1, 0) 384 385 ftbBank.io.update_write_data.valid := u_valid 386 ftbBank.io.update_write_data.bits := ftb_write 387 ftbBank.io.update_pc := update.pc 388 ftbBank.io.update_write_mask := u_way_mask 389 390 val r_updated = (0 until 64).map(i => has_update(i) === s1_pc).reduce(_||_) 391 val u_updated = (0 until 64).map(i => has_update(i) === update.pc).reduce(_||_) 392 393 when(u_valid) { 394 when(!u_updated) { has_update(has_update_ptr) := update.pc } 395 396 has_update_ptr := has_update_ptr + !u_updated 397 } 398 399 XSDebug("req_v=%b, req_pc=%x, ready=%b (resp at next cycle)\n", io.s0_fire, s0_pc, ftbBank.io.req_pc.ready) 400 XSDebug("s2_hit=%b, hit_way=%b\n", s2_hit, writeWay.asUInt) 401 XSDebug("s2_br_taken_mask=%b, s2_real_taken_mask=%b\n", 402 io.in.bits.resp_in(0).s2.preds.br_taken_mask.asUInt, io.out.resp.s2.real_slot_taken_mask().asUInt) 403 XSDebug("s2_target=%x\n", io.out.resp.s2.target) 404 405 XSDebug(u_valid, "Update from ftq\n") 406 XSDebug(u_valid, "update_pc=%x, tag=%x, update_write_way=%b, pred_cycle=%d\n", 407 update.pc, ftbAddr.getTag(update.pc), u_way_mask, u_meta.pred_cycle) 408 409 410 411 412 413 XSPerfAccumulate("ftb_first_miss", u_valid && !u_updated && !update.preds.hit) 414 XSPerfAccumulate("ftb_updated_miss", u_valid && u_updated && !update.preds.hit) 415 416 XSPerfAccumulate("ftb_read_first_miss", RegNext(io.s0_fire) && !s1_hit && !r_updated) 417 XSPerfAccumulate("ftb_read_updated_miss", RegNext(io.s0_fire) && !s1_hit && r_updated) 418 419 XSPerfAccumulate("ftb_read_hits", RegNext(io.s0_fire) && s1_hit) 420 XSPerfAccumulate("ftb_read_misses", RegNext(io.s0_fire) && !s1_hit) 421 422 XSPerfAccumulate("ftb_commit_hits", io.update.valid && io.update.bits.preds.hit) 423 XSPerfAccumulate("ftb_commit_misses", io.update.valid && !io.update.bits.preds.hit) 424 425 XSPerfAccumulate("ftb_update_req", io.update.valid) 426 XSPerfAccumulate("ftb_update_ignored", io.update.valid && io.update.bits.old_entry) 427 XSPerfAccumulate("ftb_updated", u_valid) 428} 429