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