xref: /XiangShan/src/main/scala/xiangshan/frontend/FTB.scala (revision 4b2c87ba1d7965f6f2b0a396be707a6e2f6fb345)
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***************************************************************************************/
16
17package xiangshan.frontend
18
19import chisel3._
20import chisel3.util._
21import org.chipsalliance.cde.config.Parameters
22import scala.{Tuple2 => &}
23import utility._
24import utility.mbist.MbistPipeline
25import xiangshan._
26
27trait FTBParams extends HasXSParameter with HasBPUConst {
28  val numEntries = FtbSize
29  val numWays    = FtbWays
30  val numSets    = numEntries / numWays // 512
31  val tagLength  = FtbTagLength
32
33  val TAR_STAT_SZ = 2
34  def TAR_FIT     = 0.U(TAR_STAT_SZ.W)
35  def TAR_OVF     = 1.U(TAR_STAT_SZ.W)
36  def TAR_UDF     = 2.U(TAR_STAT_SZ.W)
37
38  def BR_OFFSET_LEN  = 12
39  def JMP_OFFSET_LEN = 20
40
41  def FTBCLOSE_THRESHOLD_SZ = log2Ceil(500)
42  def FTBCLOSE_THRESHOLD    = 500.U(FTBCLOSE_THRESHOLD_SZ.W) // can be modified
43}
44
45class FtbSlot_FtqMem(implicit p: Parameters) extends XSBundle with FTBParams {
46  val offset  = UInt(log2Ceil(PredictWidth).W)
47  val sharing = Bool()
48  val valid   = Bool()
49}
50
51class FtbSlot(val offsetLen: Int, val subOffsetLen: Option[Int] = None)(implicit p: Parameters) extends FtbSlot_FtqMem
52    with FTBParams {
53  if (subOffsetLen.isDefined) {
54    require(subOffsetLen.get <= offsetLen)
55  }
56  val lower   = UInt(offsetLen.W)
57  val tarStat = UInt(TAR_STAT_SZ.W)
58
59  def setLowerStatByTarget(pc: UInt, target: UInt, isShare: Boolean) = {
60    def getTargetStatByHigher(pc_higher: UInt, target_higher: UInt) =
61      Mux(target_higher > pc_higher, TAR_OVF, Mux(target_higher < pc_higher, TAR_UDF, TAR_FIT))
62    def getLowerByTarget(target: UInt, offsetLen: Int) = target(offsetLen, 1)
63    val offLen        = if (isShare) this.subOffsetLen.get else this.offsetLen
64    val pc_higher     = pc(VAddrBits - 1, offLen + 1)
65    val target_higher = target(VAddrBits - 1, offLen + 1)
66    val stat          = getTargetStatByHigher(pc_higher, target_higher)
67    val lower         = ZeroExt(getLowerByTarget(target, offLen), this.offsetLen)
68    this.lower   := lower
69    this.tarStat := stat
70    this.sharing := isShare.B
71  }
72
73  def getTarget(pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
74    def getTarget(offLen: Int)(pc: UInt, lower: UInt, stat: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
75      val h                = pc(VAddrBits - 1, offLen + 1)
76      val higher           = Wire(UInt((VAddrBits - offLen - 1).W))
77      val higher_plus_one  = Wire(UInt((VAddrBits - offLen - 1).W))
78      val higher_minus_one = Wire(UInt((VAddrBits - offLen - 1).W))
79
80      // Switch between previous stage pc and current stage pc
81      // Give flexibility for timing
82      if (last_stage.isDefined) {
83        val last_stage_pc   = last_stage.get._1
84        val last_stage_pc_h = last_stage_pc(VAddrBits - 1, offLen + 1)
85        val stage_en        = last_stage.get._2
86        higher           := RegEnable(last_stage_pc_h, stage_en)
87        higher_plus_one  := RegEnable(last_stage_pc_h + 1.U, stage_en)
88        higher_minus_one := RegEnable(last_stage_pc_h - 1.U, stage_en)
89      } else {
90        higher           := h
91        higher_plus_one  := h + 1.U
92        higher_minus_one := h - 1.U
93      }
94      val target =
95        Cat(
96          Mux1H(Seq(
97            (stat === TAR_OVF, higher_plus_one),
98            (stat === TAR_UDF, higher_minus_one),
99            (stat === TAR_FIT, higher)
100          )),
101          lower(offLen - 1, 0),
102          0.U(1.W)
103        )
104      require(target.getWidth == VAddrBits)
105      require(offLen != 0)
106      target
107    }
108    if (subOffsetLen.isDefined)
109      Mux(
110        sharing,
111        getTarget(subOffsetLen.get)(pc, lower, tarStat, last_stage),
112        getTarget(offsetLen)(pc, lower, tarStat, last_stage)
113      )
114    else
115      getTarget(offsetLen)(pc, lower, tarStat, last_stage)
116  }
117  def fromAnotherSlot(that: FtbSlot) = {
118    require(
119      this.offsetLen > that.offsetLen && this.subOffsetLen.map(_ == that.offsetLen).getOrElse(true) ||
120        this.offsetLen == that.offsetLen
121    )
122    this.offset  := that.offset
123    this.tarStat := that.tarStat
124    this.sharing := (this.offsetLen > that.offsetLen && that.offsetLen == this.subOffsetLen.get).B
125    this.valid   := that.valid
126    this.lower   := ZeroExt(that.lower, this.offsetLen)
127  }
128
129  def slotConsistent(that: FtbSlot) =
130    VecInit(
131      this.offset === that.offset,
132      this.lower === that.lower,
133      this.tarStat === that.tarStat,
134      this.sharing === that.sharing,
135      this.valid === that.valid
136    ).reduce(_ && _)
137
138}
139
140class FTBEntry_part(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
141  val isCall = Bool()
142  val isRet  = Bool()
143  val isJalr = Bool()
144
145  def isJal = !isJalr
146}
147
148class FTBEntry_FtqMem(implicit p: Parameters) extends FTBEntry_part with FTBParams with BPUUtils {
149
150  val brSlots  = Vec(numBrSlot, new FtbSlot_FtqMem)
151  val tailSlot = new FtbSlot_FtqMem
152
153  def jmpValid =
154    tailSlot.valid && !tailSlot.sharing
155
156  def getBrRecordedVec(offset: UInt) =
157    VecInit(
158      brSlots.map(s => s.valid && s.offset === offset) :+
159        (tailSlot.valid && tailSlot.offset === offset && tailSlot.sharing)
160    )
161
162  def brIsSaved(offset: UInt) = getBrRecordedVec(offset).reduce(_ || _)
163
164  def getBrMaskByOffset(offset: UInt) =
165    brSlots.map { s =>
166      s.valid && s.offset <= offset
167    } :+
168      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
169
170  def newBrCanNotInsert(offset: UInt) = {
171    val lastSlotForBr = tailSlot
172    lastSlotForBr.valid && lastSlotForBr.offset < offset
173  }
174
175}
176
177class FTBEntry(implicit p: Parameters) extends FTBEntry_part with FTBParams with BPUUtils {
178
179  val valid = Bool()
180
181  val brSlots = Vec(numBrSlot, new FtbSlot(BR_OFFSET_LEN))
182
183  val tailSlot = new FtbSlot(JMP_OFFSET_LEN, Some(BR_OFFSET_LEN))
184
185  // Partial Fall-Through Address
186  val pftAddr = UInt(log2Up(PredictWidth).W)
187  val carry   = Bool()
188
189  val last_may_be_rvi_call = Bool()
190
191  // Mark the conditional branch for the first jump and the jalr instruction that appears for the first time,
192  // and train the tag/ittage without using its results when strong_bias is true.
193  val strong_bias = Vec(numBr, Bool())
194
195  def getSlotForBr(idx: Int): FtbSlot = {
196    require(idx <= numBr - 1)
197    (idx, numBr) match {
198      case (i, n) if i == n - 1 => this.tailSlot
199      case _                    => this.brSlots(idx)
200    }
201  }
202  def allSlotsForBr =
203    (0 until numBr).map(getSlotForBr(_))
204  def setByBrTarget(brIdx: Int, pc: UInt, target: UInt) = {
205    val slot = getSlotForBr(brIdx)
206    slot.setLowerStatByTarget(pc, target, brIdx == numBr - 1)
207  }
208  def setByJmpTarget(pc: UInt, target: UInt) =
209    this.tailSlot.setLowerStatByTarget(pc, target, false)
210
211  def getTargetVec(pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
212    /*
213    Previous design: Use the getTarget function of FTBSlot to calculate three sets of targets separately;
214    During this process, nine sets of registers will be generated to register the values of the higher plus one minus one
215    Current design: Reuse the duplicate parts of the original nine sets of registers,
216    calculate the common high bits last_stage_pc_higher of brtarget and jmptarget,
217    and the high bits last_stage_pc_middle that need to be added and subtracted from each other,
218    and then concatenate them according to the carry situation to obtain brtarget and jmptarget
219     */
220    val h_br                  = pc(VAddrBits - 1, BR_OFFSET_LEN + 1)
221    val higher_br             = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
222    val higher_plus_one_br    = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
223    val higher_minus_one_br   = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
224    val h_tail                = pc(VAddrBits - 1, JMP_OFFSET_LEN + 1)
225    val higher_tail           = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
226    val higher_plus_one_tail  = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
227    val higher_minus_one_tail = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
228    if (last_stage.isDefined) {
229      val last_stage_pc                  = last_stage.get._1
230      val stage_en                       = last_stage.get._2
231      val last_stage_pc_higher           = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1), stage_en)
232      val last_stage_pc_middle           = RegEnable(last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1), stage_en)
233      val last_stage_pc_higher_plus_one  = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1) + 1.U, stage_en)
234      val last_stage_pc_higher_minus_one = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1) - 1.U, stage_en)
235      val last_stage_pc_middle_plus_one =
236        RegEnable(Cat(0.U(1.W), last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1)) + 1.U, stage_en)
237      val last_stage_pc_middle_minus_one =
238        RegEnable(Cat(0.U(1.W), last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1)) - 1.U, stage_en)
239
240      higher_br := Cat(last_stage_pc_higher, last_stage_pc_middle)
241      higher_plus_one_br := Mux(
242        last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN),
243        Cat(last_stage_pc_higher_plus_one, last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0)),
244        Cat(last_stage_pc_higher, last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0))
245      )
246      higher_minus_one_br := Mux(
247        last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN),
248        Cat(last_stage_pc_higher_minus_one, last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0)),
249        Cat(last_stage_pc_higher, last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0))
250      )
251
252      higher_tail           := last_stage_pc_higher
253      higher_plus_one_tail  := last_stage_pc_higher_plus_one
254      higher_minus_one_tail := last_stage_pc_higher_minus_one
255    } else {
256      higher_br             := h_br
257      higher_plus_one_br    := h_br + 1.U
258      higher_minus_one_br   := h_br - 1.U
259      higher_tail           := h_tail
260      higher_plus_one_tail  := h_tail + 1.U
261      higher_minus_one_tail := h_tail - 1.U
262    }
263    val br_slots_targets = VecInit(brSlots.map(s =>
264      Cat(
265        Mux1H(Seq(
266          (s.tarStat === TAR_OVF, higher_plus_one_br),
267          (s.tarStat === TAR_UDF, higher_minus_one_br),
268          (s.tarStat === TAR_FIT, higher_br)
269        )),
270        s.lower(s.offsetLen - 1, 0),
271        0.U(1.W)
272      )
273    ))
274    val tail_target = Wire(UInt(VAddrBits.W))
275    if (tailSlot.subOffsetLen.isDefined) {
276      tail_target := Mux(
277        tailSlot.sharing,
278        Cat(
279          Mux1H(Seq(
280            (tailSlot.tarStat === TAR_OVF, higher_plus_one_br),
281            (tailSlot.tarStat === TAR_UDF, higher_minus_one_br),
282            (tailSlot.tarStat === TAR_FIT, higher_br)
283          )),
284          tailSlot.lower(tailSlot.subOffsetLen.get - 1, 0),
285          0.U(1.W)
286        ),
287        Cat(
288          Mux1H(Seq(
289            (tailSlot.tarStat === TAR_OVF, higher_plus_one_tail),
290            (tailSlot.tarStat === TAR_UDF, higher_minus_one_tail),
291            (tailSlot.tarStat === TAR_FIT, higher_tail)
292          )),
293          tailSlot.lower(tailSlot.offsetLen - 1, 0),
294          0.U(1.W)
295        )
296      )
297    } else {
298      tail_target := Cat(
299        Mux1H(Seq(
300          (tailSlot.tarStat === TAR_OVF, higher_plus_one_tail),
301          (tailSlot.tarStat === TAR_UDF, higher_minus_one_tail),
302          (tailSlot.tarStat === TAR_FIT, higher_tail)
303        )),
304        tailSlot.lower(tailSlot.offsetLen - 1, 0),
305        0.U(1.W)
306      )
307    }
308
309    br_slots_targets.map(t => require(t.getWidth == VAddrBits))
310    require(tail_target.getWidth == VAddrBits)
311    val targets = VecInit(br_slots_targets :+ tail_target)
312    targets
313  }
314
315  def getOffsetVec = VecInit(brSlots.map(_.offset) :+ tailSlot.offset)
316  def getFallThrough(pc: UInt, last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None) =
317    if (last_stage_entry.isDefined) {
318      var stashed_carry = RegEnable(last_stage_entry.get._1.carry, last_stage_entry.get._2)
319      getFallThroughAddr(pc, stashed_carry, pftAddr)
320    } else {
321      getFallThroughAddr(pc, carry, pftAddr)
322    }
323
324  def hasBr(offset: UInt) =
325    brSlots.map(s => s.valid && s.offset <= offset).reduce(_ || _) ||
326      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
327
328  def getBrMaskByOffset(offset: UInt) =
329    brSlots.map { s =>
330      s.valid && s.offset <= offset
331    } :+
332      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
333
334  def getBrRecordedVec(offset: UInt) =
335    VecInit(
336      brSlots.map(s => s.valid && s.offset === offset) :+
337        (tailSlot.valid && tailSlot.offset === offset && tailSlot.sharing)
338    )
339
340  def brIsSaved(offset: UInt) = getBrRecordedVec(offset).reduce(_ || _)
341
342  def brValids =
343    VecInit(
344      brSlots.map(_.valid) :+ (tailSlot.valid && tailSlot.sharing)
345    )
346
347  def noEmptySlotForNewBr =
348    VecInit(brSlots.map(_.valid) :+ tailSlot.valid).reduce(_ && _)
349
350  def newBrCanNotInsert(offset: UInt) = {
351    val lastSlotForBr = tailSlot
352    lastSlotForBr.valid && lastSlotForBr.offset < offset
353  }
354
355  def jmpValid =
356    tailSlot.valid && !tailSlot.sharing
357
358  def brOffset =
359    VecInit(brSlots.map(_.offset) :+ tailSlot.offset)
360
361  def entryConsistent(that: FTBEntry) = {
362    val validDiff = this.valid === that.valid
363    val brSlotsDiffSeq: IndexedSeq[Bool] =
364      this.brSlots.zip(that.brSlots).map {
365        case (x, y) => x.slotConsistent(y)
366      }
367    val tailSlotDiff         = this.tailSlot.slotConsistent(that.tailSlot)
368    val pftAddrDiff          = this.pftAddr === that.pftAddr
369    val carryDiff            = this.carry === that.carry
370    val isCallDiff           = this.isCall === that.isCall
371    val isRetDiff            = this.isRet === that.isRet
372    val isJalrDiff           = this.isJalr === that.isJalr
373    val lastMayBeRviCallDiff = this.last_may_be_rvi_call === that.last_may_be_rvi_call
374    val alwaysTakenDiff: IndexedSeq[Bool] =
375      this.strong_bias.zip(that.strong_bias).map {
376        case (x, y) => x === y
377      }
378    VecInit(
379      validDiff,
380      brSlotsDiffSeq.reduce(_ && _),
381      tailSlotDiff,
382      pftAddrDiff,
383      carryDiff,
384      isCallDiff,
385      isRetDiff,
386      isJalrDiff,
387      lastMayBeRviCallDiff,
388      alwaysTakenDiff.reduce(_ && _)
389    ).reduce(_ && _)
390  }
391
392  def display(cond: Bool): Unit = {
393    XSDebug(cond, p"-----------FTB entry----------- \n")
394    XSDebug(cond, p"v=${valid}\n")
395    for (i <- 0 until numBr) {
396      XSDebug(
397        cond,
398        p"[br$i]: v=${allSlotsForBr(i).valid}, offset=${allSlotsForBr(i).offset}," +
399          p"lower=${Hexadecimal(allSlotsForBr(i).lower)}\n"
400      )
401    }
402    XSDebug(
403      cond,
404      p"[tailSlot]: v=${tailSlot.valid}, offset=${tailSlot.offset}," +
405        p"lower=${Hexadecimal(tailSlot.lower)}, sharing=${tailSlot.sharing}}\n"
406    )
407    XSDebug(cond, p"pftAddr=${Hexadecimal(pftAddr)}, carry=$carry\n")
408    XSDebug(cond, p"isCall=$isCall, isRet=$isRet, isjalr=$isJalr\n")
409    XSDebug(cond, p"last_may_be_rvi_call=$last_may_be_rvi_call\n")
410    XSDebug(cond, p"------------------------------- \n")
411  }
412
413}
414
415class FTBEntryWithTag(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
416  val entry = new FTBEntry
417  val tag   = UInt(tagLength.W)
418  def display(cond: Bool): Unit = {
419    entry.display(cond)
420    XSDebug(cond, p"tag is ${Hexadecimal(tag)}\n------------------------------- \n")
421  }
422}
423
424class FTBMeta(implicit p: Parameters) extends XSBundle with FTBParams {
425  val writeWay   = UInt(log2Ceil(numWays).W)
426  val hit        = Bool()
427  val pred_cycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
428}
429
430object FTBMeta {
431  def apply(writeWay: UInt, hit: Bool, pred_cycle: UInt)(implicit p: Parameters): FTBMeta = {
432    val e = Wire(new FTBMeta)
433    e.writeWay := writeWay
434    e.hit      := hit
435    e.pred_cycle.map(_ := pred_cycle)
436    e
437  }
438}
439
440// class UpdateQueueEntry(implicit p: Parameters) extends XSBundle with FTBParams {
441//   val pc = UInt(VAddrBits.W)
442//   val ftb_entry = new FTBEntry
443//   val hit = Bool()
444//   val hit_way = UInt(log2Ceil(numWays).W)
445// }
446//
447// object UpdateQueueEntry {
448//   def apply(pc: UInt, fe: FTBEntry, hit: Bool, hit_way: UInt)(implicit p: Parameters): UpdateQueueEntry = {
449//     val e = Wire(new UpdateQueueEntry)
450//     e.pc := pc
451//     e.ftb_entry := fe
452//     e.hit := hit
453//     e.hit_way := hit_way
454//     e
455//   }
456// }
457
458class FTBTableAddr(val idxBits: Int, val banks: Int, val skewedBits: Int)(implicit p: Parameters) extends XSBundle {
459  val addr = new TableAddr(idxBits, banks)
460  def getIdx(x: UInt) = addr.getIdx(x) ^ Cat(addr.getTag(x), addr.getIdx(x))(idxBits + skewedBits - 1, skewedBits)
461  def getTag(x: UInt) = addr.getTag(x)
462}
463
464class FTB(implicit p: Parameters) extends BasePredictor with FTBParams with BPUUtils
465    with HasCircularQueuePtrHelper with HasPerfEvents {
466  override val meta_size = WireInit(0.U.asTypeOf(new FTBMeta)).getWidth
467
468  val ftbAddr = new FTBTableAddr(log2Up(numSets), 1, 3)
469
470  class FTBBank(val numSets: Int, val nWays: Int) extends XSModule with BPUUtils {
471    val io = IO(new Bundle {
472      val s1_fire = Input(Bool())
473
474      // when ftb hit, read_hits.valid is true, and read_hits.bits is OH of hit way
475      // when ftb not hit, read_hits.valid is false, and read_hits is OH of allocWay
476      // val read_hits = Valid(Vec(numWays, Bool()))
477      val req_pc    = Flipped(DecoupledIO(UInt(VAddrBits.W)))
478      val read_resp = Output(new FTBEntry)
479      val read_hits = Valid(UInt(log2Ceil(numWays).W))
480
481      val read_multi_entry = Output(new FTBEntry)
482      val read_multi_hits  = Valid(UInt(log2Ceil(numWays).W))
483
484      val u_req_pc      = Flipped(DecoupledIO(UInt(VAddrBits.W)))
485      val update_hits   = Valid(UInt(log2Ceil(numWays).W))
486      val update_access = Input(Bool())
487
488      val update_pc          = Input(UInt(VAddrBits.W))
489      val update_write_data  = Flipped(Valid(new FTBEntryWithTag))
490      val update_write_way   = Input(UInt(log2Ceil(numWays).W))
491      val update_write_alloc = Input(Bool())
492    })
493
494    // Extract holdRead logic to fix bug that update read override predict read result
495    val ftb = Module(new SRAMTemplate(
496      new FTBEntryWithTag,
497      set = numSets,
498      way = numWays,
499      shouldReset = true,
500      holdRead = false,
501      singlePort = true,
502      withClockGate = true,
503      hasMbist = hasMbist
504    ))
505    private val mbistPl = MbistPipeline.PlaceMbistPipeline(1, "MbistPipeFtb", hasMbist)
506    val ftb_r_entries   = ftb.io.r.resp.data.map(_.entry)
507
508    val pred_rdata = HoldUnless(
509      ftb.io.r.resp.data,
510      RegNext(io.req_pc.valid && !io.update_access),
511      init = Some(VecInit.fill(numWays)(0.U.asTypeOf(new FTBEntryWithTag)))
512    ) // rdata has ftb_entry.valid, shoud reset
513    ftb.io.r.req.valid := io.req_pc.valid || io.u_req_pc.valid // io.s0_fire
514    ftb.io.r.req.bits.setIdx := Mux(
515      io.u_req_pc.valid,
516      ftbAddr.getIdx(io.u_req_pc.bits),
517      ftbAddr.getIdx(io.req_pc.bits)
518    ) // s0_idx
519
520    assert(!(io.req_pc.valid && io.u_req_pc.valid))
521
522    io.req_pc.ready   := ftb.io.r.req.ready
523    io.u_req_pc.ready := ftb.io.r.req.ready
524
525    val req_tag = RegEnable(ftbAddr.getTag(io.req_pc.bits)(tagLength - 1, 0), io.req_pc.valid)
526    val req_idx = RegEnable(ftbAddr.getIdx(io.req_pc.bits), io.req_pc.valid)
527
528    val u_req_tag = RegEnable(ftbAddr.getTag(io.u_req_pc.bits)(tagLength - 1, 0), io.u_req_pc.valid)
529
530    val read_entries = pred_rdata.map(_.entry)
531    val read_tags    = pred_rdata.map(_.tag)
532
533    val total_hits =
534      VecInit((0 until numWays).map(b => read_tags(b) === req_tag && read_entries(b).valid && io.s1_fire))
535    val hit = total_hits.reduce(_ || _)
536    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
537    val hit_way = OHToUInt(total_hits)
538
539    // There may be two hits in the four paths of the ftbBank, and the OHToUInt will fail.
540    // If there is a redirect in s2 at this time, the wrong FTBEntry will be used to calculate the target,
541    // resulting in an address error and affecting performance.
542    // The solution is to select a hit entry during multi hit as the entry for s2.
543    // Considering timing, use this entry in s3 and trigger s3-redirect.
544    val total_hits_reg   = RegEnable(total_hits, io.s1_fire)
545    val read_entries_reg = read_entries.map(w => RegEnable(w, io.s1_fire))
546
547    val multi_hit = VecInit((0 until numWays).map {
548      i =>
549        (0 until numWays).map { j =>
550          if (i < j) total_hits_reg(i) && total_hits_reg(j)
551          else false.B
552        }.reduce(_ || _)
553    }).reduce(_ || _)
554    val multi_way = PriorityMux(Seq.tabulate(numWays)(i => (total_hits_reg(i)) -> i.asUInt(log2Ceil(numWays).W)))
555    val multi_hit_selectEntry = PriorityMux(Seq.tabulate(numWays)(i => (total_hits_reg(i)) -> read_entries_reg(i)))
556
557    // Check if the entry read by ftbBank is legal.
558    for (n <- 0 to numWays - 1) {
559      val req_pc_reg       = RegEnable(io.req_pc.bits, 0.U.asTypeOf(io.req_pc.bits), io.req_pc.valid)
560      val req_pc_reg_lower = Cat(0.U(1.W), req_pc_reg(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
561      val ftbEntryEndLowerwithCarry = Cat(read_entries(n).carry, read_entries(n).pftAddr)
562      val fallThroughErr            = req_pc_reg_lower + PredictWidth.U >= ftbEntryEndLowerwithCarry
563      when(read_entries(n).valid && total_hits(n) && io.s1_fire) {
564        assert(fallThroughErr, s"FTB read sram entry in way${n} fallThrough address error!")
565      }
566    }
567
568    val u_total_hits = VecInit((0 until numWays).map(b =>
569      ftb.io.r.resp.data(b).tag === u_req_tag && ftb.io.r.resp.data(b).entry.valid && RegNext(io.update_access)
570    ))
571    val u_hit = u_total_hits.reduce(_ || _)
572    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
573    val u_hit_way = OHToUInt(u_total_hits)
574
575    // assert(PopCount(total_hits) === 1.U || PopCount(total_hits) === 0.U)
576    // assert(PopCount(u_total_hits) === 1.U || PopCount(u_total_hits) === 0.U)
577    for (n <- 1 to numWays) {
578      XSPerfAccumulate(f"ftb_pred_${n}_way_hit", PopCount(total_hits) === n.U)
579      XSPerfAccumulate(f"ftb_update_${n}_way_hit", PopCount(u_total_hits) === n.U)
580    }
581
582    val replacer = ReplacementPolicy.fromString(Some("setplru"), numWays, numSets)
583    // val allocWriteWay = replacer.way(req_idx)
584
585    val touch_set = Seq.fill(1)(Wire(UInt(log2Ceil(numSets).W)))
586    val touch_way = Seq.fill(1)(Wire(Valid(UInt(log2Ceil(numWays).W))))
587
588    val write_set = Wire(UInt(log2Ceil(numSets).W))
589    val write_way = Wire(Valid(UInt(log2Ceil(numWays).W)))
590
591    val read_set = Wire(UInt(log2Ceil(numSets).W))
592    val read_way = Wire(Valid(UInt(log2Ceil(numWays).W)))
593
594    read_set       := req_idx
595    read_way.valid := hit
596    read_way.bits  := hit_way
597
598    // Read replacer access is postponed for 1 cycle
599    // this helps timing
600    touch_set(0)       := Mux(write_way.valid, write_set, RegNext(read_set))
601    touch_way(0).valid := write_way.valid || RegNext(read_way.valid)
602    touch_way(0).bits  := Mux(write_way.valid, write_way.bits, RegNext(read_way.bits))
603
604    replacer.access(touch_set, touch_way)
605
606    // Select the update allocate way
607    // Selection logic:
608    //    1. if any entries within the same index is not valid, select it
609    //    2. if all entries is valid, use replacer
610    def allocWay(valids: UInt, idx: UInt): UInt =
611      if (numWays > 1) {
612        val w     = Wire(UInt(log2Up(numWays).W))
613        val valid = WireInit(valids.andR)
614        w := Mux(valid, replacer.way(idx), PriorityEncoder(~valids))
615        w
616      } else {
617        val w = WireInit(0.U(log2Up(numWays).W))
618        w
619      }
620
621    io.read_resp       := Mux1H(total_hits, read_entries) // Mux1H
622    io.read_hits.valid := hit
623    io.read_hits.bits  := hit_way
624
625    io.read_multi_entry      := multi_hit_selectEntry
626    io.read_multi_hits.valid := multi_hit
627    io.read_multi_hits.bits  := multi_way
628
629    io.update_hits.valid := u_hit
630    io.update_hits.bits  := u_hit_way
631
632    // Update logic
633    val u_valid       = io.update_write_data.valid
634    val u_data        = io.update_write_data.bits
635    val u_idx         = ftbAddr.getIdx(io.update_pc)
636    val allocWriteWay = allocWay(RegNext(VecInit(ftb_r_entries.map(_.valid))).asUInt, u_idx)
637    val u_way         = Mux(io.update_write_alloc, allocWriteWay, io.update_write_way)
638    val u_mask        = UIntToOH(u_way)
639
640    for (i <- 0 until numWays) {
641      XSPerfAccumulate(f"ftb_replace_way$i", u_valid && io.update_write_alloc && u_way === i.U)
642      XSPerfAccumulate(
643        f"ftb_replace_way${i}_has_empty",
644        u_valid && io.update_write_alloc && !ftb_r_entries.map(_.valid).reduce(_ && _) && u_way === i.U
645      )
646      XSPerfAccumulate(f"ftb_hit_way$i", hit && !io.update_access && hit_way === i.U)
647    }
648
649    ftb.io.w.apply(u_valid, u_data, u_idx, u_mask)
650
651    // for replacer
652    write_set       := u_idx
653    write_way.valid := u_valid
654    write_way.bits  := Mux(io.update_write_alloc, allocWriteWay, io.update_write_way)
655
656    // print hit entry info
657    Mux1H(total_hits, ftb.io.r.resp.data).display(true.B)
658  } // FTBBank
659
660  // FTB switch register & temporary storage of fauftb prediction results
661  val s0_close_ftb_req            = RegInit(false.B)
662  val s1_close_ftb_req            = RegEnable(s0_close_ftb_req, false.B, io.s0_fire(0))
663  val s2_close_ftb_req            = RegEnable(s1_close_ftb_req, false.B, io.s1_fire(0))
664  val s2_fauftb_ftb_entry_dup     = io.s1_fire.map(f => RegEnable(io.fauftb_entry_in, f))
665  val s2_fauftb_ftb_entry_hit_dup = io.s1_fire.map(f => RegEnable(io.fauftb_entry_hit_in, f))
666
667  val ftbBank = Module(new FTBBank(numSets, numWays))
668
669  // for close ftb read_req
670  ftbBank.io.req_pc.valid := io.s0_fire(0) && !s0_close_ftb_req
671  ftbBank.io.req_pc.bits  := s0_pc_dup(0)
672
673  val s2_multi_hit        = ftbBank.io.read_multi_hits.valid && io.s2_fire(0)
674  val s2_multi_hit_way    = ftbBank.io.read_multi_hits.bits
675  val s2_multi_hit_entry  = ftbBank.io.read_multi_entry
676  val s2_multi_hit_enable = s2_multi_hit && !s2_close_ftb_req
677  XSPerfAccumulate("ftb_s2_multi_hit", s2_multi_hit)
678  XSPerfAccumulate("ftb_s2_multi_hit_enable", s2_multi_hit_enable)
679
680  // After closing ftb, the entry output from s2 is the entry of FauFTB cached in s1
681  val btb_enable_dup   = dup(RegNext(io.ctrl.btb_enable))
682  val s1_read_resp     = Mux(s1_close_ftb_req, io.fauftb_entry_in, ftbBank.io.read_resp)
683  val s2_ftbBank_dup   = io.s1_fire.map(f => RegEnable(ftbBank.io.read_resp, f))
684  val s2_ftb_entry_dup = dup(0.U.asTypeOf(new FTBEntry))
685  for (
686    ((s2_fauftb_entry, s2_ftbBank_entry), s2_ftb_entry) <-
687      s2_fauftb_ftb_entry_dup zip s2_ftbBank_dup zip s2_ftb_entry_dup
688  ) {
689    s2_ftb_entry := Mux(s2_close_ftb_req, s2_fauftb_entry, s2_ftbBank_entry)
690  }
691  val s3_ftb_entry_dup = io.s2_fire.zip(s2_ftb_entry_dup).map { case (f, e) =>
692    RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit_entry, e), f)
693  }
694  val real_s2_ftb_entry         = Mux(s2_multi_hit_enable, s2_multi_hit_entry, s2_ftb_entry_dup(0))
695  val real_s2_pc                = s2_pc_dup(0).getAddr()
696  val real_s2_startLower        = Cat(0.U(1.W), real_s2_pc(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
697  val real_s2_endLowerwithCarry = Cat(real_s2_ftb_entry.carry, real_s2_ftb_entry.pftAddr)
698  val real_s2_fallThroughErr =
699    real_s2_startLower >= real_s2_endLowerwithCarry || real_s2_endLowerwithCarry > (real_s2_startLower + PredictWidth.U)
700  val real_s3_fallThroughErr_dup = io.s2_fire.map(f => RegEnable(real_s2_fallThroughErr, f))
701
702  // After closing ftb, the hit output from s2 is the hit of FauFTB cached in s1.
703  // s1_hit is the ftbBank hit.
704  val s1_hit         = Mux(s1_close_ftb_req, false.B, ftbBank.io.read_hits.valid && io.ctrl.btb_enable)
705  val s2_ftb_hit_dup = io.s1_fire.map(f => RegEnable(s1_hit, 0.B, f))
706  val s2_hit_dup     = dup(0.U.asTypeOf(Bool()))
707  for (
708    ((s2_fauftb_hit, s2_ftb_hit), s2_hit) <-
709      s2_fauftb_ftb_entry_hit_dup zip s2_ftb_hit_dup zip s2_hit_dup
710  ) {
711    s2_hit := Mux(s2_close_ftb_req, s2_fauftb_hit, s2_ftb_hit)
712  }
713  val s3_hit_dup = io.s2_fire.zip(s2_hit_dup).map { case (f, h) =>
714    RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit, h), 0.B, f)
715  }
716  val s3_multi_hit_dup  = io.s2_fire.map(f => RegEnable(s2_multi_hit_enable, f))
717  val writeWay          = Mux(s1_close_ftb_req, 0.U, ftbBank.io.read_hits.bits)
718  val s2_ftb_meta       = RegEnable(FTBMeta(writeWay.asUInt, s1_hit, GTimer()).asUInt, io.s1_fire(0))
719  val s2_multi_hit_meta = FTBMeta(s2_multi_hit_way.asUInt, s2_multi_hit, GTimer()).asUInt
720
721  // Consistent count of entries for fauftb and ftb
722  val fauftb_ftb_entry_consistent_counter = RegInit(0.U(FTBCLOSE_THRESHOLD_SZ.W))
723  val fauftb_ftb_entry_consistent         = s2_fauftb_ftb_entry_dup(0).entryConsistent(s2_ftbBank_dup(0))
724
725  // if close ftb_req, the counter need keep
726  when(io.s2_fire(0) && s2_fauftb_ftb_entry_hit_dup(0) && s2_ftb_hit_dup(0)) {
727    fauftb_ftb_entry_consistent_counter := Mux(
728      fauftb_ftb_entry_consistent,
729      fauftb_ftb_entry_consistent_counter + 1.U,
730      0.U
731    )
732  }.elsewhen(io.s2_fire(0) && !s2_fauftb_ftb_entry_hit_dup(0) && s2_ftb_hit_dup(0)) {
733    fauftb_ftb_entry_consistent_counter := 0.U
734  }
735
736  when((fauftb_ftb_entry_consistent_counter >= FTBCLOSE_THRESHOLD) && io.s0_fire(0)) {
737    s0_close_ftb_req := true.B
738  }
739
740  val update_valid = RegNext(io.update.valid, init = false.B)
741  val update       = Wire(new BranchPredictionUpdate)
742  update := RegEnable(io.update.bits, io.update.valid)
743
744  // The pc register has been moved outside of predictor, pc field of update bundle and other update data are not in the same stage
745  // so io.update.bits.pc is used directly here
746  val update_pc = io.update.bits.pc
747
748  // To improve Clock Gating Efficiency
749  update.meta := RegEnable(io.update.bits.meta, io.update.valid && !io.update.bits.old_entry)
750
751  // Clear counter during false_hit or ifuRedirect
752  val ftb_false_hit = WireInit(false.B)
753  val needReopen    = s0_close_ftb_req && (ftb_false_hit || io.redirectFromIFU)
754  ftb_false_hit := update_valid && update.false_hit
755  when(needReopen) {
756    fauftb_ftb_entry_consistent_counter := 0.U
757    s0_close_ftb_req                    := false.B
758  }
759
760  val s2_close_consistent     = s2_fauftb_ftb_entry_dup(0).entryConsistent(s2_ftb_entry_dup(0))
761  val s2_not_close_consistent = s2_ftbBank_dup(0).entryConsistent(s2_ftb_entry_dup(0))
762
763  when(s2_close_ftb_req && io.s2_fire(0)) {
764    assert(s2_close_consistent, s"Entry inconsistency after ftb req is closed!")
765  }.elsewhen(!s2_close_ftb_req && io.s2_fire(0)) {
766    assert(s2_not_close_consistent, s"Entry inconsistency after ftb req is not closed!")
767  }
768
769  val reopenCounter         = !s1_close_ftb_req && s2_close_ftb_req && io.s2_fire(0)
770  val falseHitReopenCounter = ftb_false_hit && s1_close_ftb_req
771  XSPerfAccumulate("ftb_req_reopen_counter", reopenCounter)
772  XSPerfAccumulate("false_hit_reopen_Counter", falseHitReopenCounter)
773  XSPerfAccumulate("ifuRedirec_needReopen", s1_close_ftb_req && io.redirectFromIFU)
774  XSPerfAccumulate("this_cycle_is_close", s2_close_ftb_req && io.s2_fire(0))
775  XSPerfAccumulate("this_cycle_is_open", !s2_close_ftb_req && io.s2_fire(0))
776
777  // io.out.bits.resp := RegEnable(io.in.bits.resp_in(0), 0.U.asTypeOf(new BranchPredictionResp), io.s1_fire)
778  io.out := io.in.bits.resp_in(0)
779
780  io.out.s2.full_pred.map { case fp => fp.multiHit := false.B }
781
782  io.out.s2.full_pred.zip(s2_hit_dup).map { case (fp, h) => fp.hit := h }
783  for (
784    full_pred & s2_ftb_entry & s2_pc & s1_pc & s1_fire <-
785      io.out.s2.full_pred zip s2_ftb_entry_dup zip s2_pc_dup zip s1_pc_dup zip io.s1_fire
786  ) {
787    full_pred.fromFtbEntry(
788      s2_ftb_entry,
789      s2_pc.getAddr(),
790      // Previous stage meta for better timing
791      Some(s1_pc, s1_fire),
792      Some(s1_read_resp, s1_fire)
793    )
794  }
795
796  io.out.s3.full_pred.zip(s3_hit_dup).map { case (fp, h) => fp.hit := h }
797  io.out.s3.full_pred.zip(s3_multi_hit_dup).map { case (fp, m) => fp.multiHit := m }
798  for (
799    full_pred & s3_ftb_entry & s3_pc & s2_pc & s2_fire <-
800      io.out.s3.full_pred zip s3_ftb_entry_dup zip s3_pc_dup zip s2_pc_dup zip io.s2_fire
801  )
802    full_pred.fromFtbEntry(s3_ftb_entry, s3_pc.getAddr(), Some((s2_pc.getAddr(), s2_fire)))
803
804  // Overwrite the fallThroughErr value
805  io.out.s3.full_pred.zipWithIndex.map { case (fp, i) => fp.fallThroughErr := real_s3_fallThroughErr_dup(i) }
806
807  io.out.last_stage_ftb_entry := s3_ftb_entry_dup(0)
808  io.out.last_stage_meta      := RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit_meta, s2_ftb_meta), io.s2_fire(0))
809  io.out.s1_ftbCloseReq       := s1_close_ftb_req
810  io.out.s1_uftbHit           := io.fauftb_entry_hit_in
811  val s1_uftbHasIndirect = io.fauftb_entry_in.jmpValid &&
812    io.fauftb_entry_in.isJalr && !io.fauftb_entry_in.isRet // uFTB determines that it's real JALR, RET and JAL are excluded
813  io.out.s1_uftbHasIndirect := s1_uftbHasIndirect
814
815  // always taken logic
816  for (i <- 0 until numBr) {
817    for (
818      out_fp & in_fp & s2_hit & s2_ftb_entry <-
819        io.out.s2.full_pred zip io.in.bits.resp_in(0).s2.full_pred zip s2_hit_dup zip s2_ftb_entry_dup
820    )
821      out_fp.br_taken_mask(i) := in_fp.br_taken_mask(i) || s2_hit && s2_ftb_entry.strong_bias(i)
822    for (
823      out_fp & in_fp & s3_hit & s3_ftb_entry <-
824        io.out.s3.full_pred zip io.in.bits.resp_in(0).s3.full_pred zip s3_hit_dup zip s3_ftb_entry_dup
825    )
826      out_fp.br_taken_mask(i) := in_fp.br_taken_mask(i) || s3_hit && s3_ftb_entry.strong_bias(i)
827  }
828
829  val s3_pc_diff       = s3_pc_dup(0).getAddr()
830  val s3_pc_startLower = Cat(0.U(1.W), s3_pc_diff(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
831  val s3_ftb_entry_endLowerwithCarry = Cat(s3_ftb_entry_dup(0).carry, s3_ftb_entry_dup(0).pftAddr)
832  val fallThroughErr =
833    s3_pc_startLower >= s3_ftb_entry_endLowerwithCarry || s3_ftb_entry_endLowerwithCarry > (s3_pc_startLower + PredictWidth.U)
834  XSError(
835    s3_ftb_entry_dup(0).valid && s3_hit_dup(0) && io.s3_fire(0) && fallThroughErr,
836    "FTB read sram entry in s3 fallThrough address error!"
837  )
838
839  // Update logic
840  val u_meta  = update.meta.asTypeOf(new FTBMeta)
841  val u_valid = update_valid && !update.old_entry && !s0_close_ftb_req
842
843  val (_, delay2_pc)    = DelayNWithValid(update_pc, u_valid, 2)
844  val (_, delay2_entry) = DelayNWithValid(update.ftb_entry, u_valid, 2)
845
846  val update_now       = u_valid && u_meta.hit
847  val update_need_read = u_valid && !u_meta.hit
848  // stall one more cycle because we use a whole cycle to do update read tag hit
849  io.s1_ready := ftbBank.io.req_pc.ready && !update_need_read && !RegNext(update_need_read)
850
851  ftbBank.io.u_req_pc.valid := update_need_read
852  ftbBank.io.u_req_pc.bits  := update_pc
853
854  val ftb_write = Wire(new FTBEntryWithTag)
855  ftb_write.entry := Mux(update_now, update.ftb_entry, delay2_entry)
856  ftb_write.tag   := ftbAddr.getTag(Mux(update_now, update_pc, delay2_pc))(tagLength - 1, 0)
857
858  val write_valid = update_now || DelayN(u_valid && !u_meta.hit, 2)
859  val write_pc    = Mux(update_now, update_pc, delay2_pc)
860
861  ftbBank.io.update_write_data.valid := write_valid
862  ftbBank.io.update_write_data.bits  := ftb_write
863  ftbBank.io.update_pc               := write_pc
864  ftbBank.io.update_write_way := Mux(
865    update_now,
866    u_meta.writeWay,
867    RegNext(ftbBank.io.update_hits.bits)
868  ) // use it one cycle later
869  ftbBank.io.update_write_alloc := Mux(
870    update_now,
871    false.B,
872    RegNext(!ftbBank.io.update_hits.valid)
873  ) // use it one cycle later
874  ftbBank.io.update_access := u_valid && !u_meta.hit
875  ftbBank.io.s1_fire       := io.s1_fire(0)
876
877  val ftb_write_fallThrough = ftb_write.entry.getFallThrough(write_pc)
878  when(write_valid) {
879    assert(write_pc + (FetchWidth * 4).U >= ftb_write_fallThrough, s"FTB write_entry fallThrough address error!")
880  }
881
882  XSDebug("req_v=%b, req_pc=%x, ready=%b (resp at next cycle)\n", io.s0_fire(0), s0_pc_dup(0), ftbBank.io.req_pc.ready)
883  XSDebug("s2_hit=%b, hit_way=%b\n", s2_hit_dup(0), writeWay.asUInt)
884  XSDebug(
885    "s2_br_taken_mask=%b, s2_real_taken_mask=%b\n",
886    io.in.bits.resp_in(0).s2.full_pred(0).br_taken_mask.asUInt,
887    io.out.s2.full_pred(0).real_slot_taken_mask().asUInt
888  )
889  XSDebug("s2_target=%x\n", io.out.s2.getTarget(0))
890
891  s2_ftb_entry_dup(0).display(true.B)
892
893  XSPerfAccumulate("ftb_read_hits", RegNext(io.s0_fire(0)) && s1_hit)
894  XSPerfAccumulate("ftb_read_misses", RegNext(io.s0_fire(0)) && !s1_hit)
895
896  XSPerfAccumulate("ftb_commit_hits", update_valid && u_meta.hit)
897  XSPerfAccumulate("ftb_commit_misses", update_valid && !u_meta.hit)
898
899  XSPerfAccumulate("ftb_update_req", update_valid)
900  XSPerfAccumulate("ftb_update_ignored", update_valid && update.old_entry)
901  XSPerfAccumulate("ftb_updated", u_valid)
902  XSPerfAccumulate("ftb_closing_update_counter", s0_close_ftb_req && u_valid)
903
904  override val perfEvents = Seq(
905    ("ftb_commit_hits            ", update_valid && u_meta.hit),
906    ("ftb_commit_misses          ", update_valid && !u_meta.hit)
907  )
908  generatePerfEvent()
909}
910