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