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