xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision 61118286fd1c8344bf610cad54c0072c445559e4)
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 Stage1To2IO extends XSBundle {
25  val pc = Output(UInt(VAddrBits.W))
26  val btb = new Bundle {
27    val hits = Output(UInt(PredictWidth.W))
28    val targets = Output(Vec(PredictWidth, UInt(VAddrBits.W)))
29  }
30  val jbtac = new Bundle {
31    val hitIdx = Output(UInt(PredictWidth.W))
32    val target = Output(UInt(VAddrBits.W))
33  }
34  val tage = new Bundle {
35    val hits = Output(UInt(FetchWidth.W))
36    val takens = Output(Vec(FetchWidth, Bool()))
37  }
38  val hist = Output(Vec(PredictWidth, UInt(HistoryLength.W)))
39  val btbPred = ValidIO(new BranchPrediction)
40}
41
42class BPUStage1 extends XSModule {
43  val io = IO(new Bundle() {
44    val in = new Bundle { val pc = Flipped(Decoupled(UInt(VAddrBits.W))) }
45    // from backend
46    val redirectInfo = Input(new RedirectInfo)
47    // from Stage3
48    val flush = Input(Bool())
49    val s3RollBackHist = Input(UInt(HistoryLength.W))
50    val s3Taken = Input(Bool())
51    // to ifu, quick prediction result
52    val s1OutPred = ValidIO(new BranchPrediction)
53    // to Stage2
54    val out = Decoupled(new Stage1To2IO)
55  })
56
57  io.in.pc.ready := true.B
58
59  // flush Stage1 when io.flush
60  val flushS1 = BoolStopWatch(io.flush, io.in.pc.fire(), startHighPriority = true)
61  val s1OutPredLatch = RegEnable(io.s1OutPred.bits, RegNext(io.in.pc.fire()))
62  val outLatch = RegEnable(io.out.bits, RegNext(io.in.pc.fire()))
63
64  val s1Valid = RegInit(false.B)
65  when (io.flush || io.in.pc.fire()) {
66    s1Valid := true.B
67  }.elsewhen (io.out.fire()) {
68    s1Valid := false.B
69  }
70  io.out.valid := s1Valid
71
72
73  // global history register
74  val ghr = RegInit(0.U(HistoryLength.W))
75  // modify updateGhr and newGhr when updating ghr
76  val updateGhr = WireInit(false.B)
77  val newGhr = WireInit(0.U(HistoryLength.W))
78  when (updateGhr) { ghr := newGhr }
79  // use hist as global history!!!
80  val hist = Mux(updateGhr, newGhr, ghr)
81
82  // Tage predictor
83  val tage = if(EnableBPD) Module(new Tage) else Module(new FakeTAGE)
84  tage.io.req.valid := io.in.pc.fire()
85  tage.io.req.bits.pc := io.in.pc.bits
86  tage.io.req.bits.hist := hist
87  tage.io.redirectInfo <> io.redirectInfo
88  // io.s1OutPred.bits.tageMeta := tage.io.meta
89
90  // latch pc for 1 cycle latency when reading SRAM
91  val pcLatch = RegEnable(io.in.pc.bits, io.in.pc.fire())
92  // TODO: pass real mask in
93  // val maskLatch = RegEnable(btb.io.in.mask, io.in.pc.fire())
94  val maskLatch = Fill(PredictWidth, 1.U(1.W))
95
96  val r = io.redirectInfo.redirect
97  val updateFetchpc = r.pc - (r.fetchIdx << 1.U)
98  // BTB
99  val btb = Module(new BTB)
100  btb.io.in.pc <> io.in.pc
101  btb.io.in.pcLatch := pcLatch
102  // TODO: pass real mask in
103  btb.io.in.mask := Fill(PredictWidth, 1.U(1.W))
104  btb.io.redirectValid := io.redirectInfo.valid
105  btb.io.flush := io.flush
106
107  // btb.io.update.fetchPC := updateFetchpc
108  // btb.io.update.fetchIdx := r.fetchIdx
109  btb.io.update.pc := r.pc
110  btb.io.update.hit := r.btbHit
111  btb.io.update.misPred := io.redirectInfo.misPred
112  // btb.io.update.writeWay := r.btbVictimWay
113  btb.io.update.oldCtr := r.btbPredCtr
114  btb.io.update.taken := r.taken
115  btb.io.update.target := r.brTarget
116  btb.io.update.btbType := r.btbType
117  // TODO: add RVC logic
118  btb.io.update.isRVC := r.isRVC
119
120  // val btbHit = btb.io.out.hit
121  val btbTaken = btb.io.out.taken
122  val btbTakenIdx = btb.io.out.takenIdx
123  val btbTakenTarget = btb.io.out.target
124  // val btbWriteWay = btb.io.out.writeWay
125  val btbNotTakens = btb.io.out.notTakens
126  val btbCtrs = VecInit(btb.io.out.dEntries.map(_.pred))
127  val btbValids = btb.io.out.hits
128  val btbTargets = VecInit(btb.io.out.dEntries.map(_.target))
129  val btbTypes = VecInit(btb.io.out.dEntries.map(_.btbType))
130  val btbIsRVCs = VecInit(btb.io.out.dEntries.map(_.isRVC))
131
132
133  val jbtac = Module(new JBTAC)
134  jbtac.io.in.pc <> io.in.pc
135  jbtac.io.in.pcLatch := pcLatch
136  // TODO: pass real mask in
137  jbtac.io.in.mask := Fill(PredictWidth, 1.U(1.W))
138  jbtac.io.in.hist := hist
139  jbtac.io.redirectValid := io.redirectInfo.valid
140  jbtac.io.flush := io.flush
141
142  jbtac.io.update.fetchPC := updateFetchpc
143  jbtac.io.update.fetchIdx := r.fetchIdx
144  jbtac.io.update.misPred := io.redirectInfo.misPred
145  jbtac.io.update.btbType := r.btbType
146  jbtac.io.update.target := r.target
147  jbtac.io.update.hist := r.hist
148  jbtac.io.update.isRVC := r.isRVC
149
150  val jbtacHit = jbtac.io.out.hit
151  val jbtacTarget = jbtac.io.out.target
152  val jbtacHitIdx = jbtac.io.out.hitIdx
153  val jbtacIsRVC = jbtac.io.out.isRVC
154
155  // calculate global history of each instr
156  val firstHist = RegNext(hist)
157  val histShift = Wire(Vec(PredictWidth, UInt(log2Up(PredictWidth).W)))
158  val shift = Wire(Vec(PredictWidth, Vec(PredictWidth, UInt(1.W))))
159  (0 until PredictWidth).foreach(i => shift(i) := Mux(!btbNotTakens(i), 0.U, ~LowerMask(UIntToOH(i.U), PredictWidth)).asTypeOf(Vec(PredictWidth, UInt(1.W))))
160  for (j <- 0 until PredictWidth) {
161    var tmp = 0.U
162    for (i <- 0 until PredictWidth) {
163      tmp = tmp + shift(i)(j)
164    }
165    histShift(j) := tmp
166  }
167
168  // update ghr
169  updateGhr := io.s1OutPred.bits.redirect ||
170               RegNext(io.in.pc.fire) && ~io.s1OutPred.bits.redirect && (btbNotTakens.asUInt & maskLatch).orR || // TODO: use parallel or
171               io.flush
172  val brJumpIdx = Mux(!btbTaken, 0.U, UIntToOH(btbTakenIdx))
173  val indirectIdx = Mux(!jbtacHit, 0.U, UIntToOH(jbtacHitIdx))
174  // if backend redirects, restore history from backend;
175  // if stage3 redirects, restore history from stage3;
176  // if stage1 redirects, speculatively update history;
177  // if none of above happens, check if stage1 has not-taken branches and shift zeroes accordingly
178  newGhr := Mux(io.redirectInfo.flush(),    (r.hist << 1.U) | !(r.btbType === BTBtype.B && !r.taken),
179            Mux(io.flush,                   Mux(io.s3Taken, (io.s3RollBackHist << 1.U) | 1.U, io.s3RollBackHist),
180            Mux(io.s1OutPred.bits.redirect, (PriorityMux(brJumpIdx | indirectIdx, io.s1OutPred.bits.hist) << 1.U | 1.U),
181                                            io.s1OutPred.bits.hist(0) << PopCount(btbNotTakens.asUInt & maskLatch))))
182
183  def getInstrValid(i: Int): UInt = {
184    val vec = Wire(Vec(PredictWidth, UInt(1.W)))
185    for (j <- 0 until PredictWidth) {
186      if (j <= i)
187        vec(j) := 1.U
188      else
189        vec(j) := 0.U
190    }
191    vec.asUInt
192  }
193
194  // redirect based on BTB and JBTAC
195  val takenIdx = LowestBit(brJumpIdx | indirectIdx, PredictWidth)
196
197  // io.out.valid := RegNext(io.in.pc.fire()) && !io.flush
198
199  // io.s1OutPred.valid := io.out.valid
200  io.s1OutPred.valid := io.out.fire()
201  when (RegNext(io.in.pc.fire())) {
202    io.s1OutPred.bits.redirect := btbTaken || jbtacHit
203    // io.s1OutPred.bits.instrValid := (maskLatch & Fill(PredictWidth, ~io.s1OutPred.bits.redirect || io.s1OutPred.bits.lateJump) |
204    //   PriorityMux(brJumpIdx | indirectIdx, (0 until PredictWidth).map(getInstrValid(_)))).asTypeOf(Vec(PredictWidth, Bool()))
205    io.s1OutPred.bits.instrValid := (maskLatch & Fill(PredictWidth, ~io.s1OutPred.bits.redirect) |
206      PriorityMux(brJumpIdx | indirectIdx, (0 until PredictWidth).map(getInstrValid(_)))).asTypeOf(Vec(PredictWidth, Bool()))
207    for (i <- 0 until (PredictWidth - 1)) {
208      when (!io.s1OutPred.bits.lateJump && (1.U << i) === takenIdx && (!btbIsRVCs(i) && btbValids(i) || !jbtacIsRVC && (1.U << i) === indirectIdx)) {
209        io.s1OutPred.bits.instrValid(i+1) := maskLatch(i+1)
210      }
211    }
212    io.s1OutPred.bits.target := Mux(takenIdx === 0.U, pcLatch + (PopCount(maskLatch) << 1.U), Mux(takenIdx === brJumpIdx, btbTakenTarget, jbtacTarget))
213    io.s1OutPred.bits.lateJump := btb.io.out.isRVILateJump || jbtac.io.out.isRVILateJump
214    (0 until PredictWidth).map(i => io.s1OutPred.bits.hist(i) := firstHist << histShift(i))
215    // io.s1OutPred.bits.btbVictimWay := btbWriteWay
216    io.s1OutPred.bits.predCtr := btbCtrs
217    io.s1OutPred.bits.btbHit := btbValids
218    io.s1OutPred.bits.tageMeta := DontCare // TODO: enableBPD
219    io.s1OutPred.bits.rasSp := DontCare
220    io.s1OutPred.bits.rasTopCtr := DontCare
221  }.otherwise {
222    io.s1OutPred.bits := s1OutPredLatch
223  }
224
225  when (RegNext(io.in.pc.fire())) {
226    io.out.bits.pc := pcLatch
227    io.out.bits.btb.hits := btbValids.asUInt
228    (0 until PredictWidth).map(i => io.out.bits.btb.targets(i) := btbTargets(i))
229    io.out.bits.jbtac.hitIdx := Mux(jbtacHit, UIntToOH(jbtacHitIdx), 0.U) // UIntToOH(jbtacHitIdx)
230    io.out.bits.jbtac.target := jbtacTarget
231    io.out.bits.tage <> tage.io.out
232    // TODO: we don't need this repeatedly!
233    io.out.bits.hist := io.s1OutPred.bits.hist
234    io.out.bits.btbPred := io.s1OutPred
235  }.otherwise {
236    io.out.bits := outLatch
237  }
238
239
240  // debug info
241  XSDebug("in:(%d %d)   pc=%x ghr=%b\n", io.in.pc.valid, io.in.pc.ready, io.in.pc.bits, hist)
242  XSDebug("outPred:(%d) pc=0x%x, redirect=%d instrValid=%b tgt=%x\n",
243    io.s1OutPred.valid, pcLatch, io.s1OutPred.bits.redirect, io.s1OutPred.bits.instrValid.asUInt, io.s1OutPred.bits.target)
244  XSDebug(io.flush && io.redirectInfo.flush(),
245    "flush from backend: pc=%x tgt=%x brTgt=%x btbType=%b taken=%d oldHist=%b fetchIdx=%d isExcpt=%d\n",
246    r.pc, r.target, r.brTarget, r.btbType, r.taken, r.hist, r.fetchIdx, r.isException)
247  XSDebug(io.flush && !io.redirectInfo.flush(),
248    "flush from Stage3:  s3Taken=%d s3RollBackHist=%b\n", io.s3Taken, io.s3RollBackHist)
249
250}
251
252class Stage2To3IO extends Stage1To2IO {
253}
254
255class BPUStage2 extends XSModule {
256  val io = IO(new Bundle() {
257    // flush from Stage3
258    val flush = Input(Bool())
259    val in = Flipped(Decoupled(new Stage1To2IO))
260    val out = Decoupled(new Stage2To3IO)
261  })
262
263  // flush Stage2 when Stage3 or banckend redirects
264  val flushS2 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
265  val inLatch = RegInit(0.U.asTypeOf(io.in.bits))
266  when (io.in.fire()) { inLatch := io.in.bits }
267  val validLatch = RegInit(false.B)
268  when (io.flush) {
269    validLatch := false.B
270  }.elsewhen (io.in.fire()) {
271    validLatch := true.B
272  }.elsewhen (io.out.fire()) {
273    validLatch := false.B
274  }
275
276  io.out.valid := !io.flush && !flushS2 && validLatch
277  io.in.ready := !validLatch || io.out.fire()
278
279  // do nothing
280  io.out.bits := inLatch
281
282  // debug info
283  XSDebug("in:(%d %d) pc=%x out:(%d %d) pc=%x\n",
284    io.in.valid, io.in.ready, io.in.bits.pc, io.out.valid, io.out.ready, io.out.bits.pc)
285  XSDebug("validLatch=%d pc=%x\n", validLatch, inLatch.pc)
286  XSDebug(io.flush, "flush!!!\n")
287}
288
289class BPUStage3 extends XSModule {
290  val io = IO(new Bundle() {
291    val flush = Input(Bool())
292    val in = Flipped(Decoupled(new Stage2To3IO))
293    val out = Decoupled(new BranchPrediction)
294    // from icache
295    val predecode = Flipped(ValidIO(new Predecode))
296    // from backend
297    val redirectInfo = Input(new RedirectInfo)
298    // to Stage1 and Stage2
299    val flushBPU = Output(Bool())
300    // to Stage1, restore ghr in stage1 when flushBPU is valid
301    val s1RollBackHist = Output(UInt(HistoryLength.W))
302    val s3Taken = Output(Bool())
303  })
304
305  val flushS3 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
306  val inLatch = RegInit(0.U.asTypeOf(io.in.bits))
307  val validLatch = RegInit(false.B)
308  val predecodeLatch = RegInit(0.U.asTypeOf(io.predecode.bits))
309  val predecodeValidLatch = RegInit(false.B)
310  when (io.in.fire()) { inLatch := io.in.bits }
311  when (io.flush) {
312    validLatch := false.B
313  }.elsewhen (io.in.fire()) {
314    validLatch := true.B
315  }.elsewhen (io.out.fire()) {
316    validLatch := false.B
317  }
318
319  when (io.predecode.valid) { predecodeLatch := io.predecode.bits }
320  when (io.flush || io.out.fire()) {
321    predecodeValidLatch := false.B
322  }.elsewhen (io.predecode.valid) {
323    predecodeValidLatch := true.B
324  }
325
326  val predecodeValid = io.predecode.valid || predecodeValidLatch
327  val predecode = Mux(io.predecode.valid, io.predecode.bits, predecodeLatch)
328  io.out.valid := validLatch && predecodeValid && !flushS3 && !io.flush
329  io.in.ready := !validLatch || io.out.fire()
330
331  // RAS
332  // TODO: split retAddr and ctr
333  def rasEntry() = new Bundle {
334    val retAddr = UInt(VAddrBits.W)
335    val ctr = UInt(8.W) // layer of nested call functions
336  }
337  val ras = RegInit(VecInit(Seq.fill(RasSize)(0.U.asTypeOf(rasEntry()))))
338  val sp = Counter(RasSize)
339  val rasTop = ras(sp.value)
340  val rasTopAddr = rasTop.retAddr
341
342  // get the first taken branch/jal/call/jalr/ret in a fetch line
343  // brNotTakenIdx indicates all the not-taken branches before the first jump instruction
344
345
346  val brs = inLatch.btb.hits & Reverse(Cat(predecode.pd.map { p => p.brType === BrType.branch }).asUInt) & predecode.mask
347  // val brTakens = brs & inLatch.tage.takens.asUInt
348  val brTakens = if (EnableBPD) {
349    brs & Reverse(Cat(inLatch.tage.takens.map {t => Fill(2, t.asUInt)}).asUInt)
350  } else {
351    brs & Reverse(Cat(inLatch.btbPred.bits.predCtr.map {c => c(1)}).asUInt)
352  }
353  val jals = inLatch.btb.hits & Reverse(Cat(predecode.pd.map { p => p.brType === BrType.jal }).asUInt) & predecode.mask
354  val calls = inLatch.btb.hits & predecode.mask & Reverse(Cat(predecode.pd.map { p => p.isCall }).asUInt)
355  val jalrs = inLatch.jbtac.hitIdx & predecode.mask & Reverse(Cat(predecode.pd.map { p => p.brType === BrType.jalr }).asUInt)
356  val rets = predecode.mask & Reverse(Cat(predecode.pd.map { p => p.isRet }).asUInt)
357
358  val brTakenIdx = PriorityMux(brTakens, (0 until PredictWidth).map(_.U))
359  val jalIdx = PriorityMux(jals, (0 until PredictWidth).map(_.U))
360  val callIdx = PriorityMux(calls, (0 until PredictWidth).map(_.U))
361  val jalrIdx = PriorityMux(jalrs, (0 until PredictWidth).map(_.U))
362  val retIdx = PriorityMux(rets, (0 until PredictWidth).map(_.U))
363
364  val jmps = (if (EnableRAS) {brTakens | jals | calls | jalrs | rets} else {brTakens | jals | calls | jalrs})
365  val jmpIdx = MuxCase(0.U, (0 until PredictWidth).map(i => (jmps(i), i.U)))
366  io.s3Taken := MuxCase(false.B, (0 until PredictWidth).map(i => (jmps(i), true.B)))
367
368  val brNotTakens = if (EnableBPD) {
369    VecInit((0 until PredictWidth).map(i => brs(i) && i.U <= jmpIdx && ~inLatch.tage.takens(i>>1) && predecode.mask(i)))
370  } else {
371    VecInit((0 until PredictWidth).map(i => brs(i) && i.U <= jmpIdx && ~inLatch.btbPred.bits.predCtr(i)(1) && predecode.mask(i)))
372  }
373
374  // TODO: what if if4 and if2 late jump to the same target?
375  // val lateJump = io.s3Taken && PriorityMux(Reverse(predecode.mask), ((PredictWidth - 1) to 0).map(_.U)) === jmpIdx && !predecode.isRVC(jmpIdx)
376  val lateJump = io.s3Taken && PriorityMux(Reverse(predecode.mask), (0 until PredictWidth).map {i => (PredictWidth - 1 - i).U}) === jmpIdx && !predecode.pd(jmpIdx).isRVC
377  io.out.bits.lateJump := lateJump
378
379  io.out.bits.predCtr := inLatch.btbPred.bits.predCtr
380  io.out.bits.btbHit := inLatch.btbPred.bits.btbHit
381  io.out.bits.tageMeta := inLatch.btbPred.bits.tageMeta
382  //io.out.bits.btbType := Mux(jmpIdx === retIdx, BTBtype.R,
383  //  Mux(jmpIdx === jalrIdx, BTBtype.I,
384  //  Mux(jmpIdx === brTakenIdx, BTBtype.B, BTBtype.J)))
385  val firstHist = inLatch.btbPred.bits.hist(0)
386  // there may be several notTaken branches before the first jump instruction,
387  // so we need to calculate how many zeroes should each instruction shift in its global history.
388  // each history is exclusive of instruction's own jump direction.
389  val histShift = Wire(Vec(PredictWidth, UInt(log2Up(PredictWidth).W)))
390  val shift = Wire(Vec(PredictWidth, Vec(PredictWidth, UInt(1.W))))
391  (0 until PredictWidth).foreach(i => shift(i) := Mux(!brNotTakens(i), 0.U, ~LowerMask(UIntToOH(i.U), PredictWidth)).asTypeOf(Vec(PredictWidth, UInt(1.W))))
392  for (j <- 0 until PredictWidth) {
393    var tmp = 0.U
394    for (i <- 0 until PredictWidth) {
395      tmp = tmp + shift(i)(j)
396    }
397    histShift(j) := tmp
398  }
399  (0 until PredictWidth).foreach(i => io.out.bits.hist(i) := firstHist << histShift(i))
400  // save ras checkpoint info
401  io.out.bits.rasSp := sp.value
402  io.out.bits.rasTopCtr := rasTop.ctr
403
404  // flush BPU and redirect when target differs from the target predicted in Stage1
405  val tToNt = inLatch.btbPred.bits.redirect && ~io.s3Taken
406  val ntToT = ~inLatch.btbPred.bits.redirect && io.s3Taken
407  val dirDiffers = tToNt || ntToT
408  val tgtDiffers = inLatch.btbPred.bits.redirect && io.s3Taken && io.out.bits.target =/= inLatch.btbPred.bits.target
409  // io.out.bits.redirect := (if (EnableBPD) {dirDiffers || tgtDiffers} else false.B)
410  io.out.bits.redirect := dirDiffers || tgtDiffers
411  io.out.bits.target := Mux(!io.s3Taken, inLatch.pc + (PopCount(predecode.mask) << 1.U), // TODO: RVC
412                        Mux(jmpIdx === retIdx, rasTopAddr,
413                        Mux(jmpIdx === jalrIdx, inLatch.jbtac.target,
414                        inLatch.btb.targets(jmpIdx))))
415
416  io.out.bits.instrValid := predecode.mask.asTypeOf(Vec(PredictWidth, Bool()))
417  for (i <- PredictWidth - 1 to 0) {
418    io.out.bits.instrValid(i) := (io.s3Taken && i.U <= jmpIdx || !io.s3Taken) && predecode.mask(i)
419    if (i != (PredictWidth - 1)) {
420      when (!lateJump && !predecode.pd(i).isRVC && io.s3Taken && i.U <= jmpIdx) {
421        io.out.bits.instrValid(i+1) := predecode.mask(i+1)
422      }
423    }
424  }
425
426  io.flushBPU := io.out.bits.redirect && io.out.fire()
427
428  // speculative update RAS
429  val rasWrite = WireInit(0.U.asTypeOf(rasEntry()))
430  val retAddr = inLatch.pc + (callIdx << 1.U) + Mux(predecode.pd(callIdx).isRVC, 2.U, 4.U)
431  rasWrite.retAddr := retAddr
432  val allocNewEntry = rasWrite.retAddr =/= rasTopAddr
433  rasWrite.ctr := Mux(allocNewEntry, 1.U, rasTop.ctr + 1.U)
434  val rasWritePosition = Mux(allocNewEntry, sp.value + 1.U, sp.value)
435  when (io.out.fire() && io.s3Taken) {
436    when (jmpIdx === callIdx) {
437      ras(rasWritePosition) := rasWrite
438      when (allocNewEntry) { sp.value := sp.value + 1.U }
439    }.elsewhen (jmpIdx === retIdx) {
440      when (rasTop.ctr === 1.U) {
441        sp.value := Mux(sp.value === 0.U, 0.U, sp.value - 1.U)
442      }.otherwise {
443        ras(sp.value) := Cat(rasTop.ctr - 1.U, rasTopAddr).asTypeOf(rasEntry())
444      }
445    }
446  }
447  // use checkpoint to recover RAS
448  val recoverSp = io.redirectInfo.redirect.rasSp
449  val recoverCtr = io.redirectInfo.redirect.rasTopCtr
450  when (io.redirectInfo.flush()) {
451    sp.value := recoverSp
452    ras(recoverSp) := Cat(recoverCtr, ras(recoverSp).retAddr).asTypeOf(rasEntry())
453  }
454
455  // roll back global history in S1 if S3 redirects
456  io.s1RollBackHist := Mux(io.s3Taken, io.out.bits.hist(jmpIdx),
457                       io.out.bits.hist(0) << PopCount(brs & predecode.mask & ~Reverse(Cat(inLatch.tage.takens.map {t => Fill(2, t.asUInt)}).asUInt)))
458
459  // debug info
460  XSDebug(io.in.fire(), "in:(%d %d) pc=%x\n", io.in.valid, io.in.ready, io.in.bits.pc)
461  XSDebug(io.out.fire(), "out:(%d %d) pc=%x redirect=%d predcdMask=%b instrValid=%b tgt=%x\n",
462    io.out.valid, io.out.ready, inLatch.pc, io.out.bits.redirect, predecode.mask, io.out.bits.instrValid.asUInt, io.out.bits.target)
463  XSDebug("flushS3=%d\n", flushS3)
464  XSDebug("validLatch=%d predecode.valid=%d\n", validLatch, predecodeValid)
465  XSDebug("brs=%b brTakens=%b brNTakens=%b jals=%b jalrs=%b calls=%b rets=%b\n",
466    brs, brTakens, brNotTakens.asUInt, jals, jalrs, calls, rets)
467  // ?????condition is wrong
468  // XSDebug(io.in.fire() && callIdx.orR, "[RAS]:pc=0x%x, rasWritePosition=%d, rasWriteAddr=0x%x\n",
469  //           io.in.bits.pc, rasWritePosition, retAddr)
470}
471
472class BPU extends XSModule {
473  val io = IO(new Bundle() {
474    // from backend
475    // flush pipeline if misPred and update bpu based on redirect signals from brq
476    val redirectInfo = Input(new RedirectInfo)
477
478    val in = new Bundle { val pc = Flipped(Valid(UInt(VAddrBits.W))) }
479
480    val btbOut = ValidIO(new BranchPrediction)
481    val tageOut = Decoupled(new BranchPrediction)
482
483    // predecode info from icache
484    // TODO: simplify this after implement predecode unit
485    val predecode = Flipped(ValidIO(new Predecode))
486  })
487
488  val s1 = Module(new BPUStage1)
489  val s2 = Module(new BPUStage2)
490  val s3 = Module(new BPUStage3)
491
492  s1.io.redirectInfo <> io.redirectInfo
493  s1.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
494  s1.io.in.pc.valid := io.in.pc.valid
495  s1.io.in.pc.bits <> io.in.pc.bits
496  io.btbOut <> s1.io.s1OutPred
497  s1.io.s3RollBackHist := s3.io.s1RollBackHist
498  s1.io.s3Taken := s3.io.s3Taken
499
500  s1.io.out <> s2.io.in
501  s2.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
502
503  s2.io.out <> s3.io.in
504  s3.io.flush := io.redirectInfo.flush()
505  s3.io.predecode <> io.predecode
506  io.tageOut <> s3.io.out
507  s3.io.redirectInfo <> io.redirectInfo
508}