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