xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision 35fe60e833e30b4d56e85068ab0c6b6a66a73d68)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import utils._
6import xiangshan._
7import xiangshan.backend.ALUOpType
8import xiangshan.backend.JumpOpType
9
10class TableAddr(val idxBits: Int, val banks: Int) extends XSBundle {
11  def tagBits = VAddrBits - idxBits - 1
12
13  val tag = UInt(tagBits.W)
14  val idx = UInt(idxBits.W)
15  val offset = UInt(1.W)
16
17  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
18  def getTag(x: UInt) = fromUInt(x).tag
19  def getIdx(x: UInt) = fromUInt(x).idx
20  def getBank(x: UInt) = getIdx(x)(log2Up(banks) - 1, 0)
21  def getBankIdx(x: UInt) = getIdx(x)(idxBits - 1, log2Up(banks))
22}
23
24class PredictorResponse extends XSBundle {
25  class UbtbResp extends XSBundle {
26  // the valid bits indicates whether a target is hit
27    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
28    val hits = Vec(PredictWidth, Bool())
29    val takens = Vec(PredictWidth, Bool())
30    val notTakens = Vec(PredictWidth, Bool())
31    val is_RVC = Vec(PredictWidth, Bool())
32  }
33  class BtbResp 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 types = Vec(PredictWidth, UInt(2.W))
38    val isRVC = Vec(PredictWidth, Bool())
39  }
40  class BimResp extends XSBundle {
41    val ctrs = Vec(PredictWidth, UInt(2.W))
42  }
43  class TageResp extends XSBundle {
44  // the valid bits indicates whether a prediction is hit
45    val takens = Vec(PredictWidth, Bool())
46    val hits = Vec(PredictWidth, Bool())
47  }
48
49  val ubtb = new UbtbResp
50  val btb = new BtbResp
51  val bim = new BimResp
52  val tage = new TageResp
53}
54
55abstract class BasePredictor extends XSModule {
56  val metaLen = 0
57
58  // An implementation MUST extend the IO bundle with a response
59  // and the special input from other predictors, as well as
60  // the metas to store in BRQ
61  abstract class Resp extends XSBundle {}
62  abstract class FromOthers extends XSBundle {}
63  abstract class Meta extends XSBundle {}
64
65  class DefaultBasePredictorIO extends XSBundle {
66    val flush = Input(Bool())
67    val pc = Flipped(ValidIO(UInt(VAddrBits.W)))
68    val hist = Input(UInt(HistoryLength.W))
69    val inMask = Input(UInt(PredictWidth.W))
70    val update = Flipped(ValidIO(new BranchUpdateInfoWithHist))
71  }
72
73  val io = new DefaultBasePredictorIO
74
75  // circular shifting
76  def circularShiftLeft(source: UInt, len: Int, shamt: UInt): UInt = {
77    val res = Wire(UInt(len.W))
78    val higher = source << shamt
79    val lower = source >> (len.U - shamt)
80    res := higher | lower
81    res
82  }
83
84  def circularShiftRight(source: UInt, len: Int, shamt: UInt): UInt = {
85    val res = Wire(UInt(len.W))
86    val higher = source << (len.U - shamt)
87    val lower = source >> shamt
88    res := higher | lower
89    res
90  }
91}
92
93class BPUStageIO extends XSBundle {
94  val pc = UInt(VAddrBits.W)
95  val mask = UInt(PredictWidth.W)
96  val resp = new PredictorResponse
97  val target = UInt(VAddrBits.W)
98  val brInfo = Vec(PredictWidth, new BranchInfo)
99}
100
101
102class BPUStage extends XSModule {
103  class DefaultIO extends XSBundle {
104    val flush = Input(Bool())
105    val in = Flipped(Decoupled(new BPUStageIO))
106    val pred = Decoupled(new BranchPrediction)
107    val out = Decoupled(new BPUStageIO)
108    val predecode = Flipped(ValidIO(new Predecode))
109  }
110  val io = IO(new DefaultIO)
111
112  val predValid = RegInit(false.B)
113
114  io.in.ready := !predValid || io.out.fire() && io.pred.fire()
115
116  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
117
118  val inFire = io.in.fire()
119  val inLatch = RegEnable(io.in.bits, inFire)
120
121  val outFire = io.out.fire()
122
123  // Each stage has its own logic to decide
124  // takens, notTakens and target
125
126  val takens = VecInit((0 until PredictWidth).map(_ => false.B))
127  val notTakens = VecInit((0 until PredictWidth).map(_ => false.B))
128  val jmpIdx = PriorityEncoder(takens)
129  val hasNTBr = (0 until PredictWidth).map(i => i.U <= jmpIdx && notTakens(i)).reduce(_||_)
130  val taken = takens.reduce(_||_)
131  // get the last valid inst
132  val lastValidPos = MuxCase(0.U, (PredictWidth-1 to 0).map(i => (inLatch.mask(i), i.U)))
133  val target = WireInit(0.U(VAddrBits.W))
134
135  io.pred.bits <> DontCare
136  io.pred.bits.taken := taken
137  io.pred.bits.jmpIdx := jmpIdx
138  io.pred.bits.hasNotTakenBrs := hasNTBr
139  io.pred.bits.target := target
140
141  io.out.bits <> DontCare
142  io.out.bits.pc := inLatch.pc
143  io.out.bits.mask := inLatch.mask
144  io.out.bits.target := target
145  io.out.bits.resp <> inLatch.resp
146  io.out.bits.brInfo := inLatch.brInfo
147
148  // Default logic
149  //  pred.ready not taken into consideration
150  //  could be broken
151  when (io.flush)     { predValid := false.B }
152  .elsewhen (inFire)  { predValid := true.B }
153  .elsewhen (outFire) { predValid := false.B }
154  .otherwise          { predValid := predValid }
155
156  io.out.valid := predValid && !io.flush
157  io.pred.valid := predValid && !io.flush
158}
159
160class BPUStage1 extends BPUStage {
161
162  // 'overrides' default logic
163  // when flush, the prediction should also starts
164  when (io.flush || inFire) { predValid := true.B }
165  .elsewhen(outFire)        { predValid := false.B }
166  .otherwise                { predValid := predValid }
167  io.in.ready := !predValid || io.out.fire() && io.pred.fire()
168  io.out.valid := predValid
169
170  // ubtb is accessed with inLatch pc in s1,
171  // so we use io.in instead of inLatch
172  val ubtbResp = io.in.bits.resp.ubtb
173  // the read operation is already masked, so we do not need to mask here
174  takens    := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.takens(i)))
175  notTakens := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.notTakens(i)))
176  target    := Mux(taken, ubtbResp.targets(jmpIdx), npc(inLatch.pc, PopCount(inLatch.mask)))
177
178  io.pred.bits.redirect := taken
179  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken) || !taken ) && !ubtbResp.is_RVC(lastValidPos)
180
181  // resp and brInfo are from the components,
182  // so it does not need to be latched
183  io.out.bits.resp <> io.in.bits.resp
184  io.out.bits.brInfo := io.in.bits.brInfo
185}
186
187class BPUStage2 extends BPUStage {
188
189  // Use latched response from s1
190  val btbResp = inLatch.resp.btb
191  val bimResp = inLatch.resp.bim
192  takens    := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && bimResp.ctrs(i)(1)))
193  notTakens := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && btbResp.types(i) === BrType.branch && !bimResp.ctrs(i)(1)))
194  target    := Mux(taken, btbResp.targets(jmpIdx), npc(inLatch.pc, PopCount(inLatch.mask)))
195
196  io.pred.bits.redirect := target =/= inLatch.target
197  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken) || !taken ) && !btbResp.isRVC(lastValidPos)
198}
199
200class BPUStage3 extends BPUStage {
201
202  io.out.valid := predValid && io.predecode.valid && !io.flush
203
204  // TAGE has its own pipelines and the
205  // response comes directly from s3,
206  // so we do not use those from inLatch
207  val tageResp = io.in.bits.resp.tage
208  val tageValidTakens = VecInit((0 until PredictWidth).map( i => tageResp.takens(i) && tageResp.hits(i)))
209
210  val pdMask = io.predecode.bits.mask
211  val pds    = io.predecode.bits.pd
212
213  val btbHits   = inLatch.resp.btb.hits.asUInt
214  val bimTakens = VecInit(inLatch.resp.bim.ctrs.map(_(1)))
215
216  val brs   = pdMask & Reverse(Cat(pds.map(_.isBr)))
217  val jals  = pdMask & Reverse(Cat(pds.map(_.isJal)))
218  val jalrs = pdMask & Reverse(Cat(pds.map(_.isJalr)))
219  val calls = pdMask & Reverse(Cat(pds.map(_.isCall)))
220  val rets  = pdMask & Reverse(Cat(pds.map(_.isRet)))
221
222  val callIdx = PriorityEncoder(calls)
223  val retIdx  = PriorityEncoder(rets)
224
225  val brTakens =
226    if (EnableBPD) {
227      brs & Reverse(Cat((0 until PredictWidth).map(i => btbHits(i) && tageValidTakens(i))))
228    } else {
229      brs & Reverse(Cat((0 until PredictWidth).map(i => btbHits(i) && bimTakens(i))))
230    }
231
232  takens := VecInit((0 until PredictWidth).map(i => brTakens(i) || jals(i) || jalrs(i)))
233  // Whether should we count in branches that are not recorded in btb?
234  // PS: Currently counted in. Whenever tage does not provide a valid
235  //     taken prediction, the branch is counted as a not taken branch
236  notTakens := VecInit((0 until PredictWidth).map(i => brs(i) && !tageValidTakens(i)))
237  target := Mux(taken, inLatch.resp.btb.targets(jmpIdx), npc(inLatch.pc, PopCount(inLatch.mask)))
238
239  io.pred.bits.redirect := target =/= inLatch.target
240  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken) || !taken ) && !pds(lastValidPos).isRVC
241
242  // Wrap tage resp and tage meta in
243  // This is ugly
244  io.out.bits.resp.tage <> io.in.bits.resp.tage
245  for (i <- 0 until PredictWidth) {
246    io.out.bits.brInfo(i).tageMeta := io.in.bits.brInfo(i).tageMeta
247  }
248}
249
250trait BranchPredictorComponents extends HasXSParameter {
251  val ubtb = Module(new MicroBTB)
252  val btb = Module(new BTB)
253  val bim = Module(new BIM)
254  val tage = Module(new Tage)
255  val preds = Seq(ubtb, btb, bim, tage)
256  preds.map(_.io := DontCare)
257}
258
259class BPUReq extends XSBundle {
260  val pc = UInt(VAddrBits.W)
261  val hist = UInt(HistoryLength.W)
262  val inMask = UInt(PredictWidth.W)
263}
264
265class BranchUpdateInfoWithHist extends BranchUpdateInfo {
266  val hist = UInt(HistoryLength.W)
267}
268
269abstract class BaseBPU extends XSModule with BranchPredictorComponents{
270  val io = IO(new Bundle() {
271    // from backend
272    val inOrderBrInfo = Flipped(ValidIO(new BranchUpdateInfoWithHist))
273    // from ifu, frontend redirect
274    val flush = Input(UInt(3.W))
275    // from if1
276    val in = Flipped(ValidIO(new BPUReq))
277    // to if2/if3/if4
278    val out = Vec(3, Decoupled(new BranchPrediction))
279    // from if4
280    val predecode = Flipped(ValidIO(new Predecode))
281    // to if4, some bpu info used for updating
282    val branchInfo = Decoupled(Vec(PredictWidth, new BranchInfo))
283  })
284
285  preds.map(_.io.update <> io.inOrderBrInfo)
286
287  val s1 = Module(new BPUStage1)
288  val s2 = Module(new BPUStage2)
289  val s3 = Module(new BPUStage3)
290
291  s1.io.flush := io.flush(0)
292  s2.io.flush := io.flush(1)
293  s3.io.flush := io.flush(2)
294
295  s1.io.in <> DontCare
296  s2.io.in <> s1.io.out
297  s3.io.in <> s2.io.out
298
299  io.out(0) <> s1.io.pred
300  io.out(1) <> s2.io.pred
301  io.out(2) <> s3.io.pred
302
303  s1.io.predecode <> DontCare
304  s2.io.predecode <> DontCare
305  s3.io.predecode <> io.predecode
306
307  io.branchInfo.valid := s3.io.out.valid
308  io.branchInfo.bits := s3.io.out.bits.brInfo
309  s3.io.out.ready := io.branchInfo.ready
310}
311
312
313class FakeBPU extends BaseBPU {
314  io.out.foreach(i => {
315    // Provide not takens
316    i.valid := true.B
317    i.bits <> DontCare
318    i.bits.redirect := false.B
319  })
320  io.branchInfo <> DontCare
321}
322
323class BPU extends BaseBPU {
324
325  //**********************Stage 1****************************//
326  val s1_fire = s1.io.in.fire()
327  val s1_resp_in = Wire(new PredictorResponse)
328  val s1_brInfo_in = Wire(Vec(PredictWidth, new BranchInfo))
329
330  s1_resp_in := DontCare
331  s1_brInfo_in := DontCare
332
333  val s1_inLatch = RegEnable(io.in, s1_fire)
334  ubtb.io.flush := io.flush(0) // TODO: fix this
335  ubtb.io.pc.valid := s1_inLatch.valid
336  ubtb.io.pc.bits := s1_inLatch.bits.pc
337  ubtb.io.inMask := s1_inLatch.bits.inMask
338
339  // Wrap ubtb response into resp_in and brInfo_in
340  s1_resp_in.ubtb <> ubtb.io.out
341  for (i <- 0 until PredictWidth) {
342    s1_brInfo_in(i).ubtbWriteWay := ubtb.io.uBTBBranchInfo.writeWay(i)
343    s1_brInfo_in(i).ubtbHits := ubtb.io.uBTBBranchInfo.hits(i)
344  }
345
346  btb.io.flush := io.flush(0) // TODO: fix this
347  btb.io.pc.valid := io.in.valid
348  btb.io.pc.bits := io.in.bits.pc
349  btb.io.inMask := io.in.bits.inMask
350
351  // Wrap btb response into resp_in and brInfo_in
352  s1_resp_in.btb <> btb.io.resp
353  for (i <- 0 until PredictWidth) {
354    s1_brInfo_in(i).btbWriteWay := btb.io.meta.writeWay(i)
355  }
356
357  bim.io.flush := io.flush(0) // TODO: fix this
358  bim.io.pc.valid := io.in.valid
359  bim.io.pc.bits := io.in.bits.pc
360  bim.io.inMask := io.in.bits.inMask
361
362  // Wrap bim response into resp_in and brInfo_in
363  s1_resp_in.bim <> bim.io.resp
364  for (i <- 0 until PredictWidth) {
365    s1_brInfo_in(i).bimCtr := bim.io.meta.ctrs(i)
366  }
367
368
369  s1.io.in.valid := io.in.valid
370  s1.io.in.bits.pc := io.in.bits.pc
371  s1.io.in.bits.mask := io.in.bits.inMask
372  s1.io.in.bits.target := DontCare
373  s1.io.in.bits.resp := s1_resp_in
374  s1.io.in.bits.brInfo <> s1_brInfo_in
375
376  //**********************Stage 2****************************//
377  tage.io.flush := io.flush(1) // TODO: fix this
378  tage.io.pc.valid := s1.io.out.fire()
379  tage.io.pc.bits := s1.io.out.bits.pc // PC from s1
380  tage.io.hist := io.in.bits.hist // The inst is from s1
381  tage.io.inMask := s1.io.out.bits.mask
382  tage.io.s3Fire := s3.io.in.fire() // Tell tage to march 1 stage
383  tage.io.bim <> s1.io.out.bits.resp.bim // Use bim results from s1
384
385  //**********************Stage 3****************************//
386  // Wrap tage response and meta into s3.io.in.bits
387  // This is ugly
388
389  s3.io.in.bits.resp.tage <> tage.io.resp
390  for (i <- 0 until PredictWidth) {
391    s3.io.in.bits.brInfo(i).tageMeta := tage.io.meta(i)
392  }
393
394}
395