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