xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision b37e4b45da2333608f12413931aecdaef46443e4)
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
1809c6f1ddSLingrui98import chipsalliance.rocketchip.config.Parameters
1909c6f1ddSLingrui98import chisel3._
2009c6f1ddSLingrui98import chisel3.util._
21bf358e08SLingrui98import chisel3.experimental.chiselName
2209c6f1ddSLingrui98import xiangshan._
23*b37e4b45SLingrui98import xiangshan.frontend.icache.HasICacheParameters
2409c6f1ddSLingrui98import utils._
25c2ad24ebSLingrui98import scala.math._
2609c6f1ddSLingrui98
27bf358e08SLingrui98@chiselName
28*b37e4b45SLingrui98class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
2909c6f1ddSLingrui98  val startAddr       = UInt(VAddrBits.W)
3034a88126SJinYue  val nextlineStart   = UInt(VAddrBits.W)
316ce52296SJinYue  // val fallThruError   = Bool()
3209c6f1ddSLingrui98  val ftqIdx          = new FtqPtr
3309c6f1ddSLingrui98  val ftqOffset       = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
346ce52296SJinYue  val nextStartAddr   = UInt(VAddrBits.W)
3509c6f1ddSLingrui98  val oversize        = Bool()
3609c6f1ddSLingrui98
376ce52296SJinYue  def crossCacheline = startAddr(blockOffBits - 1) === 1.U
386ce52296SJinYue
3909c6f1ddSLingrui98  def fromFtqPcBundle(b: Ftq_RF_Components) = {
4009c6f1ddSLingrui98    this.startAddr := b.startAddr
41*b37e4b45SLingrui98    this.nextlineStart := b.nextLineAddr
4209c6f1ddSLingrui98    this.oversize := b.oversize
43*b37e4b45SLingrui98    when (b.fallThruError) {
44*b37e4b45SLingrui98      val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.startAddr, b.nextLineAddr)
45*b37e4b45SLingrui98      val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1)
46*b37e4b45SLingrui98      this.nextStartAddr :=
47*b37e4b45SLingrui98        Cat(nextBlockHigher,
48*b37e4b45SLingrui98          startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W),
49*b37e4b45SLingrui98          startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits),
50*b37e4b45SLingrui98          0.U(instOffsetBits.W)
51*b37e4b45SLingrui98        )
5209c6f1ddSLingrui98    }
5309c6f1ddSLingrui98    this
5409c6f1ddSLingrui98  }
5509c6f1ddSLingrui98  override def toPrintable: Printable = {
56*b37e4b45SLingrui98    p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" +
57*b37e4b45SLingrui98      p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" +
5809c6f1ddSLingrui98      p" offset: ${ftqOffset.bits}\n"
5909c6f1ddSLingrui98  }
6009c6f1ddSLingrui98}
6109c6f1ddSLingrui98
6209c6f1ddSLingrui98class PredecodeWritebackBundle(implicit p:Parameters) extends XSBundle {
6309c6f1ddSLingrui98  val pc           = Vec(PredictWidth, UInt(VAddrBits.W))
6409c6f1ddSLingrui98  val pd           = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode
6509c6f1ddSLingrui98  val ftqIdx       = new FtqPtr
6609c6f1ddSLingrui98  val ftqOffset    = UInt(log2Ceil(PredictWidth).W)
6709c6f1ddSLingrui98  val misOffset    = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
6809c6f1ddSLingrui98  val cfiOffset    = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
6909c6f1ddSLingrui98  val target       = UInt(VAddrBits.W)
7009c6f1ddSLingrui98  val jalTarget    = UInt(VAddrBits.W)
7109c6f1ddSLingrui98  val instrRange   = Vec(PredictWidth, Bool())
7209c6f1ddSLingrui98}
7309c6f1ddSLingrui98
7409c6f1ddSLingrui98class Exception(implicit p: Parameters) extends XSBundle {
7509c6f1ddSLingrui98
7609c6f1ddSLingrui98}
7709c6f1ddSLingrui98
7809c6f1ddSLingrui98class FetchToIBuffer(implicit p: Parameters) extends XSBundle {
7909c6f1ddSLingrui98  val instrs    = Vec(PredictWidth, UInt(32.W))
8009c6f1ddSLingrui98  val valid     = UInt(PredictWidth.W)
812a3050c2SJay  val enqEnable = UInt(PredictWidth.W)
8209c6f1ddSLingrui98  val pd        = Vec(PredictWidth, new PreDecodeInfo)
8309c6f1ddSLingrui98  val pc        = Vec(PredictWidth, UInt(VAddrBits.W))
8409c6f1ddSLingrui98  val foldpc    = Vec(PredictWidth, UInt(MemPredPCWidth.W))
8509c6f1ddSLingrui98  val ftqPtr       = new FtqPtr
8609c6f1ddSLingrui98  val ftqOffset    = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
8709c6f1ddSLingrui98  val ipf          = Vec(PredictWidth, Bool())
8809c6f1ddSLingrui98  val acf          = Vec(PredictWidth, Bool())
8909c6f1ddSLingrui98  val crossPageIPFFix = Vec(PredictWidth, Bool())
9072951335SLi Qianruo  val triggered    = Vec(PredictWidth, new TriggerCf)
9109c6f1ddSLingrui98}
9209c6f1ddSLingrui98
93c2ad24ebSLingrui98// class BitWiseUInt(val width: Int, val init: UInt) extends Module {
94c2ad24ebSLingrui98//   val io = IO(new Bundle {
95c2ad24ebSLingrui98//     val set
96c2ad24ebSLingrui98//   })
97c2ad24ebSLingrui98// }
9809c6f1ddSLingrui98// Move from BPU
99c2ad24ebSLingrui98abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst {
100c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory
101c2ad24ebSLingrui98}
102c2ad24ebSLingrui98
103c2ad24ebSLingrui98class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory {
10409c6f1ddSLingrui98  val predHist = UInt(HistoryLength.W)
10509c6f1ddSLingrui98
106c2ad24ebSLingrui98  def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = {
107c2ad24ebSLingrui98    val g = Wire(new ShiftingGlobalHistory)
10809c6f1ddSLingrui98    g.predHist := (hist << shift) | taken
10909c6f1ddSLingrui98    g
11009c6f1ddSLingrui98  }
11109c6f1ddSLingrui98
112c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = {
113eeb5ff92SLingrui98    require(br_valids.length == numBr)
114eeb5ff92SLingrui98    require(real_taken_mask.length == numBr)
115eeb5ff92SLingrui98    val last_valid_idx = PriorityMux(
116eeb5ff92SLingrui98      br_valids.reverse :+ true.B,
117eeb5ff92SLingrui98      (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W))
118eeb5ff92SLingrui98    )
119eeb5ff92SLingrui98    val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask)
120eeb5ff92SLingrui98    val smaller = Mux(last_valid_idx < first_taken_idx,
121eeb5ff92SLingrui98      last_valid_idx,
122eeb5ff92SLingrui98      first_taken_idx
123eeb5ff92SLingrui98    )
124eeb5ff92SLingrui98    val shift = smaller
125eeb5ff92SLingrui98    val taken = real_taken_mask.reduce(_||_)
126eeb5ff92SLingrui98    update(shift, taken, this.predHist)
127eeb5ff92SLingrui98  }
128eeb5ff92SLingrui98
129c2ad24ebSLingrui98  // static read
130c2ad24ebSLingrui98  def read(n: Int): Bool = predHist.asBools()(n)
131c2ad24ebSLingrui98
132c2ad24ebSLingrui98  final def === (that: ShiftingGlobalHistory): Bool = {
13309c6f1ddSLingrui98    predHist === that.predHist
13409c6f1ddSLingrui98  }
13509c6f1ddSLingrui98
136c2ad24ebSLingrui98  final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that)
137c2ad24ebSLingrui98}
13809c6f1ddSLingrui98
139c2ad24ebSLingrui98// circular global history pointer
140c2ad24ebSLingrui98class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr](
141c2ad24ebSLingrui98  p => p(XSCoreParamsKey).HistoryLength
142c2ad24ebSLingrui98){
143c2ad24ebSLingrui98  override def cloneType = (new CGHPtr).asInstanceOf[this.type]
144c2ad24ebSLingrui98}
145c2ad24ebSLingrui98class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory {
146c2ad24ebSLingrui98  val buffer = Vec(HistoryLength, Bool())
147c2ad24ebSLingrui98  type HistPtr = UInt
148c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = {
149c2ad24ebSLingrui98    this
150c2ad24ebSLingrui98  }
151c2ad24ebSLingrui98}
152c2ad24ebSLingrui98
153dd6c0695SLingrui98class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters)
154c2ad24ebSLingrui98  extends XSBundle with HasBPUConst {
155dd6c0695SLingrui98  require(compLen >= 1)
156c2ad24ebSLingrui98  require(len > 0)
157c2ad24ebSLingrui98  // require(folded_len <= len)
158dd6c0695SLingrui98  require(compLen >= max_update_num)
159dd6c0695SLingrui98  val folded_hist = UInt(compLen.W)
160dd6c0695SLingrui98
161dd6c0695SLingrui98  def info = (len, compLen)
162c2ad24ebSLingrui98  def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1)
163c2ad24ebSLingrui98  def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen)
164c2ad24ebSLingrui98  def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0)
165c2ad24ebSLingrui98  def oldest_bit_start = oldest_bit_pos_in_folded.head
166c2ad24ebSLingrui98
167dd6c0695SLingrui98  def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = {
168c2ad24ebSLingrui98    // TODO: wrap inc for histPtr value
169dd6c0695SLingrui98    oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value))
170c2ad24ebSLingrui98  }
171c2ad24ebSLingrui98
172ab890bfeSLingrui98  def circular_shift_left(src: UInt, shamt: Int) = {
173c2ad24ebSLingrui98    val srcLen = src.getWidth
174c2ad24ebSLingrui98    val src_doubled = Cat(src, src)
175ab890bfeSLingrui98    val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt)
176ab890bfeSLingrui98    shifted
177c2ad24ebSLingrui98  }
178c2ad24ebSLingrui98
179c2ad24ebSLingrui98
180ab890bfeSLingrui98  def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = {
181c2ad24ebSLingrui98    // do xors for several bitsets at specified bits
182c2ad24ebSLingrui98    def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = {
183c2ad24ebSLingrui98      val res = Wire(Vec(len, Bool()))
184c2ad24ebSLingrui98      // println(f"num bitsets: ${bitsets.length}")
185c2ad24ebSLingrui98      // println(f"bitsets $bitsets")
186c2ad24ebSLingrui98      val resArr = Array.fill(len)(List[Bool]())
187c2ad24ebSLingrui98      for (bs <- bitsets) {
188c2ad24ebSLingrui98        for ((n, b) <- bs) {
189c2ad24ebSLingrui98          resArr(n) = b :: resArr(n)
190c2ad24ebSLingrui98        }
191c2ad24ebSLingrui98      }
192c2ad24ebSLingrui98      // println(f"${resArr.mkString}")
193c2ad24ebSLingrui98      // println(f"histLen: ${this.len}, foldedLen: $folded_len")
194c2ad24ebSLingrui98      for (i <- 0 until len) {
195c2ad24ebSLingrui98        // println(f"bit[$i], ${resArr(i).mkString}")
196c2ad24ebSLingrui98        if (resArr(i).length > 2) {
197c2ad24ebSLingrui98          println(f"[warning] update logic of foldest history has two or more levels of xor gates! " +
198dd6c0695SLingrui98            f"histlen:${this.len}, compLen:$compLen")
199c2ad24ebSLingrui98        }
200c2ad24ebSLingrui98        if (resArr(i).length == 0) {
201dd6c0695SLingrui98          println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen")
202c2ad24ebSLingrui98        }
203c2ad24ebSLingrui98        res(i) := resArr(i).foldLeft(false.B)(_^_)
204c2ad24ebSLingrui98      }
205c2ad24ebSLingrui98      res.asUInt
206c2ad24ebSLingrui98    }
207dd6c0695SLingrui98    val oldest_bits = get_oldest_bits_from_ghr(ghr, histPtr)
208c2ad24ebSLingrui98
209c2ad24ebSLingrui98    // mask off bits that do not update
210c2ad24ebSLingrui98    val oldest_bits_masked = oldest_bits.zipWithIndex.map{
211ab890bfeSLingrui98      case (ob, i) => ob && (i < num).B
212c2ad24ebSLingrui98    }
213c2ad24ebSLingrui98    // if a bit does not wrap around, it should not be xored when it exits
214c2ad24ebSLingrui98    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)))
215c2ad24ebSLingrui98
216c2ad24ebSLingrui98    // println(f"old bits pos ${oldest_bits_set.map(_._1)}")
217c2ad24ebSLingrui98
218c2ad24ebSLingrui98    // only the last bit could be 1, as we have at most one taken branch at a time
219ab890bfeSLingrui98    val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt
220c2ad24ebSLingrui98    // if a bit does not wrap around, newest bits should not be xored onto it either
221e992912cSLingrui98    val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i)))
222c2ad24ebSLingrui98
223c2ad24ebSLingrui98    // println(f"new bits set ${newest_bits_set.map(_._1)}")
224c2ad24ebSLingrui98    //
225c2ad24ebSLingrui98    val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{
226ab890bfeSLingrui98      case (fb, i) => fb && !(num >= (len-i)).B
227c2ad24ebSLingrui98    })
228c2ad24ebSLingrui98    val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i)))
229c2ad24ebSLingrui98
230c2ad24ebSLingrui98
231c2ad24ebSLingrui98    // histLen too short to wrap around
232c2ad24ebSLingrui98    val new_folded_hist =
233dd6c0695SLingrui98      if (len <= compLen) {
234dd6c0695SLingrui98        ((folded_hist << num) | taken)(compLen-1,0)
235c2ad24ebSLingrui98        // circular_shift_left(max_update_num)(Cat(Reverse(newest_bits_masked), folded_hist(compLen-max_update_num-1,0)), num)
236c2ad24ebSLingrui98      } else {
237c2ad24ebSLingrui98        // do xor then shift
238c2ad24ebSLingrui98        val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set))
239ab890bfeSLingrui98        circular_shift_left(xored, num)
240c2ad24ebSLingrui98      }
241c2ad24ebSLingrui98    val fh = WireInit(this)
242c2ad24ebSLingrui98    fh.folded_hist := new_folded_hist
243c2ad24ebSLingrui98    fh
244c2ad24ebSLingrui98  }
24509c6f1ddSLingrui98}
24609c6f1ddSLingrui98
24709c6f1ddSLingrui98class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{
24809c6f1ddSLingrui98  def tagBits = VAddrBits - idxBits - instOffsetBits
24909c6f1ddSLingrui98
25009c6f1ddSLingrui98  val tag = UInt(tagBits.W)
25109c6f1ddSLingrui98  val idx = UInt(idxBits.W)
25209c6f1ddSLingrui98  val offset = UInt(instOffsetBits.W)
25309c6f1ddSLingrui98
25409c6f1ddSLingrui98  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
25509c6f1ddSLingrui98  def getTag(x: UInt) = fromUInt(x).tag
25609c6f1ddSLingrui98  def getIdx(x: UInt) = fromUInt(x).idx
25709c6f1ddSLingrui98  def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U
25809c6f1ddSLingrui98  def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x)
25909c6f1ddSLingrui98}
260eeb5ff92SLingrui98
261*b37e4b45SLingrui98trait BasicPrediction extends HasXSParameter {
262*b37e4b45SLingrui98  def cfiIndex: ValidUndirectioned[UInt]
263*b37e4b45SLingrui98  def target(pc: UInt): UInt
264*b37e4b45SLingrui98  def lastBrPosOH: Vec[Bool]
265*b37e4b45SLingrui98  def brTaken: Bool
266*b37e4b45SLingrui98  def shouldShiftVec: Vec[Bool]
267*b37e4b45SLingrui98  def fallThruError: Bool
268*b37e4b45SLingrui98  val oversize: Bool
269*b37e4b45SLingrui98}
270*b37e4b45SLingrui98class MinimalBranchPrediction(implicit p: Parameters) extends NewMicroBTBEntry with BasicPrediction {
271*b37e4b45SLingrui98  val valid = Bool()
272*b37e4b45SLingrui98  def cfiIndex = {
273*b37e4b45SLingrui98    val res = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
274*b37e4b45SLingrui98    res.valid := taken && valid
275*b37e4b45SLingrui98    res.bits := cfiOffset | Fill(res.bits.getWidth, !valid)
276*b37e4b45SLingrui98    res
277*b37e4b45SLingrui98  }
278*b37e4b45SLingrui98  def target(pc: UInt) = nextAddr
279*b37e4b45SLingrui98  def lastBrPosOH: Vec[Bool] = VecInit(brNumOH.asBools())
280*b37e4b45SLingrui98  def brTaken = takenOnBr
281*b37e4b45SLingrui98  def shouldShiftVec: Vec[Bool] = VecInit((0 until numBr).map(i => lastBrPosOH.drop(i+1).reduce(_||_)))
282*b37e4b45SLingrui98  def fallThruError: Bool = false.B
283*b37e4b45SLingrui98
284*b37e4b45SLingrui98  def fromMicroBTBEntry(valid: Bool, entry: NewMicroBTBEntry, pc: UInt) = {
285*b37e4b45SLingrui98    this.valid := valid
286*b37e4b45SLingrui98    this.nextAddr := Mux(valid, entry.nextAddr, pc + (FetchWidth*4).U)
287*b37e4b45SLingrui98    this.cfiOffset := entry.cfiOffset | Fill(cfiOffset.getWidth, !valid)
288*b37e4b45SLingrui98    this.taken := entry.taken && valid
289*b37e4b45SLingrui98    this.takenOnBr := entry.takenOnBr && valid
290*b37e4b45SLingrui98    this.brNumOH := Mux(valid, entry.brNumOH, 1.U(3.W))
291*b37e4b45SLingrui98    this.oversize := entry.oversize && valid
292*b37e4b45SLingrui98  }
293*b37e4b45SLingrui98}
294eeb5ff92SLingrui98@chiselName
295*b37e4b45SLingrui98class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction {
296eeb5ff92SLingrui98  val br_taken_mask = Vec(numBr, Bool())
29709c6f1ddSLingrui98
298eeb5ff92SLingrui98  val slot_valids = Vec(totalSlot, Bool())
29909c6f1ddSLingrui98
300eeb5ff92SLingrui98  val targets = Vec(totalSlot, UInt(VAddrBits.W))
301b30c10d6SLingrui98  val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors
302a229ab6cSLingrui98  val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W))
303a229ab6cSLingrui98  val fallThroughAddr = UInt(VAddrBits.W)
304*b37e4b45SLingrui98  val fallThroughErr = Bool()
305a229ab6cSLingrui98  val oversize = Bool()
30609c6f1ddSLingrui98
30709c6f1ddSLingrui98  val is_jal = Bool()
30809c6f1ddSLingrui98  val is_jalr = Bool()
30909c6f1ddSLingrui98  val is_call = Bool()
31009c6f1ddSLingrui98  val is_ret = Bool()
311eeb5ff92SLingrui98  val is_br_sharing = Bool()
31209c6f1ddSLingrui98
31309c6f1ddSLingrui98  // val call_is_rvc = Bool()
31409c6f1ddSLingrui98  val hit = Bool()
31509c6f1ddSLingrui98
316eeb5ff92SLingrui98  def br_slot_valids = slot_valids.init
317eeb5ff92SLingrui98  def tail_slot_valid = slot_valids.last
318eeb5ff92SLingrui98
319eeb5ff92SLingrui98  def br_valids = {
320*b37e4b45SLingrui98    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
321eeb5ff92SLingrui98  }
322eeb5ff92SLingrui98
323eeb5ff92SLingrui98  def taken_mask_on_slot = {
324eeb5ff92SLingrui98    VecInit(
325eeb5ff92SLingrui98      (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ (
326b30c10d6SLingrui98        tail_slot_valid && (
327b30c10d6SLingrui98          is_br_sharing && br_taken_mask.last || !is_br_sharing
328b30c10d6SLingrui98        )
329eeb5ff92SLingrui98      )
330eeb5ff92SLingrui98    )
331eeb5ff92SLingrui98  }
332eeb5ff92SLingrui98
333*b37e4b45SLingrui98  def real_slot_taken_mask(): Vec[Bool] = {
334*b37e4b45SLingrui98    VecInit(taken_mask_on_slot.map(_ && hit))
335*b37e4b45SLingrui98  }
336*b37e4b45SLingrui98
337*b37e4b45SLingrui98  // len numBr
338*b37e4b45SLingrui98  def real_br_taken_mask(): Vec[Bool] = {
339*b37e4b45SLingrui98    VecInit(
340*b37e4b45SLingrui98      taken_mask_on_slot.map(_ && hit).init :+
341*b37e4b45SLingrui98      (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
342*b37e4b45SLingrui98    )
343*b37e4b45SLingrui98  }
344*b37e4b45SLingrui98
345*b37e4b45SLingrui98  // the vec indicating if ghr should shift on each branch
346*b37e4b45SLingrui98  def shouldShiftVec =
347*b37e4b45SLingrui98    VecInit(br_valids.zipWithIndex.map{ case (v, i) =>
348*b37e4b45SLingrui98      v && !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B)})
349*b37e4b45SLingrui98
350*b37e4b45SLingrui98  def lastBrPosOH =
351*b37e4b45SLingrui98    VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry
352*b37e4b45SLingrui98      (0 until numBr).map(i =>
353*b37e4b45SLingrui98        br_valids(i) &&
354*b37e4b45SLingrui98        !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it
355*b37e4b45SLingrui98        (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it
356*b37e4b45SLingrui98        hit
357*b37e4b45SLingrui98      )
358*b37e4b45SLingrui98    )
359*b37e4b45SLingrui98
360*b37e4b45SLingrui98  def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b }.reduce(_||_)
361*b37e4b45SLingrui98
362*b37e4b45SLingrui98  def target(pc: UInt): UInt = {
363*b37e4b45SLingrui98    val targetVecOnHit = targets :+ fallThroughAddr
364*b37e4b45SLingrui98    val targetOnNotHit = pc + (FetchWidth * 4).U
365*b37e4b45SLingrui98    val taken_mask = taken_mask_on_slot
366*b37e4b45SLingrui98    val selVecOHOnHit =
367*b37e4b45SLingrui98      taken_mask.zipWithIndex.map{ case (t, i) => !taken_mask.take(i).fold(false.B)(_||_) && t} :+ !taken_mask.asUInt.orR
368*b37e4b45SLingrui98    val targetOnHit = Mux1H(selVecOHOnHit, targetVecOnHit)
369*b37e4b45SLingrui98    Mux(hit, targetOnHit, targetOnNotHit)
370*b37e4b45SLingrui98  }
371*b37e4b45SLingrui98
372*b37e4b45SLingrui98  def fallThruError: Bool = hit && fallThroughErr
373*b37e4b45SLingrui98
374*b37e4b45SLingrui98  def hit_taken_on_jmp =
375*b37e4b45SLingrui98    !real_slot_taken_mask().init.reduce(_||_) &&
376*b37e4b45SLingrui98    real_slot_taken_mask().last && !is_br_sharing
377*b37e4b45SLingrui98  def hit_taken_on_call = hit_taken_on_jmp && is_call
378*b37e4b45SLingrui98  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
379*b37e4b45SLingrui98  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
380*b37e4b45SLingrui98
381*b37e4b45SLingrui98  def cfiIndex = {
382*b37e4b45SLingrui98    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
383*b37e4b45SLingrui98    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
384*b37e4b45SLingrui98    // when no takens, set cfiIndex to PredictWidth-1
385*b37e4b45SLingrui98    cfiIndex.bits :=
386*b37e4b45SLingrui98      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
387*b37e4b45SLingrui98      Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
388*b37e4b45SLingrui98    cfiIndex
389*b37e4b45SLingrui98  }
390*b37e4b45SLingrui98
391eeb5ff92SLingrui98  def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr)
39209c6f1ddSLingrui98
393b30c10d6SLingrui98  def fromFtbEntry(entry: FTBEntry, pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
394eeb5ff92SLingrui98    slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
395eeb5ff92SLingrui98    targets := entry.getTargetVec(pc)
396b30c10d6SLingrui98    jalr_target := targets.last
397a229ab6cSLingrui98    offsets := entry.getOffsetVec
398a229ab6cSLingrui98    fallThroughAddr := entry.getFallThrough(pc)
399a229ab6cSLingrui98    oversize := entry.oversize
400eeb5ff92SLingrui98    is_jal := entry.tailSlot.valid && entry.isJal
401eeb5ff92SLingrui98    is_jalr := entry.tailSlot.valid && entry.isJalr
402eeb5ff92SLingrui98    is_call := entry.tailSlot.valid && entry.isCall
403eeb5ff92SLingrui98    is_ret := entry.tailSlot.valid && entry.isRet
404eeb5ff92SLingrui98    is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing
405a229ab6cSLingrui98
406*b37e4b45SLingrui98    val startLower        = Cat(0.U(1.W),    pc(instOffsetBits+log2Ceil(PredictWidth), instOffsetBits))
407*b37e4b45SLingrui98    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
408*b37e4b45SLingrui98    fallThroughErr := startLower >= endLowerwithCarry || (endLowerwithCarry - startLower) > (PredictWidth+1).U
409a229ab6cSLingrui98  }
41009c6f1ddSLingrui98
41109c6f1ddSLingrui98  def display(cond: Bool): Unit = {
412eeb5ff92SLingrui98    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
41309c6f1ddSLingrui98  }
41409c6f1ddSLingrui98}
41509c6f1ddSLingrui98
416bf358e08SLingrui98@chiselName
417*b37e4b45SLingrui98class BranchPredictionBundle(implicit p: Parameters) extends XSBundle
418*b37e4b45SLingrui98  with HasBPUConst with BPUUtils {
419*b37e4b45SLingrui98  // def full_pred_info[T <: Data](x: T) = if (is_minimal) None else Some(x)
42009c6f1ddSLingrui98  val pc = UInt(VAddrBits.W)
42109c6f1ddSLingrui98
42209c6f1ddSLingrui98  val valid = Bool()
42309c6f1ddSLingrui98
42409c6f1ddSLingrui98  val hasRedirect = Bool()
42509c6f1ddSLingrui98  val ftq_idx = new FtqPtr
42609c6f1ddSLingrui98  // val hit = Bool()
427*b37e4b45SLingrui98  val is_minimal = Bool()
428*b37e4b45SLingrui98  val minimal_pred = new MinimalBranchPrediction
429*b37e4b45SLingrui98  val full_pred = new FullBranchPrediction
430*b37e4b45SLingrui98
43109c6f1ddSLingrui98
432dd6c0695SLingrui98  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
433*b37e4b45SLingrui98  val ghr = UInt(UbtbGHRLength.W)
434c2ad24ebSLingrui98  val histPtr = new CGHPtr
43509c6f1ddSLingrui98  val rasSp = UInt(log2Ceil(RasSize).W)
43609c6f1ddSLingrui98  val rasTop = new RASEntry
437*b37e4b45SLingrui98  // val specCnt = Vec(numBr, UInt(10.W))
43809c6f1ddSLingrui98  // val meta = UInt(MaxMetaLength.W)
43909c6f1ddSLingrui98
440*b37e4b45SLingrui98  val ftb_entry = new FTBEntry()
44109c6f1ddSLingrui98
442*b37e4b45SLingrui98  def target(pc: UInt) = Mux(is_minimal, minimal_pred.target(pc),     full_pred.target(pc))
443*b37e4b45SLingrui98  def cfiIndex         = Mux(is_minimal, minimal_pred.cfiIndex,       full_pred.cfiIndex)
444*b37e4b45SLingrui98  def lastBrPosOH      = Mux(is_minimal, minimal_pred.lastBrPosOH,    full_pred.lastBrPosOH)
445*b37e4b45SLingrui98  def brTaken          = Mux(is_minimal, minimal_pred.brTaken,        full_pred.brTaken)
446*b37e4b45SLingrui98  def shouldShiftVec   = Mux(is_minimal, minimal_pred.shouldShiftVec, full_pred.shouldShiftVec)
447*b37e4b45SLingrui98  def oversize         = Mux(is_minimal, minimal_pred.oversize,       full_pred.oversize)
448*b37e4b45SLingrui98  def fallThruError    = Mux(is_minimal, minimal_pred.fallThruError,  full_pred.fallThruError)
449eeb5ff92SLingrui98
450*b37e4b45SLingrui98  def getTarget = target(pc)
451*b37e4b45SLingrui98  def taken = cfiIndex.valid
45209c6f1ddSLingrui98
45309c6f1ddSLingrui98  def display(cond: Bool): Unit = {
45409c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(pc)}\n")
455dd6c0695SLingrui98    folded_hist.display(cond)
456*b37e4b45SLingrui98    full_pred.display(cond)
45709c6f1ddSLingrui98    ftb_entry.display(cond)
45809c6f1ddSLingrui98  }
45909c6f1ddSLingrui98}
46009c6f1ddSLingrui98
461bf358e08SLingrui98@chiselName
46209c6f1ddSLingrui98class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
46309c6f1ddSLingrui98  // val valids = Vec(3, Bool())
464*b37e4b45SLingrui98  val s1 = new BranchPredictionBundle
465*b37e4b45SLingrui98  val s2 = new BranchPredictionBundle
46609c6f1ddSLingrui98
467*b37e4b45SLingrui98  def selectedResp ={
468*b37e4b45SLingrui98    val res =
46909c6f1ddSLingrui98      PriorityMux(Seq(
47009c6f1ddSLingrui98        ((s2.valid && s2.hasRedirect) -> s2),
47109c6f1ddSLingrui98        (s1.valid -> s1)
47209c6f1ddSLingrui98      ))
473*b37e4b45SLingrui98    // println("is minimal: ", res.is_minimal)
474*b37e4b45SLingrui98    res
475*b37e4b45SLingrui98  }
47609c6f1ddSLingrui98  def selectedRespIdx =
47709c6f1ddSLingrui98    PriorityMux(Seq(
47809c6f1ddSLingrui98      ((s2.valid && s2.hasRedirect) -> BP_S2),
47909c6f1ddSLingrui98      (s1.valid -> BP_S1)
48009c6f1ddSLingrui98    ))
4813e52bed1SLingrui98  def lastStage = s2
48209c6f1ddSLingrui98}
48309c6f1ddSLingrui98
48409c6f1ddSLingrui98class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp with HasBPUConst {
48509c6f1ddSLingrui98  val meta = UInt(MaxMetaLength.W)
48609c6f1ddSLingrui98}
48709c6f1ddSLingrui98
48809c6f1ddSLingrui98object BpuToFtqBundle {
48909c6f1ddSLingrui98  def apply(resp: BranchPredictionResp)(implicit p: Parameters): BpuToFtqBundle = {
49009c6f1ddSLingrui98    val e = Wire(new BpuToFtqBundle())
49109c6f1ddSLingrui98    e.s1 := resp.s1
49209c6f1ddSLingrui98    e.s2 := resp.s2
49309c6f1ddSLingrui98
49409c6f1ddSLingrui98    e.meta := DontCare
49509c6f1ddSLingrui98    e
49609c6f1ddSLingrui98  }
49709c6f1ddSLingrui98}
49809c6f1ddSLingrui98
49909c6f1ddSLingrui98class BranchPredictionUpdate(implicit p: Parameters) extends BranchPredictionBundle with HasBPUConst {
50009c6f1ddSLingrui98  val mispred_mask = Vec(numBr+1, Bool())
50109c6f1ddSLingrui98  val false_hit = Bool()
50209c6f1ddSLingrui98  val new_br_insert_pos = Vec(numBr, Bool())
50309c6f1ddSLingrui98  val old_entry = Bool()
50409c6f1ddSLingrui98  val meta = UInt(MaxMetaLength.W)
505abdbe4b7SLingrui98  val full_target = UInt(VAddrBits.W)
50609c6f1ddSLingrui98
50709c6f1ddSLingrui98  def fromFtqRedirectSram(entry: Ftq_Redirect_SRAMEntry) = {
508dd6c0695SLingrui98    folded_hist := entry.folded_hist
509*b37e4b45SLingrui98    ghr := entry.ghr
510c2ad24ebSLingrui98    histPtr := entry.histPtr
51109c6f1ddSLingrui98    rasSp := entry.rasSp
51209c6f1ddSLingrui98    rasTop := entry.rasEntry
51309c6f1ddSLingrui98    this
51409c6f1ddSLingrui98  }
51509c6f1ddSLingrui98
516c2ad24ebSLingrui98  override def display(cond: Bool) = {
51709c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
51809c6f1ddSLingrui98    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
51909c6f1ddSLingrui98    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
52009c6f1ddSLingrui98    super.display(cond)
52109c6f1ddSLingrui98    XSDebug(cond, p"--------------------------------------------\n")
52209c6f1ddSLingrui98  }
52309c6f1ddSLingrui98}
52409c6f1ddSLingrui98
52509c6f1ddSLingrui98class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
52609c6f1ddSLingrui98  // override def toPrintable: Printable = {
52709c6f1ddSLingrui98  //   p"-----------BranchPredictionRedirect----------- " +
52809c6f1ddSLingrui98  //     p"-----------cfiUpdate----------- " +
52909c6f1ddSLingrui98  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
53009c6f1ddSLingrui98  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
53109c6f1ddSLingrui98  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
53209c6f1ddSLingrui98  //     p"------------------------------- " +
5339aca92b9SYinan Xu  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
53409c6f1ddSLingrui98  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
53509c6f1ddSLingrui98  //     p"[ftqOffset] ${ftqOffset} " +
53609c6f1ddSLingrui98  //     p"[level] ${level}, [interrupt] ${interrupt} " +
53709c6f1ddSLingrui98  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
53809c6f1ddSLingrui98  //     p"[stFtqOffset] ${stFtqOffset} " +
53909c6f1ddSLingrui98  //     p"\n"
54009c6f1ddSLingrui98
54109c6f1ddSLingrui98  // }
54209c6f1ddSLingrui98
54309c6f1ddSLingrui98  def display(cond: Bool): Unit = {
54409c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
54509c6f1ddSLingrui98    XSDebug(cond, p"-----------cfiUpdate----------- \n")
54609c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
547c2ad24ebSLingrui98    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
54809c6f1ddSLingrui98    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
54909c6f1ddSLingrui98    XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n")
55009c6f1ddSLingrui98    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
55109c6f1ddSLingrui98    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
55209c6f1ddSLingrui98    XSDebug(cond, p"------------------------------- \n")
5539aca92b9SYinan Xu    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
55409c6f1ddSLingrui98    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
55509c6f1ddSLingrui98    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
55609c6f1ddSLingrui98    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
55709c6f1ddSLingrui98    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
55809c6f1ddSLingrui98    XSDebug(cond, p"---------------------------------------------- \n")
55909c6f1ddSLingrui98  }
56009c6f1ddSLingrui98}
561