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