xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision dcbc69cb2a7ea07707ede3d8f7c74421ef450202)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.backend
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import xiangshan._
24import xiangshan.backend.decode.{DecodeStage, ImmUnion}
25import xiangshan.backend.dispatch.{Dispatch, DispatchQueue}
26import xiangshan.backend.rename.{Rename, RenameTableWrapper}
27import xiangshan.backend.rob.{Rob, RobCSRIO, RobLsqIO}
28import xiangshan.backend.fu.{PFEvent}
29import xiangshan.mem.mdp.{SSIT, LFST, WaitTable}
30import xiangshan.frontend.{FtqPtr, FtqRead}
31import xiangshan.mem.{LsqEnqIO}
32import difftest._
33
34class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
35  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
36  val stage2Redirect = Valid(new Redirect)
37  val stage3Redirect = ValidIO(new Redirect)
38  val robFlush = ValidIO(new Redirect)
39}
40
41class RedirectGenerator(implicit p: Parameters) extends XSModule
42  with HasCircularQueuePtrHelper {
43  val numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
44  val io = IO(new Bundle() {
45    val hartId = Input(UInt(8.W))
46    val exuMispredict = Vec(numRedirect, Flipped(ValidIO(new ExuOutput)))
47    val loadReplay = Flipped(ValidIO(new Redirect))
48    val flush = Input(Bool())
49    val stage1PcRead = Vec(numRedirect+1, new FtqRead(UInt(VAddrBits.W)))
50    val stage2Redirect = ValidIO(new Redirect)
51    val stage3Redirect = ValidIO(new Redirect)
52    val memPredUpdate = Output(new MemPredUpdateReq)
53    val memPredPcRead = new FtqRead(UInt(VAddrBits.W)) // read req send form stage 2
54  })
55  /*
56        LoadQueue  Jump  ALU0  ALU1  ALU2  ALU3   exception    Stage1
57          |         |      |    |     |     |         |
58          |============= reg & compare =====|         |       ========
59                            |                         |
60                            |                         |
61                            |                         |        Stage2
62                            |                         |
63                    redirect (flush backend)          |
64                    |                                 |
65               === reg ===                            |       ========
66                    |                                 |
67                    |----- mux (exception first) -----|        Stage3
68                            |
69                redirect (send to frontend)
70   */
71  private class Wrapper(val n: Int) extends Bundle {
72    val redirect = new Redirect
73    val valid = Bool()
74    val idx = UInt(log2Up(n).W)
75  }
76  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
77    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
78    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
79      (if (j < i) !xs(j).valid || compareVec(i)(j)
80      else if (j == i) xs(i).valid
81      else !xs(j).valid || !compareVec(j)(i))
82    )).andR))
83    resultOnehot
84  }
85
86  val redirects = io.exuMispredict.map(_.bits.redirect) :+ io.loadReplay.bits
87  val stage1FtqReadPcs =
88    (io.stage1PcRead zip redirects).map{ case (r, redirect) =>
89      r(redirect.ftqIdx, redirect.ftqOffset)
90    }
91
92  def getRedirect(exuOut: Valid[ExuOutput]): ValidIO[Redirect] = {
93    val redirect = Wire(Valid(new Redirect))
94    redirect.valid := exuOut.valid && exuOut.bits.redirect.cfiUpdate.isMisPred
95    redirect.bits := exuOut.bits.redirect
96    redirect
97  }
98
99  val jumpOut = io.exuMispredict.head
100  val allRedirect = VecInit(io.exuMispredict.map(x => getRedirect(x)) :+ io.loadReplay)
101  val oldestOneHot = selectOldestRedirect(allRedirect)
102  val needFlushVec = VecInit(allRedirect.map(_.bits.robIdx.needFlush(io.stage2Redirect) || io.flush))
103  val oldestValid = VecInit(oldestOneHot.zip(needFlushVec).map{ case (v, f) => v && !f }).asUInt.orR
104  val oldestExuOutput = Mux1H(io.exuMispredict.indices.map(oldestOneHot), io.exuMispredict)
105  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
106
107  val s1_jumpTarget = RegEnable(jumpOut.bits.redirect.cfiUpdate.target, jumpOut.valid)
108  val s1_imm12_reg = RegNext(oldestExuOutput.bits.uop.ctrl.imm(11, 0))
109  val s1_pd = RegNext(oldestExuOutput.bits.uop.cf.pd)
110  val s1_redirect_bits_reg = RegNext(oldestRedirect.bits)
111  val s1_redirect_valid_reg = RegNext(oldestValid)
112  val s1_redirect_onehot = RegNext(oldestOneHot)
113
114  // stage1 -> stage2
115  io.stage2Redirect.valid := s1_redirect_valid_reg && !io.flush
116  io.stage2Redirect.bits := s1_redirect_bits_reg
117  io.stage2Redirect.bits.cfiUpdate := DontCare
118
119  val s1_isReplay = s1_redirect_onehot.last
120  val s1_isJump = s1_redirect_onehot.head
121  val real_pc = Mux1H(s1_redirect_onehot, stage1FtqReadPcs)
122  val brTarget = real_pc + SignExt(ImmUnion.B.toImm32(s1_imm12_reg), XLEN)
123  val snpc = real_pc + Mux(s1_pd.isRVC, 2.U, 4.U)
124  val target = Mux(s1_isReplay,
125    real_pc, // replay from itself
126    Mux(s1_redirect_bits_reg.cfiUpdate.taken,
127      Mux(s1_isJump, s1_jumpTarget, brTarget),
128      snpc
129    )
130  )
131
132  // get pc from ftq
133  // valid only if redirect is caused by load violation
134  // store_pc is used to update store set
135  val store_pc = io.memPredPcRead(s1_redirect_bits_reg.stFtqIdx, s1_redirect_bits_reg.stFtqOffset)
136
137  // update load violation predictor if load violation redirect triggered
138  io.memPredUpdate.valid := RegNext(s1_isReplay && s1_redirect_valid_reg, init = false.B)
139  // update wait table
140  io.memPredUpdate.waddr := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
141  io.memPredUpdate.wdata := true.B
142  // update store set
143  io.memPredUpdate.ldpc := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
144  // store pc is ready 1 cycle after s1_isReplay is judged
145  io.memPredUpdate.stpc := XORFold(store_pc(VAddrBits-1, 1), MemPredPCWidth)
146
147  val s2_target = RegEnable(target, enable = s1_redirect_valid_reg)
148  val s2_pd = RegEnable(s1_pd, enable = s1_redirect_valid_reg)
149  val s2_pc = RegEnable(real_pc, enable = s1_redirect_valid_reg)
150  val s2_redirect_bits_reg = RegEnable(s1_redirect_bits_reg, enable = s1_redirect_valid_reg)
151  val s2_redirect_valid_reg = RegNext(s1_redirect_valid_reg && !io.flush, init = false.B)
152
153  io.stage3Redirect.valid := s2_redirect_valid_reg
154  io.stage3Redirect.bits := s2_redirect_bits_reg
155  val stage3CfiUpdate = io.stage3Redirect.bits.cfiUpdate
156  stage3CfiUpdate.pc := s2_pc
157  stage3CfiUpdate.pd := s2_pd
158  stage3CfiUpdate.predTaken := s2_redirect_bits_reg.cfiUpdate.predTaken
159  stage3CfiUpdate.target := s2_target
160  stage3CfiUpdate.taken := s2_redirect_bits_reg.cfiUpdate.taken
161  stage3CfiUpdate.isMisPred := s2_redirect_bits_reg.cfiUpdate.isMisPred
162
163  // recover runahead checkpoint if redirect
164  if (!env.FPGAPlatform) {
165    val runahead_redirect = Module(new DifftestRunaheadRedirectEvent)
166    runahead_redirect.io.clock := clock
167    runahead_redirect.io.coreid := io.hartId
168    runahead_redirect.io.valid := io.stage3Redirect.valid
169    runahead_redirect.io.pc :=  s2_pc // for debug only
170    runahead_redirect.io.target_pc := s2_target // for debug only
171    runahead_redirect.io.checkpoint_id := io.stage3Redirect.bits.debug_runahead_checkpoint_id // make sure it is right
172  }
173}
174
175class CtrlBlock(implicit p: Parameters) extends XSModule
176  with HasCircularQueuePtrHelper {
177  val io = IO(new Bundle {
178    val hartId = Input(UInt(8.W))
179    val frontend = Flipped(new FrontendToCtrlIO)
180    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
181    val dispatch = Vec(3*dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
182    // from int block
183    val exuRedirect = Vec(exuParameters.AluCnt + exuParameters.JmpCnt, Flipped(ValidIO(new ExuOutput)))
184    val stIn = Vec(exuParameters.StuCnt, Flipped(ValidIO(new ExuInput)))
185    val stOut = Vec(exuParameters.StuCnt, Flipped(ValidIO(new ExuOutput)))
186    val memoryViolation = Flipped(ValidIO(new Redirect))
187    val jumpPc = Output(UInt(VAddrBits.W))
188    val jalr_target = Output(UInt(VAddrBits.W))
189    val robio = new Bundle {
190      // to int block
191      val toCSR = new RobCSRIO
192      val exception = ValidIO(new ExceptionInfo)
193      // to mem block
194      val lsq = new RobLsqIO
195    }
196    val csrCtrl = Input(new CustomCSRCtrlIO)
197    val perfInfo = Output(new Bundle{
198      val ctrlInfo = new Bundle {
199        val robFull   = Input(Bool())
200        val intdqFull = Input(Bool())
201        val fpdqFull  = Input(Bool())
202        val lsdqFull  = Input(Bool())
203      }
204    })
205    val writeback = Vec(NRIntWritePorts + NRFpWritePorts, Flipped(ValidIO(new ExuOutput)))
206    // redirect out
207    val redirect = ValidIO(new Redirect)
208    val debug_int_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
209    val debug_fp_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
210  })
211
212  val decode = Module(new DecodeStage)
213  val rat = Module(new RenameTableWrapper)
214  val ssit = Module(new SSIT)
215  val waittable = Module(new WaitTable)
216  val rename = Module(new Rename)
217  val dispatch = Module(new Dispatch)
218  val intDq = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth, "int"))
219  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth, "fp"))
220  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth, "ls"))
221  val redirectGen = Module(new RedirectGenerator)
222
223  val robWbSize = NRIntWritePorts + NRFpWritePorts + exuParameters.StuCnt
224  val rob = Module(new Rob(robWbSize))
225
226  val robPcRead = io.frontend.fromFtq.getRobFlushPcRead
227  val flushPC = robPcRead(rob.io.flushOut.bits.ftqIdx, rob.io.flushOut.bits.ftqOffset)
228
229  val flushRedirect = Wire(Valid(new Redirect))
230  flushRedirect.valid := RegNext(rob.io.flushOut.valid)
231  flushRedirect.bits := RegEnable(rob.io.flushOut.bits, rob.io.flushOut.valid)
232  flushRedirect.bits.cfiUpdate.target := Mux(io.robio.toCSR.isXRet || rob.io.exception.valid,
233    io.robio.toCSR.trapTarget,
234    Mux(flushRedirect.bits.flushItself(),
235      flushPC, // replay inst
236      flushPC + 4.U // flush pipe
237    )
238  )
239
240  val flushRedirectReg = Wire(Valid(new Redirect))
241  flushRedirectReg.valid := RegNext(flushRedirect.valid, init = false.B)
242  flushRedirectReg.bits := RegEnable(flushRedirect.bits, enable = flushRedirect.valid)
243
244  val stage2Redirect = Mux(flushRedirect.valid, flushRedirect, redirectGen.io.stage2Redirect)
245  val stage3Redirect = Mux(flushRedirectReg.valid, flushRedirectReg, redirectGen.io.stage3Redirect)
246
247  val exuRedirect = io.exuRedirect.map(x => {
248    val valid = x.valid && x.bits.redirectValid
249    val killedByOlder = x.bits.uop.robIdx.needFlush(stage2Redirect)
250    val delayed = Wire(Valid(new ExuOutput))
251    delayed.valid := RegNext(valid && !killedByOlder, init = false.B)
252    delayed.bits := RegEnable(x.bits, x.valid)
253    delayed
254  })
255  val loadReplay = Wire(Valid(new Redirect))
256  loadReplay.valid := RegNext(io.memoryViolation.valid &&
257    !io.memoryViolation.bits.robIdx.needFlush(stage2Redirect),
258    init = false.B
259  )
260  loadReplay.bits := RegEnable(io.memoryViolation.bits, io.memoryViolation.valid)
261  io.frontend.fromFtq.getRedirectPcRead <> redirectGen.io.stage1PcRead
262  io.frontend.fromFtq.getMemPredPcRead <> redirectGen.io.memPredPcRead
263  redirectGen.io.hartId := io.hartId
264  redirectGen.io.exuMispredict <> exuRedirect
265  redirectGen.io.loadReplay <> loadReplay
266  redirectGen.io.flush := RegNext(rob.io.flushOut.valid)
267
268  for(i <- 0 until CommitWidth){
269    io.frontend.toFtq.rob_commits(i).valid := rob.io.commits.valid(i) && !rob.io.commits.isWalk
270    io.frontend.toFtq.rob_commits(i).bits := rob.io.commits.info(i)
271  }
272  io.frontend.toFtq.stage2Redirect <> stage2Redirect
273  io.frontend.toFtq.robFlush <> RegNext(rob.io.flushOut)
274  io.frontend.toFtq.stage3Redirect := stage3Redirect
275
276  decode.io.in <> io.frontend.cfVec
277  decode.io.csrCtrl := io.csrCtrl
278
279  // memory dependency predict
280  // when decode, send fold pc to mdp
281  for (i <- 0 until DecodeWidth) {
282    val mdp_foldpc = Mux(
283      decode.io.out(i).fire(),
284      decode.io.in(i).bits.foldpc,
285      rename.io.in(i).bits.cf.foldpc
286    )
287    ssit.io.raddr(i) := mdp_foldpc
288    waittable.io.raddr(i) := mdp_foldpc
289  }
290  // currently, we only update mdp info when isReplay
291  ssit.io.update <> RegNext(redirectGen.io.memPredUpdate)
292  ssit.io.csrCtrl := RegNext(io.csrCtrl)
293  waittable.io.update <> RegNext(redirectGen.io.memPredUpdate)
294  waittable.io.csrCtrl := RegNext(io.csrCtrl)
295
296  // LFST lookup and update
297  val lfst = Module(new LFST)
298  lfst.io.redirect <> RegNext(io.redirect)
299  lfst.io.storeIssue <> RegNext(io.stIn)
300  lfst.io.csrCtrl <> RegNext(io.csrCtrl)
301  lfst.io.dispatch <> dispatch.io.lfst
302
303  rat.io.robCommits := rob.io.commits
304  for ((r, i) <- rat.io.intReadPorts.zipWithIndex) {
305    val raddr = decode.io.out(i).bits.ctrl.lsrc.take(2) :+ decode.io.out(i).bits.ctrl.ldest
306    r.map(_.addr).zip(raddr).foreach(x => x._1 := x._2)
307    rename.io.intReadPorts(i) := r.map(_.data)
308    r.foreach(_.hold := !rename.io.in(i).ready)
309  }
310  rat.io.intRenamePorts := rename.io.intRenamePorts
311  for ((r, i) <- rat.io.fpReadPorts.zipWithIndex) {
312    val raddr = decode.io.out(i).bits.ctrl.lsrc.take(3) :+ decode.io.out(i).bits.ctrl.ldest
313    r.map(_.addr).zip(raddr).foreach(x => x._1 := x._2)
314    rename.io.fpReadPorts(i) := r.map(_.data)
315    r.foreach(_.hold := !rename.io.in(i).ready)
316  }
317  rat.io.fpRenamePorts := rename.io.fpRenamePorts
318  rat.io.debug_int_rat <> io.debug_int_rat
319  rat.io.debug_fp_rat <> io.debug_fp_rat
320
321  // pipeline between decode and rename
322  for (i <- 0 until RenameWidth) {
323    PipelineConnect(decode.io.out(i), rename.io.in(i), rename.io.in(i).ready,
324      stage2Redirect.valid || stage3Redirect.valid)
325  }
326
327  rename.io.redirect <> stage2Redirect
328  rename.io.robCommits <> rob.io.commits
329  rename.io.ssit <> ssit.io.rdata
330  rename.io.waittable <> RegNext(waittable.io.rdata)
331
332  // pipeline between rename and dispatch
333  for (i <- 0 until RenameWidth) {
334    PipelineConnect(rename.io.out(i), dispatch.io.fromRename(i), dispatch.io.recv(i), stage2Redirect.valid)
335  }
336
337  dispatch.io.hartId := io.hartId
338  dispatch.io.redirect <> stage2Redirect
339  dispatch.io.enqRob <> rob.io.enq
340  dispatch.io.toIntDq <> intDq.io.enq
341  dispatch.io.toFpDq <> fpDq.io.enq
342  dispatch.io.toLsDq <> lsDq.io.enq
343  dispatch.io.allocPregs <> io.allocPregs
344  dispatch.io.singleStep := false.B
345
346  intDq.io.redirect <> stage2Redirect
347  fpDq.io.redirect <> stage2Redirect
348  lsDq.io.redirect <> stage2Redirect
349
350  io.dispatch <> intDq.io.deq ++ lsDq.io.deq ++ fpDq.io.deq
351
352  val pingpong = RegInit(false.B)
353  pingpong := !pingpong
354  val jumpInst = Mux(pingpong && (exuParameters.AluCnt > 2).B, io.dispatch(2).bits, io.dispatch(0).bits)
355  val jumpPcRead = io.frontend.fromFtq.getJumpPcRead
356  io.jumpPc := jumpPcRead(jumpInst.cf.ftqPtr, jumpInst.cf.ftqOffset)
357  val jumpTargetRead = io.frontend.fromFtq.target_read
358  io.jalr_target := jumpTargetRead(jumpInst.cf.ftqPtr, jumpInst.cf.ftqOffset)
359
360  rob.io.hartId := io.hartId
361  rob.io.redirect <> stage2Redirect
362  val exeWbResults = VecInit(io.writeback ++ io.stOut)
363  val timer = GTimer()
364  for((rob_wb, wb) <- rob.io.exeWbResults.zip(exeWbResults)) {
365    rob_wb.valid := RegNext(wb.valid && !wb.bits.uop.robIdx.needFlush(stage2Redirect))
366    rob_wb.bits := RegNext(wb.bits)
367    rob_wb.bits.uop.debugInfo.writebackTime := timer
368  }
369
370  io.redirect <> stage2Redirect
371
372  // rob to int block
373  io.robio.toCSR <> rob.io.csr
374  io.robio.toCSR.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
375  io.robio.exception := rob.io.exception
376  io.robio.exception.bits.uop.cf.pc := flushPC
377
378  // rob to mem block
379  io.robio.lsq <> rob.io.lsq
380
381  io.perfInfo.ctrlInfo.robFull := RegNext(rob.io.robFull)
382  io.perfInfo.ctrlInfo.intdqFull := RegNext(intDq.io.dqFull)
383  io.perfInfo.ctrlInfo.fpdqFull := RegNext(fpDq.io.dqFull)
384  io.perfInfo.ctrlInfo.lsdqFull := RegNext(lsDq.io.dqFull)
385
386  val pfevent = Module(new PFEvent)
387  val csrevents = pfevent.io.hpmevent.slice(8,16)
388  val perfinfo = IO(new Bundle(){
389    val perfEvents        = Output(new PerfEventsBundle(csrevents.length))
390    val perfEventsRs      = Input(new PerfEventsBundle(NumRs))
391    val perfEventsEu0     = Input(new PerfEventsBundle(10))
392    val perfEventsEu1     = Input(new PerfEventsBundle(10))
393  })
394
395  if(print_perfcounter){
396    val decode_perf     = decode.perfEvents.map(_._1).zip(decode.perfinfo.perfEvents.perf_events)
397    val rename_perf     = rename.perfEvents.map(_._1).zip(rename.perfinfo.perfEvents.perf_events)
398    val dispat_perf     = dispatch.perfEvents.map(_._1).zip(dispatch.perfinfo.perfEvents.perf_events)
399    val intdq_perf      = intDq.perfEvents.map(_._1).zip(intDq.perfinfo.perfEvents.perf_events)
400    val fpdq_perf       = fpDq.perfEvents.map(_._1).zip(fpDq.perfinfo.perfEvents.perf_events)
401    val lsdq_perf       = lsDq.perfEvents.map(_._1).zip(lsDq.perfinfo.perfEvents.perf_events)
402    val rob_perf        = rob.perfEvents.map(_._1).zip(rob.perfinfo.perfEvents.perf_events)
403    val perfEvents =  decode_perf ++ rename_perf ++ dispat_perf ++ intdq_perf ++ fpdq_perf ++ lsdq_perf ++ rob_perf
404
405    for (((perf_name,perf),i) <- perfEvents.zipWithIndex) {
406      println(s"ctrl perf $i: $perf_name")
407    }
408  }
409
410  val hpmEvents = decode.perfinfo.perfEvents.perf_events ++ rename.perfinfo.perfEvents.perf_events ++
411                  dispatch.perfinfo.perfEvents.perf_events ++
412                  intDq.perfinfo.perfEvents.perf_events ++ fpDq.perfinfo.perfEvents.perf_events ++
413                  lsDq.perfinfo.perfEvents.perf_events ++ rob.perfinfo.perfEvents.perf_events ++
414                  perfinfo.perfEventsEu0.perf_events ++ perfinfo.perfEventsEu1.perf_events ++
415                  perfinfo.perfEventsRs.perf_events
416
417  val perf_length = hpmEvents.length
418  val hpm_ctrl = Module(new HPerfmonitor(perf_length,csrevents.length))
419  hpm_ctrl.io.hpm_event := csrevents
420  hpm_ctrl.io.events_sets.perf_events := hpmEvents
421  perfinfo.perfEvents := RegNext(hpm_ctrl.io.events_selected)
422  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
423}
424