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 /* FIXME: RISC-V Machine ISA v1.13 (draft) introduced a "hardware error" exception, described as: 145 * > A Hardware Error exception is a synchronous exception triggered when corrupted or 146 * > uncorrectable data is accessed explicitly or implicitly by an instruction. In this context, 147 * > "data" encompasses all types of information used within a RISC-V hart. Upon a hardware 148 * > error exception, the xepc register is set to the address of the instruction that attempted to 149 * > access corrupted data, while the xtval register is set either to 0 or to the virtual address 150 * > of an instruction fetch, load, or store that attempted to access corrupted data. The priority 151 * > of Hardware Error exception is implementation-defined, but any given occurrence is 152 * > generally expected to be recognized at the point in the overall priority order at which the 153 * > hardware error is discovered. 154 * Maybe it's better to raise hardware error instead of access fault when ECC check failed. 155 * But it's draft and XiangShan backend does not implement this exception code yet, so we still raise af here. 156 */ 157 def fromECC(enable: Bool, corrupt: Bool): UInt = { 158 Mux(enable && corrupt, af, none) 159 } 160 161 /**Generates exception mux tree 162 * 163 * Exceptions that are further to the left in the parameter list have higher priority 164 * @example 165 * {{{ 166 * val itlb_exception = ExceptionType.fromTlbResp(io.itlb.resp.bits) 167 * // so as pmp_exception, meta_corrupt 168 * // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to: 169 * Mux( 170 * itlb_exception =/= none, 171 * itlb_exception, 172 * Mux(pmp_exception =/= none, pmp_exception, meta_corrupt) 173 * ) 174 * }}} 175 */ 176 def merge(exceptions: UInt*): UInt = { 177// // recursively generate mux tree 178// if (exceptions.length == 1) { 179// require(exceptions.head.getWidth == width) 180// exceptions.head 181// } else { 182// Mux(exceptions.head =/= none, exceptions.head, merge(exceptions.tail: _*)) 183// } 184 // use MuxCase with default 185 exceptions.foreach(e => require(e.getWidth == width)) 186 val mapping = exceptions.init.map(e => (e =/= none) -> e) 187 val default = exceptions.last 188 MuxCase(default, mapping) 189 } 190 191 /**Generates exception mux tree for multi-port exception vectors 192 * 193 * Exceptions that are further to the left in the parameter list have higher priority 194 * @example 195 * {{{ 196 * val itlb_exception = VecInit((0 until PortNumber).map(i => ExceptionType.fromTlbResp(io.itlb(i).resp.bits))) 197 * // so as pmp_exception, meta_corrupt 198 * // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to: 199 * VecInit((0 until PortNumber).map(i => Mux( 200 * itlb_exception(i) =/= none, 201 * itlb_exception(i), 202 * Mux(pmp_exception(i) =/= none, pmp_exception(i), meta_corrupt(i)) 203 * )) 204 * }}} 205 */ 206 def merge(exceptionVecs: Vec[UInt]*): Vec[UInt] = { 207// // recursively generate mux tree 208// if (exceptionVecs.length == 1) { 209// exceptionVecs.head.foreach(e => require(e.getWidth == width)) 210// exceptionVecs.head 211// } else { 212// require(exceptionVecs.head.length == exceptionVecs.last.length) 213// VecInit((exceptionVecs.head zip merge(exceptionVecs.tail: _*)).map{ case (high, low) => 214// Mux(high =/= none, high, low) 215// }) 216// } 217 // merge port-by-port 218 val length = exceptionVecs.head.length 219 exceptionVecs.tail.foreach(vec => require(vec.length == length)) 220 VecInit((0 until length).map{ i => 221 merge(exceptionVecs.map(_(i)): _*) 222 }) 223 } 224} 225 226class FetchToIBuffer(implicit p: Parameters) extends XSBundle { 227 val instrs = Vec(PredictWidth, UInt(32.W)) 228 val valid = UInt(PredictWidth.W) 229 val enqEnable = UInt(PredictWidth.W) 230 val pd = Vec(PredictWidth, new PreDecodeInfo) 231 val pc = Vec(PredictWidth, UInt(VAddrBits.W)) 232 val foldpc = Vec(PredictWidth, UInt(MemPredPCWidth.W)) 233 val ftqPtr = new FtqPtr 234 val ftqOffset = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))) 235 val exceptionType = Vec(PredictWidth, UInt(ExceptionType.width.W)) 236 val crossPageIPFFix = Vec(PredictWidth, Bool()) 237 val triggered = Vec(PredictWidth, TriggerAction()) 238 val topdown_info = new FrontendTopDownBundle 239} 240 241// class BitWiseUInt(val width: Int, val init: UInt) extends Module { 242// val io = IO(new Bundle { 243// val set 244// }) 245// } 246// Move from BPU 247abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst { 248 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory 249} 250 251class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory { 252 val predHist = UInt(HistoryLength.W) 253 254 def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = { 255 val g = Wire(new ShiftingGlobalHistory) 256 g.predHist := (hist << shift) | taken 257 g 258 } 259 260 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = { 261 require(br_valids.length == numBr) 262 require(real_taken_mask.length == numBr) 263 val last_valid_idx = PriorityMux( 264 br_valids.reverse :+ true.B, 265 (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W)) 266 ) 267 val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask) 268 val smaller = Mux(last_valid_idx < first_taken_idx, 269 last_valid_idx, 270 first_taken_idx 271 ) 272 val shift = smaller 273 val taken = real_taken_mask.reduce(_||_) 274 update(shift, taken, this.predHist) 275 } 276 277 // static read 278 def read(n: Int): Bool = predHist.asBools(n) 279 280 final def === (that: ShiftingGlobalHistory): Bool = { 281 predHist === that.predHist 282 } 283 284 final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that) 285} 286 287// circular global history pointer 288class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr]( 289 p => p(XSCoreParamsKey).HistoryLength 290){ 291} 292 293object CGHPtr { 294 def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = { 295 val ptr = Wire(new CGHPtr) 296 ptr.flag := f 297 ptr.value := v 298 ptr 299 } 300 def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr = { 301 apply(!ptr.flag, ptr.value) 302 } 303} 304 305class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory { 306 val buffer = Vec(HistoryLength, Bool()) 307 type HistPtr = UInt 308 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = { 309 this 310 } 311} 312 313class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters) 314 extends XSBundle with HasBPUConst { 315 require(compLen >= 1) 316 require(len > 0) 317 // require(folded_len <= len) 318 require(compLen >= max_update_num) 319 val folded_hist = UInt(compLen.W) 320 321 def need_oldest_bits = len > compLen 322 def info = (len, compLen) 323 def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1) 324 def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen) 325 def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0) 326 def oldest_bit_start = oldest_bit_pos_in_folded.head 327 328 def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = { 329 // TODO: wrap inc for histPtr value 330 oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value)) 331 } 332 333 def circular_shift_left(src: UInt, shamt: Int) = { 334 val srcLen = src.getWidth 335 val src_doubled = Cat(src, src) 336 val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt) 337 shifted 338 } 339 340 // slow path, read bits from ghr 341 def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = { 342 val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr)) 343 update(oldest_bits, num, taken) 344 } 345 346 347 // fast path, use pre-read oldest bits 348 def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = { 349 // do xors for several bitsets at specified bits 350 def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = { 351 val res = Wire(Vec(len, Bool())) 352 // println(f"num bitsets: ${bitsets.length}") 353 // println(f"bitsets $bitsets") 354 val resArr = Array.fill(len)(List[Bool]()) 355 for (bs <- bitsets) { 356 for ((n, b) <- bs) { 357 resArr(n) = b :: resArr(n) 358 } 359 } 360 // println(f"${resArr.mkString}") 361 // println(f"histLen: ${this.len}, foldedLen: $folded_len") 362 for (i <- 0 until len) { 363 // println(f"bit[$i], ${resArr(i).mkString}") 364 if (resArr(i).length == 0) { 365 println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen") 366 } 367 res(i) := resArr(i).foldLeft(false.B)(_^_) 368 } 369 res.asUInt 370 } 371 372 val new_folded_hist = if (need_oldest_bits) { 373 val oldest_bits = ob 374 require(oldest_bits.length == max_update_num) 375 // mask off bits that do not update 376 val oldest_bits_masked = oldest_bits.zipWithIndex.map{ 377 case (ob, i) => ob && (i < num).B 378 } 379 // if a bit does not wrap around, it should not be xored when it exits 380 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))) 381 382 // println(f"old bits pos ${oldest_bits_set.map(_._1)}") 383 384 // only the last bit could be 1, as we have at most one taken branch at a time 385 val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt 386 // if a bit does not wrap around, newest bits should not be xored onto it either 387 val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i))) 388 389 // println(f"new bits set ${newest_bits_set.map(_._1)}") 390 // 391 val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{ 392 case (fb, i) => fb && !(num >= (len-i)).B 393 }) 394 val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i))) 395 396 // do xor then shift 397 val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set)) 398 circular_shift_left(xored, num) 399 } else { 400 // histLen too short to wrap around 401 ((folded_hist << num) | taken)(compLen-1,0) 402 } 403 404 val fh = WireInit(this) 405 fh.folded_hist := new_folded_hist 406 fh 407 } 408} 409 410class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle { 411 val bits = Vec(max_update_num*2, Bool()) 412 // def info = (len, compLen) 413 def getRealOb(brNumOH: UInt): Vec[Bool] = { 414 val ob = Wire(Vec(max_update_num, Bool())) 415 for (i <- 0 until max_update_num) { 416 ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr+1)) 417 } 418 ob 419 } 420} 421 422class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst { 423 val afhob = MixedVec(gen.filter(t => t._1 > t._2).map{_._1} 424 .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates 425 require(gen.toSet.toList.equals(gen)) 426 def getObWithInfo(info: Tuple2[Int, Int]) = { 427 val selected = afhob.filter(_.len == info._1) 428 require(selected.length == 1) 429 selected(0) 430 } 431 def read(ghv: Vec[Bool], ptr: CGHPtr) = { 432 val hisLens = afhob.map(_.len) 433 val bitsToRead = hisLens.flatMap(l => (0 until numBr*2).map(i => l-i-1)).toSet // remove duplicates 434 val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr+(pos+1).U).value))) 435 for (ob <- afhob) { 436 for (i <- 0 until numBr*2) { 437 val pos = ob.len - i - 1 438 val bit_found = bitsWithInfo.filter(_._1 == pos).toList 439 require(bit_found.length == 1) 440 ob.bits(i) := bit_found(0)._2 441 } 442 } 443 } 444} 445 446class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst { 447 val hist = MixedVec(gen.map{case (l, cl) => new FoldedHistory(l, cl, numBr)}) 448 // println(gen.mkString) 449 require(gen.toSet.toList.equals(gen)) 450 def getHistWithInfo(info: Tuple2[Int, Int]) = { 451 val selected = hist.filter(_.info.equals(info)) 452 require(selected.length == 1) 453 selected(0) 454 } 455 def autoConnectFrom(that: AllFoldedHistories) = { 456 require(this.hist.length <= that.hist.length) 457 for (h <- this.hist) { 458 h := that.getHistWithInfo(h.info) 459 } 460 } 461 def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = { 462 val res = WireInit(this) 463 for (i <- 0 until this.hist.length) { 464 res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken) 465 } 466 res 467 } 468 def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = { 469 val res = WireInit(this) 470 for (i <- 0 until this.hist.length) { 471 val fh = this.hist(i) 472 if (fh.need_oldest_bits) { 473 val info = fh.info 474 val selectedAfhob = afhob.getObWithInfo(info) 475 val ob = selectedAfhob.getRealOb(lastBrNumOH) 476 res.hist(i) := this.hist(i).update(ob, shift, taken) 477 } else { 478 val dumb = Wire(Vec(numBr, Bool())) // not needed 479 dumb := DontCare 480 res.hist(i) := this.hist(i).update(dumb, shift, taken) 481 } 482 } 483 res 484 } 485 486 def display(cond: Bool) = { 487 for (h <- hist) { 488 XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n") 489 } 490 } 491} 492 493class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{ 494 def tagBits = VAddrBits - idxBits - instOffsetBits 495 496 val tag = UInt(tagBits.W) 497 val idx = UInt(idxBits.W) 498 val offset = UInt(instOffsetBits.W) 499 500 def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this) 501 def getTag(x: UInt) = fromUInt(x).tag 502 def getIdx(x: UInt) = fromUInt(x).idx 503 def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U 504 def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x) 505} 506 507trait BasicPrediction extends HasXSParameter { 508 def cfiIndex: ValidUndirectioned[UInt] 509 def target(pc: UInt): UInt 510 def lastBrPosOH: Vec[Bool] 511 def brTaken: Bool 512 def shouldShiftVec: Vec[Bool] 513 def fallThruError: Bool 514} 515 516// selectByTaken selects some data according to takenMask 517// allTargets should be in a Vec, like [taken0, taken1, ..., not taken, not hit] 518object selectByTaken { 519 def apply[T <: Data](takenMask: Vec[Bool], hit: Bool, allTargets: Vec[T]): T = { 520 val selVecOH = 521 takenMask.zipWithIndex.map { case (t, i) => !takenMask.take(i).fold(false.B)(_ || _) && t && hit } :+ 522 (!takenMask.asUInt.orR && hit) :+ !hit 523 Mux1H(selVecOH, allTargets) 524 } 525} 526 527class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction { 528 val br_taken_mask = Vec(numBr, Bool()) 529 530 val slot_valids = Vec(totalSlot, Bool()) 531 532 val targets = Vec(totalSlot, UInt(VAddrBits.W)) 533 val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors 534 val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W)) 535 val fallThroughAddr = UInt(VAddrBits.W) 536 val fallThroughErr = Bool() 537 val multiHit = Bool() 538 539 val is_jal = Bool() 540 val is_jalr = Bool() 541 val is_call = Bool() 542 val is_ret = Bool() 543 val last_may_be_rvi_call = Bool() 544 val is_br_sharing = Bool() 545 546 // val call_is_rvc = Bool() 547 val hit = Bool() 548 549 val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None 550 551 def br_slot_valids = slot_valids.init 552 def tail_slot_valid = slot_valids.last 553 554 def br_valids = { 555 VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing)) 556 } 557 558 def taken_mask_on_slot = { 559 VecInit( 560 (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ ( 561 tail_slot_valid && ( 562 is_br_sharing && br_taken_mask.last || !is_br_sharing 563 ) 564 ) 565 ) 566 } 567 568 def real_slot_taken_mask(): Vec[Bool] = { 569 VecInit(taken_mask_on_slot.map(_ && hit)) 570 } 571 572 // len numBr 573 def real_br_taken_mask(): Vec[Bool] = { 574 VecInit( 575 taken_mask_on_slot.map(_ && hit).init :+ 576 (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit) 577 ) 578 } 579 580 // the vec indicating if ghr should shift on each branch 581 def shouldShiftVec = 582 VecInit(br_valids.zipWithIndex.map{ case (v, i) => 583 v && !real_br_taken_mask().take(i).reduceOption(_||_).getOrElse(false.B)}) 584 585 def lastBrPosOH = 586 VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry 587 (0 until numBr).map(i => 588 br_valids(i) && 589 !real_br_taken_mask().take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it 590 (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it 591 hit 592 ) 593 ) 594 595 def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_) 596 597 def target(pc: UInt): UInt = { 598 selectByTaken(taken_mask_on_slot, hit, allTarget(pc)) 599 } 600 601 // allTarget return a Vec of all possible target of a BP stage 602 // in the following order: [taken_target0, taken_target1, ..., fallThroughAddr, not hit (plus fetch width)] 603 // 604 // This exposes internal targets for timing optimization, 605 // since usually targets are generated quicker than taken 606 def allTarget(pc: UInt): Vec[UInt] = { 607 VecInit(targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U)) 608 } 609 610 def fallThruError: Bool = hit && fallThroughErr 611 def ftbMultiHit: Bool = hit && multiHit 612 613 def hit_taken_on_jmp = 614 !real_slot_taken_mask().init.reduce(_||_) && 615 real_slot_taken_mask().last && !is_br_sharing 616 def hit_taken_on_call = hit_taken_on_jmp && is_call 617 def hit_taken_on_ret = hit_taken_on_jmp && is_ret 618 def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr 619 620 def cfiIndex = { 621 val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))) 622 cfiIndex.valid := real_slot_taken_mask().asUInt.orR 623 // when no takens, set cfiIndex to PredictWidth-1 624 cfiIndex.bits := 625 ParallelPriorityMux(real_slot_taken_mask(), offsets) | 626 Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt) 627 cfiIndex 628 } 629 630 def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr) 631 632 def fromFtbEntry( 633 entry: FTBEntry, 634 pc: UInt, 635 last_stage_pc: Option[Tuple2[UInt, Bool]] = None, 636 last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None 637 ) = { 638 slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid 639 targets := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing 640 jalr_target := targets.last 641 offsets := entry.getOffsetVec 642 is_jal := entry.tailSlot.valid && entry.isJal 643 is_jalr := entry.tailSlot.valid && entry.isJalr 644 is_call := entry.tailSlot.valid && entry.isCall 645 is_ret := entry.tailSlot.valid && entry.isRet 646 last_may_be_rvi_call := entry.last_may_be_rvi_call 647 is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing 648 predCycle.map(_ := GTimer()) 649 650 val startLower = Cat(0.U(1.W), pc(instOffsetBits+log2Ceil(PredictWidth)-1, instOffsetBits)) 651 val endLowerwithCarry = Cat(entry.carry, entry.pftAddr) 652 fallThroughErr := startLower >= endLowerwithCarry || endLowerwithCarry > (startLower + (PredictWidth).U) 653 fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry)) 654 } 655 656 def display(cond: Bool): Unit = { 657 XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n") 658 } 659} 660 661class SpeculativeInfo(implicit p: Parameters) extends XSBundle 662 with HasBPUConst with BPUUtils { 663 val histPtr = new CGHPtr 664 val ssp = UInt(log2Up(RasSize).W) 665 val sctr = UInt(RasCtrSize.W) 666 val TOSW = new RASPtr 667 val TOSR = new RASPtr 668 val NOS = new RASPtr 669 val topAddr = UInt(VAddrBits.W) 670} 671 672class BranchPredictionBundle(implicit p: Parameters) extends XSBundle 673 with HasBPUConst with BPUUtils { 674 val pc = Vec(numDup, UInt(VAddrBits.W)) 675 val valid = Vec(numDup, Bool()) 676 val hasRedirect = Vec(numDup, Bool()) 677 val ftq_idx = new FtqPtr 678 val full_pred = Vec(numDup, new FullBranchPrediction) 679 680 681 def target(pc: UInt) = VecInit(full_pred.map(_.target(pc))) 682 def targets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).target(pc)}) 683 def allTargets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).allTarget(pc)}) 684 def cfiIndex = VecInit(full_pred.map(_.cfiIndex)) 685 def lastBrPosOH = VecInit(full_pred.map(_.lastBrPosOH)) 686 def brTaken = VecInit(full_pred.map(_.brTaken)) 687 def shouldShiftVec = VecInit(full_pred.map(_.shouldShiftVec)) 688 def fallThruError = VecInit(full_pred.map(_.fallThruError)) 689 def ftbMultiHit = VecInit(full_pred.map(_.ftbMultiHit)) 690 691 def taken = VecInit(cfiIndex.map(_.valid)) 692 693 def getTarget = targets(pc) 694 def getAllTargets = allTargets(pc) 695 696 def display(cond: Bool): Unit = { 697 XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n") 698 full_pred(0).display(cond) 699 } 700} 701 702class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst { 703 val s1 = new BranchPredictionBundle 704 val s2 = new BranchPredictionBundle 705 val s3 = new BranchPredictionBundle 706 707 val s1_uftbHit = Bool() 708 val s1_uftbHasIndirect = Bool() 709 val s1_ftbCloseReq = Bool() 710 711 val last_stage_meta = UInt(MaxMetaLength.W) 712 val last_stage_spec_info = new Ftq_Redirect_SRAMEntry 713 val last_stage_ftb_entry = new FTBEntry 714 715 val topdown_info = new FrontendTopDownBundle 716 717 def selectedResp ={ 718 val res = 719 PriorityMux(Seq( 720 ((s3.valid(3) && s3.hasRedirect(3)) -> s3), 721 ((s2.valid(3) && s2.hasRedirect(3)) -> s2), 722 (s1.valid(3) -> s1) 723 )) 724 res 725 } 726 def selectedRespIdxForFtq = 727 PriorityMux(Seq( 728 ((s3.valid(3) && s3.hasRedirect(3)) -> BP_S3), 729 ((s2.valid(3) && s2.hasRedirect(3)) -> BP_S2), 730 (s1.valid(3) -> BP_S1) 731 )) 732 def lastStage = s3 733} 734 735class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {} 736 737class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst { 738 val pc = UInt(VAddrBits.W) 739 val spec_info = new SpeculativeInfo 740 val ftb_entry = new FTBEntry() 741 742 val cfi_idx = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 743 val br_taken_mask = Vec(numBr, Bool()) 744 val br_committed = Vec(numBr, Bool()) // High only when br valid && br committed 745 val jmp_taken = Bool() 746 val mispred_mask = Vec(numBr+1, Bool()) 747 val pred_hit = Bool() 748 val false_hit = Bool() 749 val new_br_insert_pos = Vec(numBr, Bool()) 750 val old_entry = Bool() 751 val meta = UInt(MaxMetaLength.W) 752 val full_target = UInt(VAddrBits.W) 753 val from_stage = UInt(2.W) 754 val ghist = UInt(HistoryLength.W) 755 756 def is_jal = ftb_entry.tailSlot.valid && ftb_entry.isJal 757 def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr 758 def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall 759 def is_ret = ftb_entry.tailSlot.valid && ftb_entry.isRet 760 761 def is_call_taken = is_call && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset 762 def is_ret_taken = is_ret && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset 763 764 def display(cond: Bool) = { 765 XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n") 766 XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n") 767 XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n") 768 XSDebug(cond, p"--------------------------------------------\n") 769 } 770} 771 772class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst { 773 // override def toPrintable: Printable = { 774 // p"-----------BranchPredictionRedirect----------- " + 775 // p"-----------cfiUpdate----------- " + 776 // p"[pc] ${Hexadecimal(cfiUpdate.pc)} " + 777 // p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " + 778 // p"[target] ${Hexadecimal(cfiUpdate.target)} " + 779 // p"------------------------------- " + 780 // p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " + 781 // p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " + 782 // p"[ftqOffset] ${ftqOffset} " + 783 // p"[level] ${level}, [interrupt] ${interrupt} " + 784 // p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " + 785 // p"[stFtqOffset] ${stFtqOffset} " + 786 // p"\n" 787 788 // } 789 790 // TODO: backend should pass topdown signals here 791 // must not change its parent since BPU has used asTypeOf(this type) from its parent class 792 require(isInstanceOf[Redirect]) 793 val BTBMissBubble = Bool() 794 def ControlRedirectBubble = debugIsCtrl 795 // if mispred br not in ftb, count as BTB miss 796 def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit 797 def TAGEMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit 798 def SCMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit 799 def ITTAGEMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet 800 def RASMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet 801 def MemVioRedirectBubble = debugIsMemVio 802 def OtherRedirectBubble = !debugIsCtrl && !debugIsMemVio 803 804 def connectRedirect(source: Redirect): Unit = { 805 for ((name, data) <- this.elements) { 806 if (source.elements.contains(name)) { 807 data := source.elements(name) 808 } 809 } 810 } 811 812 def display(cond: Bool): Unit = { 813 XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n") 814 XSDebug(cond, p"-----------cfiUpdate----------- \n") 815 XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n") 816 // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n") 817 XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n") 818 XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n") 819 XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n") 820 XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n") 821 XSDebug(cond, p"------------------------------- \n") 822 XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n") 823 XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n") 824 XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n") 825 XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n") 826 XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n") 827 XSDebug(cond, p"---------------------------------------------- \n") 828 } 829} 830