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***************************************************************************************/ 16package xiangshan.frontend 17 18import org.chipsalliance.cde.config.Parameters 19import chisel3._ 20import chisel3.util._ 21import xiangshan._ 22import xiangshan.frontend.icache._ 23import utils._ 24import utility._ 25import scala.math._ 26import java.util.ResourceBundle.Control 27 28class FrontendTopDownBundle(implicit p: Parameters) extends XSBundle { 29 val reasons = Vec(TopDownCounters.NumStallReasons.id, Bool()) 30 val stallWidth = UInt(log2Ceil(PredictWidth).W) 31} 32 33class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters { 34 35 //fast path: Timing critical 36 val startAddr = UInt(VAddrBits.W) 37 val nextlineStart = UInt(VAddrBits.W) 38 val nextStartAddr = UInt(VAddrBits.W) 39 //slow path 40 val ftqIdx = new FtqPtr 41 val ftqOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 42 43 val topdown_info = new FrontendTopDownBundle 44 45 def crossCacheline = startAddr(blockOffBits - 1) === 1.U 46 47 def fromFtqPcBundle(b: Ftq_RF_Components) = { 48 this.startAddr := b.startAddr 49 this.nextlineStart := b.nextLineAddr 50 when (b.fallThruError) { 51 val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.nextLineAddr, b.startAddr) 52 val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1) 53 this.nextStartAddr := 54 Cat(nextBlockHigher, 55 startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W), 56 startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits), 57 0.U(instOffsetBits.W) 58 ) 59 } 60 this 61 } 62 override def toPrintable: Printable = { 63 p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" + 64 p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" + 65 p" offset: ${ftqOffset.bits}\n" 66 } 67} 68 69class FtqICacheInfo(implicit p: Parameters)extends XSBundle with HasICacheParameters{ 70 val startAddr = UInt(VAddrBits.W) 71 val nextlineStart = UInt(VAddrBits.W) 72 val ftqIdx = new FtqPtr 73 def crossCacheline = startAddr(blockOffBits - 1) === 1.U 74 def fromFtqPcBundle(b: Ftq_RF_Components) = { 75 this.startAddr := b.startAddr 76 this.nextlineStart := b.nextLineAddr 77 this 78 } 79} 80 81class IFUICacheIO(implicit p: Parameters)extends XSBundle with HasICacheParameters{ 82 val icacheReady = Output(Bool()) 83 val resp = Vec(PortNumber, ValidIO(new ICacheMainPipeResp)) 84 val topdownIcacheMiss = Output(Bool()) 85 val topdownItlbMiss = Output(Bool()) 86} 87 88class FtqToICacheRequestBundle(implicit p: Parameters)extends XSBundle with HasICacheParameters{ 89 val pcMemRead = Vec(5, new FtqICacheInfo) 90 val readValid = Vec(5, Bool()) 91} 92 93 94class PredecodeWritebackBundle(implicit p:Parameters) extends XSBundle { 95 val pc = Vec(PredictWidth, UInt(VAddrBits.W)) 96 val pd = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode 97 val ftqIdx = new FtqPtr 98 val ftqOffset = UInt(log2Ceil(PredictWidth).W) 99 val misOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 100 val cfiOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 101 val target = UInt(VAddrBits.W) 102 val jalTarget = UInt(VAddrBits.W) 103 val instrRange = Vec(PredictWidth, Bool()) 104} 105 106class mmioCommitRead(implicit p: Parameters) extends XSBundle { 107 val mmioFtqPtr = Output(new FtqPtr) 108 val mmioLastCommit = Input(Bool()) 109} 110 111class FetchToIBuffer(implicit p: Parameters) extends XSBundle { 112 val instrs = Vec(PredictWidth, UInt(32.W)) 113 val valid = UInt(PredictWidth.W) 114 val enqEnable = UInt(PredictWidth.W) 115 val pd = Vec(PredictWidth, new PreDecodeInfo) 116 val pc = Vec(PredictWidth, UInt(VAddrBits.W)) 117 val foldpc = Vec(PredictWidth, UInt(MemPredPCWidth.W)) 118 val ftqPtr = new FtqPtr 119 val ftqOffset = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))) 120 val ipf = Vec(PredictWidth, Bool()) 121 val igpf = Vec(PredictWidth, Bool()) 122 val acf = Vec(PredictWidth, Bool()) 123 val crossPageIPFFix = Vec(PredictWidth, Bool()) 124 val triggered = Vec(PredictWidth, new TriggerCf) 125 val topdown_info = new FrontendTopDownBundle 126} 127 128// class BitWiseUInt(val width: Int, val init: UInt) extends Module { 129// val io = IO(new Bundle { 130// val set 131// }) 132// } 133// Move from BPU 134abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst { 135 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory 136} 137 138class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory { 139 val predHist = UInt(HistoryLength.W) 140 141 def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = { 142 val g = Wire(new ShiftingGlobalHistory) 143 g.predHist := (hist << shift) | taken 144 g 145 } 146 147 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = { 148 require(br_valids.length == numBr) 149 require(real_taken_mask.length == numBr) 150 val last_valid_idx = PriorityMux( 151 br_valids.reverse :+ true.B, 152 (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W)) 153 ) 154 val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask) 155 val smaller = Mux(last_valid_idx < first_taken_idx, 156 last_valid_idx, 157 first_taken_idx 158 ) 159 val shift = smaller 160 val taken = real_taken_mask.reduce(_||_) 161 update(shift, taken, this.predHist) 162 } 163 164 // static read 165 def read(n: Int): Bool = predHist.asBools(n) 166 167 final def === (that: ShiftingGlobalHistory): Bool = { 168 predHist === that.predHist 169 } 170 171 final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that) 172} 173 174// circular global history pointer 175class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr]( 176 p => p(XSCoreParamsKey).HistoryLength 177){ 178} 179 180object CGHPtr { 181 def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = { 182 val ptr = Wire(new CGHPtr) 183 ptr.flag := f 184 ptr.value := v 185 ptr 186 } 187 def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr = { 188 apply(!ptr.flag, ptr.value) 189 } 190} 191 192class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory { 193 val buffer = Vec(HistoryLength, Bool()) 194 type HistPtr = UInt 195 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = { 196 this 197 } 198} 199 200class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters) 201 extends XSBundle with HasBPUConst { 202 require(compLen >= 1) 203 require(len > 0) 204 // require(folded_len <= len) 205 require(compLen >= max_update_num) 206 val folded_hist = UInt(compLen.W) 207 208 def need_oldest_bits = len > compLen 209 def info = (len, compLen) 210 def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1) 211 def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen) 212 def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0) 213 def oldest_bit_start = oldest_bit_pos_in_folded.head 214 215 def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = { 216 // TODO: wrap inc for histPtr value 217 oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value)) 218 } 219 220 def circular_shift_left(src: UInt, shamt: Int) = { 221 val srcLen = src.getWidth 222 val src_doubled = Cat(src, src) 223 val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt) 224 shifted 225 } 226 227 // slow path, read bits from ghr 228 def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = { 229 val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr)) 230 update(oldest_bits, num, taken) 231 } 232 233 234 // fast path, use pre-read oldest bits 235 def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = { 236 // do xors for several bitsets at specified bits 237 def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = { 238 val res = Wire(Vec(len, Bool())) 239 // println(f"num bitsets: ${bitsets.length}") 240 // println(f"bitsets $bitsets") 241 val resArr = Array.fill(len)(List[Bool]()) 242 for (bs <- bitsets) { 243 for ((n, b) <- bs) { 244 resArr(n) = b :: resArr(n) 245 } 246 } 247 // println(f"${resArr.mkString}") 248 // println(f"histLen: ${this.len}, foldedLen: $folded_len") 249 for (i <- 0 until len) { 250 // println(f"bit[$i], ${resArr(i).mkString}") 251 if (resArr(i).length == 0) { 252 println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen") 253 } 254 res(i) := resArr(i).foldLeft(false.B)(_^_) 255 } 256 res.asUInt 257 } 258 259 val new_folded_hist = if (need_oldest_bits) { 260 val oldest_bits = ob 261 require(oldest_bits.length == max_update_num) 262 // mask off bits that do not update 263 val oldest_bits_masked = oldest_bits.zipWithIndex.map{ 264 case (ob, i) => ob && (i < num).B 265 } 266 // if a bit does not wrap around, it should not be xored when it exits 267 val oldest_bits_set = (0 until max_update_num).filter(oldest_bit_wrap_around).map(i => (oldest_bit_pos_in_folded(i), oldest_bits_masked(i))) 268 269 // println(f"old bits pos ${oldest_bits_set.map(_._1)}") 270 271 // only the last bit could be 1, as we have at most one taken branch at a time 272 val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt 273 // if a bit does not wrap around, newest bits should not be xored onto it either 274 val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i))) 275 276 // println(f"new bits set ${newest_bits_set.map(_._1)}") 277 // 278 val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{ 279 case (fb, i) => fb && !(num >= (len-i)).B 280 }) 281 val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i))) 282 283 // do xor then shift 284 val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set)) 285 circular_shift_left(xored, num) 286 } else { 287 // histLen too short to wrap around 288 ((folded_hist << num) | taken)(compLen-1,0) 289 } 290 291 val fh = WireInit(this) 292 fh.folded_hist := new_folded_hist 293 fh 294 } 295} 296 297class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle { 298 val bits = Vec(max_update_num*2, Bool()) 299 // def info = (len, compLen) 300 def getRealOb(brNumOH: UInt): Vec[Bool] = { 301 val ob = Wire(Vec(max_update_num, Bool())) 302 for (i <- 0 until max_update_num) { 303 ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr+1)) 304 } 305 ob 306 } 307} 308 309class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst { 310 val afhob = MixedVec(gen.filter(t => t._1 > t._2).map{_._1} 311 .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates 312 require(gen.toSet.toList.equals(gen)) 313 def getObWithInfo(info: Tuple2[Int, Int]) = { 314 val selected = afhob.filter(_.len == info._1) 315 require(selected.length == 1) 316 selected(0) 317 } 318 def read(ghv: Vec[Bool], ptr: CGHPtr) = { 319 val hisLens = afhob.map(_.len) 320 val bitsToRead = hisLens.flatMap(l => (0 until numBr*2).map(i => l-i-1)).toSet // remove duplicates 321 val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr+(pos+1).U).value))) 322 for (ob <- afhob) { 323 for (i <- 0 until numBr*2) { 324 val pos = ob.len - i - 1 325 val bit_found = bitsWithInfo.filter(_._1 == pos).toList 326 require(bit_found.length == 1) 327 ob.bits(i) := bit_found(0)._2 328 } 329 } 330 } 331} 332 333class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst { 334 val hist = MixedVec(gen.map{case (l, cl) => new FoldedHistory(l, cl, numBr)}) 335 // println(gen.mkString) 336 require(gen.toSet.toList.equals(gen)) 337 def getHistWithInfo(info: Tuple2[Int, Int]) = { 338 val selected = hist.filter(_.info.equals(info)) 339 require(selected.length == 1) 340 selected(0) 341 } 342 def autoConnectFrom(that: AllFoldedHistories) = { 343 require(this.hist.length <= that.hist.length) 344 for (h <- this.hist) { 345 h := that.getHistWithInfo(h.info) 346 } 347 } 348 def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = { 349 val res = WireInit(this) 350 for (i <- 0 until this.hist.length) { 351 res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken) 352 } 353 res 354 } 355 def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = { 356 val res = WireInit(this) 357 for (i <- 0 until this.hist.length) { 358 val fh = this.hist(i) 359 if (fh.need_oldest_bits) { 360 val info = fh.info 361 val selectedAfhob = afhob.getObWithInfo(info) 362 val ob = selectedAfhob.getRealOb(lastBrNumOH) 363 res.hist(i) := this.hist(i).update(ob, shift, taken) 364 } else { 365 val dumb = Wire(Vec(numBr, Bool())) // not needed 366 dumb := DontCare 367 res.hist(i) := this.hist(i).update(dumb, shift, taken) 368 } 369 } 370 res 371 } 372 373 def display(cond: Bool) = { 374 for (h <- hist) { 375 XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n") 376 } 377 } 378} 379 380class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{ 381 def tagBits = VAddrBits - idxBits - instOffsetBits 382 383 val tag = UInt(tagBits.W) 384 val idx = UInt(idxBits.W) 385 val offset = UInt(instOffsetBits.W) 386 387 def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this) 388 def getTag(x: UInt) = fromUInt(x).tag 389 def getIdx(x: UInt) = fromUInt(x).idx 390 def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U 391 def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x) 392} 393 394trait BasicPrediction extends HasXSParameter { 395 def cfiIndex: ValidUndirectioned[UInt] 396 def target(pc: UInt): UInt 397 def lastBrPosOH: Vec[Bool] 398 def brTaken: Bool 399 def shouldShiftVec: Vec[Bool] 400 def fallThruError: Bool 401} 402 403// selectByTaken selects some data according to takenMask 404// allTargets should be in a Vec, like [taken0, taken1, ..., not taken, not hit] 405object selectByTaken { 406 def apply[T <: Data](takenMask: Vec[Bool], hit: Bool, allTargets: Vec[T]): T = { 407 val selVecOH = 408 takenMask.zipWithIndex.map { case (t, i) => !takenMask.take(i).fold(false.B)(_ || _) && t && hit } :+ 409 (!takenMask.asUInt.orR && hit) :+ !hit 410 Mux1H(selVecOH, allTargets) 411 } 412} 413 414class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction { 415 val br_taken_mask = Vec(numBr, Bool()) 416 417 val slot_valids = Vec(totalSlot, Bool()) 418 419 val targets = Vec(totalSlot, UInt(VAddrBits.W)) 420 val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors 421 val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W)) 422 val fallThroughAddr = UInt(VAddrBits.W) 423 val fallThroughErr = Bool() 424 val multiHit = Bool() 425 426 val is_jal = Bool() 427 val is_jalr = Bool() 428 val is_call = Bool() 429 val is_ret = Bool() 430 val last_may_be_rvi_call = Bool() 431 val is_br_sharing = Bool() 432 433 // val call_is_rvc = Bool() 434 val hit = Bool() 435 436 val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None 437 438 def br_slot_valids = slot_valids.init 439 def tail_slot_valid = slot_valids.last 440 441 def br_valids = { 442 VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing)) 443 } 444 445 def taken_mask_on_slot = { 446 VecInit( 447 (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ ( 448 tail_slot_valid && ( 449 is_br_sharing && br_taken_mask.last || !is_br_sharing 450 ) 451 ) 452 ) 453 } 454 455 def real_slot_taken_mask(): Vec[Bool] = { 456 VecInit(taken_mask_on_slot.map(_ && hit)) 457 } 458 459 // len numBr 460 def real_br_taken_mask(): Vec[Bool] = { 461 VecInit( 462 taken_mask_on_slot.map(_ && hit).init :+ 463 (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit) 464 ) 465 } 466 467 // the vec indicating if ghr should shift on each branch 468 def shouldShiftVec = 469 VecInit(br_valids.zipWithIndex.map{ case (v, i) => 470 v && !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B)}) 471 472 def lastBrPosOH = 473 VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry 474 (0 until numBr).map(i => 475 br_valids(i) && 476 !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it 477 (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it 478 hit 479 ) 480 ) 481 482 def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_) 483 484 def target(pc: UInt): UInt = { 485 selectByTaken(taken_mask_on_slot, hit, allTarget(pc)) 486 } 487 488 // allTarget return a Vec of all possible target of a BP stage 489 // in the following order: [taken_target0, taken_target1, ..., fallThroughAddr, not hit (plus fetch width)] 490 // 491 // This exposes internal targets for timing optimization, 492 // since usually targets are generated quicker than taken 493 def allTarget(pc: UInt): Vec[UInt] = { 494 VecInit(targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U)) 495 } 496 497 def fallThruError: Bool = hit && fallThroughErr 498 def ftbMultiHit: Bool = hit && multiHit 499 500 def hit_taken_on_jmp = 501 !real_slot_taken_mask().init.reduce(_||_) && 502 real_slot_taken_mask().last && !is_br_sharing 503 def hit_taken_on_call = hit_taken_on_jmp && is_call 504 def hit_taken_on_ret = hit_taken_on_jmp && is_ret 505 def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr 506 507 def cfiIndex = { 508 val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))) 509 cfiIndex.valid := real_slot_taken_mask().asUInt.orR 510 // when no takens, set cfiIndex to PredictWidth-1 511 cfiIndex.bits := 512 ParallelPriorityMux(real_slot_taken_mask(), offsets) | 513 Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt) 514 cfiIndex 515 } 516 517 def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr) 518 519 def fromFtbEntry( 520 entry: FTBEntry, 521 pc: UInt, 522 last_stage_pc: Option[Tuple2[UInt, Bool]] = None, 523 last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None 524 ) = { 525 slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid 526 targets := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing 527 jalr_target := targets.last 528 offsets := entry.getOffsetVec 529 is_jal := entry.tailSlot.valid && entry.isJal 530 is_jalr := entry.tailSlot.valid && entry.isJalr 531 is_call := entry.tailSlot.valid && entry.isCall 532 is_ret := entry.tailSlot.valid && entry.isRet 533 last_may_be_rvi_call := entry.last_may_be_rvi_call 534 is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing 535 predCycle.map(_ := GTimer()) 536 537 val startLower = Cat(0.U(1.W), pc(instOffsetBits+log2Ceil(PredictWidth)-1, instOffsetBits)) 538 val endLowerwithCarry = Cat(entry.carry, entry.pftAddr) 539 fallThroughErr := startLower >= endLowerwithCarry || endLowerwithCarry > (startLower + (PredictWidth).U) 540 fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry)) 541 } 542 543 def display(cond: Bool): Unit = { 544 XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n") 545 } 546} 547 548class SpeculativeInfo(implicit p: Parameters) extends XSBundle 549 with HasBPUConst with BPUUtils { 550 val histPtr = new CGHPtr 551 val ssp = UInt(log2Up(RasSize).W) 552 val sctr = UInt(RasCtrSize.W) 553 val TOSW = new RASPtr 554 val TOSR = new RASPtr 555 val NOS = new RASPtr 556 val topAddr = UInt(VAddrBits.W) 557} 558 559class BranchPredictionBundle(implicit p: Parameters) extends XSBundle 560 with HasBPUConst with BPUUtils { 561 val pc = Vec(numDup, UInt(VAddrBits.W)) 562 val valid = Vec(numDup, Bool()) 563 val hasRedirect = Vec(numDup, Bool()) 564 val ftq_idx = new FtqPtr 565 val full_pred = Vec(numDup, new FullBranchPrediction) 566 567 568 def target(pc: UInt) = VecInit(full_pred.map(_.target(pc))) 569 def targets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).target(pc)}) 570 def allTargets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).allTarget(pc)}) 571 def cfiIndex = VecInit(full_pred.map(_.cfiIndex)) 572 def lastBrPosOH = VecInit(full_pred.map(_.lastBrPosOH)) 573 def brTaken = VecInit(full_pred.map(_.brTaken)) 574 def shouldShiftVec = VecInit(full_pred.map(_.shouldShiftVec)) 575 def fallThruError = VecInit(full_pred.map(_.fallThruError)) 576 def ftbMultiHit = VecInit(full_pred.map(_.ftbMultiHit)) 577 578 def taken = VecInit(cfiIndex.map(_.valid)) 579 580 def getTarget = targets(pc) 581 def getAllTargets = allTargets(pc) 582 583 def display(cond: Bool): Unit = { 584 XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n") 585 full_pred(0).display(cond) 586 } 587} 588 589class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst { 590 val s1 = new BranchPredictionBundle 591 val s2 = new BranchPredictionBundle 592 val s3 = new BranchPredictionBundle 593 594 val s1_uftbHit = Bool() 595 val s1_uftbHasIndirect = Bool() 596 val s1_ftbCloseReq = Bool() 597 598 val last_stage_meta = UInt(MaxMetaLength.W) 599 val last_stage_spec_info = new Ftq_Redirect_SRAMEntry 600 val last_stage_ftb_entry = new FTBEntry 601 602 val topdown_info = new FrontendTopDownBundle 603 604 def selectedResp ={ 605 val res = 606 PriorityMux(Seq( 607 ((s3.valid(3) && s3.hasRedirect(3)) -> s3), 608 ((s2.valid(3) && s2.hasRedirect(3)) -> s2), 609 (s1.valid(3) -> s1) 610 )) 611 res 612 } 613 def selectedRespIdxForFtq = 614 PriorityMux(Seq( 615 ((s3.valid(3) && s3.hasRedirect(3)) -> BP_S3), 616 ((s2.valid(3) && s2.hasRedirect(3)) -> BP_S2), 617 (s1.valid(3) -> BP_S1) 618 )) 619 def lastStage = s3 620} 621 622class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {} 623 624class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst { 625 val pc = UInt(VAddrBits.W) 626 val spec_info = new SpeculativeInfo 627 val ftb_entry = new FTBEntry() 628 629 val cfi_idx = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 630 val br_taken_mask = Vec(numBr, Bool()) 631 val br_committed = Vec(numBr, Bool()) // High only when br valid && br committed 632 val jmp_taken = Bool() 633 val mispred_mask = Vec(numBr+1, Bool()) 634 val pred_hit = Bool() 635 val false_hit = Bool() 636 val new_br_insert_pos = Vec(numBr, Bool()) 637 val old_entry = Bool() 638 val meta = UInt(MaxMetaLength.W) 639 val full_target = UInt(VAddrBits.W) 640 val from_stage = UInt(2.W) 641 val ghist = UInt(HistoryLength.W) 642 643 def is_jal = ftb_entry.tailSlot.valid && ftb_entry.isJal 644 def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr 645 def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall 646 def is_ret = ftb_entry.tailSlot.valid && ftb_entry.isRet 647 648 def is_call_taken = is_call && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset 649 def is_ret_taken = is_ret && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset 650 651 def display(cond: Bool) = { 652 XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n") 653 XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n") 654 XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n") 655 XSDebug(cond, p"--------------------------------------------\n") 656 } 657} 658 659class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst { 660 // override def toPrintable: Printable = { 661 // p"-----------BranchPredictionRedirect----------- " + 662 // p"-----------cfiUpdate----------- " + 663 // p"[pc] ${Hexadecimal(cfiUpdate.pc)} " + 664 // p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " + 665 // p"[target] ${Hexadecimal(cfiUpdate.target)} " + 666 // p"------------------------------- " + 667 // p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " + 668 // p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " + 669 // p"[ftqOffset] ${ftqOffset} " + 670 // p"[level] ${level}, [interrupt] ${interrupt} " + 671 // p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " + 672 // p"[stFtqOffset] ${stFtqOffset} " + 673 // p"\n" 674 675 // } 676 677 // TODO: backend should pass topdown signals here 678 // must not change its parent since BPU has used asTypeOf(this type) from its parent class 679 require(isInstanceOf[Redirect]) 680 val BTBMissBubble = Bool() 681 def ControlRedirectBubble = debugIsCtrl 682 // if mispred br not in ftb, count as BTB miss 683 def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit 684 def TAGEMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit 685 def SCMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit 686 def ITTAGEMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet 687 def RASMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet 688 def MemVioRedirectBubble = debugIsMemVio 689 def OtherRedirectBubble = !debugIsCtrl && !debugIsMemVio 690 691 def connectRedirect(source: Redirect): Unit = { 692 for ((name, data) <- this.elements) { 693 if (source.elements.contains(name)) { 694 data := source.elements(name) 695 } 696 } 697 } 698 699 def display(cond: Bool): Unit = { 700 XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n") 701 XSDebug(cond, p"-----------cfiUpdate----------- \n") 702 XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n") 703 // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n") 704 XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n") 705 XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n") 706 XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n") 707 XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n") 708 XSDebug(cond, p"------------------------------- \n") 709 XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n") 710 XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n") 711 XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n") 712 XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n") 713 XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n") 714 XSDebug(cond, p"---------------------------------------------- \n") 715 } 716} 717