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