xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision 56db494fddea43ab002e171c9078af81188a747f)
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 utility._
24import utils._
25import xiangshan.ExceptionNO._
26import xiangshan._
27import xiangshan.backend.Bundles.{DecodedInst, DynInst, ExceptionInfo, ExuOutput}
28import xiangshan.backend.ctrlblock.{DebugLSIO, DebugLsInfoBundle, LsTopdownInfo, MemCtrl, RedirectGenerator}
29import xiangshan.backend.datapath.DataConfig.VAddrData
30import xiangshan.backend.decode.{DecodeStage, FusionDecoder}
31import xiangshan.backend.dispatch.{CoreDispatchTopDownIO, Dispatch, DispatchQueue}
32import xiangshan.backend.fu.PFEvent
33import xiangshan.backend.fu.vector.Bundles.{VType, Vl}
34import xiangshan.backend.fu.wrapper.CSRToDecode
35import xiangshan.backend.rename.{Rename, RenameTableWrapper, SnapshotGenerator}
36import xiangshan.backend.rob.{Rob, RobCSRIO, RobCoreTopDownIO, RobDebugRollingIO, RobLsqIO, RobPtr}
37import xiangshan.frontend.{FtqPtr, FtqRead, Ftq_RF_Components}
38import xiangshan.mem.{LqPtr, LsqEnqIO}
39import xiangshan.backend.issue.{FpScheduler, IntScheduler, MemScheduler, VfScheduler}
40
41class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
42  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
43  val redirect = Valid(new Redirect)
44  val ftqIdxAhead = Vec(BackendRedirectNum, Valid(new FtqPtr))
45  val ftqIdxSelOH = Valid(UInt((BackendRedirectNum).W))
46}
47
48class CtrlBlock(params: BackendParams)(implicit p: Parameters) extends LazyModule {
49  override def shouldBeInlined: Boolean = false
50
51  val rob = LazyModule(new Rob(params))
52
53  lazy val module = new CtrlBlockImp(this)(p, params)
54
55  val gpaMem = LazyModule(new GPAMem())
56}
57
58class CtrlBlockImp(
59  override val wrapper: CtrlBlock
60)(implicit
61  p: Parameters,
62  params: BackendParams
63) extends LazyModuleImp(wrapper)
64  with HasXSParameter
65  with HasCircularQueuePtrHelper
66  with HasPerfEvents
67{
68  val pcMemRdIndexes = new NamedIndexes(Seq(
69    "redirect"  -> 1,
70    "memPred"   -> 1,
71    "robFlush"  -> 1,
72    "load"      -> params.LduCnt,
73    "hybrid"    -> params.HyuCnt,
74    "store"     -> (if(EnableStorePrefetchSMS) params.StaCnt else 0)
75  ))
76
77  private val numPcMemReadForExu = params.numPcReadPort
78  private val numPcMemRead = pcMemRdIndexes.maxIdx
79
80  // now pcMem read for exu is moved to PcTargetMem (OG0)
81  println(s"pcMem read num: $numPcMemRead")
82  println(s"pcMem read num for exu: $numPcMemReadForExu")
83
84  val io = IO(new CtrlBlockIO())
85
86  val gpaMem = wrapper.gpaMem.module
87  val decode = Module(new DecodeStage)
88  val fusionDecoder = Module(new FusionDecoder)
89  val rat = Module(new RenameTableWrapper)
90  val rename = Module(new Rename)
91  val dispatch = Module(new Dispatch)
92  val intDq0 = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth/2, dqIndex = 0))
93  val intDq1 = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth/2, dqIndex = 1))
94  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.VecDqDeqWidth))
95  val vecDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.VecDqDeqWidth))
96  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
97  val redirectGen = Module(new RedirectGenerator)
98  private def hasRen: Boolean = true
99  private val pcMem = Module(new SyncDataModuleTemplate(new Ftq_RF_Components, FtqSize, numPcMemRead, 1, "BackendPC", hasRen = hasRen))
100  private val rob = wrapper.rob.module
101  private val memCtrl = Module(new MemCtrl(params))
102
103  private val disableFusion = decode.io.csrCtrl.singlestep || !decode.io.csrCtrl.fusion_enable
104
105  private val s0_robFlushRedirect = rob.io.flushOut
106  private val s1_robFlushRedirect = Wire(Valid(new Redirect))
107  s1_robFlushRedirect.valid := GatedValidRegNext(s0_robFlushRedirect.valid, false.B)
108  s1_robFlushRedirect.bits := RegEnable(s0_robFlushRedirect.bits, s0_robFlushRedirect.valid)
109
110  pcMem.io.ren.get(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.valid
111  pcMem.io.raddr(pcMemRdIndexes("robFlush").head) := s0_robFlushRedirect.bits.ftqIdx.value
112  private val s1_robFlushPc = pcMem.io.rdata(pcMemRdIndexes("robFlush").head).getPc(RegEnable(s0_robFlushRedirect.bits.ftqOffset, s0_robFlushRedirect.valid))
113  private val s3_redirectGen = redirectGen.io.stage2Redirect
114  private val s1_s3_redirect = Mux(s1_robFlushRedirect.valid, s1_robFlushRedirect, s3_redirectGen)
115  private val s2_s4_pendingRedirectValid = RegInit(false.B)
116  when (s1_s3_redirect.valid) {
117    s2_s4_pendingRedirectValid := true.B
118  }.elsewhen (GatedValidRegNext(io.frontend.toFtq.redirect.valid)) {
119    s2_s4_pendingRedirectValid := false.B
120  }
121
122  // Redirect will be RegNext at ExuBlocks and IssueBlocks
123  val s2_s4_redirect = RegNextWithEnable(s1_s3_redirect)
124  val s3_s5_redirect = RegNextWithEnable(s2_s4_redirect)
125
126  private val delayedNotFlushedWriteBack = io.fromWB.wbData.map(x => {
127    val valid = x.valid
128    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
129    val delayed = Wire(Valid(new ExuOutput(x.bits.params)))
130    delayed.valid := GatedValidRegNext(valid && !killedByOlder)
131    delayed.bits := RegEnable(x.bits, x.valid)
132    delayed.bits.debugInfo.writebackTime := GTimer()
133    delayed
134  }).toSeq
135  private val delayedWriteBack = Wire(chiselTypeOf(io.fromWB.wbData))
136  delayedWriteBack.zipWithIndex.map{ case (x,i) =>
137    x.valid := GatedValidRegNext(io.fromWB.wbData(i).valid)
138    x.bits := delayedNotFlushedWriteBack(i).bits
139  }
140  val delayedNotFlushedWriteBackNeedFlush = Wire(Vec(params.allExuParams.filter(_.needExceptionGen).length, Bool()))
141  delayedNotFlushedWriteBackNeedFlush := delayedNotFlushedWriteBack.filter(_.bits.params.needExceptionGen).map{ x =>
142    x.bits.exceptionVec.get.asUInt.orR || x.bits.flushPipe.getOrElse(false.B) || x.bits.replay.getOrElse(false.B) ||
143      (if (x.bits.trigger.nonEmpty) x.bits.trigger.get.getBackendCanFire else false.B)
144  }
145
146  val wbDataNoStd = io.fromWB.wbData.filter(!_.bits.params.hasStdFu)
147  val intScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[IntScheduler])
148  val fpScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[FpScheduler])
149  val vfScheWbData = io.fromWB.wbData.filter(_.bits.params.schdType.isInstanceOf[VfScheduler])
150  val intCanCompress = intScheWbData.filter(_.bits.params.CanCompress)
151  val i2vWbData = intScheWbData.filter(_.bits.params.writeVecRf)
152  val f2vWbData = fpScheWbData.filter(_.bits.params.writeVecRf)
153  val memVloadWbData = io.fromWB.wbData.filter(x => x.bits.params.schdType.isInstanceOf[MemScheduler] && x.bits.params.hasVLoadFu)
154  private val delayedNotFlushedWriteBackNums = wbDataNoStd.map(x => {
155    val valid = x.valid
156    val killedByOlder = x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
157    val delayed = Wire(Valid(UInt(io.fromWB.wbData.size.U.getWidth.W)))
158    delayed.valid := GatedValidRegNext(valid && !killedByOlder)
159    val isIntSche = intCanCompress.contains(x)
160    val isFpSche = fpScheWbData.contains(x)
161    val isVfSche = vfScheWbData.contains(x)
162    val isMemVload = memVloadWbData.contains(x)
163    val isi2v = i2vWbData.contains(x)
164    val isf2v = f2vWbData.contains(x)
165    val canSameRobidxWbData = if(isVfSche) {
166      i2vWbData ++ f2vWbData ++ vfScheWbData
167    } else if(isi2v) {
168      intCanCompress ++ fpScheWbData ++ vfScheWbData
169    } else if (isf2v) {
170      intCanCompress ++ fpScheWbData ++ vfScheWbData
171    } else if (isIntSche) {
172      intCanCompress ++ fpScheWbData
173    } else if (isFpSche) {
174      intCanCompress ++ fpScheWbData
175    }  else if (isMemVload) {
176      memVloadWbData
177    } else {
178      Seq(x)
179    }
180    val sameRobidxBools = VecInit(canSameRobidxWbData.map( wb => {
181      val killedByOlderThat = wb.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect, s3_s5_redirect))
182      (wb.bits.robIdx === x.bits.robIdx) && wb.valid && x.valid && !killedByOlderThat && !killedByOlder
183    }).toSeq)
184    delayed.bits := RegEnable(PopCount(sameRobidxBools), x.valid)
185    delayed
186  }).toSeq
187
188  private val exuPredecode = VecInit(
189    io.fromWB.wbData.filter(_.bits.redirect.nonEmpty).map(x => x.bits.predecodeInfo.get).toSeq
190  )
191
192  private val exuRedirects: Seq[ValidIO[Redirect]] = io.fromWB.wbData.filter(_.bits.redirect.nonEmpty).map(x => {
193    val out = Wire(Valid(new Redirect()))
194    out.valid := x.valid && x.bits.redirect.get.valid && x.bits.redirect.get.bits.cfiUpdate.isMisPred && !x.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
195    out.bits := x.bits.redirect.get.bits
196    out.bits.debugIsCtrl := true.B
197    out.bits.debugIsMemVio := false.B
198    out
199  }).toSeq
200  private val oldestOneHot = Redirect.selectOldestRedirect(exuRedirects)
201  private val oldestExuRedirect = Mux1H(oldestOneHot, exuRedirects)
202  private val oldestExuPredecode = Mux1H(oldestOneHot, exuPredecode)
203
204  private val memViolation = io.fromMem.violation
205  val loadReplay = Wire(ValidIO(new Redirect))
206  loadReplay.valid := GatedValidRegNext(memViolation.valid)
207  loadReplay.bits := RegEnable(memViolation.bits, memViolation.valid)
208  loadReplay.bits.debugIsCtrl := false.B
209  loadReplay.bits.debugIsMemVio := true.B
210
211  pcMem.io.ren.get(pcMemRdIndexes("redirect").head) := memViolation.valid
212  pcMem.io.raddr(pcMemRdIndexes("redirect").head) := memViolation.bits.ftqIdx.value
213  pcMem.io.ren.get(pcMemRdIndexes("memPred").head) := memViolation.valid
214  pcMem.io.raddr(pcMemRdIndexes("memPred").head) := memViolation.bits.stFtqIdx.value
215  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(pcMemRdIndexes("memPred").head).getPc(RegEnable(memViolation.bits.stFtqOffset, memViolation.valid))
216
217  for ((pcMemIdx, i) <- pcMemRdIndexes("load").zipWithIndex) {
218    // load read pcMem (s0) -> get rdata (s1) -> reg next in Memblock (s2) -> reg next in Memblock (s3) -> consumed by pf (s3)
219    pcMem.io.ren.get(pcMemIdx) := io.memLdPcRead(i).valid
220    pcMem.io.raddr(pcMemIdx) := io.memLdPcRead(i).ptr.value
221    io.memLdPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegEnable(io.memLdPcRead(i).offset, io.memLdPcRead(i).valid))
222  }
223
224  for ((pcMemIdx, i) <- pcMemRdIndexes("hybrid").zipWithIndex) {
225    // load read pcMem (s0) -> get rdata (s1) -> reg next in Memblock (s2) -> reg next in Memblock (s3) -> consumed by pf (s3)
226    pcMem.io.ren.get(pcMemIdx) := io.memHyPcRead(i).valid
227    pcMem.io.raddr(pcMemIdx) := io.memHyPcRead(i).ptr.value
228    io.memHyPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegEnable(io.memHyPcRead(i).offset, io.memHyPcRead(i).valid))
229  }
230
231  if (EnableStorePrefetchSMS) {
232    for ((pcMemIdx, i) <- pcMemRdIndexes("store").zipWithIndex) {
233      pcMem.io.ren.get(pcMemIdx) := io.memStPcRead(i).valid
234      pcMem.io.raddr(pcMemIdx) := io.memStPcRead(i).ptr.value
235      io.memStPcRead(i).data := pcMem.io.rdata(pcMemIdx).getPc(RegEnable(io.memStPcRead(i).offset, io.memStPcRead(i).valid))
236    }
237  } else {
238    io.memStPcRead.foreach(_.data := 0.U)
239  }
240
241  redirectGen.io.hartId := io.fromTop.hartId
242  redirectGen.io.oldestExuRedirect.valid := GatedValidRegNext(oldestExuRedirect.valid)
243  redirectGen.io.oldestExuRedirect.bits := RegEnable(oldestExuRedirect.bits, oldestExuRedirect.valid)
244  redirectGen.io.oldestExuOutPredecode.valid := GatedValidRegNext(oldestExuPredecode.valid)
245  redirectGen.io.oldestExuOutPredecode := RegEnable(oldestExuPredecode, oldestExuPredecode.valid)
246  redirectGen.io.loadReplay <> loadReplay
247  val loadRedirectPcRead = pcMem.io.rdata(pcMemRdIndexes("redirect").head).getPc(RegEnable(memViolation.bits.ftqOffset, memViolation.valid))
248  redirectGen.io.loadReplay.bits.cfiUpdate.pc := loadRedirectPcRead
249  val load_pc_offset = Mux(loadReplay.bits.flushItself(), 0.U, Mux(loadReplay.bits.isRVC, 2.U, 4.U))
250  val load_target = loadRedirectPcRead + load_pc_offset
251  redirectGen.io.loadReplay.bits.cfiUpdate.target := load_target
252
253  redirectGen.io.robFlush := s1_robFlushRedirect
254
255  val s5_flushFromRobValidAhead = DelayN(s1_robFlushRedirect.valid, 4)
256  val s6_flushFromRobValid = GatedValidRegNext(s5_flushFromRobValidAhead)
257  val frontendFlushBits = RegEnable(s1_robFlushRedirect.bits, s1_robFlushRedirect.valid) // ??
258  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
259  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
260  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
261  for (i <- 0 until CommitWidth) {
262    // why flushOut: instructions with flushPipe are not commited to frontend
263    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
264    val s1_isCommit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !s0_robFlushRedirect.valid
265    io.frontend.toFtq.rob_commits(i).valid := GatedValidRegNext(s1_isCommit)
266    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), s1_isCommit)
267  }
268  io.frontend.toFtq.redirect.valid := s6_flushFromRobValid || s3_redirectGen.valid
269  io.frontend.toFtq.redirect.bits := Mux(s6_flushFromRobValid, frontendFlushBits, s3_redirectGen.bits)
270  io.frontend.toFtq.ftqIdxSelOH.valid := s6_flushFromRobValid || redirectGen.io.stage2Redirect.valid
271  io.frontend.toFtq.ftqIdxSelOH.bits := Cat(s6_flushFromRobValid, redirectGen.io.stage2oldestOH & Fill(NumRedirect + 1, !s6_flushFromRobValid))
272
273  //jmp/brh, sel oldest first, only use one read port
274  io.frontend.toFtq.ftqIdxAhead(0).valid := RegNext(oldestExuRedirect.valid) && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
275  io.frontend.toFtq.ftqIdxAhead(0).bits := RegEnable(oldestExuRedirect.bits.ftqIdx, oldestExuRedirect.valid)
276  //loadreplay
277  io.frontend.toFtq.ftqIdxAhead(NumRedirect).valid := loadReplay.valid && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
278  io.frontend.toFtq.ftqIdxAhead(NumRedirect).bits := loadReplay.bits.ftqIdx
279  //exception
280  io.frontend.toFtq.ftqIdxAhead.last.valid := s5_flushFromRobValidAhead
281  io.frontend.toFtq.ftqIdxAhead.last.bits := frontendFlushBits.ftqIdx
282
283  io.frontend.canAccept := decode.io.canAccept
284
285  // Be careful here:
286  // T0: rob.io.flushOut, s0_robFlushRedirect
287  // T1: s1_robFlushRedirect, rob.io.exception.valid
288  // T2: csr.redirect.valid
289  // T3: csr.exception.valid
290  // T4: csr.trapTarget
291  // T5: ctrlBlock.trapTarget
292  // T6: io.frontend.toFtq.stage2Redirect.valid
293  val s2_robFlushPc = RegEnable(Mux(s1_robFlushRedirect.bits.flushItself(),
294    s1_robFlushPc, // replay inst
295    s1_robFlushPc + Mux(s1_robFlushRedirect.bits.isRVC, 2.U, 4.U) // flush pipe
296  ), s1_robFlushRedirect.valid)
297  private val s5_csrIsTrap = DelayN(rob.io.exception.valid, 4)
298  private val s5_trapTargetFromCsr = io.robio.csr.trapTarget
299
300  val flushTarget = Mux(s5_csrIsTrap, s5_trapTargetFromCsr, s2_robFlushPc)
301  when (s6_flushFromRobValid) {
302    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
303    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegEnable(flushTarget, s5_flushFromRobValidAhead)
304  }
305
306  for (i <- 0 until DecodeWidth) {
307    gpaMem.io.fromIFU := io.frontend.fromIfu
308    gpaMem.io.exceptionReadAddr.valid := rob.io.readGPAMemAddr.valid
309    gpaMem.io.exceptionReadAddr.bits.ftqPtr := rob.io.readGPAMemAddr.bits.ftqPtr
310    gpaMem.io.exceptionReadAddr.bits.ftqOffset := rob.io.readGPAMemAddr.bits.ftqOffset
311  }
312
313  // vtype commit
314  decode.io.fromCSR := io.fromCSR.toDecode
315  decode.io.isResumeVType := rob.io.toDecode.isResumeVType
316  decode.io.commitVType := rob.io.toDecode.commitVType
317  decode.io.walkVType := rob.io.toDecode.walkVType
318
319  decode.io.redirect := s1_s3_redirect.valid || s2_s4_pendingRedirectValid
320  decode.io.vtypeRedirect := s1_s3_redirect.valid
321
322  decode.io.in.zip(io.frontend.cfVec).foreach { case (decodeIn, frontendCf) =>
323    decodeIn.valid := frontendCf.valid
324    frontendCf.ready := decodeIn.ready
325    decodeIn.bits.connectCtrlFlow(frontendCf.bits)
326  }
327  decode.io.csrCtrl := RegNext(io.csrCtrl)
328  decode.io.intRat <> rat.io.intReadPorts
329  decode.io.fpRat <> rat.io.fpReadPorts
330  decode.io.vecRat <> rat.io.vecReadPorts
331  decode.io.v0Rat <> rat.io.v0ReadPorts
332  decode.io.vlRat <> rat.io.vlReadPorts
333  decode.io.fusion := 0.U.asTypeOf(decode.io.fusion) // Todo
334  decode.io.stallReason.in <> io.frontend.stallReason
335
336  // snapshot check
337  class CFIRobIdx extends Bundle {
338    val robIdx = Vec(RenameWidth, new RobPtr)
339    val isCFI = Vec(RenameWidth, Bool())
340  }
341  val genSnapshot = Cat(rename.io.out.map(out => out.fire && out.bits.snapshot)).orR
342  val snpt = Module(new SnapshotGenerator(0.U.asTypeOf(new CFIRobIdx)))
343  snpt.io.enq := genSnapshot
344  snpt.io.enqData.robIdx := rename.io.out.map(_.bits.robIdx)
345  snpt.io.enqData.isCFI := rename.io.out.map(_.bits.snapshot)
346  snpt.io.deq := snpt.io.valids(snpt.io.deqPtr.value) && rob.io.commits.isCommit &&
347    Cat(rob.io.commits.commitValid.zip(rob.io.commits.robIdx).map(x => x._1 && x._2 === snpt.io.snapshots(snpt.io.deqPtr.value).robIdx.head)).orR
348  snpt.io.redirect := s1_s3_redirect.valid
349  val flushVec = VecInit(snpt.io.snapshots.map { snapshot =>
350    val notCFIMask = snapshot.isCFI.map(~_)
351    val shouldFlush = snapshot.robIdx.map(robIdx => robIdx >= s1_s3_redirect.bits.robIdx || robIdx.value === s1_s3_redirect.bits.robIdx.value)
352    val shouldFlushMask = (1 to RenameWidth).map(shouldFlush take _ reduce (_ || _))
353    s1_s3_redirect.valid && Cat(shouldFlushMask.zip(notCFIMask).map(x => x._1 | x._2)).andR
354  })
355  val flushVecNext = flushVec zip snpt.io.valids map (x => GatedValidRegNext(x._1 && x._2, false.B))
356  snpt.io.flushVec := flushVecNext
357
358  val useSnpt = VecInit.tabulate(RenameSnapshotNum)(idx =>
359    snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
360      !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head)
361  ).reduceTree(_ || _)
362  val snptSelect = MuxCase(
363    0.U(log2Ceil(RenameSnapshotNum).W),
364    (1 to RenameSnapshotNum).map(i => (snpt.io.enqPtr - i.U).value).map(idx =>
365      (snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
366        !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head), idx)
367    )
368  )
369
370  rob.io.snpt.snptEnq := DontCare
371  rob.io.snpt.snptDeq := snpt.io.deq
372  rob.io.snpt.useSnpt := useSnpt
373  rob.io.snpt.snptSelect := snptSelect
374  rob.io.snpt.flushVec := flushVecNext
375  rat.io.snpt.snptEnq := genSnapshot
376  rat.io.snpt.snptDeq := snpt.io.deq
377  rat.io.snpt.useSnpt := useSnpt
378  rat.io.snpt.snptSelect := snptSelect
379  rat.io.snpt.flushVec := flushVec
380
381  val decodeHasException = decode.io.out.map(x => x.bits.exceptionVec(instrPageFault) || x.bits.exceptionVec(instrAccessFault))
382  // fusion decoder
383  for (i <- 0 until DecodeWidth) {
384    fusionDecoder.io.in(i).valid := decode.io.out(i).valid && !(decodeHasException(i) || disableFusion)
385    fusionDecoder.io.in(i).bits := decode.io.out(i).bits.instr
386    if (i > 0) {
387      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
388    }
389  }
390
391  private val decodePipeRename = Wire(Vec(RenameWidth, DecoupledIO(new DecodedInst)))
392
393  for (i <- 0 until RenameWidth) {
394    PipelineConnect(decode.io.out(i), decodePipeRename(i), rename.io.in(i).ready,
395      s1_s3_redirect.valid || s2_s4_pendingRedirectValid, moduleName = Some("decodePipeRenameModule"))
396
397    decodePipeRename(i).ready := rename.io.in(i).ready
398    rename.io.in(i).valid := decodePipeRename(i).valid && !fusionDecoder.io.clear(i)
399    rename.io.in(i).bits := decodePipeRename(i).bits
400  }
401
402  for (i <- 0 until RenameWidth - 1) {
403    fusionDecoder.io.dec(i) := decodePipeRename(i).bits
404    rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
405
406    // update the first RenameWidth - 1 instructions
407    decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
408    when (fusionDecoder.io.out(i).valid) {
409      fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits)
410      // TODO: remove this dirty code for ftq update
411      val sameFtqPtr = rename.io.in(i).bits.ftqPtr.value === rename.io.in(i + 1).bits.ftqPtr.value
412      val ftqOffset0 = rename.io.in(i).bits.ftqOffset
413      val ftqOffset1 = rename.io.in(i + 1).bits.ftqOffset
414      val ftqOffsetDiff = ftqOffset1 - ftqOffset0
415      val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
416      val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
417      val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
418      val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
419      rename.io.in(i).bits.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
420      XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
421    }
422
423  }
424
425  // memory dependency predict
426  // when decode, send fold pc to mdp
427  private val mdpFlodPcVecVld = Wire(Vec(DecodeWidth, Bool()))
428  private val mdpFlodPcVec = Wire(Vec(DecodeWidth, UInt(MemPredPCWidth.W)))
429  for (i <- 0 until DecodeWidth) {
430    mdpFlodPcVecVld(i) := decode.io.out(i).fire || GatedValidRegNext(decode.io.out(i).fire)
431    mdpFlodPcVec(i) := Mux(
432      decode.io.out(i).fire,
433      decode.io.in(i).bits.foldpc,
434      rename.io.in(i).bits.foldpc
435    )
436  }
437
438  // currently, we only update mdp info when isReplay
439  memCtrl.io.redirect := s1_s3_redirect
440  memCtrl.io.csrCtrl := io.csrCtrl                          // RegNext in memCtrl
441  memCtrl.io.stIn := io.fromMem.stIn                        // RegNext in memCtrl
442  memCtrl.io.memPredUpdate := redirectGen.io.memPredUpdate  // RegNext in memCtrl
443  memCtrl.io.mdpFoldPcVecVld := mdpFlodPcVecVld
444  memCtrl.io.mdpFlodPcVec := mdpFlodPcVec
445  memCtrl.io.dispatchLFSTio <> dispatch.io.lfst
446
447  rat.io.redirect := s1_s3_redirect.valid
448  rat.io.rabCommits := rob.io.rabCommits
449  rat.io.diffCommits.foreach(_ := rob.io.diffCommits.get)
450  rat.io.intRenamePorts := rename.io.intRenamePorts
451  rat.io.fpRenamePorts := rename.io.fpRenamePorts
452  rat.io.vecRenamePorts := rename.io.vecRenamePorts
453  rat.io.v0RenamePorts := rename.io.v0RenamePorts
454  rat.io.vlRenamePorts := rename.io.vlRenamePorts
455
456  rename.io.redirect := s1_s3_redirect
457  rename.io.rabCommits := rob.io.rabCommits
458  rename.io.waittable := (memCtrl.io.waitTable2Rename zip decode.io.out).map{ case(waittable2rename, decodeOut) =>
459    RegEnable(waittable2rename, decodeOut.fire)
460  }
461  rename.io.ssit := memCtrl.io.ssit2Rename
462  rename.io.intReadPorts := VecInit(rat.io.intReadPorts.map(x => VecInit(x.map(_.data))))
463  rename.io.fpReadPorts := VecInit(rat.io.fpReadPorts.map(x => VecInit(x.map(_.data))))
464  rename.io.vecReadPorts := VecInit(rat.io.vecReadPorts.map(x => VecInit(x.map(_.data))))
465  rename.io.v0ReadPorts := VecInit(rat.io.v0ReadPorts.map(x => VecInit(x.data)))
466  rename.io.vlReadPorts := VecInit(rat.io.vlReadPorts.map(x => VecInit(x.data)))
467  rename.io.int_need_free := rat.io.int_need_free
468  rename.io.int_old_pdest := rat.io.int_old_pdest
469  rename.io.fp_old_pdest := rat.io.fp_old_pdest
470  rename.io.vec_old_pdest := rat.io.vec_old_pdest
471  rename.io.v0_old_pdest := rat.io.v0_old_pdest
472  rename.io.vl_old_pdest := rat.io.vl_old_pdest
473  rename.io.debug_int_rat.foreach(_ := rat.io.debug_int_rat.get)
474  rename.io.debug_fp_rat.foreach(_ := rat.io.debug_fp_rat.get)
475  rename.io.debug_vec_rat.foreach(_ := rat.io.debug_vec_rat.get)
476  rename.io.debug_v0_rat.foreach(_ := rat.io.debug_v0_rat.get)
477  rename.io.debug_vl_rat.foreach(_ := rat.io.debug_vl_rat.get)
478  rename.io.stallReason.in <> decode.io.stallReason.out
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  rename.io.snptIsFull := snpt.io.valids.asUInt.andR
484  rename.io.snpt.flushVec := flushVecNext
485  rename.io.snptLastEnq.valid := !isEmpty(snpt.io.enqPtr, snpt.io.deqPtr)
486  rename.io.snptLastEnq.bits := snpt.io.snapshots((snpt.io.enqPtr - 1.U).value).robIdx.head
487
488  val renameOut = Wire(chiselTypeOf(rename.io.out))
489  renameOut <> rename.io.out
490  // pass all snapshot in the first element for correctness of blockBackward
491  renameOut.tail.foreach(_.bits.snapshot := false.B)
492  renameOut.head.bits.snapshot := Mux(isFull(snpt.io.enqPtr, snpt.io.deqPtr),
493    false.B,
494    Cat(rename.io.out.map(out => out.valid && out.bits.snapshot)).orR
495  )
496
497  // pipeline between rename and dispatch
498  PipeGroupConnect(renameOut, dispatch.io.fromRename, s1_s3_redirect.valid, dispatch.io.toRenameAllFire, "renamePipeDispatch")
499  dispatch.io.intIQValidNumVec := io.intIQValidNumVec
500  dispatch.io.fpIQValidNumVec := io.fpIQValidNumVec
501  dispatch.io.fromIntDQ.intDQ0ValidDeq0Num := intDq0.io.validDeq0Num
502  dispatch.io.fromIntDQ.intDQ0ValidDeq1Num := intDq0.io.validDeq1Num
503  dispatch.io.fromIntDQ.intDQ1ValidDeq0Num := intDq1.io.validDeq0Num
504  dispatch.io.fromIntDQ.intDQ1ValidDeq1Num := intDq1.io.validDeq1Num
505
506  dispatch.io.hartId := io.fromTop.hartId
507  dispatch.io.redirect := s1_s3_redirect
508  dispatch.io.enqRob <> rob.io.enq
509  dispatch.io.robHead := rob.io.debugRobHead
510  dispatch.io.stallReason <> rename.io.stallReason.out
511  dispatch.io.lqCanAccept := io.lqCanAccept
512  dispatch.io.sqCanAccept := io.sqCanAccept
513  dispatch.io.robHeadNotReady := rob.io.headNotReady
514  dispatch.io.robFull := rob.io.robFull
515  dispatch.io.singleStep := GatedValidRegNext(io.csrCtrl.singlestep)
516
517  intDq0.io.enq <> dispatch.io.toIntDq0
518  intDq0.io.redirect <> s2_s4_redirect
519  intDq1.io.enq <> dispatch.io.toIntDq1
520  intDq1.io.redirect <> s2_s4_redirect
521
522  fpDq.io.enq <> dispatch.io.toFpDq
523  fpDq.io.redirect <> s2_s4_redirect
524
525  vecDq.io.enq <> dispatch.io.toVecDq
526  vecDq.io.redirect <> s2_s4_redirect
527
528  lsDq.io.enq <> dispatch.io.toLsDq
529  lsDq.io.redirect <> s2_s4_redirect
530
531  io.toIssueBlock.intUops <> (intDq0.io.deq :++ intDq1.io.deq)
532  io.toIssueBlock.fpUops <> fpDq.io.deq
533  io.toIssueBlock.vfUops  <> vecDq.io.deq
534  io.toIssueBlock.memUops <> lsDq.io.deq
535  io.toIssueBlock.allocPregs <> dispatch.io.allocPregs
536  io.toIssueBlock.flush   <> s2_s4_redirect
537
538  pcMem.io.wen.head   := GatedValidRegNext(io.frontend.fromFtq.pc_mem_wen)
539  pcMem.io.waddr.head := RegEnable(io.frontend.fromFtq.pc_mem_waddr.value, io.frontend.fromFtq.pc_mem_wen)
540  pcMem.io.wdata.head := RegEnable(io.frontend.fromFtq.pc_mem_wdata, io.frontend.fromFtq.pc_mem_wen)
541
542  io.toDataPath.flush := s2_s4_redirect
543  io.toExuBlock.flush := s2_s4_redirect
544
545
546  rob.io.hartId := io.fromTop.hartId
547  rob.io.redirect := s1_s3_redirect
548  rob.io.writeback := delayedNotFlushedWriteBack
549  rob.io.exuWriteback := delayedWriteBack
550  rob.io.writebackNums := VecInit(delayedNotFlushedWriteBackNums)
551  rob.io.writebackNeedFlush := delayedNotFlushedWriteBackNeedFlush
552  rob.io.readGPAMemData := gpaMem.io.exceptionReadData
553
554  io.redirect := s1_s3_redirect
555
556  // rob to int block
557  io.robio.csr <> rob.io.csr
558  // When wfi is disabled, it will not block ROB commit.
559  rob.io.csr.wfiEvent := io.robio.csr.wfiEvent
560  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
561
562  io.toTop.cpuHalt := DelayN(rob.io.cpu_halt, 5)
563
564  io.robio.csr.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
565  io.robio.exception := rob.io.exception
566  io.robio.exception.bits.pc := s1_robFlushPc
567
568  // rob to mem block
569  io.robio.lsq <> rob.io.lsq
570
571  io.debug_int_rat    .foreach(_ := rat.io.diff_int_rat.get)
572  io.debug_fp_rat     .foreach(_ := rat.io.diff_fp_rat.get)
573  io.debug_vec_rat    .foreach(_ := rat.io.diff_vec_rat.get)
574  io.debug_v0_rat.foreach(_ := rat.io.diff_v0_rat.get)
575  io.debug_vl_rat.foreach(_ := rat.io.diff_vl_rat.get)
576
577  rob.io.debug_ls := io.robio.debug_ls
578  rob.io.debugHeadLsIssue := io.robio.robHeadLsIssue
579  rob.io.lsTopdownInfo := io.robio.lsTopdownInfo
580  rob.io.debugEnqLsq := io.debugEnqLsq
581
582  io.robio.robDeqPtr := rob.io.robDeqPtr
583
584  // rob to backend
585  io.robio.commitVType := rob.io.toDecode.commitVType
586  // exu block to decode
587  decode.io.vsetvlVType := io.toDecode.vsetvlVType
588  // backend to decode
589  decode.io.vstart := io.toDecode.vstart
590  // backend to rob
591  rob.io.vstartIsZero := io.toDecode.vstart === 0.U
592
593  io.debugTopDown.fromRob := rob.io.debugTopDown.toCore
594  dispatch.io.debugTopDown.fromRob := rob.io.debugTopDown.toDispatch
595  dispatch.io.debugTopDown.fromCore := io.debugTopDown.fromCore
596  io.debugRolling := rob.io.debugRolling
597
598  io.perfInfo.ctrlInfo.robFull := GatedValidRegNext(rob.io.robFull)
599  io.perfInfo.ctrlInfo.intdqFull := GatedValidRegNext(intDq0.io.dqFull || intDq1.io.dqFull)
600  io.perfInfo.ctrlInfo.fpdqFull := GatedValidRegNext(vecDq.io.dqFull)
601  io.perfInfo.ctrlInfo.lsdqFull := GatedValidRegNext(lsDq.io.dqFull)
602
603  val perfEvents = Seq(decode, rename, dispatch, intDq0, intDq1, vecDq, lsDq, rob).flatMap(_.getPerfEvents)
604  generatePerfEvent()
605}
606
607class CtrlBlockIO()(implicit p: Parameters, params: BackendParams) extends XSBundle {
608  val fromTop = new Bundle {
609    val hartId = Input(UInt(8.W))
610  }
611  val toTop = new Bundle {
612    val cpuHalt = Output(Bool())
613  }
614  val frontend = Flipped(new FrontendToCtrlIO())
615  val fromCSR = new Bundle{
616    val toDecode = Input(new CSRToDecode)
617  }
618  val toIssueBlock = new Bundle {
619    val flush = ValidIO(new Redirect)
620    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
621    val intUops = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new DynInst))
622    val vfUops = Vec(dpParams.VecDqDeqWidth, DecoupledIO(new DynInst))
623    val fpUops = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new DynInst))
624    val memUops = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new DynInst))
625  }
626  val toDataPath = new Bundle {
627    val flush = ValidIO(new Redirect)
628  }
629  val toExuBlock = new Bundle {
630    val flush = ValidIO(new Redirect)
631  }
632  val intIQValidNumVec = Input(MixedVec(params.genIntIQValidNumBundle))
633  val fpIQValidNumVec = Input(MixedVec(params.genFpIQValidNumBundle))
634  val fromWB = new Bundle {
635    val wbData = Flipped(MixedVec(params.genWrite2CtrlBundles))
636  }
637  val redirect = ValidIO(new Redirect)
638  val fromMem = new Bundle {
639    val stIn = Vec(params.StaExuCnt, Flipped(ValidIO(new DynInst))) // use storeSetHit, ssid, robIdx
640    val violation = Flipped(ValidIO(new Redirect))
641  }
642  val memLdPcRead = Vec(params.LduCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
643  val memStPcRead = Vec(params.StaCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
644  val memHyPcRead = Vec(params.HyuCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
645
646  val csrCtrl = Input(new CustomCSRCtrlIO)
647  val robio = new Bundle {
648    val csr = new RobCSRIO
649    val exception = ValidIO(new ExceptionInfo)
650    val lsq = new RobLsqIO
651    val lsTopdownInfo = Vec(params.LduCnt + params.HyuCnt, Input(new LsTopdownInfo))
652    val debug_ls = Input(new DebugLSIO())
653    val robHeadLsIssue = Input(Bool())
654    val robDeqPtr = Output(new RobPtr)
655    val commitVType = new Bundle {
656      val vtype = Output(ValidIO(VType()))
657      val hasVsetvl = Output(Bool())
658    }
659  }
660
661  val toDecode = new Bundle {
662    val vsetvlVType = Input(VType())
663    val vstart = Input(Vl())
664  }
665
666  val perfInfo = Output(new Bundle{
667    val ctrlInfo = new Bundle {
668      val robFull   = Bool()
669      val intdqFull = Bool()
670      val fpdqFull  = Bool()
671      val lsdqFull  = Bool()
672    }
673  })
674  val debug_int_rat     = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
675  val debug_fp_rat      = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
676  val debug_vec_rat     = if (params.debugEn) Some(Vec(31, Output(UInt(PhyRegIdxWidth.W)))) else None
677  val debug_v0_rat      = if (params.debugEn) Some(Vec(1, Output(UInt(PhyRegIdxWidth.W)))) else None
678  val debug_vl_rat      = if (params.debugEn) Some(Vec(1, Output(UInt(PhyRegIdxWidth.W)))) else None
679
680  val sqCanAccept = Input(Bool())
681  val lqCanAccept = Input(Bool())
682
683  val debugTopDown = new Bundle {
684    val fromRob = new RobCoreTopDownIO
685    val fromCore = new CoreDispatchTopDownIO
686  }
687  val debugRolling = new RobDebugRollingIO
688  val debugEnqLsq = Input(new LsqEnqIO)
689}
690
691class NamedIndexes(namedCnt: Seq[(String, Int)]) {
692  require(namedCnt.map(_._1).distinct.size == namedCnt.size, "namedCnt should not have the same name")
693
694  val maxIdx = namedCnt.map(_._2).sum
695  val nameRangeMap: Map[String, (Int, Int)] = namedCnt.indices.map { i =>
696    val begin = namedCnt.slice(0, i).map(_._2).sum
697    val end = begin + namedCnt(i)._2
698    (namedCnt(i)._1, (begin, end))
699  }.toMap
700
701  def apply(name: String): Seq[Int] = {
702    require(nameRangeMap.contains(name))
703    nameRangeMap(name)._1 until nameRangeMap(name)._2
704  }
705}
706