xref: /XiangShan/src/main/scala/xiangshan/frontend/FTB.scala (revision c3abb8b6b92c14ec0f3dbbac60a8caa531994a95)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage}
22import chisel3.util._
23import xiangshan._
24import utils._
25import chisel3.experimental.chiselName
26
27import scala.math.min
28
29
30trait FTBParams extends HasXSParameter with HasBPUConst {
31  val numEntries = 4096
32  val numWays    = 4
33  val numSets    = numEntries/numWays // 512
34  val tagSize    = 20
35
36  val TAR_STAT_SZ = 2
37  def TAR_FIT = 0.U(TAR_STAT_SZ.W)
38  def TAR_OVF = 1.U(TAR_STAT_SZ.W)
39  def TAR_UDF = 2.U(TAR_STAT_SZ.W)
40
41  def BR_OFFSET_LEN = 13
42  def JMP_OFFSET_LEN = 21
43}
44
45class FTBEntry(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
46  val valid       = Bool()
47
48  val brOffset    = Vec(numBr, UInt(log2Up(FetchWidth*2).W))
49  val brLowers    = Vec(numBr, UInt(BR_OFFSET_LEN.W))
50  val brTarStats  = Vec(numBr, UInt(TAR_STAT_SZ.W))
51  val brValids    = Vec(numBr, Bool())
52
53  val jmpOffset = UInt(log2Ceil(PredictWidth).W)
54  val jmpLower   = UInt(JMP_OFFSET_LEN.W)
55  val jmpTarStat = UInt(TAR_STAT_SZ.W)
56  val jmpValid    = Bool()
57
58  // Partial Fall-Through Address
59  val pftAddr     = UInt((log2Up(PredictWidth)+1).W)
60  val carry       = Bool()
61
62  val isCall      = Bool()
63  val isRet       = Bool()
64  val isJalr      = Bool()
65
66  val oversize    = Bool()
67
68  val last_is_rvc = Bool()
69
70  val always_taken = Vec(numBr, Bool())
71
72  def getTarget(offsetLen: Int)(pc: UInt, lower: UInt, stat: UInt) = {
73    val higher = pc(VAddrBits-1, offsetLen)
74    Cat(
75      Mux(stat === TAR_OVF, higher+1.U,
76        Mux(stat === TAR_UDF, higher-1.U, higher)),
77      lower
78    )
79  }
80  val getBrTarget = getTarget(BR_OFFSET_LEN)(_, _, _)
81
82  def getBrTargets(pc: UInt) = {
83    VecInit((brLowers zip brTarStats).map{
84      case (lower, stat) => getBrTarget(pc, lower, stat)
85    })
86  }
87
88  def getJmpTarget(pc: UInt) = getTarget(JMP_OFFSET_LEN)(pc, jmpLower, jmpTarStat)
89
90  def getLowerStatByTarget(offsetLen: Int)(pc: UInt, target: UInt) = {
91    val pc_higher = pc(VAddrBits-1, offsetLen)
92    val target_higher = target(VAddrBits-1, offsetLen)
93    val stat = WireInit(Mux(target_higher > pc_higher, TAR_OVF,
94      Mux(target_higher < pc_higher, TAR_UDF, TAR_FIT)))
95    val lower = WireInit(target(offsetLen-1, 0))
96    (lower, stat)
97  }
98  def getBrLowerStatByTarget(pc: UInt, target: UInt) = getLowerStatByTarget(BR_OFFSET_LEN)(pc, target)
99  def getJmpLowerStatByTarget(pc: UInt, target: UInt) = getLowerStatByTarget(JMP_OFFSET_LEN)(pc, target)
100  def setByBrTarget(brIdx: Int, pc: UInt, target: UInt) = {
101    val (lower, stat) = getBrLowerStatByTarget(pc, target)
102    this.brLowers(brIdx) := lower
103    this.brTarStats(brIdx) := stat
104  }
105  def setByJmpTarget(pc: UInt, target: UInt) = {
106    val (lower, stat) = getJmpLowerStatByTarget(pc, target)
107    this.jmpLower := lower
108    this.jmpTarStat := stat
109  }
110
111
112  def getOffsetVec = VecInit(brOffset :+ jmpOffset)
113  def isJal = !isJalr
114  def getFallThrough(pc: UInt) = getFallThroughAddr(pc, carry, pftAddr)
115  def hasBr(offset: UInt) = (brValids zip brOffset).map{
116    case (v, off) => v && off <= offset
117  }.reduce(_||_)
118
119  def getBrMaskByOffset(offset: UInt) = (brValids zip brOffset).map{
120    case (v, off) => v && off <= offset
121  }
122
123  def brIsSaved(offset: UInt) = (brValids zip brOffset).map{
124    case (v, off) => v && off === offset
125  }.reduce(_||_)
126  def display(cond: Bool): Unit = {
127    XSDebug(cond, p"-----------FTB entry----------- \n")
128    XSDebug(cond, p"v=${valid}\n")
129    for(i <- 0 until numBr) {
130      XSDebug(cond, p"[br$i]: v=${brValids(i)}, offset=${brOffset(i)}, lower=${Hexadecimal(brLowers(i))}\n")
131    }
132    XSDebug(cond, p"[jmp]: v=${jmpValid}, offset=${jmpOffset}, lower=${Hexadecimal(jmpLower)}\n")
133    XSDebug(cond, p"pftAddr=${Hexadecimal(pftAddr)}, carry=$carry\n")
134    XSDebug(cond, p"isCall=$isCall, isRet=$isRet, isjalr=$isJalr\n")
135    XSDebug(cond, p"oversize=$oversize, last_is_rvc=$last_is_rvc\n")
136    XSDebug(cond, p"------------------------------- \n")
137  }
138
139}
140
141class FTBEntryWithTag(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
142  val entry = new FTBEntry
143  val tag = UInt(tagSize.W)
144  def display(cond: Bool): Unit = {
145    XSDebug(cond, p"-----------FTB entry----------- \n")
146    XSDebug(cond, p"v=${entry.valid}, tag=${Hexadecimal(tag)}\n")
147    for(i <- 0 until numBr) {
148      XSDebug(cond, p"[br$i]: v=${entry.brValids(i)}, offset=${entry.brOffset(i)}, lower=${Hexadecimal(entry.brLowers(i))}\n")
149    }
150    XSDebug(cond, p"[jmp]: v=${entry.jmpValid}, offset=${entry.jmpOffset}, lower=${Hexadecimal(entry.jmpLower)}\n")
151    XSDebug(cond, p"pftAddr=${Hexadecimal(entry.pftAddr)}, carry=${entry.carry}\n")
152    XSDebug(cond, p"isCall=${entry.isCall}, isRet=${entry.isRet}, isjalr=${entry.isJalr}\n")
153    XSDebug(cond, p"oversize=${entry.oversize}, last_is_rvc=${entry.last_is_rvc}\n")
154    XSDebug(cond, p"------------------------------- \n")
155  }
156}
157
158class FTBMeta(implicit p: Parameters) extends XSBundle with FTBParams {
159  val writeWay = UInt(log2Ceil(numWays).W)
160  val hit = Bool()
161  val pred_cycle = UInt(64.W) // TODO: Use Option
162}
163
164object FTBMeta {
165  def apply(writeWay: UInt, hit: Bool, pred_cycle: UInt)(implicit p: Parameters): FTBMeta = {
166    val e = Wire(new FTBMeta)
167    e.writeWay := writeWay
168    e.hit := hit
169    e.pred_cycle := pred_cycle
170    e
171  }
172}
173
174// class UpdateQueueEntry(implicit p: Parameters) extends XSBundle with FTBParams {
175//   val pc = UInt(VAddrBits.W)
176//   val ftb_entry = new FTBEntry
177//   val hit = Bool()
178//   val hit_way = UInt(log2Ceil(numWays).W)
179// }
180//
181// object UpdateQueueEntry {
182//   def apply(pc: UInt, fe: FTBEntry, hit: Bool, hit_way: UInt)(implicit p: Parameters): UpdateQueueEntry = {
183//     val e = Wire(new UpdateQueueEntry)
184//     e.pc := pc
185//     e.ftb_entry := fe
186//     e.hit := hit
187//     e.hit_way := hit_way
188//     e
189//   }
190// }
191
192class FTB(implicit p: Parameters) extends BasePredictor with FTBParams with BPUUtils with HasCircularQueuePtrHelper {
193  override val meta_size = WireInit(0.U.asTypeOf(new FTBMeta)).getWidth
194
195  val ftbAddr = new TableAddr(log2Up(numSets), 1)
196
197  class FTBBank(val numSets: Int, val nWays: Int) extends XSModule with BPUUtils {
198    val io = IO(new Bundle {
199      val s1_fire = Input(Bool())
200
201      // when ftb hit, read_hits.valid is true, and read_hits.bits is OH of hit way
202      // when ftb not hit, read_hits.valid is false, and read_hits is OH of allocWay
203      // val read_hits = Valid(Vec(numWays, Bool()))
204      val req_pc = Flipped(DecoupledIO(UInt(VAddrBits.W)))
205      val read_resp = Output(new FTBEntry)
206      val read_hits = Valid(UInt(log2Ceil(numWays).W))
207
208      val u_req_pc = Flipped(DecoupledIO(UInt(VAddrBits.W)))
209      val update_hits = Valid(UInt(log2Ceil(numWays).W))
210      val update_access = Input(Bool())
211
212      val update_pc = Input(UInt(VAddrBits.W))
213      val update_write_data = Flipped(Valid(new FTBEntryWithTag))
214      val update_write_way = Input(UInt(log2Ceil(numWays).W))
215      val update_write_alloc = Input(Bool())
216    })
217
218    // Extract holdRead logic to fix bug that update read override predict read result
219    val ftb = Module(new SRAMTemplate(new FTBEntryWithTag, set = numSets, way = numWays, shouldReset = true, holdRead = false, singlePort = true))
220
221    val pred_rdata   = HoldUnless(ftb.io.r.resp.data, RegNext(io.req_pc.valid && !io.update_access))
222    ftb.io.r.req.valid := io.req_pc.valid || io.u_req_pc.valid // io.s0_fire
223    ftb.io.r.req.bits.setIdx := Mux(io.u_req_pc.valid, ftbAddr.getIdx(io.u_req_pc.bits), ftbAddr.getIdx(io.req_pc.bits)) // s0_idx
224
225    assert(!(io.req_pc.valid && io.u_req_pc.valid))
226
227    io.req_pc.ready := ftb.io.r.req.ready
228    io.u_req_pc.ready := ftb.io.r.req.ready
229
230    val req_tag = RegEnable(ftbAddr.getTag(io.req_pc.bits)(tagSize-1, 0), io.req_pc.valid)
231    val req_idx = RegEnable(ftbAddr.getIdx(io.req_pc.bits), io.req_pc.valid)
232
233    val u_req_tag = RegEnable(ftbAddr.getTag(io.u_req_pc.bits)(tagSize-1, 0), io.u_req_pc.valid)
234
235    val read_entries = pred_rdata.map(_.entry)
236    val read_tags    = pred_rdata.map(_.tag)
237
238    val total_hits = VecInit((0 until numWays).map(b => read_tags(b) === req_tag && read_entries(b).valid && io.s1_fire))
239    val hit = total_hits.reduce(_||_)
240    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
241    val hit_way = PriorityEncoder(total_hits)
242
243    val u_total_hits = VecInit((0 until numWays).map(b =>
244        ftb.io.r.resp.data(b).tag === u_req_tag && ftb.io.r.resp.data(b).entry.valid && RegNext(io.update_access)))
245    val u_hit = u_total_hits.reduce(_||_)
246    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
247    val u_hit_way = PriorityEncoder(u_total_hits)
248
249    assert(PopCount(total_hits) === 1.U || PopCount(total_hits) === 0.U)
250    assert(PopCount(u_total_hits) === 1.U || PopCount(u_total_hits) === 0.U)
251
252    val replacer = ReplacementPolicy.fromString(Some("setplru"), numWays, numSets)
253    // val allocWriteWay = replacer.way(req_idx)
254
255    val touch_set = Seq.fill(1)(Wire(UInt(log2Ceil(numSets).W)))
256    val touch_way = Seq.fill(1)(Wire(Valid(UInt(log2Ceil(numWays).W))))
257
258    touch_set(0) := req_idx
259
260    touch_way(0).valid := hit
261    touch_way(0).bits := hit_way
262
263    replacer.access(touch_set, touch_way)
264
265    // def allocWay(valids: UInt, meta_tags: UInt, req_tag: UInt) = {
266    //   val randomAlloc = false
267    //   if (numWays > 1) {
268    //     val w = Wire(UInt(log2Up(numWays).W))
269    //     val valid = WireInit(valids.andR)
270    //     val tags = Cat(meta_tags, req_tag)
271    //     val l = log2Up(numWays)
272    //     val nChunks = (tags.getWidth + l - 1) / l
273    //     val chunks = (0 until nChunks).map( i =>
274    //       tags(min((i+1)*l, tags.getWidth)-1, i*l)
275    //     )
276    //     w := Mux(valid, if (randomAlloc) {LFSR64()(log2Up(numWays)-1,0)} else {chunks.reduce(_^_)}, PriorityEncoder(~valids))
277    //     w
278    //   } else {
279    //     val w = WireInit(0.U)
280    //     w
281    //   }
282    // }
283
284    // val allocWriteWay = allocWay(
285    //   VecInit(read_entries.map(_.valid)).asUInt,
286    //   VecInit(read_tags).asUInt,
287    //   req_tag
288    // )
289
290    def allocWay(valids: UInt, idx: UInt) = {
291      if (numWays > 1) {
292        val w = Wire(UInt(log2Up(numWays).W))
293        val valid = WireInit(valids.andR)
294        w := Mux(valid, replacer.way(idx), PriorityEncoder(~valids))
295        w
296      }else {
297        val w = WireInit(0.U)
298        w
299      }
300    }
301
302    io.read_resp := PriorityMux(total_hits, read_entries) // Mux1H
303    io.read_hits.valid := hit
304    // io.read_hits.bits := Mux(hit, hit_way_1h, VecInit(UIntToOH(allocWriteWay).asBools()))
305    io.read_hits.bits := hit_way
306
307    io.update_hits.valid := u_hit
308    io.update_hits.bits := u_hit_way
309
310    // XSDebug(!hit, "FTB not hit, alloc a way: %d\n", allocWriteWay)
311
312    // Update logic
313    val u_valid = io.update_write_data.valid
314    val u_data = io.update_write_data.bits
315    val u_idx = ftbAddr.getIdx(io.update_pc)
316    val allocWriteWay = allocWay(VecInit(read_entries.map(_.valid)).asUInt, u_idx)
317    val u_mask = UIntToOH(Mux(io.update_write_alloc, allocWriteWay, io.update_write_way))
318
319    for (i <- 0 until numWays) {
320      XSPerfAccumulate(f"ftb_replace_way$i", u_valid && io.update_write_alloc && OHToUInt(u_mask) === i.U)
321      XSPerfAccumulate(f"ftb_replace_way${i}_has_empty", u_valid && io.update_write_alloc && !read_entries.map(_.valid).reduce(_&&_) && OHToUInt(u_mask) === i.U)
322      XSPerfAccumulate(f"ftb_hit_way$i", hit && !io.update_access && hit_way === i.U)
323    }
324
325    ftb.io.w.apply(u_valid, u_data, u_idx, u_mask)
326  } // FTBBank
327
328  val ftbBank = Module(new FTBBank(numSets, numWays))
329
330  ftbBank.io.req_pc.valid := io.s0_fire
331  ftbBank.io.req_pc.bits := s0_pc
332
333  val ftb_entry = RegEnable(ftbBank.io.read_resp, io.s1_fire)
334  val s1_hit = ftbBank.io.read_hits.valid
335  val s2_hit = RegEnable(s1_hit, io.s1_fire)
336  val writeWay = ftbBank.io.read_hits.bits
337
338  val fallThruAddr = getFallThroughAddr(s2_pc, ftb_entry.carry, ftb_entry.pftAddr)
339
340  // io.out.bits.resp := RegEnable(io.in.bits.resp_in(0), 0.U.asTypeOf(new BranchPredictionResp), io.s1_fire)
341  io.out.resp := io.in.bits.resp_in(0)
342
343  val s1_latch_call_is_rvc   = DontCare // TODO: modify when add RAS
344
345  io.out.resp.s2.preds.taken_mask    := io.in.bits.resp_in(0).s2.preds.taken_mask
346  for (i <- 0 until numBr) {
347    when (ftb_entry.always_taken(i)) {
348      io.out.resp.s2.preds.taken_mask(i) := true.B
349    }
350  }
351
352  io.out.resp.s2.preds.hit           := s2_hit
353  io.out.resp.s2.pc                  := s2_pc
354  io.out.resp.s2.ftb_entry           := ftb_entry
355  io.out.resp.s2.preds.fromFtbEntry(ftb_entry, s2_pc)
356
357  io.out.s3_meta                     := RegEnable(RegEnable(FTBMeta(writeWay, s1_hit, GTimer()).asUInt(), io.s1_fire), io.s2_fire)
358
359  when(s2_hit) {
360    io.out.resp.s2.ftb_entry.pftAddr := ftb_entry.pftAddr
361    io.out.resp.s2.ftb_entry.carry := ftb_entry.carry
362  }.otherwise {
363    io.out.resp.s2.ftb_entry.pftAddr := s2_pc(instOffsetBits + log2Ceil(PredictWidth), instOffsetBits) ^ (1 << log2Ceil(PredictWidth)).U
364    io.out.resp.s2.ftb_entry.carry := s2_pc(instOffsetBits + log2Ceil(PredictWidth)).asBool
365    io.out.resp.s2.ftb_entry.oversize := false.B
366  }
367
368  // always taken logic
369  when (s2_hit) {
370    for (i <- 0 until numBr) {
371      when (ftb_entry.always_taken(i)) {
372        io.out.resp.s2.preds.taken_mask(i) := true.B
373      }
374    }
375  }
376
377  // Update logic
378  val update = RegNext(io.update.bits)
379
380  // val update_queue = Mem(64, new UpdateQueueEntry)
381  // val head, tail = RegInit(UpdateQueuePtr(false.B, 0.U))
382  // val u_queue = Module(new Queue(new UpdateQueueEntry, entries = 64, flow = true))
383  // assert(u_queue.io.count < 64.U)
384
385  val u_meta = update.meta.asTypeOf(new FTBMeta)
386  val u_valid = RegNext(io.update.valid && !io.update.bits.old_entry)
387
388  // io.s1_ready := ftbBank.io.req_pc.ready && u_queue.io.count === 0.U && !u_valid
389  io.s1_ready := ftbBank.io.req_pc.ready && !(u_valid && !u_meta.hit)
390
391  // val update_now = u_queue.io.deq.fire && u_queue.io.deq.bits.hit
392  val update_now = u_valid && u_meta.hit
393
394  ftbBank.io.u_req_pc.valid := u_valid && !u_meta.hit
395  ftbBank.io.u_req_pc.bits := update.pc
396
397  // assert(!(u_valid && RegNext(u_valid) && update.pc === RegNext(update.pc)))
398  // assert(!(u_valid && RegNext(u_valid)))
399
400  // val u_way = u_queue.io.deq.bits.hit_way
401
402  val ftb_write = Wire(new FTBEntryWithTag)
403  // ftb_write.entry := Mux(update_now, u_queue.io.deq.bits.ftb_entry, RegNext(u_queue.io.deq.bits.ftb_entry))
404  // ftb_write.tag   := ftbAddr.getTag(Mux(update_now, u_queue.io.deq.bits.pc, RegNext(u_queue.io.deq.bits.pc)))(tagSize-1, 0)
405  ftb_write.entry := Mux(update_now, update.ftb_entry, RegNext(update.ftb_entry))
406  ftb_write.tag   := ftbAddr.getTag(Mux(update_now, update.pc, RegNext(update.pc)))(tagSize-1, 0)
407
408  // val write_valid = update_now || RegNext(u_queue.io.deq.fire && !u_queue.io.deq.bits.hit)
409  val write_valid = update_now || RegNext(u_valid && !u_meta.hit)
410
411  // u_queue.io.enq.valid := u_valid
412  // u_queue.io.enq.bits := UpdateQueueEntry(update.pc, update.ftb_entry, u_meta.hit, u_meta.writeWay)
413  // u_queue.io.deq.ready := RegNext(!u_queue.io.deq.fire || update_now)
414
415  ftbBank.io.update_write_data.valid := write_valid
416  ftbBank.io.update_write_data.bits := ftb_write
417  // ftbBank.io.update_pc := Mux(update_now, u_queue.io.deq.bits.pc, RegNext(u_queue.io.deq.bits.pc))
418  ftbBank.io.update_pc := Mux(update_now, update.pc, RegNext(update.pc))
419  ftbBank.io.update_write_way := Mux(update_now, u_meta.writeWay, ftbBank.io.update_hits.bits)
420  // ftbBank.io.update_write_alloc := Mux(update_now, !u_queue.io.deq.bits.hit, !ftbBank.io.update_hits.valid)
421  ftbBank.io.update_write_alloc := Mux(update_now, false.B, !ftbBank.io.update_hits.valid)
422  ftbBank.io.update_access := u_valid && !u_meta.hit
423  ftbBank.io.s1_fire := io.s1_fire
424
425  XSDebug("req_v=%b, req_pc=%x, ready=%b (resp at next cycle)\n", io.s0_fire, s0_pc, ftbBank.io.req_pc.ready)
426  XSDebug("s2_hit=%b, hit_way=%b\n", s2_hit, writeWay.asUInt)
427  XSDebug("s2_taken_mask=%b, s2_real_taken_mask=%b\n",
428    io.in.bits.resp_in(0).s2.preds.taken_mask.asUInt, io.out.resp.s2.real_taken_mask().asUInt)
429  XSDebug("s2_target=%x\n", io.out.resp.s2.target)
430
431  ftb_entry.display(true.B)
432
433  // XSDebug(u_valid, "Update from ftq\n")
434  // XSDebug(u_valid, "update_pc=%x, tag=%x, pred_cycle=%d\n",
435  //   update.pc, ftbAddr.getTag(update.pc), u_meta.pred_cycle)
436  // XSDebug(RegNext(u_valid), "Write into FTB\n")
437  // XSDebug(RegNext(u_valid), "hit=%d, update_write_way=%d\n",
438  //   ftbBank.io.update_hits.valid, u_meta.writeWay)
439
440
441
442
443
444  XSPerfAccumulate("ftb_read_hits", RegNext(io.s0_fire) && s1_hit)
445  XSPerfAccumulate("ftb_read_misses", RegNext(io.s0_fire) && !s1_hit)
446
447  XSPerfAccumulate("ftb_commit_hits", io.update.valid && io.update.bits.preds.hit)
448  XSPerfAccumulate("ftb_commit_misses", io.update.valid && !io.update.bits.preds.hit)
449
450  XSPerfAccumulate("ftb_update_req", io.update.valid)
451  XSPerfAccumulate("ftb_update_ignored", io.update.valid && io.update.bits.old_entry)
452  XSPerfAccumulate("ftb_updated", u_valid)
453}
454