xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision 67402d755e80728b85a28ad33ba1f7b84036bdc1)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16package xiangshan.frontend
17
18import chipsalliance.rocketchip.config.Parameters
19import chisel3._
20import chisel3.util._
21import chisel3.experimental.chiselName
22import xiangshan._
23import xiangshan.frontend.icache.HasICacheParameters
24import utils._
25import scala.math._
26
27@chiselName
28class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
29  val startAddr       = UInt(VAddrBits.W)
30  val nextlineStart   = UInt(VAddrBits.W)
31  // val fallThruError   = Bool()
32  val ftqIdx          = new FtqPtr
33  val ftqOffset       = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
34  val nextStartAddr   = UInt(VAddrBits.W)
35  val oversize        = Bool()
36
37  def crossCacheline = startAddr(blockOffBits - 1) === 1.U
38
39  def fromFtqPcBundle(b: Ftq_RF_Components) = {
40    this.startAddr := b.startAddr
41    this.nextlineStart := b.nextLineAddr
42    this.oversize := b.oversize
43    when (b.fallThruError) {
44      val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.startAddr, b.nextLineAddr)
45      val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1)
46      this.nextStartAddr :=
47        Cat(nextBlockHigher,
48          startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W),
49          startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits),
50          0.U(instOffsetBits.W)
51        )
52    }
53    this
54  }
55  override def toPrintable: Printable = {
56    p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" +
57      p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" +
58      p" offset: ${ftqOffset.bits}\n"
59  }
60}
61
62class PredecodeWritebackBundle(implicit p:Parameters) extends XSBundle {
63  val pc           = Vec(PredictWidth, UInt(VAddrBits.W))
64  val pd           = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode
65  val ftqIdx       = new FtqPtr
66  val ftqOffset    = UInt(log2Ceil(PredictWidth).W)
67  val misOffset    = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
68  val cfiOffset    = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
69  val target       = UInt(VAddrBits.W)
70  val jalTarget    = UInt(VAddrBits.W)
71  val instrRange   = Vec(PredictWidth, Bool())
72}
73
74// Ftq send req to Prefetch
75class PrefetchRequest(implicit p:Parameters) extends XSBundle {
76  val target          = UInt(VAddrBits.W)
77}
78
79class FtqPrefechBundle(implicit p:Parameters) extends XSBundle {
80  val req = DecoupledIO(new PrefetchRequest)
81}
82
83class FetchToIBuffer(implicit p: Parameters) extends XSBundle {
84  val instrs    = Vec(PredictWidth, UInt(32.W))
85  val valid     = UInt(PredictWidth.W)
86  val enqEnable = UInt(PredictWidth.W)
87  val pd        = Vec(PredictWidth, new PreDecodeInfo)
88  val pc        = Vec(PredictWidth, UInt(VAddrBits.W))
89  val foldpc    = Vec(PredictWidth, UInt(MemPredPCWidth.W))
90  val ftqPtr       = new FtqPtr
91  val ftqOffset    = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
92  val ipf          = Vec(PredictWidth, Bool())
93  val acf          = Vec(PredictWidth, Bool())
94  val crossPageIPFFix = Vec(PredictWidth, Bool())
95  val triggered    = Vec(PredictWidth, new TriggerCf)
96}
97
98// class BitWiseUInt(val width: Int, val init: UInt) extends Module {
99//   val io = IO(new Bundle {
100//     val set
101//   })
102// }
103// Move from BPU
104abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst {
105  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory
106}
107
108class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory {
109  val predHist = UInt(HistoryLength.W)
110
111  def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = {
112    val g = Wire(new ShiftingGlobalHistory)
113    g.predHist := (hist << shift) | taken
114    g
115  }
116
117  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = {
118    require(br_valids.length == numBr)
119    require(real_taken_mask.length == numBr)
120    val last_valid_idx = PriorityMux(
121      br_valids.reverse :+ true.B,
122      (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W))
123    )
124    val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask)
125    val smaller = Mux(last_valid_idx < first_taken_idx,
126      last_valid_idx,
127      first_taken_idx
128    )
129    val shift = smaller
130    val taken = real_taken_mask.reduce(_||_)
131    update(shift, taken, this.predHist)
132  }
133
134  // static read
135  def read(n: Int): Bool = predHist.asBools()(n)
136
137  final def === (that: ShiftingGlobalHistory): Bool = {
138    predHist === that.predHist
139  }
140
141  final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that)
142}
143
144// circular global history pointer
145class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr](
146  p => p(XSCoreParamsKey).HistoryLength
147){
148  override def cloneType = (new CGHPtr).asInstanceOf[this.type]
149}
150class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory {
151  val buffer = Vec(HistoryLength, Bool())
152  type HistPtr = UInt
153  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = {
154    this
155  }
156}
157
158class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters)
159  extends XSBundle with HasBPUConst {
160  require(compLen >= 1)
161  require(len > 0)
162  // require(folded_len <= len)
163  require(compLen >= max_update_num)
164  val folded_hist = UInt(compLen.W)
165
166  def need_oldest_bits = len > compLen
167  def info = (len, compLen)
168  def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1)
169  def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen)
170  def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0)
171  def oldest_bit_start = oldest_bit_pos_in_folded.head
172
173  def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = {
174    // TODO: wrap inc for histPtr value
175    oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value))
176  }
177
178  def circular_shift_left(src: UInt, shamt: Int) = {
179    val srcLen = src.getWidth
180    val src_doubled = Cat(src, src)
181    val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt)
182    shifted
183  }
184
185  // slow path, read bits from ghr
186  def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = {
187    val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr))
188    update(oldest_bits, num, taken)
189  }
190
191
192  // fast path, use pre-read oldest bits
193  def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = {
194    // do xors for several bitsets at specified bits
195    def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = {
196      val res = Wire(Vec(len, Bool()))
197      // println(f"num bitsets: ${bitsets.length}")
198      // println(f"bitsets $bitsets")
199      val resArr = Array.fill(len)(List[Bool]())
200      for (bs <- bitsets) {
201        for ((n, b) <- bs) {
202          resArr(n) = b :: resArr(n)
203        }
204      }
205      // println(f"${resArr.mkString}")
206      // println(f"histLen: ${this.len}, foldedLen: $folded_len")
207      for (i <- 0 until len) {
208        // println(f"bit[$i], ${resArr(i).mkString}")
209        if (resArr(i).length > 2) {
210          println(f"[warning] update logic of foldest history has two or more levels of xor gates! " +
211            f"histlen:${this.len}, compLen:$compLen, at bit $i")
212        }
213        if (resArr(i).length == 0) {
214          println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen")
215        }
216        res(i) := resArr(i).foldLeft(false.B)(_^_)
217      }
218      res.asUInt
219    }
220
221    val new_folded_hist = if (need_oldest_bits) {
222      val oldest_bits = ob
223      require(oldest_bits.length == max_update_num)
224      // mask off bits that do not update
225      val oldest_bits_masked = oldest_bits.zipWithIndex.map{
226        case (ob, i) => ob && (i < num).B
227      }
228      // if a bit does not wrap around, it should not be xored when it exits
229      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)))
230
231      // println(f"old bits pos ${oldest_bits_set.map(_._1)}")
232
233      // only the last bit could be 1, as we have at most one taken branch at a time
234      val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt
235      // if a bit does not wrap around, newest bits should not be xored onto it either
236      val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i)))
237
238      // println(f"new bits set ${newest_bits_set.map(_._1)}")
239      //
240      val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{
241        case (fb, i) => fb && !(num >= (len-i)).B
242      })
243      val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i)))
244
245      // do xor then shift
246      val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set))
247      circular_shift_left(xored, num)
248    } else {
249      // histLen too short to wrap around
250      ((folded_hist << num) | taken)(compLen-1,0)
251    }
252
253    val fh = WireInit(this)
254    fh.folded_hist := new_folded_hist
255    fh
256  }
257}
258
259class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle {
260  val bits = Vec(max_update_num*2, Bool())
261  // def info = (len, compLen)
262  def getRealOb(brNumOH: UInt): Vec[Bool] = {
263    val ob = Wire(Vec(max_update_num, Bool()))
264    for (i <- 0 until max_update_num) {
265      ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr+1))
266    }
267    ob
268  }
269}
270
271class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
272  val afhob = MixedVec(gen.filter(t => t._1 > t._2).map{_._1}
273    .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates
274  require(gen.toSet.toList.equals(gen))
275  def getObWithInfo(info: Tuple2[Int, Int]) = {
276    val selected = afhob.filter(_.len == info._1)
277    require(selected.length == 1)
278    selected(0)
279  }
280  def read(ghv: Vec[Bool], ptr: CGHPtr) = {
281    val hisLens = afhob.map(_.len)
282    val bitsToRead = hisLens.flatMap(l => (0 until numBr*2).map(i => l-i-1)).toSet // remove duplicates
283    val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr+(pos+1).U).value)))
284    for (ob <- afhob) {
285      for (i <- 0 until numBr*2) {
286        val pos = ob.len - i - 1
287        val bit_found = bitsWithInfo.filter(_._1 == pos).toList
288        require(bit_found.length == 1)
289        ob.bits(i) := bit_found(0)._2
290      }
291    }
292  }
293}
294
295class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
296  val hist = MixedVec(gen.map{case (l, cl) => new FoldedHistory(l, cl, numBr)})
297  // println(gen.mkString)
298  require(gen.toSet.toList.equals(gen))
299  def getHistWithInfo(info: Tuple2[Int, Int]) = {
300    val selected = hist.filter(_.info.equals(info))
301    require(selected.length == 1)
302    selected(0)
303  }
304  def autoConnectFrom(that: AllFoldedHistories) = {
305    require(this.hist.length <= that.hist.length)
306    for (h <- this.hist) {
307      h := that.getHistWithInfo(h.info)
308    }
309  }
310  def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = {
311    val res = WireInit(this)
312    for (i <- 0 until this.hist.length) {
313      res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken)
314    }
315    res
316  }
317  def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = {
318    val res = WireInit(this)
319    for (i <- 0 until this.hist.length) {
320      val fh = this.hist(i)
321      if (fh.need_oldest_bits) {
322        val info = fh.info
323        val selectedAfhob = afhob.getObWithInfo(info)
324        val ob = selectedAfhob.getRealOb(lastBrNumOH)
325        res.hist(i) := this.hist(i).update(ob, shift, taken)
326      } else {
327        val dumb = Wire(Vec(numBr, Bool())) // not needed
328        dumb := DontCare
329        res.hist(i) := this.hist(i).update(dumb, shift, taken)
330      }
331    }
332    res
333  }
334
335  def display(cond: Bool) = {
336    for (h <- hist) {
337      XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n")
338    }
339  }
340}
341
342class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{
343  def tagBits = VAddrBits - idxBits - instOffsetBits
344
345  val tag = UInt(tagBits.W)
346  val idx = UInt(idxBits.W)
347  val offset = UInt(instOffsetBits.W)
348
349  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
350  def getTag(x: UInt) = fromUInt(x).tag
351  def getIdx(x: UInt) = fromUInt(x).idx
352  def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U
353  def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x)
354}
355
356trait BasicPrediction extends HasXSParameter {
357  def cfiIndex: ValidUndirectioned[UInt]
358  def target(pc: UInt): UInt
359  def lastBrPosOH: Vec[Bool]
360  def brTaken: Bool
361  def shouldShiftVec: Vec[Bool]
362  def fallThruError: Bool
363  val oversize: Bool
364}
365class MinimalBranchPrediction(implicit p: Parameters) extends NewMicroBTBEntry with BasicPrediction {
366  val valid = Bool()
367  def cfiIndex = {
368    val res = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
369    res.valid := taken && valid
370    res.bits := cfiOffset | Fill(res.bits.getWidth, !valid)
371    res
372  }
373  def target(pc: UInt) = nextAddr
374  def lastBrPosOH: Vec[Bool] = VecInit(brNumOH.asBools())
375  def brTaken = takenOnBr
376  def shouldShiftVec: Vec[Bool] = VecInit((0 until numBr).map(i => lastBrPosOH.drop(i+1).reduce(_||_)))
377  def fallThruError: Bool = false.B
378
379  def fromMicroBTBEntry(valid: Bool, entry: NewMicroBTBEntry, pc: UInt) = {
380    this.valid := valid
381    this.nextAddr := Mux(valid, entry.nextAddr, pc + (FetchWidth*4).U)
382    this.cfiOffset := entry.cfiOffset | Fill(cfiOffset.getWidth, !valid)
383    this.taken := entry.taken && valid
384    this.takenOnBr := entry.takenOnBr && valid
385    this.brNumOH := Mux(valid, entry.brNumOH, 1.U(3.W))
386    this.oversize := entry.oversize && valid
387  }
388}
389@chiselName
390class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction {
391  val br_taken_mask = Vec(numBr, Bool())
392
393  val slot_valids = Vec(totalSlot, Bool())
394
395  val targets = Vec(totalSlot, UInt(VAddrBits.W))
396  val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors
397  val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W))
398  val fallThroughAddr = UInt(VAddrBits.W)
399  val fallThroughErr = Bool()
400  val oversize = Bool()
401
402  val is_jal = Bool()
403  val is_jalr = Bool()
404  val is_call = Bool()
405  val is_ret = Bool()
406  val is_br_sharing = Bool()
407
408  // val call_is_rvc = Bool()
409  val hit = Bool()
410
411  def br_slot_valids = slot_valids.init
412  def tail_slot_valid = slot_valids.last
413
414  def br_valids = {
415    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
416  }
417
418  def taken_mask_on_slot = {
419    VecInit(
420      (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ (
421        tail_slot_valid && (
422          is_br_sharing && br_taken_mask.last || !is_br_sharing
423        )
424      )
425    )
426  }
427
428  def real_slot_taken_mask(): Vec[Bool] = {
429    VecInit(taken_mask_on_slot.map(_ && hit))
430  }
431
432  // len numBr
433  def real_br_taken_mask(): Vec[Bool] = {
434    VecInit(
435      taken_mask_on_slot.map(_ && hit).init :+
436      (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
437    )
438  }
439
440  // the vec indicating if ghr should shift on each branch
441  def shouldShiftVec =
442    VecInit(br_valids.zipWithIndex.map{ case (v, i) =>
443      v && !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B)})
444
445  def lastBrPosOH =
446    VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry
447      (0 until numBr).map(i =>
448        br_valids(i) &&
449        !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it
450        (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it
451        hit
452      )
453    )
454
455  def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_)
456
457  def target(pc: UInt): UInt = {
458    val targetVec = targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U)
459    val tm = taken_mask_on_slot
460    val selVecOH =
461      tm.zipWithIndex.map{ case (t, i) => !tm.take(i).fold(false.B)(_||_) && t && hit} :+
462      (!tm.asUInt.orR && hit) :+ !hit
463    Mux1H(selVecOH, targetVec)
464  }
465
466  def fallThruError: Bool = hit && fallThroughErr
467
468  def hit_taken_on_jmp =
469    !real_slot_taken_mask().init.reduce(_||_) &&
470    real_slot_taken_mask().last && !is_br_sharing
471  def hit_taken_on_call = hit_taken_on_jmp && is_call
472  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
473  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
474
475  def cfiIndex = {
476    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
477    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
478    // when no takens, set cfiIndex to PredictWidth-1
479    cfiIndex.bits :=
480      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
481      Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
482    cfiIndex
483  }
484
485  def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr)
486
487  def fromFtbEntry(entry: FTBEntry, pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
488    slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
489    targets := entry.getTargetVec(pc)
490    jalr_target := targets.last
491    offsets := entry.getOffsetVec
492    oversize := entry.oversize
493    is_jal := entry.tailSlot.valid && entry.isJal
494    is_jalr := entry.tailSlot.valid && entry.isJalr
495    is_call := entry.tailSlot.valid && entry.isCall
496    is_ret := entry.tailSlot.valid && entry.isRet
497    is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing
498
499    val startLower        = Cat(0.U(1.W),    pc(instOffsetBits+log2Ceil(PredictWidth), instOffsetBits))
500    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
501    fallThroughErr := startLower >= endLowerwithCarry || (endLowerwithCarry - startLower) > (PredictWidth+1).U
502    fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc))
503  }
504
505  def display(cond: Bool): Unit = {
506    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
507  }
508}
509
510@chiselName
511class BranchPredictionBundle(implicit p: Parameters) extends XSBundle
512  with HasBPUConst with BPUUtils {
513  // def full_pred_info[T <: Data](x: T) = if (is_minimal) None else Some(x)
514  val pc = UInt(VAddrBits.W)
515
516  val valid = Bool()
517
518  val hasRedirect = Bool()
519  val ftq_idx = new FtqPtr
520  // val hit = Bool()
521  val is_minimal = Bool()
522  val minimal_pred = new MinimalBranchPrediction
523  val full_pred = new FullBranchPrediction
524
525
526  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
527  val afhob = new AllAheadFoldedHistoryOldestBits(foldedGHistInfos)
528  val lastBrNumOH = UInt((numBr+1).W)
529  val histPtr = new CGHPtr
530  val rasSp = UInt(log2Ceil(RasSize).W)
531  val rasTop = new RASEntry
532  // val specCnt = Vec(numBr, UInt(10.W))
533  // val meta = UInt(MaxMetaLength.W)
534
535  val ftb_entry = new FTBEntry()
536
537  def target(pc: UInt) = Mux(is_minimal, minimal_pred.target(pc),     full_pred.target(pc))
538  def cfiIndex         = Mux(is_minimal, minimal_pred.cfiIndex,       full_pred.cfiIndex)
539  def lastBrPosOH      = Mux(is_minimal, minimal_pred.lastBrPosOH,    full_pred.lastBrPosOH)
540  def brTaken          = Mux(is_minimal, minimal_pred.brTaken,        full_pred.brTaken)
541  def shouldShiftVec   = Mux(is_minimal, minimal_pred.shouldShiftVec, full_pred.shouldShiftVec)
542  def oversize         = Mux(is_minimal, minimal_pred.oversize,       full_pred.oversize)
543  def fallThruError    = Mux(is_minimal, minimal_pred.fallThruError,  full_pred.fallThruError)
544
545  def getTarget = target(pc)
546  def taken = cfiIndex.valid
547
548  def display(cond: Bool): Unit = {
549    XSDebug(cond, p"[pc] ${Hexadecimal(pc)}\n")
550    folded_hist.display(cond)
551    full_pred.display(cond)
552    ftb_entry.display(cond)
553  }
554}
555
556@chiselName
557class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
558  // val valids = Vec(3, Bool())
559  val s1 = new BranchPredictionBundle
560  val s2 = new BranchPredictionBundle
561  val s3 = new BranchPredictionBundle
562
563  def selectedResp ={
564    val res =
565      PriorityMux(Seq(
566        ((s3.valid && s3.hasRedirect) -> s3),
567        ((s2.valid && s2.hasRedirect) -> s2),
568        (s1.valid -> s1)
569      ))
570    // println("is minimal: ", res.is_minimal)
571    res
572  }
573  def selectedRespIdx =
574    PriorityMux(Seq(
575      ((s3.valid && s3.hasRedirect) -> BP_S3),
576      ((s2.valid && s2.hasRedirect) -> BP_S2),
577      (s1.valid -> BP_S1)
578    ))
579  def lastStage = s3
580}
581
582class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp with HasBPUConst {
583  val meta = UInt(MaxMetaLength.W)
584}
585
586object BpuToFtqBundle {
587  def apply(resp: BranchPredictionResp)(implicit p: Parameters): BpuToFtqBundle = {
588    val e = Wire(new BpuToFtqBundle())
589    e.s1 := resp.s1
590    e.s2 := resp.s2
591    e.s3 := resp.s3
592
593    e.meta := DontCare
594    e
595  }
596}
597
598class BranchPredictionUpdate(implicit p: Parameters) extends BranchPredictionBundle with HasBPUConst {
599  val mispred_mask = Vec(numBr+1, Bool())
600  val pred_hit = Bool()
601  val false_hit = Bool()
602  val new_br_insert_pos = Vec(numBr, Bool())
603  val old_entry = Bool()
604  val meta = UInt(MaxMetaLength.W)
605  val full_target = UInt(VAddrBits.W)
606  val from_stage = UInt(2.W)
607  val ghist = UInt(HistoryLength.W)
608
609  def fromFtqRedirectSram(entry: Ftq_Redirect_SRAMEntry) = {
610    folded_hist := entry.folded_hist
611    afhob := entry.afhob
612    lastBrNumOH := entry.lastBrNumOH
613    histPtr := entry.histPtr
614    rasSp := entry.rasSp
615    rasTop := entry.rasEntry
616    this
617  }
618
619  override def display(cond: Bool) = {
620    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
621    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
622    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
623    super.display(cond)
624    XSDebug(cond, p"--------------------------------------------\n")
625  }
626}
627
628class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
629  // override def toPrintable: Printable = {
630  //   p"-----------BranchPredictionRedirect----------- " +
631  //     p"-----------cfiUpdate----------- " +
632  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
633  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
634  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
635  //     p"------------------------------- " +
636  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
637  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
638  //     p"[ftqOffset] ${ftqOffset} " +
639  //     p"[level] ${level}, [interrupt] ${interrupt} " +
640  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
641  //     p"[stFtqOffset] ${stFtqOffset} " +
642  //     p"\n"
643
644  // }
645
646  def display(cond: Bool): Unit = {
647    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
648    XSDebug(cond, p"-----------cfiUpdate----------- \n")
649    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
650    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
651    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
652    XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n")
653    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
654    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
655    XSDebug(cond, p"------------------------------- \n")
656    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
657    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
658    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
659    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
660    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
661    XSDebug(cond, p"---------------------------------------------- \n")
662  }
663}
664