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