xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision b5f5fbe65aa24ddf52ae58a99625c6f67fba9fdf)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import xiangshan._
6import xiangshan.utils._
7import xiangshan.backend.ALUOpType
8import utils._
9import chisel3.util.experimental.BoringUtils
10import xiangshan.backend.decode.XSTrap
11
12class TableAddr(val idxBits: Int, val banks: Int) extends XSBundle {
13  def tagBits = VAddrBits - idxBits - 2
14
15  val tag = UInt(tagBits.W)
16  val idx = UInt(idxBits.W)
17  val offset = UInt(2.W)
18
19  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
20  def getTag(x: UInt) = fromUInt(x).tag
21  def getIdx(x: UInt) = fromUInt(x).idx
22  def getBank(x: UInt) = getIdx(x)(log2Up(banks) - 1, 0)
23  def getBankIdx(x: UInt) = getIdx(x)(idxBits - 1, log2Up(banks))
24}
25
26class Stage1To2IO extends XSBundle {
27  val pc = Output(UInt(VAddrBits.W))
28  val btb = new Bundle {
29    val hits = Output(UInt(FetchWidth.W))
30    val targets = Output(Vec(FetchWidth, UInt(VAddrBits.W)))
31  }
32  val jbtac = new Bundle {
33    val hitIdx = Output(UInt(FetchWidth.W))
34    val target = Output(UInt(VAddrBits.W))
35  }
36  val tage = new Bundle {
37    val hits = Output(UInt(FetchWidth.W))
38    val takens = Output(Vec(FetchWidth, Bool()))
39  }
40  val hist = Output(Vec(FetchWidth, UInt(HistoryLength.W)))
41  val btbPred = ValidIO(new BranchPrediction)
42}
43
44class BPUStage1 extends XSModule {
45  val io = IO(new Bundle() {
46    val in = new Bundle { val pc = Flipped(Decoupled(UInt(VAddrBits.W))) }
47    // from backend
48    val redirectInfo = Input(new RedirectInfo)
49    // from Stage3
50    val flush = Input(Bool())
51    val s3RollBackHist = Input(UInt(HistoryLength.W))
52    val s3Taken = Input(Bool())
53    // to ifu, quick prediction result
54    val s1OutPred = ValidIO(new BranchPrediction)
55    // to Stage2
56    val out = Decoupled(new Stage1To2IO)
57  })
58
59  // flush Stage1 when io.flush
60  val flushS1 = BoolStopWatch(io.flush, io.in.pc.fire(), startHighPriority = true)
61
62  // global history register
63  val ghr = RegInit(0.U(HistoryLength.W))
64  // modify updateGhr and newGhr when updating ghr
65  val updateGhr = WireInit(false.B)
66  val newGhr = WireInit(0.U(HistoryLength.W))
67  when (updateGhr) { ghr := newGhr }
68  // use hist as global history!!!
69  val hist = Mux(updateGhr, newGhr, ghr)
70
71  // Tage predictor
72  // val tage = Module(new FakeTAGE)
73  val tage = Module(new Tage)
74  tage.io.req.valid := io.in.pc.fire()
75  tage.io.req.bits.pc := io.in.pc.bits
76  tage.io.req.bits.hist := hist
77  tage.io.redirectInfo <> io.redirectInfo
78  io.out.bits.tage <> tage.io.out
79  io.s1OutPred.bits.tageMeta := tage.io.meta
80
81  // BTB
82  val btbAddr = new TableAddr(log2Up(BtbSets), BtbBanks)
83  val predictWidth = FetchWidth
84  def btbDataEntry() = new Bundle {
85    val valid = Bool()
86    val target = UInt(VAddrBits.W)
87    val pred = UInt(2.W) // 2-bit saturated counter as a quick predictor
88    val _type = UInt(2.W)
89    val offset = UInt(offsetBits().W) // Could be zero
90
91    def offsetBits() = log2Up(FetchWidth / predictWidth)
92  }
93  def btbMetaEntry() = new Bundle {
94    val valid = Bool()
95    // TODO: don't need full length of tag
96    val tag = UInt(btbAddr.tagBits.W)
97  }
98
99  val btbMeta = List.fill(BtbWays)(List.fill(BtbBanks)(
100    Module(new SRAMTemplate(btbMetaEntry(), set = BtbSets / BtbBanks, way = 1, shouldReset = true, holdRead = true))
101  ))
102  val btbData = List.fill(BtbWays)(List.fill(BtbBanks)(
103    Module(new SRAMTemplate(btbDataEntry(), set = BtbSets / BtbBanks, way = predictWidth, shouldReset = true, holdRead = true))
104  ))
105
106  // BTB read requests
107  // read addr comes from pc[6:2]
108  // read 4 ways in parallel
109  (0 until BtbWays).map(
110    w => (0 until BtbBanks).map(
111      b => {
112        btbMeta(w)(b).reset := reset.asBool
113        btbMeta(w)(b).io.r.req.valid := io.in.pc.fire() && b.U === btbAddr.getBank(io.in.pc.bits)
114        btbMeta(w)(b).io.r.req.bits.setIdx := btbAddr.getBankIdx(io.in.pc.bits)
115        btbData(w)(b).reset := reset.asBool
116        btbData(w)(b).io.r.req.valid := io.in.pc.fire() && b.U === btbAddr.getBank(io.in.pc.bits)
117        btbData(w)(b).io.r.req.bits.setIdx := btbAddr.getBankIdx(io.in.pc.bits)
118      }
119    )
120  )
121
122  // latch pc for 1 cycle latency when reading SRAM
123  val pcLatch = RegEnable(io.in.pc.bits, io.in.pc.fire())
124  // Entries read from SRAM
125  val btbMetaRead = Wire(Vec(BtbWays, btbMetaEntry()))
126  val btbDataRead = Wire(Vec(BtbWays, Vec(predictWidth, btbDataEntry())))
127  val btbReadFire = Wire(Vec(BtbWays, Vec(BtbBanks, Bool())))
128  // 1/4 hit
129  val btbWayHits = Wire(Vec(BtbWays, Bool()))
130
131  // #(predictWidth) results
132  val btbTargets = Wire(Vec(predictWidth, UInt(VAddrBits.W)))
133  val btbTypes = Wire(Vec(predictWidth, UInt(2.W)))
134  // val btbPreds = Wire(Vec(FetchWidth, UInt(2.W)))
135  val btbCtrs = Wire(Vec(predictWidth, UInt(2.W)))
136  val btbTakens = Wire(Vec(predictWidth, Bool()))
137  val btbValids = Wire(Vec(predictWidth, Bool()))
138
139  val btbHitWay = Wire(UInt(log2Up(BtbWays).W))
140  val btbHitBank = btbAddr.getBank(pcLatch)
141
142  btbMetaRead := DontCare
143  btbDataRead := DontCare
144  for (w <- 0 until BtbWays) {
145    for (b <- 0 until BtbBanks) {
146      when (b.U === btbHitBank) {
147        btbMetaRead(w) := btbMeta(w)(b).io.r.resp.data(0)
148        (0 until predictWidth).map(i => btbDataRead(w)(i) := btbData(w)(b).io.r.resp.data(i))
149      }
150    }
151  }
152
153  btbWayHits := 0.U.asTypeOf(Vec(BtbWays, Bool()))
154  btbValids := 0.U.asTypeOf(Vec(predictWidth, Bool()))
155  btbTargets := DontCare
156  btbCtrs := DontCare
157  btbTakens := DontCare
158  btbTypes := DontCare
159  for (w <- 0 until BtbWays) {
160    for (b <- 0 until BtbBanks) { btbReadFire(w)(b) := btbMeta(w)(b).io.r.req.fire() && btbData(w)(b).io.r.req.fire() }
161    when (btbMetaRead(w).valid && btbMetaRead(w).tag === btbAddr.getTag(pcLatch)) {
162      // btbWayHits(w) := !flushS1 && RegNext(btbReadFire(w)(btbHitBank), init = false.B)
163      btbWayHits(w) := !io.flush && RegNext(btbReadFire(w)(btbHitBank), init = false.B)
164      for (i <- 0 until predictWidth) {
165        btbValids(i) := btbDataRead(w)(i).valid
166        btbTargets(i) := btbDataRead(w)(i).target
167        btbCtrs(i) := btbDataRead(w)(i).pred
168        btbTakens(i) := (btbDataRead(w)(i).pred)(1).asBool
169        btbTypes(i) := btbDataRead(w)(i)._type
170      }
171    }
172  }
173
174  val btbHit = btbWayHits.reduce(_|_)
175  btbHitWay := OHToUInt(HighestBit(btbWayHits.asUInt, BtbWays))
176
177  // Priority mux which corresponds with inst orders
178  // BTB only produce one single prediction
179  val btbJumps = Wire(Vec(predictWidth, Bool()))
180  (0 until predictWidth).map(i => btbJumps(i) := btbValids(i) && (btbTypes(i) === BTBtype.J || btbTypes(i) === BTBtype.B && btbTakens(i)))
181  val btbTakenTarget = MuxCase(0.U, btbJumps zip btbTargets)
182  val btbTakenType   = MuxCase(0.U, btbJumps zip btbTypes)
183  val btbTaken       = btbJumps.reduce(_|_)
184  // Record which inst is predicted taken
185  val btbTakenIdx = MuxCase(0.U, btbJumps zip (0 until predictWidth).map(_.U))
186
187  // JBTAC, divided into 8 banks, makes prediction for indirect jump except ret.
188  val jbtacAddr = new TableAddr(log2Up(JbtacSize), JbtacBanks)
189  def jbtacEntry() = new Bundle {
190    val valid = Bool()
191    // TODO: don't need full length of tag and target
192    val tag = UInt(jbtacAddr.tagBits.W)
193    val target = UInt(VAddrBits.W)
194    val offset = UInt(log2Up(FetchWidth).W)
195  }
196
197  val jbtac = List.fill(JbtacBanks)(Module(new SRAMTemplate(jbtacEntry(), set = JbtacSize / JbtacBanks, shouldReset = true, holdRead = true, singlePort = false)))
198
199  val jbtacRead = Wire(Vec(JbtacBanks, jbtacEntry()))
200
201  val jbtacFire = Reg(Vec(JbtacBanks, Bool()))
202  // Only read one bank
203  val histXORAddr = io.in.pc.bits ^ Cat(hist, 0.U(2.W))(VAddrBits - 1, 0)
204  val histXORAddrLatch = RegEnable(histXORAddr, io.in.pc.valid)
205  jbtacFire := 0.U.asTypeOf(Vec(JbtacBanks, Bool()))
206  (0 until JbtacBanks).map(
207    b => {
208      jbtac(b).reset := reset.asBool
209      jbtac(b).io.r.req.valid := io.in.pc.fire() && b.U === jbtacAddr.getBank(histXORAddr)
210      jbtac(b).io.r.req.bits.setIdx := jbtacAddr.getBankIdx(histXORAddr)
211      jbtacFire(b) := jbtac(b).io.r.req.fire()
212      jbtacRead(b) := jbtac(b).io.r.resp.data(0)
213    }
214  )
215
216  val jbtacBank = jbtacAddr.getBank(histXORAddrLatch)
217  // val jbtacHit = jbtacRead(jbtacBank).valid && jbtacRead(jbtacBank).tag === jbtacAddr.getTag(pcLatch) && !flushS1 && jbtacFire(jbtacBank)
218  val jbtacHit = jbtacRead(jbtacBank).valid && jbtacRead(jbtacBank).tag === jbtacAddr.getTag(pcLatch) && !io.flush && jbtacFire(jbtacBank)
219  val jbtacHitIdx = jbtacRead(jbtacBank).offset
220  val jbtacTarget = jbtacRead(jbtacBank).target
221
222  // choose one way as victim way
223  val btbWayInvalids = Cat(btbMetaRead.map(e => !e.valid)).asUInt
224  val victim = Mux(btbHit, btbHitWay, Mux(btbWayInvalids.orR, OHToUInt(LowestBit(btbWayInvalids, BtbWays)), LFSR64()(log2Up(BtbWays) - 1, 0)))
225
226  // calculate global history of each instr
227  val firstHist = RegNext(hist)
228  val histShift = Wire(Vec(FetchWidth, UInt(log2Up(FetchWidth).W)))
229  val btbNotTakens = Wire(Vec(FetchWidth, Bool()))
230  (0 until FetchWidth).map(i => btbNotTakens(i) := btbValids(i) && btbTypes(i) === BTBtype.B && !btbCtrs(1))
231  val shift = Wire(Vec(FetchWidth, Vec(FetchWidth, UInt(1.W))))
232  (0 until FetchWidth).map(i => shift(i) := Mux(!btbNotTakens(i), 0.U, ~LowerMask(UIntToOH(i.U), FetchWidth)).asTypeOf(Vec(FetchWidth, UInt(1.W))))
233  for (j <- 0 until FetchWidth) {
234    var tmp = 0.U
235    for (i <- 0 until FetchWidth) {
236      tmp = tmp + shift(i)(j)
237    }
238    histShift(j) := tmp
239  }
240  (0 until FetchWidth).map(i => io.s1OutPred.bits.hist(i) := firstHist << histShift(i))
241
242  // update btb, jbtac, ghr
243  val r = io.redirectInfo.redirect
244  val updateFetchpc = r.pc - r.fetchIdx << 2.U
245  val updateMisPred = io.redirectInfo.misPred
246  val updateFetchIdx = r.fetchIdx
247  val updateVictimWay = r.btbVictimWay
248  val updateOldCtr = r.btbPredCtr
249  // 1. update btb
250  // 1.1 calculate new 2-bit saturated counter value
251  val newPredCtr = Mux(!r.btbHitWay, "b01".U, Mux(r.taken, Mux(updateOldCtr === "b11".U, "b11".U, updateOldCtr + 1.U),
252                                                           Mux(updateOldCtr === "b00".U, "b00".U, updateOldCtr - 1.U)))
253  // 1.2 write btb
254  val updateBank = btbAddr.getBank(updateFetchpc)
255  val updateBankIdx = btbAddr.getBankIdx(updateFetchpc)
256  val updateWaymask = UIntToOH(updateFetchIdx)
257  val btbMetaWrite = Wire(btbMetaEntry())
258  btbMetaWrite.valid := true.B
259  btbMetaWrite.tag := btbAddr.getTag(updateFetchpc)
260  val btbDataWrite = Wire(btbDataEntry())
261  btbDataWrite.valid := true.B
262  btbDataWrite.target := r.brTarget
263  btbDataWrite.pred := newPredCtr
264  btbDataWrite._type := r._type
265  btbDataWrite.offset := DontCare
266  val btbWriteValid = io.redirectInfo.valid && (r._type === BTBtype.B || r._type === BTBtype.J)
267
268  for (w <- 0 until BtbWays) {
269    for (b <- 0 until BtbBanks) {
270      // println(s"${btbData(w)(b).io.w.req.bits.waymask.nonEmpty}")
271      when (b.U === updateBank && w.U === updateVictimWay) {
272        btbMeta(w)(b).io.w.req.valid := btbWriteValid
273        btbMeta(w)(b).io.w.req.bits.setIdx := updateBankIdx
274        btbMeta(w)(b).io.w.req.bits.data := btbMetaWrite
275        btbData(w)(b).io.w.req.valid := btbWriteValid
276        btbData(w)(b).io.w.req.bits.setIdx := updateBankIdx
277        btbData(w)(b).io.w.req.bits.waymask.map(_ := updateWaymask)
278        btbData(w)(b).io.w.req.bits.data := btbDataWrite
279      }.otherwise {
280        btbMeta(w)(b).io.w.req.valid := false.B
281        btbMeta(w)(b).io.w.req.bits.setIdx := DontCare
282        btbMeta(w)(b).io.w.req.bits.data := DontCare
283        btbData(w)(b).io.w.req.valid := false.B
284        btbData(w)(b).io.w.req.bits.setIdx := DontCare
285        btbData(w)(b).io.w.req.bits.waymask.map(_ := 0.U)
286        btbData(w)(b).io.w.req.bits.data := DontCare
287      }
288    }
289  }
290
291  // 2. update jbtac
292  val jbtacWrite = Wire(jbtacEntry())
293  val updateHistXORAddr = updateFetchpc ^ Cat(r.hist, 0.U(2.W))(VAddrBits - 1, 0)
294  jbtacWrite.valid := true.B
295  jbtacWrite.tag := jbtacAddr.getTag(updateFetchpc)
296  jbtacWrite.target := r.target
297  jbtacWrite.offset := updateFetchIdx
298  for (b <- 0 until JbtacBanks) {
299    when (b.U === jbtacAddr.getBank(updateHistXORAddr)) {
300      jbtac(b).io.w.req.valid := io.redirectInfo.valid && updateMisPred && r._type === BTBtype.I
301      jbtac(b).io.w.req.bits.setIdx := jbtacAddr.getBankIdx(updateHistXORAddr)
302      jbtac(b).io.w.req.bits.data := jbtacWrite
303    }.otherwise {
304      jbtac(b).io.w.req.valid := false.B
305      jbtac(b).io.w.req.bits.setIdx := DontCare
306      jbtac(b).io.w.req.bits.data := DontCare
307    }
308  }
309
310  // 3. update ghr
311  updateGhr := io.s1OutPred.bits.redirect || io.flush
312  val brJumpIdx = Mux(!(btbHit && btbTaken), 0.U, UIntToOH(btbTakenIdx))
313  val indirectIdx = Mux(!jbtacHit, 0.U, UIntToOH(jbtacHitIdx))
314  //val newTaken = Mux(io.redirectInfo.flush(), !(r._type === BTBtype.B && !r.taken), )
315  newGhr := Mux(io.redirectInfo.flush(),    (r.hist << 1.U) | !(r._type === BTBtype.B && !r.taken),
316            Mux(io.flush,                   Mux(io.s3Taken, io.s3RollBackHist << 1.U | 1.U, io.s3RollBackHist),
317            Mux(io.s1OutPred.bits.redirect, PriorityMux(brJumpIdx | indirectIdx, io.s1OutPred.bits.hist) << 1.U | 1.U,
318                                            io.s1OutPred.bits.hist(0) << PopCount(btbNotTakens))))
319
320  // redirect based on BTB and JBTAC
321  // io.out.valid := RegNext(io.in.pc.fire()) && !flushS1
322  io.out.valid := RegNext(io.in.pc.fire()) && !io.flush
323
324  io.s1OutPred.valid := io.out.valid
325  io.s1OutPred.bits.redirect := btbHit && btbTaken || jbtacHit
326  // io.s1OutPred.bits.instrValid := LowerMask(UIntToOH(btbTakenIdx), FetchWidth) & LowerMask(UIntToOH(jbtacHitIdx), FetchWidth)
327  io.s1OutPred.bits.instrValid := Mux(io.s1OutPred.bits.redirect, LowerMask(LowestBit(brJumpIdx | indirectIdx, FetchWidth), FetchWidth), Fill(FetchWidth, 1.U(1.W))).asTypeOf(Vec(FetchWidth, Bool()))
328  io.s1OutPred.bits.target := Mux(brJumpIdx === LowestBit(brJumpIdx | indirectIdx, FetchWidth), btbTakenTarget, jbtacTarget)
329  io.s1OutPred.bits.btbVictimWay := victim
330  io.s1OutPred.bits.predCtr := btbCtrs
331  io.s1OutPred.bits.btbHitWay := btbHit
332  io.s1OutPred.bits.rasSp := DontCare
333  io.s1OutPred.bits.rasTopCtr := DontCare
334
335  io.out.bits.pc := pcLatch
336  io.out.bits.btb.hits := btbValids.asUInt
337  (0 until FetchWidth).map(i => io.out.bits.btb.targets(i) := btbTargets(i))
338  io.out.bits.jbtac.hitIdx := UIntToOH(jbtacHitIdx)
339  io.out.bits.jbtac.target := jbtacTarget
340  // TODO: we don't need this repeatedly!
341  io.out.bits.hist := io.s1OutPred.bits.hist
342  io.out.bits.btbPred := io.s1OutPred
343
344  io.in.pc.ready := true.B
345
346  // debug info
347  XSDebug(true.B, "[BPUS1]in:(%d %d)   pc=%x ghr=%b\n", io.in.pc.valid, io.in.pc.ready, io.in.pc.bits, hist)
348  XSDebug(true.B, "[BPUS1]outPred:(%d) redirect=%d instrValid=%b tgt=%x\n",
349    io.s1OutPred.valid, io.s1OutPred.bits.redirect, io.s1OutPred.bits.instrValid.asUInt, io.s1OutPred.bits.target)
350  XSDebug(io.flush && io.redirectInfo.flush(),
351    "[BPUS1]flush from backend: pc=%x tgt=%x brTgt=%x _type=%b taken=%d oldHist=%b fetchIdx=%d isExcpt=%d\n",
352    r.pc, r.target, r.brTarget, r._type, r.taken, r.hist, r.fetchIdx, r.isException)
353  XSDebug(io.flush && !io.redirectInfo.flush(),
354    "[BPUS1]flush from Stage3:  s3Taken=%d s3RollBackHist=%b\n", io.s3Taken, io.s3RollBackHist)
355
356}
357
358class Stage2To3IO extends Stage1To2IO {
359}
360
361class BPUStage2 extends XSModule {
362  val io = IO(new Bundle() {
363    // flush from Stage3
364    val flush = Input(Bool())
365    val in = Flipped(Decoupled(new Stage1To2IO))
366    val out = Decoupled(new Stage2To3IO)
367  })
368
369  // flush Stage2 when Stage3 or banckend redirects
370  val flushS2 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
371  io.out.valid := !io.flush && !flushS2 && RegNext(io.in.fire())
372  io.in.ready := !io.out.valid || io.out.fire()
373
374  // do nothing
375  io.out.bits := RegEnable(io.in.bits, io.in.fire())
376
377  // debug info
378  XSDebug(true.B, "[BPUS2]in:(%d %d) pc=%x out:(%d %d) pc=%x\n",
379    io.in.valid, io.in.ready, io.in.bits.pc, io.out.valid, io.out.ready, io.out.bits.pc)
380  XSDebug(io.flush, "[BPUS2]flush!!!\n")
381}
382
383class BPUStage3 extends XSModule {
384  val io = IO(new Bundle() {
385    val flush = Input(Bool())
386    val in = Flipped(Decoupled(new Stage2To3IO))
387    val out = ValidIO(new BranchPrediction)
388    // from icache
389    val predecode = Flipped(ValidIO(new Predecode))
390    // from backend
391    val redirectInfo = Input(new RedirectInfo)
392    // to Stage1 and Stage2
393    val flushBPU = Output(Bool())
394    // to Stage1, restore ghr in stage1 when flushBPU is valid
395    val s1RollBackHist = Output(UInt(HistoryLength.W))
396    val s3Taken = Output(Bool())
397  })
398
399  val flushS3 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
400  val inLatch = RegInit(0.U.asTypeOf(io.in.bits))
401  val validLatch = RegInit(false.B)
402  when (io.in.fire()) { inLatch := io.in.bits }
403  when (io.in.fire()) {
404    validLatch := !io.flush
405  }.elsewhen (io.out.valid) {
406    validLatch := false.B
407  }
408  io.out.valid := validLatch && io.predecode.valid && !flushS3
409  io.in.ready := !validLatch || io.out.valid
410
411  // RAS
412  // TODO: split retAddr and ctr
413  def rasEntry() = new Bundle {
414    val retAddr = UInt(VAddrBits.W)
415    val ctr = UInt(8.W) // layer of nested call functions
416  }
417  val ras = RegInit(VecInit(Seq.fill(RasSize)(0.U.asTypeOf(rasEntry()))))
418  val sp = Counter(RasSize)
419  val rasTop = ras(sp.value)
420  val rasTopAddr = rasTop.retAddr
421
422  // get the first taken branch/jal/call/jalr/ret in a fetch line
423  // brTakenIdx/jalIdx/callIdx/jalrIdx/retIdx/jmpIdx is one-hot encoded.
424  // brNotTakenIdx indicates all the not-taken branches before the first jump instruction.
425  val brIdx = inLatch.btb.hits & Cat(io.predecode.bits.fuOpTypes.map { t => ALUOpType.isBranch(t) }).asUInt & io.predecode.bits.mask
426  val brTakenIdx = LowestBit(brIdx & inLatch.tage.takens.asUInt, FetchWidth)
427  val jalIdx = LowestBit(inLatch.btb.hits & Cat(io.predecode.bits.fuOpTypes.map { t => t === ALUOpType.jal }).asUInt & io.predecode.bits.mask, FetchWidth)
428  val callIdx = LowestBit(inLatch.btb.hits & io.predecode.bits.mask & Cat(io.predecode.bits.fuOpTypes.map { t => t === ALUOpType.call }).asUInt, FetchWidth)
429  val jalrIdx = LowestBit(inLatch.jbtac.hitIdx & io.predecode.bits.mask & Cat(io.predecode.bits.fuOpTypes.map { t => t === ALUOpType.jalr }).asUInt, FetchWidth)
430  val retIdx = LowestBit(io.predecode.bits.mask & Cat(io.predecode.bits.fuOpTypes.map { t => t === ALUOpType.ret }).asUInt, FetchWidth)
431
432  val jmpIdx = LowestBit(brTakenIdx | jalIdx | callIdx | jalrIdx | retIdx, FetchWidth)
433  val brNotTakenIdx = brIdx & ~inLatch.tage.takens.asUInt & LowerMask(jmpIdx, FetchWidth) & io.predecode.bits.mask
434
435  io.out.bits.redirect := jmpIdx.orR.asBool
436  io.out.bits.target := Mux(jmpIdx === retIdx, rasTopAddr,
437    Mux(jmpIdx === jalrIdx, inLatch.jbtac.target,
438    Mux(jmpIdx === 0.U, inLatch.pc + 32.U, // TODO: RVC
439    PriorityMux(jmpIdx, inLatch.btb.targets))))
440  io.out.bits.instrValid := Mux(jmpIdx.orR, LowerMask(jmpIdx, FetchWidth), Fill(FetchWidth, 1.U(1.W))).asTypeOf(Vec(FetchWidth, Bool()))
441  io.out.bits.btbVictimWay := inLatch.btbPred.bits.btbVictimWay
442  io.out.bits.predCtr := inLatch.btbPred.bits.predCtr
443  io.out.bits.btbHitWay := inLatch.btbPred.bits.btbHitWay
444  io.out.bits.tageMeta := inLatch.btbPred.bits.tageMeta
445  //io.out.bits._type := Mux(jmpIdx === retIdx, BTBtype.R,
446  //  Mux(jmpIdx === jalrIdx, BTBtype.I,
447  //  Mux(jmpIdx === brTakenIdx, BTBtype.B, BTBtype.J)))
448  val firstHist = inLatch.btbPred.bits.hist(0)
449  // there may be several notTaken branches before the first jump instruction,
450  // so we need to calculate how many zeroes should each instruction shift in its global history.
451  // each history is exclusive of instruction's own jump direction.
452  val histShift = Wire(Vec(FetchWidth, UInt(log2Up(FetchWidth).W)))
453  val shift = Wire(Vec(FetchWidth, Vec(FetchWidth, UInt(1.W))))
454  (0 until FetchWidth).map(i => shift(i) := Mux(!brNotTakenIdx(i), 0.U, ~LowerMask(UIntToOH(i.U), FetchWidth)).asTypeOf(Vec(FetchWidth, UInt(1.W))))
455  for (j <- 0 until FetchWidth) {
456    var tmp = 0.U
457    for (i <- 0 until FetchWidth) {
458      tmp = tmp + shift(i)(j)
459    }
460    histShift(j) := tmp
461  }
462  (0 until FetchWidth).map(i => io.out.bits.hist(i) := firstHist << histShift(i))
463  // save ras checkpoint info
464  io.out.bits.rasSp := sp.value
465  io.out.bits.rasTopCtr := rasTop.ctr
466
467  // flush BPU and redirect when target differs from the target predicted in Stage1
468  io.out.bits.redirect := inLatch.btbPred.bits.redirect ^ jmpIdx.orR.asBool ||
469    inLatch.btbPred.bits.redirect && jmpIdx.orR.asBool && io.out.bits.target =/= inLatch.btbPred.bits.target
470  io.flushBPU := io.out.bits.redirect && io.out.valid
471
472  // speculative update RAS
473  val rasWrite = WireInit(0.U.asTypeOf(rasEntry()))
474  rasWrite.retAddr := inLatch.pc + OHToUInt(callIdx) << 2.U + 4.U
475  val allocNewEntry = rasWrite.retAddr =/= rasTopAddr
476  rasWrite.ctr := Mux(allocNewEntry, 1.U, rasTop.ctr + 1.U)
477  when (io.out.valid) {
478    when (jmpIdx === callIdx) {
479      ras(Mux(allocNewEntry, sp.value + 1.U, sp.value)) := rasWrite
480      when (allocNewEntry) { sp.value := sp.value + 1.U }
481    }.elsewhen (jmpIdx === retIdx) {
482      when (rasTop.ctr === 1.U) {
483        sp.value := Mux(sp.value === 0.U, 0.U, sp.value - 1.U)
484      }.otherwise {
485        ras(sp.value) := Cat(rasTop.ctr - 1.U, rasTopAddr).asTypeOf(rasEntry())
486      }
487    }
488  }
489  // use checkpoint to recover RAS
490  val recoverSp = io.redirectInfo.redirect.rasSp
491  val recoverCtr = io.redirectInfo.redirect.rasTopCtr
492  when (io.redirectInfo.valid && io.redirectInfo.misPred) {
493    sp.value := recoverSp
494    ras(recoverSp) := Cat(recoverCtr, ras(recoverSp).retAddr).asTypeOf(rasEntry())
495  }
496
497  // roll back global history in S1 if S3 redirects
498  io.s1RollBackHist := Mux(io.s3Taken, PriorityMux(jmpIdx, io.out.bits.hist), io.out.bits.hist(0) << PopCount(brIdx & ~inLatch.tage.takens.asUInt))
499  // whether Stage3 has a taken jump
500  io.s3Taken := jmpIdx.orR.asBool
501
502  // debug info
503  XSDebug(io.in.fire(), "[BPUS3]in:(%d %d) pc=%x\n", io.in.valid, io.in.ready, io.in.bits.pc)
504  XSDebug(io.out.valid, "[BPUS3]out:%d pc=%x redirect=%d predcdMask=%b instrValid=%b tgt=%x\n",
505    io.out.valid, inLatch.pc, io.out.bits.redirect, io.predecode.bits.mask, io.out.bits.instrValid.asUInt, io.out.bits.target)
506  XSDebug(true.B, "[BPUS3]flushS3=%d\n", flushS3)
507  XSDebug(true.B, "[BPUS3]validLatch=%d predecode.valid=%d\n", validLatch, io.predecode.valid)
508  XSDebug(true.B, "[BPUS3]brIdx=%b brTakenIdx=%b brNTakenIdx=%b jalIdx=%d jalrIdx=%d callIdx=%d retIdx=%b\n",
509    brIdx, brTakenIdx, brNotTakenIdx, jalIdx, jalrIdx, callIdx, retIdx)
510}
511
512class BPU extends XSModule {
513  val io = IO(new Bundle() {
514    // from backend
515    // flush pipeline if misPred and update bpu based on redirect signals from brq
516    val redirectInfo = Input(new RedirectInfo)
517
518    val in = new Bundle { val pc = Flipped(Valid(UInt(VAddrBits.W))) }
519
520    val btbOut = ValidIO(new BranchPrediction)
521    val tageOut = ValidIO(new BranchPrediction)
522
523    // predecode info from icache
524    // TODO: simplify this after implement predecode unit
525    val predecode = Flipped(ValidIO(new Predecode))
526  })
527
528  val s1 = Module(new BPUStage1)
529  val s2 = Module(new BPUStage2)
530  val s3 = Module(new BPUStage3)
531
532  s1.io.redirectInfo <> io.redirectInfo
533  s1.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
534  s1.io.in.pc.valid := io.in.pc.valid
535  s1.io.in.pc.bits <> io.in.pc.bits
536  io.btbOut <> s1.io.s1OutPred
537  s1.io.s3RollBackHist := s3.io.s1RollBackHist
538  s1.io.s3Taken := s3.io.s3Taken
539
540  s1.io.out <> s2.io.in
541  s2.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
542
543  s2.io.out <> s3.io.in
544  s3.io.flush := io.redirectInfo.flush()
545  s3.io.predecode <> io.predecode
546  io.tageOut <> s3.io.out
547  s3.io.redirectInfo <> io.redirectInfo
548
549  // TODO: temp and ugly code, when perf counters is added( may after adding CSR), please mv the below counter
550  val bpuPerfCntList = List(
551    "MbpInstr",
552    "MbpRight",
553    "MbpWrong",
554    "MbpBRight",
555    "MbpBWrong",
556    "MbpJRight",
557    "MbpJWrong",
558    "MbpIRight",
559    "MbpIWrong",
560    "MbpRRight",
561    "MbpRWrong"
562  )
563
564  val bpuPerfCnts = List.fill(bpuPerfCntList.length)(RegInit(0.U(XLEN.W)))
565  val bpuPerfCntConds = List.fill(bpuPerfCntList.length)(WireInit(false.B))
566  (bpuPerfCnts zip bpuPerfCntConds) map { case (cnt, cond) => { when (cond) { cnt := cnt + 1.U }}}
567
568  for(i <- bpuPerfCntList.indices) {
569    BoringUtils.addSink(bpuPerfCntConds(i), bpuPerfCntList(i))
570  }
571
572  val xsTrap = WireInit(false.B)
573  BoringUtils.addSink(xsTrap, "XSTRAP_BPU")
574
575  // if (!p.FPGAPlatform) {
576    when (xsTrap) {
577      printf("=================BPU's PerfCnt================\n")
578      for(i <- bpuPerfCntList.indices) {
579        printf(bpuPerfCntList(i) + " <- " + "%d\n", bpuPerfCnts(i))
580      }
581    }
582  // }
583}