xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision 1592abd11eecf7bec0f1453ffe4a7617167f8ba9)
109c6f1ddSLingrui98/***************************************************************************************
2e3da8badSTang Haojin* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3e3da8badSTang Haojin* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
409c6f1ddSLingrui98* Copyright (c) 2020-2021 Peng Cheng Laboratory
509c6f1ddSLingrui98*
609c6f1ddSLingrui98* XiangShan is licensed under Mulan PSL v2.
709c6f1ddSLingrui98* You can use this software according to the terms and conditions of the Mulan PSL v2.
809c6f1ddSLingrui98* You may obtain a copy of Mulan PSL v2 at:
909c6f1ddSLingrui98*          http://license.coscl.org.cn/MulanPSL2
1009c6f1ddSLingrui98*
1109c6f1ddSLingrui98* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
1209c6f1ddSLingrui98* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
1309c6f1ddSLingrui98* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
1409c6f1ddSLingrui98*
1509c6f1ddSLingrui98* See the Mulan PSL v2 for more details.
1609c6f1ddSLingrui98***************************************************************************************/
1709c6f1ddSLingrui98package xiangshan.frontend
1809c6f1ddSLingrui98
1909c6f1ddSLingrui98import chisel3._
2009c6f1ddSLingrui98import chisel3.util._
21cf7d6b7aSMuziimport org.chipsalliance.cde.config.Parameters
22cf7d6b7aSMuziimport utility._
23cf7d6b7aSMuziimport xiangshan._
24cf7d6b7aSMuziimport xiangshan.backend.fu.PMPRespBundle
25cf7d6b7aSMuziimport xiangshan.cache.mmu.TlbResp
26cf7d6b7aSMuziimport xiangshan.frontend.icache._
27d2b20d1aSTang Haojin
28d2b20d1aSTang Haojinclass FrontendTopDownBundle(implicit p: Parameters) extends XSBundle {
29d2b20d1aSTang Haojin  val reasons    = Vec(TopDownCounters.NumStallReasons.id, Bool())
30d2b20d1aSTang Haojin  val stallWidth = UInt(log2Ceil(PredictWidth).W)
31d2b20d1aSTang Haojin}
3209c6f1ddSLingrui98
33b37e4b45SLingrui98class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
34c5c5edaeSJenius
35c5c5edaeSJenius  // fast path: Timing critical
3609c6f1ddSLingrui98  val startAddr     = UInt(VAddrBits.W)
3734a88126SJinYue  val nextlineStart = UInt(VAddrBits.W)
38c5c5edaeSJenius  val nextStartAddr = UInt(VAddrBits.W)
39c5c5edaeSJenius  // slow path
4009c6f1ddSLingrui98  val ftqIdx    = new FtqPtr
4109c6f1ddSLingrui98  val ftqOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
4209c6f1ddSLingrui98
43d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
44d2b20d1aSTang Haojin
456ce52296SJinYue  def crossCacheline = startAddr(blockOffBits - 1) === 1.U
466ce52296SJinYue
4709c6f1ddSLingrui98  def fromFtqPcBundle(b: Ftq_RF_Components) = {
4809c6f1ddSLingrui98    this.startAddr     := b.startAddr
49b37e4b45SLingrui98    this.nextlineStart := b.nextLineAddr
509402431eSmy-mayfly    // when (b.fallThruError) {
519402431eSmy-mayfly    //   val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.nextLineAddr, b.startAddr)
529402431eSmy-mayfly    //   val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1)
539402431eSmy-mayfly    //   this.nextStartAddr :=
549402431eSmy-mayfly    //     Cat(nextBlockHigher,
559402431eSmy-mayfly    //       startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W),
569402431eSmy-mayfly    //       startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits),
579402431eSmy-mayfly    //       0.U(instOffsetBits.W)
589402431eSmy-mayfly    //     )
599402431eSmy-mayfly    // }
6009c6f1ddSLingrui98    this
6109c6f1ddSLingrui98  }
62cf7d6b7aSMuzi  override def toPrintable: Printable =
63b37e4b45SLingrui98    p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" +
64b37e4b45SLingrui98      p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" +
6509c6f1ddSLingrui98      p" offset: ${ftqOffset.bits}\n"
6609c6f1ddSLingrui98}
6709c6f1ddSLingrui98
68f22cf846SJeniusclass FtqICacheInfo(implicit p: Parameters) extends XSBundle with HasICacheParameters {
69c5c5edaeSJenius  val startAddr      = UInt(VAddrBits.W)
70c5c5edaeSJenius  val nextlineStart  = UInt(VAddrBits.W)
71b92f8445Sssszwic  val ftqIdx         = new FtqPtr
72c5c5edaeSJenius  def crossCacheline = startAddr(blockOffBits - 1) === 1.U
73b004fa13SJenius  def fromFtqPcBundle(b: Ftq_RF_Components) = {
74b004fa13SJenius    this.startAddr     := b.startAddr
75b004fa13SJenius    this.nextlineStart := b.nextLineAddr
76b004fa13SJenius    this
77b004fa13SJenius  }
78f22cf846SJenius}
79f22cf846SJenius
8050780602SJeniusclass IFUICacheIO(implicit p: Parameters) extends XSBundle with HasICacheParameters {
8150780602SJenius  val icacheReady       = Output(Bool())
824690c88aSxu_zh  val resp              = ValidIO(new ICacheMainPipeResp)
83d2b20d1aSTang Haojin  val topdownIcacheMiss = Output(Bool())
84d2b20d1aSTang Haojin  val topdownItlbMiss   = Output(Bool())
8550780602SJenius}
8650780602SJenius
87f22cf846SJeniusclass FtqToICacheRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
88f56177cbSJenius  val pcMemRead        = Vec(5, new FtqICacheInfo)
89dc270d3bSJenius  val readValid        = Vec(5, Bool())
90fbdb359dSMuzi  val backendException = Bool()
91c5c5edaeSJenius}
92c5c5edaeSJenius
9309c6f1ddSLingrui98class PredecodeWritebackBundle(implicit p: Parameters) extends XSBundle {
9409c6f1ddSLingrui98  val pc         = Vec(PredictWidth, UInt(VAddrBits.W))
9509c6f1ddSLingrui98  val pd         = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode
9609c6f1ddSLingrui98  val ftqIdx     = new FtqPtr
9709c6f1ddSLingrui98  val ftqOffset  = UInt(log2Ceil(PredictWidth).W)
9809c6f1ddSLingrui98  val misOffset  = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
9909c6f1ddSLingrui98  val cfiOffset  = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
10009c6f1ddSLingrui98  val target     = UInt(VAddrBits.W)
10109c6f1ddSLingrui98  val jalTarget  = UInt(VAddrBits.W)
10209c6f1ddSLingrui98  val instrRange = Vec(PredictWidth, Bool())
10309c6f1ddSLingrui98}
10409c6f1ddSLingrui98
1051d1e6d4dSJeniusclass mmioCommitRead(implicit p: Parameters) extends XSBundle {
1061d1e6d4dSJenius  val mmioFtqPtr     = Output(new FtqPtr)
1071d1e6d4dSJenius  val mmioLastCommit = Input(Bool())
1081d1e6d4dSJenius}
1091d1e6d4dSJenius
1106b46af8dSMuziobject ExceptionType {
11188895b11Sxu_zh  def width: Int  = 2
1123642c22fSMuzi  def none:  UInt = "b00".U(width.W)
1133642c22fSMuzi  def pf:    UInt = "b01".U(width.W) // instruction page fault
1143642c22fSMuzi  def gpf:   UInt = "b10".U(width.W) // instruction guest page fault
1153642c22fSMuzi  def af:    UInt = "b11".U(width.W) // instruction access fault
11688895b11Sxu_zh
117fbdb359dSMuzi  def hasException(e: UInt):             Bool = e =/= none
118dd02bc3fSxu_zh  def hasException(e: Vec[UInt]):        Bool = e.map(_ =/= none).reduce(_ || _)
119dd02bc3fSxu_zh  def hasException(e: IndexedSeq[UInt]): Bool = hasException(VecInit(e))
120fbdb359dSMuzi
121c1b28b66STang Haojin  def fromOH(has_pf: Bool, has_gpf: Bool, has_af: Bool): UInt = {
122c1b28b66STang Haojin    assert(
123c1b28b66STang Haojin      PopCount(VecInit(has_pf, has_gpf, has_af)) <= 1.U,
124c1b28b66STang Haojin      "ExceptionType.fromOH receives input that is not one-hot: pf=%d, gpf=%d, af=%d",
125cf7d6b7aSMuzi      has_pf,
126cf7d6b7aSMuzi      has_gpf,
127cf7d6b7aSMuzi      has_af
128c1b28b66STang Haojin    )
129c1b28b66STang Haojin    // input is at-most-one-hot encoded, so we don't worry about priority here.
130cf7d6b7aSMuzi    MuxCase(
131cf7d6b7aSMuzi      none,
132cf7d6b7aSMuzi      Seq(
133c1b28b66STang Haojin        has_pf  -> pf,
134c1b28b66STang Haojin        has_gpf -> gpf,
135c1b28b66STang Haojin        has_af  -> af
136cf7d6b7aSMuzi      )
137cf7d6b7aSMuzi    )
138c1b28b66STang Haojin  }
139c1b28b66STang Haojin
14088895b11Sxu_zh  // raise pf/gpf/af according to itlb response
14188895b11Sxu_zh  def fromTlbResp(resp: TlbResp, useDup: Int = 0): UInt = {
14288895b11Sxu_zh    require(useDup >= 0 && useDup < resp.excp.length)
143c1b28b66STang Haojin    // itlb is guaranteed to respond at most one exception
144c1b28b66STang Haojin    fromOH(
145c1b28b66STang Haojin      resp.excp(useDup).pf.instr,
146c1b28b66STang Haojin      resp.excp(useDup).gpf.instr,
147c1b28b66STang Haojin      resp.excp(useDup).af.instr
14888895b11Sxu_zh    )
14988895b11Sxu_zh  }
15088895b11Sxu_zh
15188895b11Sxu_zh  // raise af if pmp check failed
152cf7d6b7aSMuzi  def fromPMPResp(resp: PMPRespBundle): UInt =
15388895b11Sxu_zh    Mux(resp.instr, af, none)
15488895b11Sxu_zh
15588895b11Sxu_zh  // raise af if meta/data array ecc check failed or l2 cache respond with tilelink corrupt
156f80535c3Sxu_zh  /* FIXME: RISC-V Machine ISA v1.13 (draft) introduced a "hardware error" exception, described as:
157f80535c3Sxu_zh   * > A Hardware Error exception is a synchronous exception triggered when corrupted or
158f80535c3Sxu_zh   * > uncorrectable data is accessed explicitly or implicitly by an instruction. In this context,
159f80535c3Sxu_zh   * > "data" encompasses all types of information used within a RISC-V hart. Upon a hardware
160f80535c3Sxu_zh   * > error exception, the xepc register is set to the address of the instruction that attempted to
161f80535c3Sxu_zh   * > access corrupted data, while the xtval register is set either to 0 or to the virtual address
162f80535c3Sxu_zh   * > of an instruction fetch, load, or store that attempted to access corrupted data. The priority
163f80535c3Sxu_zh   * > of Hardware Error exception is implementation-defined, but any given occurrence is
164f80535c3Sxu_zh   * > generally expected to be recognized at the point in the overall priority order at which the
165f80535c3Sxu_zh   * > hardware error is discovered.
166f80535c3Sxu_zh   * Maybe it's better to raise hardware error instead of access fault when ECC check failed.
167f80535c3Sxu_zh   * But it's draft and XiangShan backend does not implement this exception code yet, so we still raise af here.
168f80535c3Sxu_zh   */
169cf7d6b7aSMuzi  def fromECC(enable: Bool, corrupt: Bool): UInt =
170f80535c3Sxu_zh    Mux(enable && corrupt, af, none)
17188895b11Sxu_zh
172dfb03ba2Sxu_zh  def fromTilelink(corrupt: Bool): UInt =
173dfb03ba2Sxu_zh    Mux(corrupt, af, none)
174dfb03ba2Sxu_zh
17588895b11Sxu_zh  /**Generates exception mux tree
17688895b11Sxu_zh   *
17788895b11Sxu_zh   * Exceptions that are further to the left in the parameter list have higher priority
17888895b11Sxu_zh   * @example
17988895b11Sxu_zh   * {{{
18088895b11Sxu_zh   *   val itlb_exception = ExceptionType.fromTlbResp(io.itlb.resp.bits)
18188895b11Sxu_zh   *   // so as pmp_exception, meta_corrupt
18288895b11Sxu_zh   *   // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to:
18388895b11Sxu_zh   *   Mux(
18488895b11Sxu_zh   *     itlb_exception =/= none,
18588895b11Sxu_zh   *     itlb_exception,
18688895b11Sxu_zh   *     Mux(pmp_exception =/= none, pmp_exception, meta_corrupt)
18788895b11Sxu_zh   *   )
18888895b11Sxu_zh   * }}}
18988895b11Sxu_zh   */
19088895b11Sxu_zh  def merge(exceptions: UInt*): UInt = {
19188895b11Sxu_zh//    // recursively generate mux tree
19288895b11Sxu_zh//    if (exceptions.length == 1) {
19388895b11Sxu_zh//      require(exceptions.head.getWidth == width)
19488895b11Sxu_zh//      exceptions.head
19588895b11Sxu_zh//    } else {
19688895b11Sxu_zh//      Mux(exceptions.head =/= none, exceptions.head, merge(exceptions.tail: _*))
19788895b11Sxu_zh//    }
19888895b11Sxu_zh    // use MuxCase with default
19988895b11Sxu_zh    exceptions.foreach(e => require(e.getWidth == width))
20088895b11Sxu_zh    val mapping = exceptions.init.map(e => (e =/= none) -> e)
20188895b11Sxu_zh    val default = exceptions.last
20288895b11Sxu_zh    MuxCase(default, mapping)
20388895b11Sxu_zh  }
20488895b11Sxu_zh
20588895b11Sxu_zh  /**Generates exception mux tree for multi-port exception vectors
20688895b11Sxu_zh   *
20788895b11Sxu_zh   * Exceptions that are further to the left in the parameter list have higher priority
20888895b11Sxu_zh   * @example
20988895b11Sxu_zh   * {{{
21088895b11Sxu_zh   *   val itlb_exception = VecInit((0 until PortNumber).map(i => ExceptionType.fromTlbResp(io.itlb(i).resp.bits)))
21188895b11Sxu_zh   *   // so as pmp_exception, meta_corrupt
21288895b11Sxu_zh   *   // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to:
21388895b11Sxu_zh   *   VecInit((0 until PortNumber).map(i => Mux(
21488895b11Sxu_zh   *     itlb_exception(i) =/= none,
21588895b11Sxu_zh   *     itlb_exception(i),
21688895b11Sxu_zh   *     Mux(pmp_exception(i) =/= none, pmp_exception(i), meta_corrupt(i))
21788895b11Sxu_zh   *   ))
21888895b11Sxu_zh   * }}}
21988895b11Sxu_zh   */
22088895b11Sxu_zh  def merge(exceptionVecs: Vec[UInt]*): Vec[UInt] = {
22188895b11Sxu_zh//    // recursively generate mux tree
22288895b11Sxu_zh//    if (exceptionVecs.length == 1) {
22388895b11Sxu_zh//      exceptionVecs.head.foreach(e => require(e.getWidth == width))
22488895b11Sxu_zh//      exceptionVecs.head
22588895b11Sxu_zh//    } else {
22688895b11Sxu_zh//      require(exceptionVecs.head.length == exceptionVecs.last.length)
22788895b11Sxu_zh//      VecInit((exceptionVecs.head zip merge(exceptionVecs.tail: _*)).map{ case (high, low) =>
22888895b11Sxu_zh//        Mux(high =/= none, high, low)
22988895b11Sxu_zh//      })
23088895b11Sxu_zh//    }
23188895b11Sxu_zh    // merge port-by-port
23288895b11Sxu_zh    val length = exceptionVecs.head.length
23388895b11Sxu_zh    exceptionVecs.tail.foreach(vec => require(vec.length == length))
234cf7d6b7aSMuzi    VecInit((0 until length).map(i => merge(exceptionVecs.map(_(i)): _*)))
23588895b11Sxu_zh  }
2366b46af8dSMuzi}
2376b46af8dSMuzi
23809c6f1ddSLingrui98class FetchToIBuffer(implicit p: Parameters) extends XSBundle {
23909c6f1ddSLingrui98  val instrs           = Vec(PredictWidth, UInt(32.W))
24009c6f1ddSLingrui98  val valid            = UInt(PredictWidth.W)
2412a3050c2SJay  val enqEnable        = UInt(PredictWidth.W)
24209c6f1ddSLingrui98  val pd               = Vec(PredictWidth, new PreDecodeInfo)
24309c6f1ddSLingrui98  val foldpc           = Vec(PredictWidth, UInt(MemPredPCWidth.W))
24409c6f1ddSLingrui98  val ftqOffset        = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
245fbdb359dSMuzi  val backendException = Vec(PredictWidth, Bool())
2466b46af8dSMuzi  val exceptionType    = Vec(PredictWidth, UInt(ExceptionType.width.W))
24709c6f1ddSLingrui98  val crossPageIPFFix  = Vec(PredictWidth, Bool())
24892c61038SXuan Hu  val illegalInstr     = Vec(PredictWidth, Bool())
2497e0f64b0SGuanghui Cheng  val triggered        = Vec(PredictWidth, TriggerAction())
250948e8159SEaston Man  val isLastInFtqEntry = Vec(PredictWidth, Bool())
251948e8159SEaston Man
252948e8159SEaston Man  val pc           = Vec(PredictWidth, UInt(VAddrBits.W))
253*1592abd1SYan Xu  val debug_seqNum = Vec(PredictWidth, InstSeqNum())
254948e8159SEaston Man  val ftqPtr       = new FtqPtr
255d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
25609c6f1ddSLingrui98}
25709c6f1ddSLingrui98
258c2ad24ebSLingrui98// class BitWiseUInt(val width: Int, val init: UInt) extends Module {
259c2ad24ebSLingrui98//   val io = IO(new Bundle {
260c2ad24ebSLingrui98//     val set
261c2ad24ebSLingrui98//   })
262c2ad24ebSLingrui98// }
26309c6f1ddSLingrui98// Move from BPU
264c2ad24ebSLingrui98abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst {
265c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory
266c2ad24ebSLingrui98}
267c2ad24ebSLingrui98
268c2ad24ebSLingrui98class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory {
26909c6f1ddSLingrui98  val predHist = UInt(HistoryLength.W)
27009c6f1ddSLingrui98
271c2ad24ebSLingrui98  def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = {
272c2ad24ebSLingrui98    val g = Wire(new ShiftingGlobalHistory)
27309c6f1ddSLingrui98    g.predHist := (hist << shift) | taken
27409c6f1ddSLingrui98    g
27509c6f1ddSLingrui98  }
27609c6f1ddSLingrui98
277c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = {
278eeb5ff92SLingrui98    require(br_valids.length == numBr)
279eeb5ff92SLingrui98    require(real_taken_mask.length == numBr)
280eeb5ff92SLingrui98    val last_valid_idx = PriorityMux(
281eeb5ff92SLingrui98      br_valids.reverse :+ true.B,
282eeb5ff92SLingrui98      (numBr to 0 by -1).map(_.U(log2Ceil(numBr + 1).W))
283eeb5ff92SLingrui98    )
284eeb5ff92SLingrui98    val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask)
285cf7d6b7aSMuzi    val smaller         = Mux(last_valid_idx < first_taken_idx, last_valid_idx, first_taken_idx)
286eeb5ff92SLingrui98    val shift           = smaller
287eeb5ff92SLingrui98    val taken           = real_taken_mask.reduce(_ || _)
288eeb5ff92SLingrui98    update(shift, taken, this.predHist)
289eeb5ff92SLingrui98  }
290eeb5ff92SLingrui98
291c2ad24ebSLingrui98  // static read
292935edac4STang Haojin  def read(n: Int): Bool = predHist.asBools(n)
293c2ad24ebSLingrui98
294cf7d6b7aSMuzi  final def ===(that: ShiftingGlobalHistory): Bool =
29509c6f1ddSLingrui98    predHist === that.predHist
29609c6f1ddSLingrui98
297c2ad24ebSLingrui98  final def =/=(that: ShiftingGlobalHistory): Bool = !(this === that)
298c2ad24ebSLingrui98}
29909c6f1ddSLingrui98
300c2ad24ebSLingrui98// circular global history pointer
301cf7d6b7aSMuziclass CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr](p => p(XSCoreParamsKey).HistoryLength) {}
302c7fabd05SSteve Gou
303c7fabd05SSteve Gouobject CGHPtr {
304c7fabd05SSteve Gou  def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = {
305c7fabd05SSteve Gou    val ptr = Wire(new CGHPtr)
306c7fabd05SSteve Gou    ptr.flag  := f
307c7fabd05SSteve Gou    ptr.value := v
308c7fabd05SSteve Gou    ptr
309c7fabd05SSteve Gou  }
310cf7d6b7aSMuzi  def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr =
311c7fabd05SSteve Gou    apply(!ptr.flag, ptr.value)
312c7fabd05SSteve Gou}
313c7fabd05SSteve Gou
314c2ad24ebSLingrui98class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory {
315c2ad24ebSLingrui98  val buffer = Vec(HistoryLength, Bool())
316c2ad24ebSLingrui98  type HistPtr = UInt
317cf7d6b7aSMuzi  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory =
318c2ad24ebSLingrui98    this
319c2ad24ebSLingrui98}
320c2ad24ebSLingrui98
321dd6c0695SLingrui98class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters)
322c2ad24ebSLingrui98    extends XSBundle with HasBPUConst {
323dd6c0695SLingrui98  require(compLen >= 1)
324c2ad24ebSLingrui98  require(len > 0)
325c2ad24ebSLingrui98  // require(folded_len <= len)
326dd6c0695SLingrui98  require(compLen >= max_update_num)
327dd6c0695SLingrui98  val folded_hist = UInt(compLen.W)
328dd6c0695SLingrui98
32967402d75SLingrui98  def need_oldest_bits           = len > compLen
330dd6c0695SLingrui98  def info                       = (len, compLen)
331c2ad24ebSLingrui98  def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1)
332c2ad24ebSLingrui98  def oldest_bit_pos_in_folded   = oldest_bit_to_get_from_ghr map (_ % compLen)
333c2ad24ebSLingrui98  def oldest_bit_wrap_around     = oldest_bit_to_get_from_ghr map (_ / compLen > 0)
334c2ad24ebSLingrui98  def oldest_bit_start           = oldest_bit_pos_in_folded.head
335c2ad24ebSLingrui98
336cf7d6b7aSMuzi  def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) =
337c2ad24ebSLingrui98    // TODO: wrap inc for histPtr value
338dd6c0695SLingrui98    oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i + 1).U).value))
339c2ad24ebSLingrui98
340ab890bfeSLingrui98  def circular_shift_left(src: UInt, shamt: Int) = {
341c2ad24ebSLingrui98    val srcLen      = src.getWidth
342c2ad24ebSLingrui98    val src_doubled = Cat(src, src)
343ab890bfeSLingrui98    val shifted     = src_doubled(srcLen * 2 - 1 - shamt, srcLen - shamt)
344ab890bfeSLingrui98    shifted
345c2ad24ebSLingrui98  }
346c2ad24ebSLingrui98
34767402d75SLingrui98  // slow path, read bits from ghr
348ab890bfeSLingrui98  def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = {
34967402d75SLingrui98    val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr))
35067402d75SLingrui98    update(oldest_bits, num, taken)
35167402d75SLingrui98  }
35267402d75SLingrui98
35367402d75SLingrui98  // fast path, use pre-read oldest bits
35467402d75SLingrui98  def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = {
355c2ad24ebSLingrui98    // do xors for several bitsets at specified bits
356c2ad24ebSLingrui98    def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = {
357c2ad24ebSLingrui98      val res = Wire(Vec(len, Bool()))
358c2ad24ebSLingrui98      // println(f"num bitsets: ${bitsets.length}")
359c2ad24ebSLingrui98      // println(f"bitsets $bitsets")
360c2ad24ebSLingrui98      val resArr = Array.fill(len)(List[Bool]())
361c2ad24ebSLingrui98      for (bs <- bitsets) {
362c2ad24ebSLingrui98        for ((n, b) <- bs) {
363c2ad24ebSLingrui98          resArr(n) = b :: resArr(n)
364c2ad24ebSLingrui98        }
365c2ad24ebSLingrui98      }
366c2ad24ebSLingrui98      // println(f"${resArr.mkString}")
367c2ad24ebSLingrui98      // println(f"histLen: ${this.len}, foldedLen: $folded_len")
368c2ad24ebSLingrui98      for (i <- 0 until len) {
369c2ad24ebSLingrui98        // println(f"bit[$i], ${resArr(i).mkString}")
370c2ad24ebSLingrui98        if (resArr(i).length == 0) {
371dd6c0695SLingrui98          println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen")
372c2ad24ebSLingrui98        }
373c2ad24ebSLingrui98        res(i) := resArr(i).foldLeft(false.B)(_ ^ _)
374c2ad24ebSLingrui98      }
375c2ad24ebSLingrui98      res.asUInt
376c2ad24ebSLingrui98    }
377c2ad24ebSLingrui98
37867402d75SLingrui98    val new_folded_hist = if (need_oldest_bits) {
37967402d75SLingrui98      val oldest_bits = ob
38067402d75SLingrui98      require(oldest_bits.length == max_update_num)
381c2ad24ebSLingrui98      // mask off bits that do not update
382c2ad24ebSLingrui98      val oldest_bits_masked = oldest_bits.zipWithIndex.map {
383ab890bfeSLingrui98        case (ob, i) => ob && (i < num).B
384c2ad24ebSLingrui98      }
385c2ad24ebSLingrui98      // if a bit does not wrap around, it should not be xored when it exits
386cf7d6b7aSMuzi      val oldest_bits_set = (0 until max_update_num).filter(oldest_bit_wrap_around).map(i =>
387cf7d6b7aSMuzi        (oldest_bit_pos_in_folded(i), oldest_bits_masked(i))
388cf7d6b7aSMuzi      )
389c2ad24ebSLingrui98
390c2ad24ebSLingrui98      // println(f"old bits pos ${oldest_bits_set.map(_._1)}")
391c2ad24ebSLingrui98
392c2ad24ebSLingrui98      // only the last bit could be 1, as we have at most one taken branch at a time
393ab890bfeSLingrui98      val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i + 1) == num).B)).asUInt
394c2ad24ebSLingrui98      // if a bit does not wrap around, newest bits should not be xored onto it either
395e992912cSLingrui98      val newest_bits_set = (0 until max_update_num).map(i => (compLen - 1 - i, newest_bits_masked(i)))
396c2ad24ebSLingrui98
397c2ad24ebSLingrui98      // println(f"new bits set ${newest_bits_set.map(_._1)}")
398c2ad24ebSLingrui98      //
399c2ad24ebSLingrui98      val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map {
400ab890bfeSLingrui98        case (fb, i) => fb && !(num >= (len - i)).B
401c2ad24ebSLingrui98      })
402c2ad24ebSLingrui98      val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i)))
403c2ad24ebSLingrui98
404c2ad24ebSLingrui98      // do xor then shift
405c2ad24ebSLingrui98      val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set))
406ab890bfeSLingrui98      circular_shift_left(xored, num)
40767402d75SLingrui98    } else {
40867402d75SLingrui98      // histLen too short to wrap around
40967402d75SLingrui98      ((folded_hist << num) | taken)(compLen - 1, 0)
410c2ad24ebSLingrui98    }
41167402d75SLingrui98
412c2ad24ebSLingrui98    val fh = WireInit(this)
413c2ad24ebSLingrui98    fh.folded_hist := new_folded_hist
414c2ad24ebSLingrui98    fh
415c2ad24ebSLingrui98  }
41609c6f1ddSLingrui98}
41709c6f1ddSLingrui98
41867402d75SLingrui98class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle {
41967402d75SLingrui98  val bits = Vec(max_update_num * 2, Bool())
42067402d75SLingrui98  // def info = (len, compLen)
42167402d75SLingrui98  def getRealOb(brNumOH: UInt): Vec[Bool] = {
42267402d75SLingrui98    val ob = Wire(Vec(max_update_num, Bool()))
42367402d75SLingrui98    for (i <- 0 until max_update_num) {
42467402d75SLingrui98      ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr + 1))
42567402d75SLingrui98    }
42667402d75SLingrui98    ob
42767402d75SLingrui98  }
42867402d75SLingrui98}
42967402d75SLingrui98
430cf7d6b7aSMuziclass AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle
431cf7d6b7aSMuzi    with HasBPUConst {
432cf7d6b7aSMuzi  val afhob = MixedVec(gen.filter(t => t._1 > t._2).map(_._1)
43367402d75SLingrui98    .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates
43467402d75SLingrui98  require(gen.toSet.toList.equals(gen))
43567402d75SLingrui98  def getObWithInfo(info: Tuple2[Int, Int]) = {
43667402d75SLingrui98    val selected = afhob.filter(_.len == info._1)
43767402d75SLingrui98    require(selected.length == 1)
43867402d75SLingrui98    selected(0)
43967402d75SLingrui98  }
44067402d75SLingrui98  def read(ghv: Vec[Bool], ptr: CGHPtr) = {
44167402d75SLingrui98    val hisLens      = afhob.map(_.len)
44267402d75SLingrui98    val bitsToRead   = hisLens.flatMap(l => (0 until numBr * 2).map(i => l - i - 1)).toSet // remove duplicates
44367402d75SLingrui98    val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr + (pos + 1).U).value)))
44467402d75SLingrui98    for (ob <- afhob) {
44567402d75SLingrui98      for (i <- 0 until numBr * 2) {
44667402d75SLingrui98        val pos       = ob.len - i - 1
44767402d75SLingrui98        val bit_found = bitsWithInfo.filter(_._1 == pos).toList
44867402d75SLingrui98        require(bit_found.length == 1)
44967402d75SLingrui98        ob.bits(i) := bit_found(0)._2
45067402d75SLingrui98      }
45167402d75SLingrui98    }
45267402d75SLingrui98  }
45367402d75SLingrui98}
45467402d75SLingrui98
45567402d75SLingrui98class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
45667402d75SLingrui98  val hist = MixedVec(gen.map { case (l, cl) => new FoldedHistory(l, cl, numBr) })
45767402d75SLingrui98  // println(gen.mkString)
45867402d75SLingrui98  require(gen.toSet.toList.equals(gen))
45967402d75SLingrui98  def getHistWithInfo(info: Tuple2[Int, Int]) = {
46067402d75SLingrui98    val selected = hist.filter(_.info.equals(info))
46167402d75SLingrui98    require(selected.length == 1)
46267402d75SLingrui98    selected(0)
46367402d75SLingrui98  }
46467402d75SLingrui98  def autoConnectFrom(that: AllFoldedHistories) = {
46567402d75SLingrui98    require(this.hist.length <= that.hist.length)
46667402d75SLingrui98    for (h <- this.hist) {
46767402d75SLingrui98      h := that.getHistWithInfo(h.info)
46867402d75SLingrui98    }
46967402d75SLingrui98  }
47067402d75SLingrui98  def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = {
47167402d75SLingrui98    val res = WireInit(this)
47267402d75SLingrui98    for (i <- 0 until this.hist.length) {
47367402d75SLingrui98      res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken)
47467402d75SLingrui98    }
47567402d75SLingrui98    res
47667402d75SLingrui98  }
47767402d75SLingrui98  def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = {
47867402d75SLingrui98    val res = WireInit(this)
47967402d75SLingrui98    for (i <- 0 until this.hist.length) {
48067402d75SLingrui98      val fh = this.hist(i)
48167402d75SLingrui98      if (fh.need_oldest_bits) {
48267402d75SLingrui98        val info          = fh.info
48367402d75SLingrui98        val selectedAfhob = afhob.getObWithInfo(info)
48467402d75SLingrui98        val ob            = selectedAfhob.getRealOb(lastBrNumOH)
48567402d75SLingrui98        res.hist(i) := this.hist(i).update(ob, shift, taken)
48667402d75SLingrui98      } else {
48767402d75SLingrui98        val dumb = Wire(Vec(numBr, Bool())) // not needed
48867402d75SLingrui98        dumb        := DontCare
48967402d75SLingrui98        res.hist(i) := this.hist(i).update(dumb, shift, taken)
49067402d75SLingrui98      }
49167402d75SLingrui98    }
49267402d75SLingrui98    res
49367402d75SLingrui98  }
49467402d75SLingrui98
495cf7d6b7aSMuzi  def display(cond: Bool) =
49667402d75SLingrui98    for (h <- hist) {
49767402d75SLingrui98      XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n")
49867402d75SLingrui98    }
49967402d75SLingrui98}
50067402d75SLingrui98
50109c6f1ddSLingrui98class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle {
50209c6f1ddSLingrui98  def tagBits = VAddrBits - idxBits - instOffsetBits
50309c6f1ddSLingrui98
50409c6f1ddSLingrui98  val tag    = UInt(tagBits.W)
50509c6f1ddSLingrui98  val idx    = UInt(idxBits.W)
50609c6f1ddSLingrui98  val offset = UInt(instOffsetBits.W)
50709c6f1ddSLingrui98
50809c6f1ddSLingrui98  def fromUInt(x:   UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
50909c6f1ddSLingrui98  def getTag(x:     UInt) = fromUInt(x).tag
51009c6f1ddSLingrui98  def getIdx(x:     UInt) = fromUInt(x).idx
51109c6f1ddSLingrui98  def getBank(x:    UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U
51209c6f1ddSLingrui98  def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x)
51309c6f1ddSLingrui98}
514eeb5ff92SLingrui98
515b37e4b45SLingrui98trait BasicPrediction extends HasXSParameter {
516b37e4b45SLingrui98  def cfiIndex: ValidUndirectioned[UInt]
517b37e4b45SLingrui98  def target(pc: UInt): UInt
518b37e4b45SLingrui98  def lastBrPosOH:    Vec[Bool]
519b37e4b45SLingrui98  def brTaken:        Bool
520b37e4b45SLingrui98  def shouldShiftVec: Vec[Bool]
521b37e4b45SLingrui98  def fallThruError:  Bool
522b37e4b45SLingrui98}
523935edac4STang Haojin
524b166c0eaSEaston Man// selectByTaken selects some data according to takenMask
5252bf6e0ecSEaston Man// allTargets should be in a Vec, like [taken0, taken1, ..., not taken, not hit]
526b166c0eaSEaston Manobject selectByTaken {
527b166c0eaSEaston Man  def apply[T <: Data](takenMask: Vec[Bool], hit: Bool, allTargets: Vec[T]): T = {
528b166c0eaSEaston Man    val selVecOH =
529cf7d6b7aSMuzi      takenMask.zipWithIndex.map { case (t, i) =>
530cf7d6b7aSMuzi        !takenMask.take(i).fold(false.B)(_ || _) && t && hit
531cf7d6b7aSMuzi      } :+
532b166c0eaSEaston Man        (!takenMask.asUInt.orR && hit) :+ !hit
533b166c0eaSEaston Man    Mux1H(selVecOH, allTargets)
534b166c0eaSEaston Man  }
535b166c0eaSEaston Man}
536b166c0eaSEaston Man
537cf7d6b7aSMuziclass FullBranchPrediction(val isNotS3: Boolean)(implicit p: Parameters) extends XSBundle with HasBPUConst
538cf7d6b7aSMuzi    with BasicPrediction {
539eeb5ff92SLingrui98  val br_taken_mask = Vec(numBr, Bool())
54009c6f1ddSLingrui98
541eeb5ff92SLingrui98  val slot_valids = Vec(totalSlot, Bool())
54209c6f1ddSLingrui98
543eeb5ff92SLingrui98  val targets         = Vec(totalSlot, UInt(VAddrBits.W))
544b30c10d6SLingrui98  val jalr_target     = UInt(VAddrBits.W) // special path for indirect predictors
545a229ab6cSLingrui98  val offsets         = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W))
546a229ab6cSLingrui98  val fallThroughAddr = UInt(VAddrBits.W)
547b37e4b45SLingrui98  val fallThroughErr  = Bool()
548fd3aa057SYuandongliang  val multiHit        = Bool()
54909c6f1ddSLingrui98
55009c6f1ddSLingrui98  val is_jal               = Bool()
55109c6f1ddSLingrui98  val is_jalr              = Bool()
55209c6f1ddSLingrui98  val is_call              = Bool()
55309c6f1ddSLingrui98  val is_ret               = Bool()
554f4ebc4b2SLingrui98  val last_may_be_rvi_call = Bool()
555eeb5ff92SLingrui98  val is_br_sharing        = Bool()
55609c6f1ddSLingrui98
55709c6f1ddSLingrui98  // val call_is_rvc = Bool()
55809c6f1ddSLingrui98  val hit = Bool()
55909c6f1ddSLingrui98
560209a4cafSSteve Gou  val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
561209a4cafSSteve Gou
562eeb5ff92SLingrui98  def br_slot_valids  = slot_valids.init
563eeb5ff92SLingrui98  def tail_slot_valid = slot_valids.last
564eeb5ff92SLingrui98
565cf7d6b7aSMuzi  def br_valids =
566b37e4b45SLingrui98    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
567eeb5ff92SLingrui98
568cf7d6b7aSMuzi  def taken_mask_on_slot =
569eeb5ff92SLingrui98    VecInit(
570eeb5ff92SLingrui98      (br_slot_valids zip br_taken_mask.init).map { case (t, v) => t && v } :+ (
571b30c10d6SLingrui98        tail_slot_valid && (
572b30c10d6SLingrui98          is_br_sharing && br_taken_mask.last || !is_br_sharing
573b30c10d6SLingrui98        )
574eeb5ff92SLingrui98      )
575eeb5ff92SLingrui98    )
576eeb5ff92SLingrui98
577cf7d6b7aSMuzi  def real_slot_taken_mask(): Vec[Bool] =
578b37e4b45SLingrui98    VecInit(taken_mask_on_slot.map(_ && hit))
579b37e4b45SLingrui98
580b37e4b45SLingrui98  // len numBr
581cf7d6b7aSMuzi  def real_br_taken_mask(): Vec[Bool] =
582b37e4b45SLingrui98    VecInit(
583b37e4b45SLingrui98      taken_mask_on_slot.map(_ && hit).init :+
584b37e4b45SLingrui98        (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
585b37e4b45SLingrui98    )
586b37e4b45SLingrui98
587b37e4b45SLingrui98  // the vec indicating if ghr should shift on each branch
588b37e4b45SLingrui98  def shouldShiftVec =
589b37e4b45SLingrui98    VecInit(br_valids.zipWithIndex.map { case (v, i) =>
590cf7d6b7aSMuzi      v && hit && !real_br_taken_mask().take(i).reduceOption(_ || _).getOrElse(false.B)
591cf7d6b7aSMuzi    })
592b37e4b45SLingrui98
593b37e4b45SLingrui98  def lastBrPosOH =
594b37e4b45SLingrui98    VecInit((!hit || !br_valids.reduce(_ || _)) +: // not hit or no brs in entry
595b37e4b45SLingrui98      (0 until numBr).map(i =>
596b37e4b45SLingrui98        br_valids(i) &&
597e3da8badSTang Haojin          !real_br_taken_mask().take(i).reduceOption(_ || _).getOrElse(false.B) && // no brs taken in front it
598cf7d6b7aSMuzi          (real_br_taken_mask()(i) || !br_valids.drop(i + 1).reduceOption(_ || _).getOrElse(
599cf7d6b7aSMuzi            false.B
600cf7d6b7aSMuzi          )) && // no brs behind it
601b37e4b45SLingrui98          hit
602cf7d6b7aSMuzi      ))
603b37e4b45SLingrui98
60486d9c530SLingrui98  def brTaken = (br_valids zip br_taken_mask).map { case (a, b) => a && b && hit }.reduce(_ || _)
605b37e4b45SLingrui98
606cf7d6b7aSMuzi  def target(pc: UInt): UInt =
607c6a44c35Smy-mayfly    if (isNotS3) {
608b166c0eaSEaston Man      selectByTaken(taken_mask_on_slot, hit, allTarget(pc))
609c6a44c35Smy-mayfly    } else {
610c6a44c35Smy-mayfly      selectByTaken(taken_mask_on_slot, hit && !fallThroughErr, allTarget(pc))
611c6a44c35Smy-mayfly    }
612b166c0eaSEaston Man
6132bf6e0ecSEaston Man  // allTarget return a Vec of all possible target of a BP stage
6142bf6e0ecSEaston Man  // in the following order: [taken_target0, taken_target1, ..., fallThroughAddr, not hit (plus fetch width)]
615b166c0eaSEaston Man  //
616b166c0eaSEaston Man  // This exposes internal targets for timing optimization,
617b166c0eaSEaston Man  // since usually targets are generated quicker than taken
618cf7d6b7aSMuzi  def allTarget(pc: UInt): Vec[UInt] =
619b166c0eaSEaston Man    VecInit(targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U))
620b37e4b45SLingrui98
621b37e4b45SLingrui98  def fallThruError: Bool = hit && fallThroughErr
622fd3aa057SYuandongliang  def ftbMultiHit:   Bool = hit && multiHit
623b37e4b45SLingrui98
624b37e4b45SLingrui98  def hit_taken_on_jmp =
625b37e4b45SLingrui98    !real_slot_taken_mask().init.reduce(_ || _) &&
626b37e4b45SLingrui98      real_slot_taken_mask().last && !is_br_sharing
627b37e4b45SLingrui98  def hit_taken_on_call = hit_taken_on_jmp && is_call
628b37e4b45SLingrui98  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
629b37e4b45SLingrui98  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
630b37e4b45SLingrui98
631b37e4b45SLingrui98  def cfiIndex = {
632b37e4b45SLingrui98    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
633b37e4b45SLingrui98    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
634b37e4b45SLingrui98    // when no takens, set cfiIndex to PredictWidth-1
635b37e4b45SLingrui98    cfiIndex.bits :=
636b37e4b45SLingrui98      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
637b37e4b45SLingrui98        Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
638b37e4b45SLingrui98    cfiIndex
639b37e4b45SLingrui98  }
640b37e4b45SLingrui98
641eeb5ff92SLingrui98  def taken = br_taken_mask.reduce(_ || _) || slot_valids.last // || (is_jal || is_jalr)
64209c6f1ddSLingrui98
64347c003a9SEaston Man  def fromFtbEntry(
64447c003a9SEaston Man      entry:            FTBEntry,
64547c003a9SEaston Man      pc:               UInt,
64647c003a9SEaston Man      last_stage_pc:    Option[Tuple2[UInt, Bool]] = None,
64747c003a9SEaston Man      last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None
64847c003a9SEaston Man  ) = {
649eeb5ff92SLingrui98    slot_valids          := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
65047c003a9SEaston Man    targets              := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing
651b30c10d6SLingrui98    jalr_target          := targets.last
652a229ab6cSLingrui98    offsets              := entry.getOffsetVec
653eeb5ff92SLingrui98    is_jal               := entry.tailSlot.valid && entry.isJal
654eeb5ff92SLingrui98    is_jalr              := entry.tailSlot.valid && entry.isJalr
655eeb5ff92SLingrui98    is_call              := entry.tailSlot.valid && entry.isCall
656eeb5ff92SLingrui98    is_ret               := entry.tailSlot.valid && entry.isRet
657f4ebc4b2SLingrui98    last_may_be_rvi_call := entry.last_may_be_rvi_call
658eeb5ff92SLingrui98    is_br_sharing        := entry.tailSlot.valid && entry.tailSlot.sharing
659209a4cafSSteve Gou    predCycle.map(_ := GTimer())
660a229ab6cSLingrui98
661a60a2901SLingrui98    val startLower        = Cat(0.U(1.W), pc(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
662b37e4b45SLingrui98    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
663cf7d6b7aSMuzi    fallThroughErr  := startLower >= endLowerwithCarry || endLowerwithCarry > (startLower + PredictWidth.U)
66447c003a9SEaston Man    fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry))
665a229ab6cSLingrui98  }
66609c6f1ddSLingrui98
667cf7d6b7aSMuzi  def display(cond: Bool): Unit =
668eeb5ff92SLingrui98    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
66909c6f1ddSLingrui98}
67009c6f1ddSLingrui98
671803124a6SLingrui98class SpeculativeInfo(implicit p: Parameters) extends XSBundle
672803124a6SLingrui98    with HasBPUConst with BPUUtils {
673803124a6SLingrui98  val histPtr = new CGHPtr
674c89b4642SGuokai Chen  val ssp     = UInt(log2Up(RasSize).W)
675deb3a97eSGao-Zeyu  val sctr    = UInt(RasCtrSize.W)
676c89b4642SGuokai Chen  val TOSW    = new RASPtr
677c89b4642SGuokai Chen  val TOSR    = new RASPtr
678c89b4642SGuokai Chen  val NOS     = new RASPtr
679c89b4642SGuokai Chen  val topAddr = UInt(VAddrBits.W)
680803124a6SLingrui98}
681803124a6SLingrui98
682c6a44c35Smy-mayfly//
683c6a44c35Smy-mayflyclass BranchPredictionBundle(val isNotS3: Boolean)(implicit p: Parameters) extends XSBundle
684b37e4b45SLingrui98    with HasBPUConst with BPUUtils {
685adc0b8dfSGuokai Chen  val pc          = Vec(numDup, UInt(VAddrBits.W))
686adc0b8dfSGuokai Chen  val valid       = Vec(numDup, Bool())
687adc0b8dfSGuokai Chen  val hasRedirect = Vec(numDup, Bool())
68809c6f1ddSLingrui98  val ftq_idx     = new FtqPtr
689c6a44c35Smy-mayfly  val full_pred   = Vec(numDup, new FullBranchPrediction(isNotS3))
690b37e4b45SLingrui98
691adc0b8dfSGuokai Chen  def target(pc:     UInt)      = VecInit(full_pred.map(_.target(pc)))
692b166c0eaSEaston Man  def targets(pc:    Vec[UInt]) = VecInit(pc.zipWithIndex.map { case (pc, idx) => full_pred(idx).target(pc) })
693b166c0eaSEaston Man  def allTargets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map { case (pc, idx) => full_pred(idx).allTarget(pc) })
694adc0b8dfSGuokai Chen  def cfiIndex       = VecInit(full_pred.map(_.cfiIndex))
695adc0b8dfSGuokai Chen  def lastBrPosOH    = VecInit(full_pred.map(_.lastBrPosOH))
696adc0b8dfSGuokai Chen  def brTaken        = VecInit(full_pred.map(_.brTaken))
697adc0b8dfSGuokai Chen  def shouldShiftVec = VecInit(full_pred.map(_.shouldShiftVec))
698adc0b8dfSGuokai Chen  def fallThruError  = VecInit(full_pred.map(_.fallThruError))
699fd3aa057SYuandongliang  def ftbMultiHit    = VecInit(full_pred.map(_.ftbMultiHit))
700eeb5ff92SLingrui98
701adc0b8dfSGuokai Chen  def taken = VecInit(cfiIndex.map(_.valid))
702adc0b8dfSGuokai Chen
703adc0b8dfSGuokai Chen  def getTarget     = targets(pc)
704b166c0eaSEaston Man  def getAllTargets = allTargets(pc)
70509c6f1ddSLingrui98
70609c6f1ddSLingrui98  def display(cond: Bool): Unit = {
707adc0b8dfSGuokai Chen    XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n")
708adc0b8dfSGuokai Chen    full_pred(0).display(cond)
70909c6f1ddSLingrui98  }
71009c6f1ddSLingrui98}
71109c6f1ddSLingrui98
71209c6f1ddSLingrui98class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
713c6a44c35Smy-mayfly  val s1 = new BranchPredictionBundle(isNotS3 = true)
714c6a44c35Smy-mayfly  val s2 = new BranchPredictionBundle(isNotS3 = true)
715c6a44c35Smy-mayfly  val s3 = new BranchPredictionBundle(isNotS3 = false)
71609c6f1ddSLingrui98
717c4a59f19SYuandongliang  val s1_uftbHit         = Bool()
718c4a59f19SYuandongliang  val s1_uftbHasIndirect = Bool()
719c4a59f19SYuandongliang  val s1_ftbCloseReq     = Bool()
720c4a59f19SYuandongliang
721c2d1ec7dSLingrui98  val last_stage_meta      = UInt(MaxMetaLength.W)
7223711cf36S小造xu_zh  val last_stage_spec_info = new Ftq_Redirect_SRAMEntry
723c2d1ec7dSLingrui98  val last_stage_ftb_entry = new FTBEntry
724c2d1ec7dSLingrui98
725d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
726d2b20d1aSTang Haojin
727b37e4b45SLingrui98  def selectedResp = {
728b37e4b45SLingrui98    val res =
72909c6f1ddSLingrui98      PriorityMux(Seq(
730cf7d6b7aSMuzi        (s3.valid(3) && s3.hasRedirect(3)) -> s3,
731cf7d6b7aSMuzi        (s2.valid(3) && s2.hasRedirect(3)) -> s2,
732cf7d6b7aSMuzi        s1.valid(3)                        -> s1
73309c6f1ddSLingrui98      ))
734b37e4b45SLingrui98    res
735b37e4b45SLingrui98  }
736adc0b8dfSGuokai Chen  def selectedRespIdxForFtq =
73709c6f1ddSLingrui98    PriorityMux(Seq(
738cf7d6b7aSMuzi      (s3.valid(3) && s3.hasRedirect(3)) -> BP_S3,
739cf7d6b7aSMuzi      (s2.valid(3) && s2.hasRedirect(3)) -> BP_S2,
740cf7d6b7aSMuzi      s1.valid(3)                        -> BP_S1
74109c6f1ddSLingrui98    ))
742cb4f77ceSLingrui98  def lastStage = s3
74309c6f1ddSLingrui98}
74409c6f1ddSLingrui98
745c2d1ec7dSLingrui98class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {}
74609c6f1ddSLingrui98
747803124a6SLingrui98class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst {
748803124a6SLingrui98  val pc        = UInt(VAddrBits.W)
749803124a6SLingrui98  val spec_info = new SpeculativeInfo
750803124a6SLingrui98  val ftb_entry = new FTBEntry()
751803124a6SLingrui98
752803124a6SLingrui98  val cfi_idx           = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
753803124a6SLingrui98  val br_taken_mask     = Vec(numBr, Bool())
754cc2d1573SEaston Man  val br_committed      = Vec(numBr, Bool()) // High only when br valid && br committed
755803124a6SLingrui98  val jmp_taken         = Bool()
75609c6f1ddSLingrui98  val mispred_mask      = Vec(numBr + 1, Bool())
757edc18578SLingrui98  val pred_hit          = Bool()
75809c6f1ddSLingrui98  val false_hit         = Bool()
75909c6f1ddSLingrui98  val new_br_insert_pos = Vec(numBr, Bool())
76009c6f1ddSLingrui98  val old_entry         = Bool()
76109c6f1ddSLingrui98  val meta              = UInt(MaxMetaLength.W)
762abdbe4b7SLingrui98  val full_target       = UInt(VAddrBits.W)
763edc18578SLingrui98  val from_stage        = UInt(2.W)
76486d9c530SLingrui98  val ghist             = UInt(HistoryLength.W)
76509c6f1ddSLingrui98
766803124a6SLingrui98  def is_jal  = ftb_entry.tailSlot.valid && ftb_entry.isJal
767803124a6SLingrui98  def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr
768803124a6SLingrui98  def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall
769803124a6SLingrui98  def is_ret  = ftb_entry.tailSlot.valid && ftb_entry.isRet
770803124a6SLingrui98
771c89b4642SGuokai Chen  def is_call_taken = is_call && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset
772c89b4642SGuokai Chen  def is_ret_taken  = is_ret && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset
773c89b4642SGuokai Chen
774803124a6SLingrui98  def display(cond: Bool) = {
77509c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
77609c6f1ddSLingrui98    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
77709c6f1ddSLingrui98    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
77809c6f1ddSLingrui98    XSDebug(cond, p"--------------------------------------------\n")
77909c6f1ddSLingrui98  }
78009c6f1ddSLingrui98}
78109c6f1ddSLingrui98
78209c6f1ddSLingrui98class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
78309c6f1ddSLingrui98  // override def toPrintable: Printable = {
78409c6f1ddSLingrui98  //   p"-----------BranchPredictionRedirect----------- " +
78509c6f1ddSLingrui98  //     p"-----------cfiUpdate----------- " +
78609c6f1ddSLingrui98  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
78709c6f1ddSLingrui98  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
78809c6f1ddSLingrui98  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
78909c6f1ddSLingrui98  //     p"------------------------------- " +
7909aca92b9SYinan Xu  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
79109c6f1ddSLingrui98  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
79209c6f1ddSLingrui98  //     p"[ftqOffset] ${ftqOffset} " +
79309c6f1ddSLingrui98  //     p"[level] ${level}, [interrupt] ${interrupt} " +
79409c6f1ddSLingrui98  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
79509c6f1ddSLingrui98  //     p"[stFtqOffset] ${stFtqOffset} " +
79609c6f1ddSLingrui98  //     p"\n"
79709c6f1ddSLingrui98
79809c6f1ddSLingrui98  // }
79909c6f1ddSLingrui98
800d2b20d1aSTang Haojin  // TODO: backend should pass topdown signals here
801d2b20d1aSTang Haojin  // must not change its parent since BPU has used asTypeOf(this type) from its parent class
802d2b20d1aSTang Haojin  require(isInstanceOf[Redirect])
803d2b20d1aSTang Haojin  val BTBMissBubble         = Bool()
804d2b20d1aSTang Haojin  def ControlRedirectBubble = debugIsCtrl
805d2b20d1aSTang Haojin  // if mispred br not in ftb, count as BTB miss
806d2b20d1aSTang Haojin  def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit
807d2b20d1aSTang Haojin  def TAGEMissBubble       = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit
808d2b20d1aSTang Haojin  def SCMissBubble         = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit
809d2b20d1aSTang Haojin  def ITTAGEMissBubble     = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet
810d2b20d1aSTang Haojin  def RASMissBubble        = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet
811d2b20d1aSTang Haojin  def MemVioRedirectBubble = debugIsMemVio
812d2b20d1aSTang Haojin  def OtherRedirectBubble  = !debugIsCtrl && !debugIsMemVio
813d2b20d1aSTang Haojin
814cf7d6b7aSMuzi  def connectRedirect(source: Redirect): Unit =
815d2b20d1aSTang Haojin    for ((name, data) <- this.elements) {
816d2b20d1aSTang Haojin      if (source.elements.contains(name)) {
817d2b20d1aSTang Haojin        data := source.elements(name)
818d2b20d1aSTang Haojin      }
819d2b20d1aSTang Haojin    }
820d2b20d1aSTang Haojin
82109c6f1ddSLingrui98  def display(cond: Bool): Unit = {
82209c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
82309c6f1ddSLingrui98    XSDebug(cond, p"-----------cfiUpdate----------- \n")
82409c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
825c2ad24ebSLingrui98    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
82609c6f1ddSLingrui98    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
827cf7d6b7aSMuzi    XSDebug(
828cf7d6b7aSMuzi      cond,
829cf7d6b7aSMuzi      p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n"
830cf7d6b7aSMuzi    )
83109c6f1ddSLingrui98    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
83209c6f1ddSLingrui98    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
83309c6f1ddSLingrui98    XSDebug(cond, p"------------------------------- \n")
8349aca92b9SYinan Xu    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
83509c6f1ddSLingrui98    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
83609c6f1ddSLingrui98    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
83709c6f1ddSLingrui98    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
83809c6f1ddSLingrui98    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
83909c6f1ddSLingrui98    XSDebug(cond, p"---------------------------------------------- \n")
84009c6f1ddSLingrui98  }
84109c6f1ddSLingrui98}
842