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