xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision 2225d46ebbe2fd16b9b29963c27a7d0385a42709)
1package xiangshan.frontend
2
3import chipsalliance.rocketchip.config.Parameters
4import chisel3._
5import chisel3.util._
6import utils._
7import xiangshan._
8import chisel3.experimental.chiselName
9
10trait HasBPUParameter extends HasXSParameter {
11  val BPUDebug = true && !env.FPGAPlatform
12  val EnableCFICommitLog = true
13  val EnbaleCFIPredLog = true
14  val EnableBPUTimeRecord = (EnableCFICommitLog || EnbaleCFIPredLog) && !env.FPGAPlatform
15  val EnableCommit = false
16}
17
18class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle with HasIFUConst {
19  def tagBits = VAddrBits - idxBits - instOffsetBits
20
21  val tag = UInt(tagBits.W)
22  val idx = UInt(idxBits.W)
23  val offset = UInt(instOffsetBits.W)
24
25  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
26  def getTag(x: UInt) = fromUInt(x).tag
27  def getIdx(x: UInt) = fromUInt(x).idx
28  def getBank(x: UInt) = getIdx(x)(log2Up(banks) - 1, 0)
29  def getBankIdx(x: UInt) = getIdx(x)(idxBits - 1, log2Up(banks))
30}
31
32class PredictorResponse(implicit p: Parameters) extends XSBundle {
33  class UbtbResp extends XSBundle {
34  // the valid bits indicates whether a target is hit
35    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
36    val hits = Vec(PredictWidth, Bool())
37    val takens = Vec(PredictWidth, Bool())
38    val brMask = Vec(PredictWidth, Bool())
39    val is_RVC = Vec(PredictWidth, Bool())
40  }
41  class BtbResp extends XSBundle {
42  // the valid bits indicates whether a target is hit
43    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
44    val hits = Vec(PredictWidth, Bool())
45    val isBrs = Vec(PredictWidth, Bool())
46    val isRVC = Vec(PredictWidth, Bool())
47  }
48  class BimResp extends XSBundle {
49    val ctrs = Vec(PredictWidth, UInt(2.W))
50  }
51  class TageResp extends XSBundle {
52  // the valid bits indicates whether a prediction is hit
53    val takens = Vec(PredictWidth, Bool())
54    val hits = Vec(PredictWidth, Bool())
55  }
56  class LoopResp extends XSBundle {
57    val exit = Vec(PredictWidth, Bool())
58  }
59
60  val ubtb = new UbtbResp
61  val btb = new BtbResp
62  val bim = new BimResp
63  val tage = new TageResp
64  val loop = new LoopResp
65}
66
67trait PredictorUtils {
68  // circular shifting
69  def circularShiftLeft(source: UInt, len: Int, shamt: UInt): UInt = {
70    val res = Wire(UInt(len.W))
71    val higher = source << shamt
72    val lower = source >> (len.U - shamt)
73    res := higher | lower
74    res
75  }
76
77  def circularShiftRight(source: UInt, len: Int, shamt: UInt): UInt = {
78    val res = Wire(UInt(len.W))
79    val higher = source << (len.U - shamt)
80    val lower = source >> shamt
81    res := higher | lower
82    res
83  }
84
85  // To be verified
86  def satUpdate(old: UInt, len: Int, taken: Bool): UInt = {
87    val oldSatTaken = old === ((1 << len)-1).U
88    val oldSatNotTaken = old === 0.U
89    Mux(oldSatTaken && taken, ((1 << len)-1).U,
90      Mux(oldSatNotTaken && !taken, 0.U,
91        Mux(taken, old + 1.U, old - 1.U)))
92  }
93
94  def signedSatUpdate(old: SInt, len: Int, taken: Bool): SInt = {
95    val oldSatTaken = old === ((1 << (len-1))-1).S
96    val oldSatNotTaken = old === (-(1 << (len-1))).S
97    Mux(oldSatTaken && taken, ((1 << (len-1))-1).S,
98      Mux(oldSatNotTaken && !taken, (-(1 << (len-1))).S,
99        Mux(taken, old + 1.S, old - 1.S)))
100  }
101}
102
103trait HasIFUFire { this: MultiIOModule =>
104  val fires = IO(Input(Vec(4, Bool())))
105  val s1_fire  = fires(0)
106  val s2_fire  = fires(1)
107  val s3_fire  = fires(2)
108  val out_fire = fires(3)
109}
110
111trait HasCtrl { this: BasePredictor =>
112  val ctrl = IO(Input(new BPUCtrl))
113}
114
115abstract class BasePredictor(implicit p: Parameters) extends XSModule
116  with HasBPUParameter with HasIFUConst with PredictorUtils
117  with HasIFUFire with HasCtrl {
118  val metaLen = 0
119
120  // An implementation MUST extend the IO bundle with a response
121  // and the special input from other predictors, as well as
122  // the metas to store in BRQ
123  abstract class Resp extends XSBundle {}
124  abstract class FromOthers extends XSBundle {}
125  abstract class Meta extends XSBundle {}
126
127  class DefaultBasePredictorIO extends XSBundle {
128    val pc = Flipped(ValidIO(UInt(VAddrBits.W)))
129    val hist = Input(UInt(HistoryLength.W))
130    val inMask = Input(UInt(PredictWidth.W))
131    val update = Flipped(ValidIO(new FtqEntry))
132  }
133  val io = new DefaultBasePredictorIO
134  val in_ready = IO(Output(Bool()))
135  in_ready := true.B
136  val debug = true
137}
138
139class BrInfo(implicit p: Parameters) extends XSBundle {
140  val metas = Vec(PredictWidth, new BpuMeta)
141  val rasSp = UInt(log2Ceil(RasSize).W)
142  val rasTop = new RASEntry
143  val specCnt = Vec(PredictWidth, UInt(10.W))
144}
145class BPUStageIO(implicit p: Parameters) extends XSBundle {
146  val pc = UInt(VAddrBits.W)
147  val mask = UInt(PredictWidth.W)
148  val resp = new PredictorResponse
149  val brInfo = new BrInfo
150}
151
152
153abstract class BPUStage(implicit p: Parameters) extends XSModule with HasBPUParameter
154  with HasIFUConst with HasIFUFire {
155  class DefaultIO extends XSBundle {
156    val in = Input(new BPUStageIO)
157    val inFire = Input(Bool())
158    val pred = Output(new BranchPrediction) // to ifu
159    val out = Output(new BPUStageIO)        // to the next stage
160    val outFire = Input(Bool())
161
162    val debug_hist = Input(UInt((if (BPUDebug) (HistoryLength) else 0).W))
163  }
164  val io = IO(new DefaultIO)
165
166  val inLatch = RegEnable(io.in, io.inFire)
167
168  // Each stage has its own logic to decide
169  // takens, brMask, jalMask, targets and hasHalfRVI
170  val takens = Wire(Vec(PredictWidth, Bool()))
171  val brMask = Wire(Vec(PredictWidth, Bool()))
172  val jalMask = Wire(Vec(PredictWidth, Bool()))
173  val targets = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
174  val hasHalfRVI = Wire(Bool())
175
176  io.pred <> DontCare
177  io.pred.takens := takens.asUInt
178  io.pred.brMask := brMask.asUInt
179  io.pred.jalMask := jalMask.asUInt
180  io.pred.targets := targets
181  io.pred.hasHalfRVI := hasHalfRVI
182
183  io.out <> DontCare
184  io.out.pc := inLatch.pc
185  io.out.mask := inLatch.mask
186  io.out.resp <> inLatch.resp
187  io.out.brInfo := inLatch.brInfo
188
189  if (BPUDebug) {
190    val jmpIdx = io.pred.jmpIdx
191    val taken  = io.pred.taken
192    val target = Mux(taken, io.pred.targets(jmpIdx), snpc(inLatch.pc))
193    XSDebug("in(%d): pc=%x, mask=%b\n", io.inFire, io.in.pc, io.in.mask)
194    XSDebug("inLatch: pc=%x, mask=%b\n", inLatch.pc, inLatch.mask)
195    XSDebug("out(%d): pc=%x, mask=%b, taken=%d, jmpIdx=%d, target=%x, hasHalfRVI=%d\n",
196      io.outFire, io.out.pc, io.out.mask, taken, jmpIdx, target, hasHalfRVI)
197    //val p = io.pred
198  }
199}
200
201@chiselName
202class BPUStage1(implicit p: Parameters) extends BPUStage {
203
204  // ubtb is accessed with inLatch pc in s1,
205  // so we use io.in instead of inLatch
206  val ubtbResp = io.in.resp.ubtb
207  // the read operation is already masked, so we do not need to mask here
208  takens    := VecInit((0 until PredictWidth).map(i => ubtbResp.takens(i)))
209  // notTakens := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && !ubtbResp.takens(i) && ubtbResp.brMask(i)))
210  brMask := ubtbResp.brMask
211  jalMask := DontCare
212  targets := ubtbResp.targets
213
214  hasHalfRVI := ubtbResp.hits(PredictWidth-1) && !ubtbResp.is_RVC(PredictWidth-1) && HasCExtension.B
215
216  // resp and brInfo are from the components,
217  // so it does not need to be latched
218  io.out.resp <> io.in.resp
219  io.out.brInfo := io.in.brInfo
220
221  // For perf counters
222  if (!env.FPGAPlatform && env.EnablePerfDebug) {
223    io.out.brInfo.metas.zipWithIndex.foreach{case (meta, i) =>
224      // record ubtb pred result
225      meta.ubtbAns.hit := ubtbResp.hits(i)
226      meta.ubtbAns.taken := ubtbResp.takens(i)
227      meta.ubtbAns.target := ubtbResp.targets(i)
228    }
229  }
230
231  if (BPUDebug) {
232    XSDebug(io.outFire, "outPred using ubtb resp: hits:%b, takens:%b, notTakens:%b, isRVC:%b\n",
233      ubtbResp.hits.asUInt, ubtbResp.takens.asUInt, ~ubtbResp.takens.asUInt & brMask.asUInt, ubtbResp.is_RVC.asUInt)
234  }
235  if (EnableBPUTimeRecord) {
236    io.out.brInfo.metas.map(_.debug_ubtb_cycle := GTimer())
237  }
238}
239@chiselName
240class BPUStage2(implicit p: Parameters) extends BPUStage {
241  // Use latched response from s1
242  val btbResp = inLatch.resp.btb
243  val bimResp = inLatch.resp.bim
244  takens    := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && (btbResp.isBrs(i) && bimResp.ctrs(i)(1) || !btbResp.isBrs(i))))
245  targets := btbResp.targets
246  brMask  := VecInit((0 until PredictWidth).map(i => btbResp.isBrs(i) && btbResp.hits(i)))
247  jalMask := DontCare
248
249  hasHalfRVI  := btbResp.hits(PredictWidth-1) && !btbResp.isRVC(PredictWidth-1) && HasCExtension.B
250
251  // For perf counters
252  if (!env.FPGAPlatform && env.EnablePerfDebug) {
253    io.out.brInfo.metas.zipWithIndex.foreach{case (meta, i) =>
254      // record btb pred result
255      meta.btbAns.hit := btbResp.hits(i)
256      meta.btbAns.taken := takens(i)
257      meta.btbAns.target := btbResp.targets(i)
258    }
259  }
260
261  if (BPUDebug) {
262    XSDebug(io.outFire, "outPred using btb&bim resp: hits:%b, ctrTakens:%b\n",
263      btbResp.hits.asUInt, VecInit(bimResp.ctrs.map(_(1))).asUInt)
264  }
265  if (EnableBPUTimeRecord) {
266    io.out.brInfo.metas.map(_.debug_btb_cycle := GTimer())
267  }
268}
269@chiselName
270class BPUStage3(implicit p: Parameters) extends BPUStage {
271  class S3IO extends XSBundle {
272    val predecode = Input(new Predecode)
273    val redirect =  Flipped(ValidIO(new Redirect))
274    val ctrl = Input(new BPUCtrl)
275  }
276  val s3IO = IO(new S3IO)
277  // TAGE has its own pipelines and the
278  // response comes directly from s3,
279  // so we do not use those from inLatch
280  val tageResp = io.in.resp.tage
281  val tageTakens = tageResp.takens
282
283  val loopResp = io.in.resp.loop.exit
284
285  val pdMask     = s3IO.predecode.mask
286  val pdLastHalf = s3IO.predecode.lastHalf
287  val pds        = s3IO.predecode.pd
288
289  val btbResp   = WireInit(inLatch.resp.btb)
290  val btbHits   = WireInit(btbResp.hits.asUInt)
291  val bimTakens = VecInit(inLatch.resp.bim.ctrs.map(_(1)))
292
293  val brs   = pdMask & Reverse(Cat(pds.map(_.isBr)))
294  val jals  = pdMask & Reverse(Cat(pds.map(_.isJal)))
295  val jalrs = pdMask & Reverse(Cat(pds.map(_.isJalr)))
296  val calls = pdMask & Reverse(Cat(pds.map(_.isCall)))
297  val rets  = pdMask & Reverse(Cat(pds.map(_.isRet)))
298  val RVCs  = pdMask & Reverse(Cat(pds.map(_.isRVC)))
299
300  val callIdx = PriorityEncoder(calls)
301  val retIdx  = PriorityEncoder(rets)
302
303  val brPred = (if(EnableBPD) tageTakens else bimTakens).asUInt
304  val loopRes = (if (EnableLoop) loopResp else VecInit(Fill(PredictWidth, 0.U(1.W)))).asUInt
305  val brTakens = ((brs & brPred) & ~loopRes)
306  // we should provide btb resp as well
307  btbHits := btbResp.hits.asUInt
308
309  // predict taken only if btb has a target, jal and br targets will be provided by IFU
310  takens := VecInit((0 until PredictWidth).map(i => jalrs(i) && btbHits(i) || (jals(i) || brTakens(i))))
311
312
313  targets := inLatch.resp.btb.targets
314
315  brMask  := WireInit(brs.asTypeOf(Vec(PredictWidth, Bool())))
316  jalMask := WireInit(jals.asTypeOf(Vec(PredictWidth, Bool())))
317
318  hasHalfRVI  := pdLastHalf && HasCExtension.B
319
320  //RAS
321  if(EnableRAS){
322    val ras = Module(new RAS)
323    ras.io <> DontCare
324    ras.io.pc.bits := packetAligned(inLatch.pc)
325    ras.io.pc.valid := io.outFire//predValid
326    ras.io.is_ret := rets.orR  && (retIdx === io.pred.jmpIdx)
327    ras.io.callIdx.valid := calls.orR && (callIdx === io.pred.jmpIdx)
328    ras.io.callIdx.bits := callIdx
329    ras.io.isRVC := (calls & RVCs).orR   //TODO: this is ugly
330    ras.io.isLastHalfRVI := s3IO.predecode.hasLastHalfRVI
331    ras.io.redirect := s3IO.redirect
332    ras.fires <> fires
333    ras.ctrl := s3IO.ctrl
334
335    for(i <- 0 until PredictWidth){
336      io.out.brInfo.rasSp :=  ras.io.meta.rasSp
337      io.out.brInfo.rasTop :=  ras.io.meta.rasTop
338    }
339    val rasEn = s3IO.ctrl.ras_enable
340    takens := VecInit((0 until PredictWidth).map(i => {
341      (jalrs(i) && btbHits(i)) ||
342          jals(i) || brTakens(i) ||
343          (rasEn && rets(i)) ||
344          (!rasEn && rets(i) && btbHits(i))
345      }
346    ))
347
348    for (i <- 0 until PredictWidth) {
349      when(rets(i)){
350        targets(i) := ras.io.out.target
351      }
352    }
353
354    // For perf counters
355    if (!env.FPGAPlatform && env.EnablePerfDebug) {
356      io.out.brInfo.metas.zipWithIndex.foreach{case (meta, i) =>
357        // record tage pred result
358        meta.tageAns.hit := tageResp.hits(i)
359        meta.tageAns.taken := tageResp.takens(i)
360        meta.tageAns.target := DontCare
361
362        // record ras pred result
363        meta.rasAns.hit := true.B
364        meta.rasAns.taken := true.B
365        meta.rasAns.target := ras.io.out.target
366
367        // record loop pred result
368        meta.loopAns.hit := loopRes(i)
369        meta.loopAns.taken := false.B
370        meta.loopAns.target := DontCare
371      }
372    }
373  }
374
375
376  // Wrap tage resp and tage meta in
377  // This is ugly
378  io.out.resp.tage <> io.in.resp.tage
379  io.out.resp.loop <> io.in.resp.loop
380  for (i <- 0 until PredictWidth) {
381    io.out.brInfo.metas(i).tageMeta := io.in.brInfo.metas(i).tageMeta
382    io.out.brInfo.specCnt(i) := io.in.brInfo.specCnt(i)
383  }
384
385  if (BPUDebug) {
386    XSDebug(io.inFire, "predecode: pc:%x, mask:%b\n", inLatch.pc, s3IO.predecode.mask)
387    for (i <- 0 until PredictWidth) {
388      val pd = s3IO.predecode.pd(i)
389      XSDebug(io.inFire && s3IO.predecode.mask(i), "predecode(%d): brType:%d, br:%d, jal:%d, jalr:%d, call:%d, ret:%d, RVC:%d, excType:%d\n",
390        i.U, pd.brType, pd.isBr, pd.isJal, pd.isJalr, pd.isCall, pd.isRet, pd.isRVC, pd.excType)
391    }
392    XSDebug(p"brs:${Binary(brs)} jals:${Binary(jals)} jalrs:${Binary(jalrs)} calls:${Binary(calls)} rets:${Binary(rets)} rvcs:${Binary(RVCs)}\n")
393    XSDebug(p"callIdx:${callIdx} retIdx:${retIdx}\n")
394    XSDebug(p"brPred:${Binary(brPred)} loopRes:${Binary(loopRes)} brTakens:${Binary(brTakens)}\n")
395  }
396
397  if (EnbaleCFIPredLog) {
398    val out = io.out
399    XSDebug(io.outFire, p"cfi_pred: fetchpc(${Hexadecimal(out.pc)}) mask(${out.mask}) brmask(${brMask.asUInt}) hist(${Hexadecimal(io.debug_hist)})\n")
400  }
401
402  if (EnableBPUTimeRecord) {
403    io.out.brInfo.metas.map(_.debug_tage_cycle := GTimer())
404  }
405}
406
407trait BranchPredictorComponents extends HasXSParameter {
408  val ubtb = Module(new MicroBTB)
409  val btb = Module(new BTB)
410  val bim = Module(new BIM)
411  val tage = (if(EnableBPD) { if (EnableSC) Module(new Tage_SC)
412                              else          Module(new Tage) }
413              else          { Module(new FakeTage) })
414  val loop = Module(new LoopPredictor)
415  val preds = Seq(ubtb, btb, bim, tage, loop)
416  preds.map(_.io := DontCare)
417}
418
419class BPUReq(implicit p: Parameters) extends XSBundle {
420  val pc = UInt(VAddrBits.W)
421  val hist = UInt(HistoryLength.W)
422  val inMask = UInt(PredictWidth.W)
423}
424
425class BPUCtrl(implicit p: Parameters) extends XSBundle {
426  val ubtb_enable = Bool()
427  val btb_enable  = Bool()
428  val bim_enable  = Bool()
429  val tage_enable = Bool()
430  val sc_enable   = Bool()
431  val ras_enable  = Bool()
432  val loop_enable = Bool()
433}
434
435abstract class BaseBPU(implicit p: Parameters) extends XSModule with BranchPredictorComponents
436  with HasBPUParameter with HasIFUConst {
437  val io = IO(new Bundle() {
438    // from backend
439    val redirect = Flipped(ValidIO(new Redirect))
440    val ctrl     = Input(new BPUCtrl)
441    val commit   = Flipped(ValidIO(new FtqEntry))
442    // from if1
443    val in = Input(new BPUReq)
444    val inFire = Input(Vec(4, Bool()))
445    // to if1
446    val in_ready = Output(Bool())
447    // to if2/if3/if4
448    val out = Vec(3, Output(new BranchPrediction))
449    // from if4
450    val predecode = Input(new Predecode)
451    // to if4, some bpu info used for updating
452    val brInfo = Output(new BrInfo)
453  })
454
455  preds.map(p => {
456    p.io.update <> io.commit
457    p.fires <> io.inFire
458    p.ctrl <> io.ctrl
459  })
460
461  io.in_ready := preds.map(p => p.in_ready).reduce(_&&_)
462
463  val s1 = Module(new BPUStage1)
464  val s2 = Module(new BPUStage2)
465  val s3 = Module(new BPUStage3)
466
467  Seq(s1, s2, s3).foreach(s => s.fires <> io.inFire)
468
469  val s1_fire = io.inFire(0)
470  val s2_fire = io.inFire(1)
471  val s3_fire = io.inFire(2)
472  val s4_fire = io.inFire(3)
473
474  s1.io.in <> DontCare
475  s2.io.in <> s1.io.out
476  s3.io.in <> s2.io.out
477
478  s1.io.inFire := s1_fire
479  s2.io.inFire := s2_fire
480  s3.io.inFire := s3_fire
481
482  s1.io.outFire := s2_fire
483  s2.io.outFire := s3_fire
484  s3.io.outFire := s4_fire
485
486  io.out(0) <> s1.io.pred
487  io.out(1) <> s2.io.pred
488  io.out(2) <> s3.io.pred
489
490  io.brInfo := s3.io.out.brInfo
491
492  if (BPUDebug) {
493    XSDebug(io.inFire(3), "bpuMeta sent!\n")
494    for (i <- 0 until PredictWidth) {
495      val b = io.brInfo.metas(i)
496      XSDebug(io.inFire(3), "brInfo(%d): btbWrWay:%d, bimCtr:%d\n",
497        i.U, b.btbWriteWay, b.bimCtr)
498      val t = b.tageMeta
499      XSDebug(io.inFire(3), "  tageMeta: pvder(%d):%d, altDiffers:%d, pvderU:%d, pvderCtr:%d, allocate(%d):%d\n",
500        t.provider.valid, t.provider.bits, t.altDiffers, t.providerU, t.providerCtr, t.allocate.valid, t.allocate.bits)
501    }
502  }
503  val debug_verbose = false
504}
505
506
507class FakeBPU(implicit p: Parameters) extends BaseBPU {
508  io.out.foreach(i => {
509    // Provide not takens
510    i <> DontCare
511    i.takens := 0.U
512  })
513  io.brInfo <> DontCare
514}
515@chiselName
516class BPU(implicit p: Parameters) extends BaseBPU {
517
518  //**********************Stage 1****************************//
519
520  val s1_resp_in = Wire(new PredictorResponse)
521  val s1_brInfo_in = Wire(new BrInfo)
522
523  s1_resp_in.tage := DontCare
524  s1_resp_in.loop := DontCare
525  s1_brInfo_in    := DontCare
526
527  val s1_inLatch = RegEnable(io.in, s1_fire)
528  ubtb.io.pc.valid := s2_fire
529  ubtb.io.pc.bits := s1_inLatch.pc
530  ubtb.io.inMask := s1_inLatch.inMask
531
532
533
534  // Wrap ubtb response into resp_in and brInfo_in
535  s1_resp_in.ubtb <> ubtb.io.out
536  for (i <- 0 until PredictWidth) {
537    s1_brInfo_in.metas(i).ubtbHit := ubtb.io.out.hits(i)
538  }
539
540  btb.io.pc.valid := s1_fire
541  btb.io.pc.bits := io.in.pc
542  btb.io.inMask := io.in.inMask
543
544
545
546  // Wrap btb response into resp_in and brInfo_in
547  s1_resp_in.btb <> btb.io.resp
548  for (i <- 0 until PredictWidth) {
549    s1_brInfo_in.metas(i).btbWriteWay := btb.io.meta.writeWay(i)
550    s1_brInfo_in.metas(i).btbHit := btb.io.meta.hits(i)
551  }
552
553  bim.io.pc.valid := s1_fire
554  bim.io.pc.bits := io.in.pc
555  bim.io.inMask := io.in.inMask
556
557
558  // Wrap bim response into resp_in and brInfo_in
559  s1_resp_in.bim <> bim.io.resp
560  for (i <- 0 until PredictWidth) {
561    s1_brInfo_in.metas(i).bimCtr := bim.io.meta.ctrs(i)
562  }
563
564
565  s1.io.inFire := s1_fire
566  s1.io.in.pc := io.in.pc
567  s1.io.in.mask := io.in.inMask
568  s1.io.in.resp <> s1_resp_in
569  s1.io.in.brInfo <> s1_brInfo_in
570
571  val s1_hist = RegEnable(io.in.hist, enable=s1_fire)
572  val s2_hist = RegEnable(s1_hist, enable=s2_fire)
573  val s3_hist = RegEnable(s2_hist, enable=s3_fire)
574
575  s1.io.debug_hist := s1_hist
576  s2.io.debug_hist := s2_hist
577  s3.io.debug_hist := s3_hist
578
579  //**********************Stage 2****************************//
580  tage.io.pc.valid := s2_fire
581  tage.io.pc.bits := s2.io.in.pc // PC from s1
582  tage.io.hist := s1_hist // The inst is from s1
583  tage.io.inMask := s2.io.in.mask
584  tage.io.bim <> s1.io.out.resp.bim // Use bim results from s1
585
586  //**********************Stage 3****************************//
587  // Wrap tage response and meta into s3.io.in.bits
588  // This is ugly
589
590  loop.io.pc.valid := s2_fire
591  loop.io.if3_fire := s3_fire
592  loop.io.pc.bits := s2.io.in.pc
593  loop.io.inMask := io.predecode.mask
594  loop.io.respIn.taken := s3.io.pred.taken
595  loop.io.respIn.jmpIdx := s3.io.pred.jmpIdx
596  loop.io.redirect := s3.s3IO.redirect
597
598
599  s3.io.in.resp.tage <> tage.io.resp
600  s3.io.in.resp.loop <> loop.io.resp
601  for (i <- 0 until PredictWidth) {
602    s3.io.in.brInfo.metas(i).tageMeta := tage.io.meta(i)
603    s3.io.in.brInfo.specCnt(i) := loop.io.meta.specCnts(i)
604  }
605
606  s3.s3IO.predecode <> io.predecode
607  s3.s3IO.redirect <> io.redirect
608  s3.s3IO.ctrl <> io.ctrl
609
610
611  if (BPUDebug) {
612    if (debug_verbose) {
613      val uo = ubtb.io.out
614      XSDebug("debug: ubtb hits:%b, takens:%b, notTakens:%b\n", uo.hits.asUInt, uo.takens.asUInt, ~uo.takens.asUInt & uo.brMask.asUInt)
615      val bio = bim.io.resp
616      XSDebug("debug: bim takens:%b\n", VecInit(bio.ctrs.map(_(1))).asUInt)
617      val bo = btb.io.resp
618      XSDebug("debug: btb hits:%b\n", bo.hits.asUInt)
619    }
620  }
621
622
623
624  if (EnableCFICommitLog) {
625    val buValid = io.commit.valid
626    val buinfo  = io.commit.bits
627    for (i <- 0 until PredictWidth) {
628      val cfi_idx = buinfo.cfiIndex
629      val isTaken = cfi_idx.valid && cfi_idx.bits === i.U
630      val isCfi = buinfo.valids(i) && (buinfo.br_mask(i) || cfi_idx.valid && cfi_idx.bits === i.U)
631      val isBr = buinfo.br_mask(i)
632      val pc = packetAligned(buinfo.ftqPC) + (i * instBytes).U - Mux((i==0).B && buinfo.hasLastPrev, 2.U, 0.U)
633      val tage_cycle = buinfo.metas(i).debug_tage_cycle
634      XSDebug(buValid && isCfi, p"cfi_update: isBr(${isBr}) pc(${Hexadecimal(pc)}) taken(${isTaken}) mispred(${buinfo.mispred(i)}) cycle($tage_cycle) hist(${Hexadecimal(buinfo.predHist.asUInt)})\n")
635    }
636  }
637
638}
639
640object BPU{
641  def apply(enableBPU: Boolean = true)(implicit p: Parameters) = {
642      if(enableBPU) {
643        val BPU = Module(new BPU)
644        BPU
645      }
646      else {
647        val FakeBPU = Module(new FakeBPU)
648        FakeBPU
649      }
650  }
651}
652