xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision eb163ef08fc5ac1da1f32d948699bd6de053e444)
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 freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
23import utils._
24import xiangshan._
25import xiangshan.backend.decode.{DecodeStage, FusionDecoder, ImmUnion}
26import xiangshan.backend.dispatch.{Dispatch, Dispatch2Rs, DispatchQueue}
27import xiangshan.backend.fu.PFEvent
28import xiangshan.backend.rename.{Rename, RenameTableWrapper}
29import xiangshan.backend.rob.{Rob, RobCSRIO, RobLsqIO}
30import xiangshan.frontend.{FtqRead, Ftq_RF_Components}
31import xiangshan.mem.mdp.{LFST, SSIT, WaitTable}
32import xiangshan.ExceptionNO._
33import xiangshan.backend.exu.ExuConfig
34import xiangshan.mem.{LsqEnqCtrl, LsqEnqIO}
35
36class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
37  def numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
38  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
39  val redirect = Valid(new Redirect)
40}
41
42class RedirectGenerator(implicit p: Parameters) extends XSModule
43  with HasCircularQueuePtrHelper {
44
45  class RedirectGeneratorIO(implicit p: Parameters) extends XSBundle {
46    def numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
47    val hartId = Input(UInt(8.W))
48    val exuMispredict = Vec(numRedirect, Flipped(ValidIO(new ExuOutput)))
49    val loadReplay = Flipped(ValidIO(new Redirect))
50    val flush = Input(Bool())
51    val redirectPcRead = new FtqRead(UInt(VAddrBits.W))
52    val stage2Redirect = ValidIO(new Redirect)
53    val stage3Redirect = ValidIO(new Redirect)
54    val memPredUpdate = Output(new MemPredUpdateReq)
55    val memPredPcRead = new FtqRead(UInt(VAddrBits.W)) // read req send form stage 2
56    val isMisspreRedirect = Output(Bool())
57  }
58  val io = IO(new RedirectGeneratorIO)
59  /*
60        LoadQueue  Jump  ALU0  ALU1  ALU2  ALU3   exception    Stage1
61          |         |      |    |     |     |         |
62          |============= reg & compare =====|         |       ========
63                            |                         |
64                            |                         |
65                            |                         |        Stage2
66                            |                         |
67                    redirect (flush backend)          |
68                    |                                 |
69               === reg ===                            |       ========
70                    |                                 |
71                    |----- mux (exception first) -----|        Stage3
72                            |
73                redirect (send to frontend)
74   */
75  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
76    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
77    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
78      (if (j < i) !xs(j).valid || compareVec(i)(j)
79      else if (j == i) xs(i).valid
80      else !xs(j).valid || !compareVec(j)(i))
81    )).andR))
82    resultOnehot
83  }
84
85  def getRedirect(exuOut: Valid[ExuOutput]): ValidIO[Redirect] = {
86    val redirect = Wire(Valid(new Redirect))
87    redirect.valid := exuOut.valid && exuOut.bits.redirect.cfiUpdate.isMisPred
88    redirect.bits := exuOut.bits.redirect
89    redirect
90  }
91
92  val jumpOut = io.exuMispredict.head
93  val allRedirect = VecInit(io.exuMispredict.map(x => getRedirect(x)) :+ io.loadReplay)
94  val oldestOneHot = selectOldestRedirect(allRedirect)
95  val needFlushVec = VecInit(allRedirect.map(_.bits.robIdx.needFlush(io.stage2Redirect) || io.flush))
96  val oldestValid = VecInit(oldestOneHot.zip(needFlushVec).map{ case (v, f) => v && !f }).asUInt.orR
97  val oldestExuOutput = Mux1H(io.exuMispredict.indices.map(oldestOneHot), io.exuMispredict)
98  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
99  io.isMisspreRedirect := VecInit(io.exuMispredict.map(x => getRedirect(x).valid)).asUInt.orR
100  io.redirectPcRead.ptr := oldestRedirect.bits.ftqIdx
101  io.redirectPcRead.offset := oldestRedirect.bits.ftqOffset
102
103  val s1_jumpTarget = RegEnable(jumpOut.bits.redirect.cfiUpdate.target, jumpOut.valid)
104  val s1_imm12_reg = RegNext(oldestExuOutput.bits.uop.ctrl.imm(11, 0))
105  val s1_pd = RegNext(oldestExuOutput.bits.uop.cf.pd)
106  val s1_redirect_bits_reg = RegNext(oldestRedirect.bits)
107  val s1_redirect_valid_reg = RegNext(oldestValid)
108  val s1_redirect_onehot = RegNext(oldestOneHot)
109
110  // stage1 -> stage2
111  io.stage2Redirect.valid := s1_redirect_valid_reg && !io.flush
112  io.stage2Redirect.bits := s1_redirect_bits_reg
113
114  val s1_isReplay = s1_redirect_onehot.last
115  val s1_isJump = s1_redirect_onehot.head
116  val real_pc = io.redirectPcRead.data
117  val brTarget = real_pc + SignExt(ImmUnion.B.toImm32(s1_imm12_reg), XLEN)
118  val snpc = real_pc + Mux(s1_pd.isRVC, 2.U, 4.U)
119  val target = Mux(s1_isReplay,
120    real_pc, // replay from itself
121    Mux(s1_redirect_bits_reg.cfiUpdate.taken,
122      Mux(s1_isJump, s1_jumpTarget, brTarget),
123      snpc
124    )
125  )
126
127  val stage2CfiUpdate = io.stage2Redirect.bits.cfiUpdate
128  stage2CfiUpdate.pc := real_pc
129  stage2CfiUpdate.pd := s1_pd
130  // stage2CfiUpdate.predTaken := s1_redirect_bits_reg.cfiUpdate.predTaken
131  stage2CfiUpdate.target := target
132  // stage2CfiUpdate.taken := s1_redirect_bits_reg.cfiUpdate.taken
133  // stage2CfiUpdate.isMisPred := s1_redirect_bits_reg.cfiUpdate.isMisPred
134
135  val s2_target = RegEnable(target, s1_redirect_valid_reg)
136  val s2_pc = RegEnable(real_pc, s1_redirect_valid_reg)
137  val s2_redirect_bits_reg = RegEnable(s1_redirect_bits_reg, s1_redirect_valid_reg)
138  val s2_redirect_valid_reg = RegNext(s1_redirect_valid_reg && !io.flush, init = false.B)
139
140  io.stage3Redirect.valid := s2_redirect_valid_reg
141  io.stage3Redirect.bits := s2_redirect_bits_reg
142
143  // get pc from ftq
144  // valid only if redirect is caused by load violation
145  // store_pc is used to update store set
146  val store_pc = io.memPredPcRead(s1_redirect_bits_reg.stFtqIdx, s1_redirect_bits_reg.stFtqOffset)
147
148  // update load violation predictor if load violation redirect triggered
149  io.memPredUpdate.valid := RegNext(s1_isReplay && s1_redirect_valid_reg, init = false.B)
150  // update wait table
151  io.memPredUpdate.waddr := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
152  io.memPredUpdate.wdata := true.B
153  // update store set
154  io.memPredUpdate.ldpc := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
155  // store pc is ready 1 cycle after s1_isReplay is judged
156  io.memPredUpdate.stpc := XORFold(store_pc(VAddrBits-1, 1), MemPredPCWidth)
157
158  // // recover runahead checkpoint if redirect
159  // if (!env.FPGAPlatform) {
160  //   val runahead_redirect = Module(new DifftestRunaheadRedirectEvent)
161  //   runahead_redirect.io.clock := clock
162  //   runahead_redirect.io.coreid := io.hartId
163  //   runahead_redirect.io.valid := io.stage3Redirect.valid
164  //   runahead_redirect.io.pc :=  s2_pc // for debug only
165  //   runahead_redirect.io.target_pc := s2_target // for debug only
166  //   runahead_redirect.io.checkpoint_id := io.stage3Redirect.bits.debug_runahead_checkpoint_id // make sure it is right
167  // }
168}
169
170class CtrlBlock(dpExuConfigs: Seq[Seq[Seq[ExuConfig]]])(implicit p: Parameters) extends LazyModule
171  with HasWritebackSink with HasWritebackSource {
172  val rob = LazyModule(new Rob)
173
174  override def addWritebackSink(source: Seq[HasWritebackSource], index: Option[Seq[Int]]): HasWritebackSink = {
175    rob.addWritebackSink(Seq(this), Some(Seq(writebackSinks.length)))
176    super.addWritebackSink(source, index)
177  }
178
179  // duplicated dispatch2 here to avoid cross-module timing path loop.
180  val dispatch2 = dpExuConfigs.map(c => LazyModule(new Dispatch2Rs(c)))
181  lazy val module = new CtrlBlockImp(this)
182
183  override lazy val writebackSourceParams: Seq[WritebackSourceParams] = {
184    writebackSinksParams
185  }
186  override lazy val writebackSourceImp: HasWritebackSourceImp = module
187
188  override def generateWritebackIO(
189    thisMod: Option[HasWritebackSource] = None,
190    thisModImp: Option[HasWritebackSourceImp] = None
191  ): Unit = {
192    module.io.writeback.zip(writebackSinksImp(thisMod, thisModImp)).foreach(x => x._1 := x._2)
193  }
194}
195
196class CtrlBlockImp(outer: CtrlBlock)(implicit p: Parameters) extends LazyModuleImp(outer)
197  with HasXSParameter
198  with HasCircularQueuePtrHelper
199  with HasWritebackSourceImp
200  with HasPerfEvents
201{
202  val writebackLengths = outer.writebackSinksParams.map(_.length)
203
204  val io = IO(new Bundle {
205    val hartId = Input(UInt(8.W))
206    val cpu_halt = Output(Bool())
207    val frontend = Flipped(new FrontendToCtrlIO)
208    // to exu blocks
209    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
210    val dispatch = Vec(3*dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
211    val rsReady = Vec(outer.dispatch2.map(_.module.io.out.length).sum, Input(Bool()))
212    val enqLsq = Flipped(new LsqEnqIO)
213    val lqCancelCnt = Input(UInt(log2Up(LoadQueueSize + 1).W))
214    val sqCancelCnt = Input(UInt(log2Up(StoreQueueSize + 1).W))
215    val sqDeq = Input(UInt(log2Ceil(EnsbufferWidth + 1).W))
216    // from int block
217    val exuRedirect = Vec(exuParameters.AluCnt + exuParameters.JmpCnt, Flipped(ValidIO(new ExuOutput)))
218    val stIn = Vec(exuParameters.StuCnt, Flipped(ValidIO(new ExuInput)))
219    val memoryViolation = Flipped(ValidIO(new Redirect))
220    val jumpPc = Output(UInt(VAddrBits.W))
221    val jalr_target = Output(UInt(VAddrBits.W))
222    val robio = new Bundle {
223      // to int block
224      val toCSR = new RobCSRIO
225      val exception = ValidIO(new ExceptionInfo)
226      // to mem block
227      val lsq = new RobLsqIO
228    }
229    val csrCtrl = Input(new CustomCSRCtrlIO)
230    val perfInfo = Output(new Bundle{
231      val ctrlInfo = new Bundle {
232        val robFull   = Input(Bool())
233        val intdqFull = Input(Bool())
234        val fpdqFull  = Input(Bool())
235        val lsdqFull  = Input(Bool())
236      }
237    })
238    val writeback = MixedVec(writebackLengths.map(num => Vec(num, Flipped(ValidIO(new ExuOutput)))))
239    // redirect out
240    val redirect = ValidIO(new Redirect)
241    val debug_int_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
242    val debug_fp_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
243  })
244
245  override def writebackSource: Option[Seq[Seq[Valid[ExuOutput]]]] = {
246    Some(io.writeback.map(writeback => {
247      val exuOutput = WireInit(writeback)
248      val timer = GTimer()
249      for ((wb_next, wb) <- exuOutput.zip(writeback)) {
250        wb_next.valid := RegNext(wb.valid && !wb.bits.uop.robIdx.needFlush(Seq(stage2Redirect, redirectForExu)))
251        wb_next.bits := RegNext(wb.bits)
252        wb_next.bits.uop.debugInfo.writebackTime := timer
253      }
254      exuOutput
255    }))
256  }
257
258  val decode = Module(new DecodeStage)
259  val fusionDecoder = Module(new FusionDecoder)
260  val rat = Module(new RenameTableWrapper)
261  val ssit = Module(new SSIT)
262  val waittable = Module(new WaitTable)
263  val rename = Module(new Rename)
264  val dispatch = Module(new Dispatch)
265  val intDq = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth))
266  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth))
267  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
268  val redirectGen = Module(new RedirectGenerator)
269  // jumpPc (2) + redirects (1) + loadPredUpdate (1) + jalr_target (1) + robFlush (1)
270  val pcMem = Module(new SyncDataModuleTemplate(new Ftq_RF_Components, FtqSize, 6, 1, "BackendPC"))
271  val rob = outer.rob.module
272
273  pcMem.io.wen.head   := RegNext(io.frontend.fromFtq.pc_mem_wen)
274  pcMem.io.waddr.head := RegNext(io.frontend.fromFtq.pc_mem_waddr)
275  pcMem.io.wdata.head := RegNext(io.frontend.fromFtq.pc_mem_wdata)
276
277
278  pcMem.io.raddr.last := rob.io.flushOut.bits.ftqIdx.value
279  val flushPC = pcMem.io.rdata.last.getPc(RegNext(rob.io.flushOut.bits.ftqOffset))
280
281  val flushRedirect = Wire(Valid(new Redirect))
282  flushRedirect.valid := RegNext(rob.io.flushOut.valid)
283  flushRedirect.bits := RegEnable(rob.io.flushOut.bits, rob.io.flushOut.valid)
284
285  val flushRedirectReg = Wire(Valid(new Redirect))
286  flushRedirectReg.valid := RegNext(flushRedirect.valid, init = false.B)
287  flushRedirectReg.bits := RegEnable(flushRedirect.bits, flushRedirect.valid)
288
289  val stage2Redirect = Mux(flushRedirect.valid, flushRedirect, redirectGen.io.stage2Redirect)
290  // Redirect will be RegNext at ExuBlocks.
291  val redirectForExu = RegNextWithEnable(stage2Redirect)
292
293  val exuRedirect = io.exuRedirect.map(x => {
294    val valid = x.valid && x.bits.redirectValid
295    val killedByOlder = x.bits.uop.robIdx.needFlush(Seq(stage2Redirect, redirectForExu))
296    val delayed = Wire(Valid(new ExuOutput))
297    delayed.valid := RegNext(valid && !killedByOlder, init = false.B)
298    delayed.bits := RegEnable(x.bits, x.valid)
299    delayed
300  })
301  val loadReplay = Wire(Valid(new Redirect))
302  loadReplay.valid := RegNext(io.memoryViolation.valid &&
303    !io.memoryViolation.bits.robIdx.needFlush(Seq(stage2Redirect, redirectForExu)),
304    init = false.B
305  )
306  loadReplay.bits := RegEnable(io.memoryViolation.bits, io.memoryViolation.valid)
307  pcMem.io.raddr(2) := redirectGen.io.redirectPcRead.ptr.value
308  redirectGen.io.redirectPcRead.data := pcMem.io.rdata(2).getPc(RegNext(redirectGen.io.redirectPcRead.offset))
309  pcMem.io.raddr(3) := redirectGen.io.memPredPcRead.ptr.value
310  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(3).getPc(RegNext(redirectGen.io.memPredPcRead.offset))
311  redirectGen.io.hartId := io.hartId
312  redirectGen.io.exuMispredict <> exuRedirect
313  redirectGen.io.loadReplay <> loadReplay
314  redirectGen.io.flush := flushRedirect.valid
315
316  val frontendFlushValid = DelayN(flushRedirect.valid, 5)
317  val frontendFlushBits = RegEnable(flushRedirect.bits, flushRedirect.valid)
318  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
319  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
320  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
321  for (i <- 0 until CommitWidth) {
322    // why flushOut: instructions with flushPipe are not commited to frontend
323    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
324    val is_commit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !rob.io.flushOut.valid
325    io.frontend.toFtq.rob_commits(i).valid := RegNext(is_commit)
326    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), is_commit)
327  }
328  io.frontend.toFtq.redirect.valid := frontendFlushValid || redirectGen.io.stage2Redirect.valid
329  io.frontend.toFtq.redirect.bits := Mux(frontendFlushValid, frontendFlushBits, redirectGen.io.stage2Redirect.bits)
330  // Be careful here:
331  // T0: flushRedirect.valid, exception.valid
332  // T1: csr.redirect.valid
333  // T2: csr.exception.valid
334  // T3: csr.trapTarget
335  // T4: ctrlBlock.trapTarget
336  // T5: io.frontend.toFtq.stage2Redirect.valid
337  val pc_from_csr = io.robio.toCSR.isXRet || DelayN(rob.io.exception.valid, 4)
338  val rob_flush_pc = RegEnable(Mux(flushRedirect.bits.flushItself(),
339    flushPC, // replay inst
340    flushPC + 4.U // flush pipe
341  ), flushRedirect.valid)
342  val flushTarget = Mux(pc_from_csr, io.robio.toCSR.trapTarget, rob_flush_pc)
343  when (frontendFlushValid) {
344    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
345    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegNext(flushTarget)
346  }
347
348
349  val pendingRedirect = RegInit(false.B)
350  when (stage2Redirect.valid) {
351    pendingRedirect := true.B
352  }.elsewhen (RegNext(io.frontend.toFtq.redirect.valid)) {
353    pendingRedirect := false.B
354  }
355
356  if (env.EnableTopDown) {
357    val stage2Redirect_valid_when_pending = pendingRedirect && stage2Redirect.valid
358
359    val stage2_redirect_cycles = RegInit(false.B)                                         // frontend_bound->fetch_lantency->stage2_redirect
360    val MissPredPending = RegInit(false.B); val branch_resteers_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->branch_resteers
361    val RobFlushPending = RegInit(false.B); val robFlush_bubble_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->robflush_bubble
362    val LdReplayPending = RegInit(false.B); val ldReplay_bubble_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->ldReplay_bubble
363
364    when(redirectGen.io.isMisspreRedirect) { MissPredPending := true.B }
365    when(flushRedirect.valid)              { RobFlushPending := true.B }
366    when(redirectGen.io.loadReplay.valid)  { LdReplayPending := true.B }
367
368    when (RegNext(io.frontend.toFtq.redirect.valid)) {
369      when(pendingRedirect) {                             stage2_redirect_cycles := true.B }
370      when(MissPredPending) { MissPredPending := false.B; branch_resteers_cycles := true.B }
371      when(RobFlushPending) { RobFlushPending := false.B; robFlush_bubble_cycles := true.B }
372      when(LdReplayPending) { LdReplayPending := false.B; ldReplay_bubble_cycles := true.B }
373    }
374
375    when(VecInit(decode.io.out.map(x => x.valid)).asUInt.orR){
376      when(stage2_redirect_cycles) { stage2_redirect_cycles := false.B }
377      when(branch_resteers_cycles) { branch_resteers_cycles := false.B }
378      when(robFlush_bubble_cycles) { robFlush_bubble_cycles := false.B }
379      when(ldReplay_bubble_cycles) { ldReplay_bubble_cycles := false.B }
380    }
381
382    XSPerfAccumulate("stage2_redirect_cycles", stage2_redirect_cycles)
383    XSPerfAccumulate("branch_resteers_cycles", branch_resteers_cycles)
384    XSPerfAccumulate("robFlush_bubble_cycles", robFlush_bubble_cycles)
385    XSPerfAccumulate("ldReplay_bubble_cycles", ldReplay_bubble_cycles)
386    XSPerfAccumulate("s2Redirect_pend_cycles", stage2Redirect_valid_when_pending)
387  }
388
389  decode.io.in <> io.frontend.cfVec
390  decode.io.csrCtrl := RegNext(io.csrCtrl)
391  decode.io.intRat <> rat.io.intReadPorts
392  decode.io.fpRat <> rat.io.fpReadPorts
393
394  // memory dependency predict
395  // when decode, send fold pc to mdp
396  for (i <- 0 until DecodeWidth) {
397    val mdp_foldpc = Mux(
398      decode.io.out(i).fire,
399      decode.io.in(i).bits.foldpc,
400      rename.io.in(i).bits.cf.foldpc
401    )
402    ssit.io.raddr(i) := mdp_foldpc
403    waittable.io.raddr(i) := mdp_foldpc
404  }
405  // currently, we only update mdp info when isReplay
406  ssit.io.update <> RegNext(redirectGen.io.memPredUpdate)
407  ssit.io.csrCtrl := RegNext(io.csrCtrl)
408  waittable.io.update <> RegNext(redirectGen.io.memPredUpdate)
409  waittable.io.csrCtrl := RegNext(io.csrCtrl)
410
411  // LFST lookup and update
412  val lfst = Module(new LFST)
413  lfst.io.redirect <> RegNext(io.redirect)
414  lfst.io.storeIssue <> RegNext(io.stIn)
415  lfst.io.csrCtrl <> RegNext(io.csrCtrl)
416  lfst.io.dispatch <> dispatch.io.lfst
417
418  rat.io.redirect := stage2Redirect.valid
419  rat.io.robCommits := rob.io.commits
420  rat.io.intRenamePorts := rename.io.intRenamePorts
421  rat.io.fpRenamePorts := rename.io.fpRenamePorts
422  rat.io.debug_int_rat <> io.debug_int_rat
423  rat.io.debug_fp_rat <> io.debug_fp_rat
424
425  // pipeline between decode and rename
426  for (i <- 0 until RenameWidth) {
427    // fusion decoder
428    val decodeHasException = io.frontend.cfVec(i).bits.exceptionVec(instrPageFault) || io.frontend.cfVec(i).bits.exceptionVec(instrAccessFault)
429    val disableFusion = decode.io.csrCtrl.singlestep
430    fusionDecoder.io.in(i).valid := io.frontend.cfVec(i).valid && !(decodeHasException || disableFusion)
431    fusionDecoder.io.in(i).bits := io.frontend.cfVec(i).bits.instr
432    if (i > 0) {
433      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
434    }
435
436    // Pipeline
437    val renamePipe = PipelineNext(decode.io.out(i), rename.io.in(i).ready,
438      stage2Redirect.valid || pendingRedirect)
439    renamePipe.ready := rename.io.in(i).ready
440    rename.io.in(i).valid := renamePipe.valid && !fusionDecoder.io.clear(i)
441    rename.io.in(i).bits := renamePipe.bits
442    rename.io.intReadPorts(i) := rat.io.intReadPorts(i).map(_.data)
443    rename.io.fpReadPorts(i) := rat.io.fpReadPorts(i).map(_.data)
444    rename.io.waittable(i) := RegEnable(waittable.io.rdata(i), decode.io.out(i).fire)
445
446    if (i < RenameWidth - 1) {
447      // fusion decoder sees the raw decode info
448      fusionDecoder.io.dec(i) := renamePipe.bits.ctrl
449      rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
450
451      // update the first RenameWidth - 1 instructions
452      decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
453      when (fusionDecoder.io.out(i).valid) {
454        fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits.ctrl)
455        // TODO: remove this dirty code for ftq update
456        val sameFtqPtr = rename.io.in(i).bits.cf.ftqPtr.value === rename.io.in(i + 1).bits.cf.ftqPtr.value
457        val ftqOffset0 = rename.io.in(i).bits.cf.ftqOffset
458        val ftqOffset1 = rename.io.in(i + 1).bits.cf.ftqOffset
459        val ftqOffsetDiff = ftqOffset1 - ftqOffset0
460        val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
461        val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
462        val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
463        val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
464        rename.io.in(i).bits.ctrl.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
465        XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
466      }
467    }
468  }
469
470  rename.io.redirect <> stage2Redirect
471  rename.io.robCommits <> rob.io.commits
472  rename.io.ssit <> ssit.io.rdata
473  rename.io.debug_int_rat <> rat.io.debug_int_rat
474  rename.io.debug_fp_rat <> rat.io.debug_fp_rat
475
476  // pipeline between rename and dispatch
477  for (i <- 0 until RenameWidth) {
478    PipelineConnect(rename.io.out(i), dispatch.io.fromRename(i), dispatch.io.recv(i), stage2Redirect.valid)
479  }
480
481  dispatch.io.hartId := io.hartId
482  dispatch.io.redirect <> stage2Redirect
483  dispatch.io.enqRob <> rob.io.enq
484  dispatch.io.toIntDq <> intDq.io.enq
485  dispatch.io.toFpDq <> fpDq.io.enq
486  dispatch.io.toLsDq <> lsDq.io.enq
487  dispatch.io.allocPregs <> io.allocPregs
488  dispatch.io.singleStep := RegNext(io.csrCtrl.singlestep)
489
490  intDq.io.redirect <> redirectForExu
491  fpDq.io.redirect <> redirectForExu
492  lsDq.io.redirect <> redirectForExu
493
494  val dpqOut = intDq.io.deq ++ lsDq.io.deq ++ fpDq.io.deq
495  io.dispatch <> dpqOut
496
497  for (dp2 <- outer.dispatch2.map(_.module.io)) {
498    dp2.redirect := redirectForExu
499    if (dp2.readFpState.isDefined) {
500      dp2.readFpState.get := DontCare
501    }
502    if (dp2.readIntState.isDefined) {
503      dp2.readIntState.get := DontCare
504    }
505    if (dp2.enqLsq.isDefined) {
506      val lsqCtrl = Module(new LsqEnqCtrl)
507      lsqCtrl.io.redirect <> redirectForExu
508      lsqCtrl.io.enq <> dp2.enqLsq.get
509      lsqCtrl.io.lcommit := rob.io.lsq.lcommit
510      lsqCtrl.io.scommit := io.sqDeq
511      lsqCtrl.io.lqCancelCnt := io.lqCancelCnt
512      lsqCtrl.io.sqCancelCnt := io.sqCancelCnt
513      io.enqLsq <> lsqCtrl.io.enqLsq
514    }
515  }
516  for ((dp2In, i) <- outer.dispatch2.flatMap(_.module.io.in).zipWithIndex) {
517    dp2In.valid := dpqOut(i).valid
518    dp2In.bits := dpqOut(i).bits
519    // override ready here to avoid cross-module loop path
520    dpqOut(i).ready := dp2In.ready
521  }
522  for ((dp2Out, i) <- outer.dispatch2.flatMap(_.module.io.out).zipWithIndex) {
523    dp2Out.ready := io.rsReady(i)
524  }
525
526  val pingpong = RegInit(false.B)
527  pingpong := !pingpong
528  pcMem.io.raddr(0) := intDq.io.deqNext(0).cf.ftqPtr.value
529  pcMem.io.raddr(1) := intDq.io.deqNext(2).cf.ftqPtr.value
530  val jumpPcRead0 = pcMem.io.rdata(0).getPc(RegNext(intDq.io.deqNext(0).cf.ftqOffset))
531  val jumpPcRead1 = pcMem.io.rdata(1).getPc(RegNext(intDq.io.deqNext(2).cf.ftqOffset))
532  io.jumpPc := Mux(pingpong && (exuParameters.AluCnt > 2).B, jumpPcRead1, jumpPcRead0)
533  val jalrTargetReadPtr = Mux(pingpong && (exuParameters.AluCnt > 2).B,
534    io.dispatch(2).bits.cf.ftqPtr,
535    io.dispatch(0).bits.cf.ftqPtr)
536  pcMem.io.raddr(4) := (jalrTargetReadPtr + 1.U).value
537  val jalrTargetRead = pcMem.io.rdata(4).startAddr
538  val read_from_newest_entry = RegNext(jalrTargetReadPtr) === RegNext(io.frontend.fromFtq.newest_entry_ptr)
539  io.jalr_target := Mux(read_from_newest_entry, RegNext(io.frontend.fromFtq.newest_entry_target), jalrTargetRead)
540
541  rob.io.hartId := io.hartId
542  io.cpu_halt := DelayN(rob.io.cpu_halt, 5)
543  rob.io.redirect <> stage2Redirect
544  outer.rob.generateWritebackIO(Some(outer), Some(this))
545
546  io.redirect <> stage2Redirect
547
548  // rob to int block
549  io.robio.toCSR <> rob.io.csr
550  io.robio.toCSR.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
551  io.robio.exception := rob.io.exception
552  io.robio.exception.bits.uop.cf.pc := flushPC
553
554  // rob to mem block
555  io.robio.lsq <> rob.io.lsq
556
557  io.perfInfo.ctrlInfo.robFull := RegNext(rob.io.robFull)
558  io.perfInfo.ctrlInfo.intdqFull := RegNext(intDq.io.dqFull)
559  io.perfInfo.ctrlInfo.fpdqFull := RegNext(fpDq.io.dqFull)
560  io.perfInfo.ctrlInfo.lsdqFull := RegNext(lsDq.io.dqFull)
561
562  val pfevent = Module(new PFEvent)
563  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
564  val csrevents = pfevent.io.hpmevent.slice(8,16)
565
566  val perfinfo = IO(new Bundle(){
567    val perfEventsRs      = Input(Vec(NumRs, new PerfEvent))
568    val perfEventsEu0     = Input(Vec(6, new PerfEvent))
569    val perfEventsEu1     = Input(Vec(6, new PerfEvent))
570  })
571
572  val allPerfEvents = Seq(decode, rename, dispatch, intDq, fpDq, lsDq, rob).flatMap(_.getPerf)
573  val hpmEvents = allPerfEvents ++ perfinfo.perfEventsEu0 ++ perfinfo.perfEventsEu1 ++ perfinfo.perfEventsRs
574  val perfEvents = HPerfMonitor(csrevents, hpmEvents).getPerfEvents
575  generatePerfEvent()
576}
577