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