xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision deb3a97e58d721e6a26af0a95252e2bc60838d10)
109c6f1ddSLingrui98/***************************************************************************************
209c6f1ddSLingrui98* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
309c6f1ddSLingrui98* Copyright (c) 2020-2021 Peng Cheng Laboratory
409c6f1ddSLingrui98*
509c6f1ddSLingrui98* XiangShan is licensed under Mulan PSL v2.
609c6f1ddSLingrui98* You can use this software according to the terms and conditions of the Mulan PSL v2.
709c6f1ddSLingrui98* You may obtain a copy of Mulan PSL v2 at:
809c6f1ddSLingrui98*          http://license.coscl.org.cn/MulanPSL2
909c6f1ddSLingrui98*
1009c6f1ddSLingrui98* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
1109c6f1ddSLingrui98* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
1209c6f1ddSLingrui98* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
1309c6f1ddSLingrui98*
1409c6f1ddSLingrui98* See the Mulan PSL v2 for more details.
1509c6f1ddSLingrui98***************************************************************************************/
1609c6f1ddSLingrui98package xiangshan.frontend
1709c6f1ddSLingrui98
188891a219SYinan Xuimport org.chipsalliance.cde.config.Parameters
1909c6f1ddSLingrui98import chisel3._
2009c6f1ddSLingrui98import chisel3.util._
2109c6f1ddSLingrui98import xiangshan._
2250780602SJeniusimport xiangshan.frontend.icache._
2309c6f1ddSLingrui98import utils._
243c02ee8fSwakafaimport utility._
25c2ad24ebSLingrui98import scala.math._
26d2b20d1aSTang Haojinimport java.util.ResourceBundle.Control
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
50b37e4b45SLingrui98    when (b.fallThruError) {
51b37e4b45SLingrui98      val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.startAddr, b.nextLineAddr)
52b37e4b45SLingrui98      val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1)
53b37e4b45SLingrui98      this.nextStartAddr :=
54b37e4b45SLingrui98        Cat(nextBlockHigher,
55b37e4b45SLingrui98          startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W),
56b37e4b45SLingrui98          startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits),
57b37e4b45SLingrui98          0.U(instOffsetBits.W)
58b37e4b45SLingrui98        )
5909c6f1ddSLingrui98    }
6009c6f1ddSLingrui98    this
6109c6f1ddSLingrui98  }
6209c6f1ddSLingrui98  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}
6809c6f1ddSLingrui98
69f22cf846SJeniusclass FtqICacheInfo(implicit p: Parameters)extends XSBundle with HasICacheParameters{
70c5c5edaeSJenius  val startAddr           = UInt(VAddrBits.W)
71c5c5edaeSJenius  val nextlineStart       = UInt(VAddrBits.W)
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())
8250780602SJenius  val resp              = Vec(PortNumber, 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())
90c5c5edaeSJenius}
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
1057052722fSJay// Ftq send req to Prefetch
1067052722fSJayclass PrefetchRequest(implicit p:Parameters) extends XSBundle {
1077052722fSJay  val target          = UInt(VAddrBits.W)
1087052722fSJay}
10909c6f1ddSLingrui98
1107052722fSJayclass FtqPrefechBundle(implicit p:Parameters) extends XSBundle {
1117052722fSJay  val req = DecoupledIO(new PrefetchRequest)
11209c6f1ddSLingrui98}
11309c6f1ddSLingrui98
1141d1e6d4dSJeniusclass mmioCommitRead(implicit p: Parameters) extends XSBundle {
1151d1e6d4dSJenius  val mmioFtqPtr = Output(new FtqPtr)
1161d1e6d4dSJenius  val mmioLastCommit = Input(Bool())
1171d1e6d4dSJenius}
1181d1e6d4dSJenius
11909c6f1ddSLingrui98class FetchToIBuffer(implicit p: Parameters) extends XSBundle {
12009c6f1ddSLingrui98  val instrs    = Vec(PredictWidth, UInt(32.W))
12109c6f1ddSLingrui98  val valid     = UInt(PredictWidth.W)
1222a3050c2SJay  val enqEnable = UInt(PredictWidth.W)
12309c6f1ddSLingrui98  val pd        = Vec(PredictWidth, new PreDecodeInfo)
12409c6f1ddSLingrui98  val pc        = Vec(PredictWidth, UInt(VAddrBits.W))
12509c6f1ddSLingrui98  val foldpc    = Vec(PredictWidth, UInt(MemPredPCWidth.W))
12609c6f1ddSLingrui98  val ftqPtr       = new FtqPtr
12709c6f1ddSLingrui98  val ftqOffset    = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
12809c6f1ddSLingrui98  val ipf          = Vec(PredictWidth, Bool())
129d0de7e4aSpeixiaokun  val igpf          = Vec(PredictWidth, Bool())
13009c6f1ddSLingrui98  val acf          = Vec(PredictWidth, Bool())
13109c6f1ddSLingrui98  val crossPageIPFFix = Vec(PredictWidth, Bool())
13272951335SLi Qianruo  val triggered    = Vec(PredictWidth, new TriggerCf)
133d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
13409c6f1ddSLingrui98}
13509c6f1ddSLingrui98
136c2ad24ebSLingrui98// class BitWiseUInt(val width: Int, val init: UInt) extends Module {
137c2ad24ebSLingrui98//   val io = IO(new Bundle {
138c2ad24ebSLingrui98//     val set
139c2ad24ebSLingrui98//   })
140c2ad24ebSLingrui98// }
14109c6f1ddSLingrui98// Move from BPU
142c2ad24ebSLingrui98abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst {
143c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory
144c2ad24ebSLingrui98}
145c2ad24ebSLingrui98
146c2ad24ebSLingrui98class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory {
14709c6f1ddSLingrui98  val predHist = UInt(HistoryLength.W)
14809c6f1ddSLingrui98
149c2ad24ebSLingrui98  def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = {
150c2ad24ebSLingrui98    val g = Wire(new ShiftingGlobalHistory)
15109c6f1ddSLingrui98    g.predHist := (hist << shift) | taken
15209c6f1ddSLingrui98    g
15309c6f1ddSLingrui98  }
15409c6f1ddSLingrui98
155c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = {
156eeb5ff92SLingrui98    require(br_valids.length == numBr)
157eeb5ff92SLingrui98    require(real_taken_mask.length == numBr)
158eeb5ff92SLingrui98    val last_valid_idx = PriorityMux(
159eeb5ff92SLingrui98      br_valids.reverse :+ true.B,
160eeb5ff92SLingrui98      (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W))
161eeb5ff92SLingrui98    )
162eeb5ff92SLingrui98    val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask)
163eeb5ff92SLingrui98    val smaller = Mux(last_valid_idx < first_taken_idx,
164eeb5ff92SLingrui98      last_valid_idx,
165eeb5ff92SLingrui98      first_taken_idx
166eeb5ff92SLingrui98    )
167eeb5ff92SLingrui98    val shift = smaller
168eeb5ff92SLingrui98    val taken = real_taken_mask.reduce(_||_)
169eeb5ff92SLingrui98    update(shift, taken, this.predHist)
170eeb5ff92SLingrui98  }
171eeb5ff92SLingrui98
172c2ad24ebSLingrui98  // static read
173935edac4STang Haojin  def read(n: Int): Bool = predHist.asBools(n)
174c2ad24ebSLingrui98
175c2ad24ebSLingrui98  final def === (that: ShiftingGlobalHistory): Bool = {
17609c6f1ddSLingrui98    predHist === that.predHist
17709c6f1ddSLingrui98  }
17809c6f1ddSLingrui98
179c2ad24ebSLingrui98  final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that)
180c2ad24ebSLingrui98}
18109c6f1ddSLingrui98
182c2ad24ebSLingrui98// circular global history pointer
183c2ad24ebSLingrui98class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr](
184c2ad24ebSLingrui98  p => p(XSCoreParamsKey).HistoryLength
185c2ad24ebSLingrui98){
186c2ad24ebSLingrui98}
187c7fabd05SSteve Gou
188c7fabd05SSteve Gouobject CGHPtr {
189c7fabd05SSteve Gou  def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = {
190c7fabd05SSteve Gou    val ptr = Wire(new CGHPtr)
191c7fabd05SSteve Gou    ptr.flag := f
192c7fabd05SSteve Gou    ptr.value := v
193c7fabd05SSteve Gou    ptr
194c7fabd05SSteve Gou  }
195c7fabd05SSteve Gou  def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr = {
196c7fabd05SSteve Gou    apply(!ptr.flag, ptr.value)
197c7fabd05SSteve Gou  }
198c7fabd05SSteve Gou}
199c7fabd05SSteve Gou
200c2ad24ebSLingrui98class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory {
201c2ad24ebSLingrui98  val buffer = Vec(HistoryLength, Bool())
202c2ad24ebSLingrui98  type HistPtr = UInt
203c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = {
204c2ad24ebSLingrui98    this
205c2ad24ebSLingrui98  }
206c2ad24ebSLingrui98}
207c2ad24ebSLingrui98
208dd6c0695SLingrui98class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters)
209c2ad24ebSLingrui98  extends XSBundle with HasBPUConst {
210dd6c0695SLingrui98  require(compLen >= 1)
211c2ad24ebSLingrui98  require(len > 0)
212c2ad24ebSLingrui98  // require(folded_len <= len)
213dd6c0695SLingrui98  require(compLen >= max_update_num)
214dd6c0695SLingrui98  val folded_hist = UInt(compLen.W)
215dd6c0695SLingrui98
21667402d75SLingrui98  def need_oldest_bits = len > compLen
217dd6c0695SLingrui98  def info = (len, compLen)
218c2ad24ebSLingrui98  def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1)
219c2ad24ebSLingrui98  def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen)
220c2ad24ebSLingrui98  def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0)
221c2ad24ebSLingrui98  def oldest_bit_start = oldest_bit_pos_in_folded.head
222c2ad24ebSLingrui98
223dd6c0695SLingrui98  def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = {
224c2ad24ebSLingrui98    // TODO: wrap inc for histPtr value
225dd6c0695SLingrui98    oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value))
226c2ad24ebSLingrui98  }
227c2ad24ebSLingrui98
228ab890bfeSLingrui98  def circular_shift_left(src: UInt, shamt: Int) = {
229c2ad24ebSLingrui98    val srcLen = src.getWidth
230c2ad24ebSLingrui98    val src_doubled = Cat(src, src)
231ab890bfeSLingrui98    val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt)
232ab890bfeSLingrui98    shifted
233c2ad24ebSLingrui98  }
234c2ad24ebSLingrui98
23567402d75SLingrui98  // slow path, read bits from ghr
236ab890bfeSLingrui98  def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = {
23767402d75SLingrui98    val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr))
23867402d75SLingrui98    update(oldest_bits, num, taken)
23967402d75SLingrui98  }
24067402d75SLingrui98
24167402d75SLingrui98
24267402d75SLingrui98  // fast path, use pre-read oldest bits
24367402d75SLingrui98  def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = {
244c2ad24ebSLingrui98    // do xors for several bitsets at specified bits
245c2ad24ebSLingrui98    def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = {
246c2ad24ebSLingrui98      val res = Wire(Vec(len, Bool()))
247c2ad24ebSLingrui98      // println(f"num bitsets: ${bitsets.length}")
248c2ad24ebSLingrui98      // println(f"bitsets $bitsets")
249c2ad24ebSLingrui98      val resArr = Array.fill(len)(List[Bool]())
250c2ad24ebSLingrui98      for (bs <- bitsets) {
251c2ad24ebSLingrui98        for ((n, b) <- bs) {
252c2ad24ebSLingrui98          resArr(n) = b :: resArr(n)
253c2ad24ebSLingrui98        }
254c2ad24ebSLingrui98      }
255c2ad24ebSLingrui98      // println(f"${resArr.mkString}")
256c2ad24ebSLingrui98      // println(f"histLen: ${this.len}, foldedLen: $folded_len")
257c2ad24ebSLingrui98      for (i <- 0 until len) {
258c2ad24ebSLingrui98        // println(f"bit[$i], ${resArr(i).mkString}")
259c2ad24ebSLingrui98        if (resArr(i).length == 0) {
260dd6c0695SLingrui98          println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen")
261c2ad24ebSLingrui98        }
262c2ad24ebSLingrui98        res(i) := resArr(i).foldLeft(false.B)(_^_)
263c2ad24ebSLingrui98      }
264c2ad24ebSLingrui98      res.asUInt
265c2ad24ebSLingrui98    }
266c2ad24ebSLingrui98
26767402d75SLingrui98    val new_folded_hist = if (need_oldest_bits) {
26867402d75SLingrui98      val oldest_bits = ob
26967402d75SLingrui98      require(oldest_bits.length == max_update_num)
270c2ad24ebSLingrui98      // mask off bits that do not update
271c2ad24ebSLingrui98      val oldest_bits_masked = oldest_bits.zipWithIndex.map{
272ab890bfeSLingrui98        case (ob, i) => ob && (i < num).B
273c2ad24ebSLingrui98      }
274c2ad24ebSLingrui98      // if a bit does not wrap around, it should not be xored when it exits
275c2ad24ebSLingrui98      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)))
276c2ad24ebSLingrui98
277c2ad24ebSLingrui98      // println(f"old bits pos ${oldest_bits_set.map(_._1)}")
278c2ad24ebSLingrui98
279c2ad24ebSLingrui98      // only the last bit could be 1, as we have at most one taken branch at a time
280ab890bfeSLingrui98      val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt
281c2ad24ebSLingrui98      // if a bit does not wrap around, newest bits should not be xored onto it either
282e992912cSLingrui98      val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i)))
283c2ad24ebSLingrui98
284c2ad24ebSLingrui98      // println(f"new bits set ${newest_bits_set.map(_._1)}")
285c2ad24ebSLingrui98      //
286c2ad24ebSLingrui98      val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{
287ab890bfeSLingrui98        case (fb, i) => fb && !(num >= (len-i)).B
288c2ad24ebSLingrui98      })
289c2ad24ebSLingrui98      val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i)))
290c2ad24ebSLingrui98
291c2ad24ebSLingrui98      // do xor then shift
292c2ad24ebSLingrui98      val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set))
293ab890bfeSLingrui98      circular_shift_left(xored, num)
29467402d75SLingrui98    } else {
29567402d75SLingrui98      // histLen too short to wrap around
29667402d75SLingrui98      ((folded_hist << num) | taken)(compLen-1,0)
297c2ad24ebSLingrui98    }
29867402d75SLingrui98
299c2ad24ebSLingrui98    val fh = WireInit(this)
300c2ad24ebSLingrui98    fh.folded_hist := new_folded_hist
301c2ad24ebSLingrui98    fh
302c2ad24ebSLingrui98  }
30309c6f1ddSLingrui98}
30409c6f1ddSLingrui98
30567402d75SLingrui98class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle {
30667402d75SLingrui98  val bits = Vec(max_update_num*2, Bool())
30767402d75SLingrui98  // def info = (len, compLen)
30867402d75SLingrui98  def getRealOb(brNumOH: UInt): Vec[Bool] = {
30967402d75SLingrui98    val ob = Wire(Vec(max_update_num, Bool()))
31067402d75SLingrui98    for (i <- 0 until max_update_num) {
31167402d75SLingrui98      ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr+1))
31267402d75SLingrui98    }
31367402d75SLingrui98    ob
31467402d75SLingrui98  }
31567402d75SLingrui98}
31667402d75SLingrui98
31767402d75SLingrui98class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
31867402d75SLingrui98  val afhob = MixedVec(gen.filter(t => t._1 > t._2).map{_._1}
31967402d75SLingrui98    .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates
32067402d75SLingrui98  require(gen.toSet.toList.equals(gen))
32167402d75SLingrui98  def getObWithInfo(info: Tuple2[Int, Int]) = {
32267402d75SLingrui98    val selected = afhob.filter(_.len == info._1)
32367402d75SLingrui98    require(selected.length == 1)
32467402d75SLingrui98    selected(0)
32567402d75SLingrui98  }
32667402d75SLingrui98  def read(ghv: Vec[Bool], ptr: CGHPtr) = {
32767402d75SLingrui98    val hisLens = afhob.map(_.len)
32867402d75SLingrui98    val bitsToRead = hisLens.flatMap(l => (0 until numBr*2).map(i => l-i-1)).toSet // remove duplicates
32967402d75SLingrui98    val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr+(pos+1).U).value)))
33067402d75SLingrui98    for (ob <- afhob) {
33167402d75SLingrui98      for (i <- 0 until numBr*2) {
33267402d75SLingrui98        val pos = ob.len - i - 1
33367402d75SLingrui98        val bit_found = bitsWithInfo.filter(_._1 == pos).toList
33467402d75SLingrui98        require(bit_found.length == 1)
33567402d75SLingrui98        ob.bits(i) := bit_found(0)._2
33667402d75SLingrui98      }
33767402d75SLingrui98    }
33867402d75SLingrui98  }
33967402d75SLingrui98}
34067402d75SLingrui98
34167402d75SLingrui98class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
34267402d75SLingrui98  val hist = MixedVec(gen.map{case (l, cl) => new FoldedHistory(l, cl, numBr)})
34367402d75SLingrui98  // println(gen.mkString)
34467402d75SLingrui98  require(gen.toSet.toList.equals(gen))
34567402d75SLingrui98  def getHistWithInfo(info: Tuple2[Int, Int]) = {
34667402d75SLingrui98    val selected = hist.filter(_.info.equals(info))
34767402d75SLingrui98    require(selected.length == 1)
34867402d75SLingrui98    selected(0)
34967402d75SLingrui98  }
35067402d75SLingrui98  def autoConnectFrom(that: AllFoldedHistories) = {
35167402d75SLingrui98    require(this.hist.length <= that.hist.length)
35267402d75SLingrui98    for (h <- this.hist) {
35367402d75SLingrui98      h := that.getHistWithInfo(h.info)
35467402d75SLingrui98    }
35567402d75SLingrui98  }
35667402d75SLingrui98  def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = {
35767402d75SLingrui98    val res = WireInit(this)
35867402d75SLingrui98    for (i <- 0 until this.hist.length) {
35967402d75SLingrui98      res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken)
36067402d75SLingrui98    }
36167402d75SLingrui98    res
36267402d75SLingrui98  }
36367402d75SLingrui98  def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = {
36467402d75SLingrui98    val res = WireInit(this)
36567402d75SLingrui98    for (i <- 0 until this.hist.length) {
36667402d75SLingrui98      val fh = this.hist(i)
36767402d75SLingrui98      if (fh.need_oldest_bits) {
36867402d75SLingrui98        val info = fh.info
36967402d75SLingrui98        val selectedAfhob = afhob.getObWithInfo(info)
37067402d75SLingrui98        val ob = selectedAfhob.getRealOb(lastBrNumOH)
37167402d75SLingrui98        res.hist(i) := this.hist(i).update(ob, shift, taken)
37267402d75SLingrui98      } else {
37367402d75SLingrui98        val dumb = Wire(Vec(numBr, Bool())) // not needed
37467402d75SLingrui98        dumb := DontCare
37567402d75SLingrui98        res.hist(i) := this.hist(i).update(dumb, shift, taken)
37667402d75SLingrui98      }
37767402d75SLingrui98    }
37867402d75SLingrui98    res
37967402d75SLingrui98  }
38067402d75SLingrui98
38167402d75SLingrui98  def display(cond: Bool) = {
38267402d75SLingrui98    for (h <- hist) {
38367402d75SLingrui98      XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n")
38467402d75SLingrui98    }
38567402d75SLingrui98  }
38667402d75SLingrui98}
38767402d75SLingrui98
38809c6f1ddSLingrui98class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{
38909c6f1ddSLingrui98  def tagBits = VAddrBits - idxBits - instOffsetBits
39009c6f1ddSLingrui98
39109c6f1ddSLingrui98  val tag = UInt(tagBits.W)
39209c6f1ddSLingrui98  val idx = UInt(idxBits.W)
39309c6f1ddSLingrui98  val offset = UInt(instOffsetBits.W)
39409c6f1ddSLingrui98
39509c6f1ddSLingrui98  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
39609c6f1ddSLingrui98  def getTag(x: UInt) = fromUInt(x).tag
39709c6f1ddSLingrui98  def getIdx(x: UInt) = fromUInt(x).idx
39809c6f1ddSLingrui98  def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U
39909c6f1ddSLingrui98  def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x)
40009c6f1ddSLingrui98}
401eeb5ff92SLingrui98
402b37e4b45SLingrui98trait BasicPrediction extends HasXSParameter {
403b37e4b45SLingrui98  def cfiIndex: ValidUndirectioned[UInt]
404b37e4b45SLingrui98  def target(pc: UInt): UInt
405b37e4b45SLingrui98  def lastBrPosOH: Vec[Bool]
406b37e4b45SLingrui98  def brTaken: Bool
407b37e4b45SLingrui98  def shouldShiftVec: Vec[Bool]
408b37e4b45SLingrui98  def fallThruError: Bool
409b37e4b45SLingrui98}
410935edac4STang Haojin
411b166c0eaSEaston Man// selectByTaken selects some data according to takenMask
4122bf6e0ecSEaston Man// allTargets should be in a Vec, like [taken0, taken1, ..., not taken, not hit]
413b166c0eaSEaston Manobject selectByTaken {
414b166c0eaSEaston Man  def apply[T <: Data](takenMask: Vec[Bool], hit: Bool, allTargets: Vec[T]): T = {
415b166c0eaSEaston Man    val selVecOH =
416b166c0eaSEaston Man      takenMask.zipWithIndex.map { case (t, i) => !takenMask.take(i).fold(false.B)(_ || _) && t && hit } :+
417b166c0eaSEaston Man        (!takenMask.asUInt.orR && hit) :+ !hit
418b166c0eaSEaston Man    Mux1H(selVecOH, allTargets)
419b166c0eaSEaston Man  }
420b166c0eaSEaston Man}
421b166c0eaSEaston Man
422b37e4b45SLingrui98class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction {
423eeb5ff92SLingrui98  val br_taken_mask = Vec(numBr, Bool())
42409c6f1ddSLingrui98
425eeb5ff92SLingrui98  val slot_valids = Vec(totalSlot, Bool())
42609c6f1ddSLingrui98
427eeb5ff92SLingrui98  val targets = Vec(totalSlot, UInt(VAddrBits.W))
428b30c10d6SLingrui98  val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors
429a229ab6cSLingrui98  val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W))
430a229ab6cSLingrui98  val fallThroughAddr = UInt(VAddrBits.W)
431b37e4b45SLingrui98  val fallThroughErr = Bool()
43209c6f1ddSLingrui98
43309c6f1ddSLingrui98  val is_jal = Bool()
43409c6f1ddSLingrui98  val is_jalr = Bool()
43509c6f1ddSLingrui98  val is_call = Bool()
43609c6f1ddSLingrui98  val is_ret = Bool()
437f4ebc4b2SLingrui98  val last_may_be_rvi_call = Bool()
438eeb5ff92SLingrui98  val is_br_sharing = Bool()
43909c6f1ddSLingrui98
44009c6f1ddSLingrui98  // val call_is_rvc = Bool()
44109c6f1ddSLingrui98  val hit = Bool()
44209c6f1ddSLingrui98
443209a4cafSSteve Gou  val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
444209a4cafSSteve Gou
445eeb5ff92SLingrui98  def br_slot_valids = slot_valids.init
446eeb5ff92SLingrui98  def tail_slot_valid = slot_valids.last
447eeb5ff92SLingrui98
448eeb5ff92SLingrui98  def br_valids = {
449b37e4b45SLingrui98    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
450eeb5ff92SLingrui98  }
451eeb5ff92SLingrui98
452eeb5ff92SLingrui98  def taken_mask_on_slot = {
453eeb5ff92SLingrui98    VecInit(
454eeb5ff92SLingrui98      (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ (
455b30c10d6SLingrui98        tail_slot_valid && (
456b30c10d6SLingrui98          is_br_sharing && br_taken_mask.last || !is_br_sharing
457b30c10d6SLingrui98        )
458eeb5ff92SLingrui98      )
459eeb5ff92SLingrui98    )
460eeb5ff92SLingrui98  }
461eeb5ff92SLingrui98
462b37e4b45SLingrui98  def real_slot_taken_mask(): Vec[Bool] = {
463b37e4b45SLingrui98    VecInit(taken_mask_on_slot.map(_ && hit))
464b37e4b45SLingrui98  }
465b37e4b45SLingrui98
466b37e4b45SLingrui98  // len numBr
467b37e4b45SLingrui98  def real_br_taken_mask(): Vec[Bool] = {
468b37e4b45SLingrui98    VecInit(
469b37e4b45SLingrui98      taken_mask_on_slot.map(_ && hit).init :+
470b37e4b45SLingrui98      (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
471b37e4b45SLingrui98    )
472b37e4b45SLingrui98  }
473b37e4b45SLingrui98
474b37e4b45SLingrui98  // the vec indicating if ghr should shift on each branch
475b37e4b45SLingrui98  def shouldShiftVec =
476b37e4b45SLingrui98    VecInit(br_valids.zipWithIndex.map{ case (v, i) =>
477b37e4b45SLingrui98      v && !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B)})
478b37e4b45SLingrui98
479b37e4b45SLingrui98  def lastBrPosOH =
480b37e4b45SLingrui98    VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry
481b37e4b45SLingrui98      (0 until numBr).map(i =>
482b37e4b45SLingrui98        br_valids(i) &&
483b37e4b45SLingrui98        !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it
484b37e4b45SLingrui98        (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it
485b37e4b45SLingrui98        hit
486b37e4b45SLingrui98      )
487b37e4b45SLingrui98    )
488b37e4b45SLingrui98
48986d9c530SLingrui98  def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_)
490b37e4b45SLingrui98
491b37e4b45SLingrui98  def target(pc: UInt): UInt = {
492b166c0eaSEaston Man    selectByTaken(taken_mask_on_slot, hit, allTarget(pc))
493b166c0eaSEaston Man  }
494b166c0eaSEaston Man
4952bf6e0ecSEaston Man  // allTarget return a Vec of all possible target of a BP stage
4962bf6e0ecSEaston Man  // in the following order: [taken_target0, taken_target1, ..., fallThroughAddr, not hit (plus fetch width)]
497b166c0eaSEaston Man  //
498b166c0eaSEaston Man  // This exposes internal targets for timing optimization,
499b166c0eaSEaston Man  // since usually targets are generated quicker than taken
500b166c0eaSEaston Man  def allTarget(pc: UInt): Vec[UInt] = {
501b166c0eaSEaston Man    VecInit(targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U))
502b37e4b45SLingrui98  }
503b37e4b45SLingrui98
504b37e4b45SLingrui98  def fallThruError: Bool = hit && fallThroughErr
505b37e4b45SLingrui98
506b37e4b45SLingrui98  def hit_taken_on_jmp =
507b37e4b45SLingrui98    !real_slot_taken_mask().init.reduce(_||_) &&
508b37e4b45SLingrui98    real_slot_taken_mask().last && !is_br_sharing
509b37e4b45SLingrui98  def hit_taken_on_call = hit_taken_on_jmp && is_call
510b37e4b45SLingrui98  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
511b37e4b45SLingrui98  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
512b37e4b45SLingrui98
513b37e4b45SLingrui98  def cfiIndex = {
514b37e4b45SLingrui98    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
515b37e4b45SLingrui98    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
516b37e4b45SLingrui98    // when no takens, set cfiIndex to PredictWidth-1
517b37e4b45SLingrui98    cfiIndex.bits :=
518b37e4b45SLingrui98      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
519b37e4b45SLingrui98      Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
520b37e4b45SLingrui98    cfiIndex
521b37e4b45SLingrui98  }
522b37e4b45SLingrui98
523eeb5ff92SLingrui98  def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr)
52409c6f1ddSLingrui98
52547c003a9SEaston Man  def fromFtbEntry(
52647c003a9SEaston Man                    entry: FTBEntry,
52747c003a9SEaston Man                    pc: UInt,
52847c003a9SEaston Man                    last_stage_pc: Option[Tuple2[UInt, Bool]] = None,
52947c003a9SEaston Man                    last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None
53047c003a9SEaston Man                  ) = {
531eeb5ff92SLingrui98    slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
53247c003a9SEaston Man    targets := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing
533b30c10d6SLingrui98    jalr_target := targets.last
534a229ab6cSLingrui98    offsets := entry.getOffsetVec
535eeb5ff92SLingrui98    is_jal := entry.tailSlot.valid && entry.isJal
536eeb5ff92SLingrui98    is_jalr := entry.tailSlot.valid && entry.isJalr
537eeb5ff92SLingrui98    is_call := entry.tailSlot.valid && entry.isCall
538eeb5ff92SLingrui98    is_ret := entry.tailSlot.valid && entry.isRet
539f4ebc4b2SLingrui98    last_may_be_rvi_call := entry.last_may_be_rvi_call
540eeb5ff92SLingrui98    is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing
541209a4cafSSteve Gou    predCycle.map(_ := GTimer())
542a229ab6cSLingrui98
543a60a2901SLingrui98    val startLower        = Cat(0.U(1.W),    pc(instOffsetBits+log2Ceil(PredictWidth)-1, instOffsetBits))
544b37e4b45SLingrui98    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
545a60a2901SLingrui98    fallThroughErr := startLower >= endLowerwithCarry
54647c003a9SEaston Man    fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry))
547a229ab6cSLingrui98  }
54809c6f1ddSLingrui98
54909c6f1ddSLingrui98  def display(cond: Bool): Unit = {
550eeb5ff92SLingrui98    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
55109c6f1ddSLingrui98  }
55209c6f1ddSLingrui98}
55309c6f1ddSLingrui98
554803124a6SLingrui98class SpeculativeInfo(implicit p: Parameters) extends XSBundle
555803124a6SLingrui98  with HasBPUConst with BPUUtils {
556803124a6SLingrui98  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
557803124a6SLingrui98  val afhob = new AllAheadFoldedHistoryOldestBits(foldedGHistInfos)
558803124a6SLingrui98  val lastBrNumOH = UInt((numBr+1).W)
559803124a6SLingrui98  val histPtr = new CGHPtr
560c89b4642SGuokai Chen  val ssp = UInt(log2Up(RasSize).W)
561*deb3a97eSGao-Zeyu  val sctr = UInt(RasCtrSize.W)
562c89b4642SGuokai Chen  val TOSW = new RASPtr
563c89b4642SGuokai Chen  val TOSR = new RASPtr
564c89b4642SGuokai Chen  val NOS = new RASPtr
565c89b4642SGuokai Chen  val topAddr = UInt(VAddrBits.W)
566803124a6SLingrui98}
567803124a6SLingrui98
568b37e4b45SLingrui98class BranchPredictionBundle(implicit p: Parameters) extends XSBundle
569b37e4b45SLingrui98  with HasBPUConst with BPUUtils {
570adc0b8dfSGuokai Chen  val pc    = Vec(numDup, UInt(VAddrBits.W))
571adc0b8dfSGuokai Chen  val valid = Vec(numDup, Bool())
572adc0b8dfSGuokai Chen  val hasRedirect  = Vec(numDup, Bool())
57309c6f1ddSLingrui98  val ftq_idx = new FtqPtr
574adc0b8dfSGuokai Chen  val full_pred    = Vec(numDup, new FullBranchPrediction)
575b37e4b45SLingrui98
57609c6f1ddSLingrui98
577adc0b8dfSGuokai Chen  def target(pc: UInt) = VecInit(full_pred.map(_.target(pc)))
578b166c0eaSEaston Man  def targets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).target(pc)})
579b166c0eaSEaston Man  def allTargets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).allTarget(pc)})
580adc0b8dfSGuokai Chen  def cfiIndex         = VecInit(full_pred.map(_.cfiIndex))
581adc0b8dfSGuokai Chen  def lastBrPosOH      = VecInit(full_pred.map(_.lastBrPosOH))
582adc0b8dfSGuokai Chen  def brTaken          = VecInit(full_pred.map(_.brTaken))
583adc0b8dfSGuokai Chen  def shouldShiftVec   = VecInit(full_pred.map(_.shouldShiftVec))
584adc0b8dfSGuokai Chen  def fallThruError    = VecInit(full_pred.map(_.fallThruError))
585eeb5ff92SLingrui98
586adc0b8dfSGuokai Chen  def taken = VecInit(cfiIndex.map(_.valid))
587adc0b8dfSGuokai Chen
588adc0b8dfSGuokai Chen  def getTarget = targets(pc)
589b166c0eaSEaston Man  def getAllTargets = allTargets(pc)
59009c6f1ddSLingrui98
59109c6f1ddSLingrui98  def display(cond: Bool): Unit = {
592adc0b8dfSGuokai Chen    XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n")
593adc0b8dfSGuokai Chen    full_pred(0).display(cond)
59409c6f1ddSLingrui98  }
59509c6f1ddSLingrui98}
59609c6f1ddSLingrui98
59709c6f1ddSLingrui98class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
59809c6f1ddSLingrui98  // val valids = Vec(3, Bool())
599b37e4b45SLingrui98  val s1 = new BranchPredictionBundle
600b37e4b45SLingrui98  val s2 = new BranchPredictionBundle
601cb4f77ceSLingrui98  val s3 = new BranchPredictionBundle
60209c6f1ddSLingrui98
603c2d1ec7dSLingrui98  val last_stage_meta = UInt(MaxMetaLength.W)
6043711cf36S小造xu_zh  val last_stage_spec_info = new Ftq_Redirect_SRAMEntry
605c2d1ec7dSLingrui98  val last_stage_ftb_entry = new FTBEntry
606c2d1ec7dSLingrui98
607d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
608d2b20d1aSTang Haojin
609b37e4b45SLingrui98  def selectedResp ={
610b37e4b45SLingrui98    val res =
61109c6f1ddSLingrui98      PriorityMux(Seq(
612adc0b8dfSGuokai Chen        ((s3.valid(3) && s3.hasRedirect(3)) -> s3),
613adc0b8dfSGuokai Chen        ((s2.valid(3) && s2.hasRedirect(3)) -> s2),
614adc0b8dfSGuokai Chen        (s1.valid(3) -> s1)
61509c6f1ddSLingrui98      ))
616b37e4b45SLingrui98    res
617b37e4b45SLingrui98  }
618adc0b8dfSGuokai Chen  def selectedRespIdxForFtq =
61909c6f1ddSLingrui98    PriorityMux(Seq(
620adc0b8dfSGuokai Chen      ((s3.valid(3) && s3.hasRedirect(3)) -> BP_S3),
621adc0b8dfSGuokai Chen      ((s2.valid(3) && s2.hasRedirect(3)) -> BP_S2),
622adc0b8dfSGuokai Chen      (s1.valid(3) -> BP_S1)
62309c6f1ddSLingrui98    ))
624cb4f77ceSLingrui98  def lastStage = s3
62509c6f1ddSLingrui98}
62609c6f1ddSLingrui98
627c2d1ec7dSLingrui98class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {}
62809c6f1ddSLingrui98
629803124a6SLingrui98class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst {
630803124a6SLingrui98  val pc = UInt(VAddrBits.W)
631803124a6SLingrui98  val spec_info = new SpeculativeInfo
632803124a6SLingrui98  val ftb_entry = new FTBEntry()
633803124a6SLingrui98
634803124a6SLingrui98  val cfi_idx = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
635803124a6SLingrui98  val br_taken_mask = Vec(numBr, Bool())
636cc2d1573SEaston Man  val br_committed = Vec(numBr, Bool()) // High only when br valid && br committed
637803124a6SLingrui98  val jmp_taken = Bool()
63809c6f1ddSLingrui98  val mispred_mask = Vec(numBr+1, Bool())
639edc18578SLingrui98  val pred_hit = Bool()
64009c6f1ddSLingrui98  val false_hit = Bool()
64109c6f1ddSLingrui98  val new_br_insert_pos = Vec(numBr, Bool())
64209c6f1ddSLingrui98  val old_entry = Bool()
64309c6f1ddSLingrui98  val meta = UInt(MaxMetaLength.W)
644abdbe4b7SLingrui98  val full_target = UInt(VAddrBits.W)
645edc18578SLingrui98  val from_stage = UInt(2.W)
64686d9c530SLingrui98  val ghist = UInt(HistoryLength.W)
64709c6f1ddSLingrui98
648803124a6SLingrui98  def is_jal = ftb_entry.tailSlot.valid && ftb_entry.isJal
649803124a6SLingrui98  def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr
650803124a6SLingrui98  def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall
651803124a6SLingrui98  def is_ret = ftb_entry.tailSlot.valid && ftb_entry.isRet
652803124a6SLingrui98
653c89b4642SGuokai Chen  def is_call_taken = is_call && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset
654c89b4642SGuokai Chen  def is_ret_taken = is_ret && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset
655c89b4642SGuokai Chen
656803124a6SLingrui98  def display(cond: Bool) = {
65709c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
65809c6f1ddSLingrui98    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
65909c6f1ddSLingrui98    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
66009c6f1ddSLingrui98    XSDebug(cond, p"--------------------------------------------\n")
66109c6f1ddSLingrui98  }
66209c6f1ddSLingrui98}
66309c6f1ddSLingrui98
66409c6f1ddSLingrui98class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
66509c6f1ddSLingrui98  // override def toPrintable: Printable = {
66609c6f1ddSLingrui98  //   p"-----------BranchPredictionRedirect----------- " +
66709c6f1ddSLingrui98  //     p"-----------cfiUpdate----------- " +
66809c6f1ddSLingrui98  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
66909c6f1ddSLingrui98  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
67009c6f1ddSLingrui98  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
67109c6f1ddSLingrui98  //     p"------------------------------- " +
6729aca92b9SYinan Xu  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
67309c6f1ddSLingrui98  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
67409c6f1ddSLingrui98  //     p"[ftqOffset] ${ftqOffset} " +
67509c6f1ddSLingrui98  //     p"[level] ${level}, [interrupt] ${interrupt} " +
67609c6f1ddSLingrui98  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
67709c6f1ddSLingrui98  //     p"[stFtqOffset] ${stFtqOffset} " +
67809c6f1ddSLingrui98  //     p"\n"
67909c6f1ddSLingrui98
68009c6f1ddSLingrui98  // }
68109c6f1ddSLingrui98
682d2b20d1aSTang Haojin  // TODO: backend should pass topdown signals here
683d2b20d1aSTang Haojin  // must not change its parent since BPU has used asTypeOf(this type) from its parent class
684d2b20d1aSTang Haojin  require(isInstanceOf[Redirect])
685d2b20d1aSTang Haojin  val BTBMissBubble = Bool()
686d2b20d1aSTang Haojin  def ControlRedirectBubble = debugIsCtrl
687d2b20d1aSTang Haojin  // if mispred br not in ftb, count as BTB miss
688d2b20d1aSTang Haojin  def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit
689d2b20d1aSTang Haojin  def TAGEMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit
690d2b20d1aSTang Haojin  def SCMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit
691d2b20d1aSTang Haojin  def ITTAGEMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet
692d2b20d1aSTang Haojin  def RASMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet
693d2b20d1aSTang Haojin  def MemVioRedirectBubble = debugIsMemVio
694d2b20d1aSTang Haojin  def OtherRedirectBubble = !debugIsCtrl && !debugIsMemVio
695d2b20d1aSTang Haojin
696d2b20d1aSTang Haojin  def connectRedirect(source: Redirect): Unit = {
697d2b20d1aSTang Haojin    for ((name, data) <- this.elements) {
698d2b20d1aSTang Haojin      if (source.elements.contains(name)) {
699d2b20d1aSTang Haojin        data := source.elements(name)
700d2b20d1aSTang Haojin      }
701d2b20d1aSTang Haojin    }
702d2b20d1aSTang Haojin  }
703d2b20d1aSTang Haojin
70409c6f1ddSLingrui98  def display(cond: Bool): Unit = {
70509c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
70609c6f1ddSLingrui98    XSDebug(cond, p"-----------cfiUpdate----------- \n")
70709c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
708c2ad24ebSLingrui98    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
70909c6f1ddSLingrui98    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
71009c6f1ddSLingrui98    XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n")
71109c6f1ddSLingrui98    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
71209c6f1ddSLingrui98    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
71309c6f1ddSLingrui98    XSDebug(cond, p"------------------------------- \n")
7149aca92b9SYinan Xu    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
71509c6f1ddSLingrui98    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
71609c6f1ddSLingrui98    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
71709c6f1ddSLingrui98    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
71809c6f1ddSLingrui98    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
71909c6f1ddSLingrui98    XSDebug(cond, p"---------------------------------------------- \n")
72009c6f1ddSLingrui98  }
72109c6f1ddSLingrui98}
722