xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision b03c55a5df5dc8793cb44b42dd60141566e57e78)
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, s3_s5_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    delayedNotFlushedWriteBack.filter(_.bits.redirect.nonEmpty).map(x => x.bits.predecodeInfo.get).toSeq
190  )
191
192  private val exuRedirects: Seq[ValidIO[Redirect]] = delayedNotFlushedWriteBack.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
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
201  private val memViolation = io.fromMem.violation
202  val loadReplay = Wire(ValidIO(new Redirect))
203  loadReplay.valid := GatedValidRegNext(memViolation.valid &&
204    !memViolation.bits.robIdx.needFlush(Seq(s1_s3_redirect, s2_s4_redirect))
205  )
206  loadReplay.bits := RegEnable(memViolation.bits, memViolation.valid)
207  loadReplay.bits.debugIsCtrl := false.B
208  loadReplay.bits.debugIsMemVio := true.B
209
210  pcMem.io.ren.get(pcMemRdIndexes("redirect").head) := redirectGen.io.redirectPcRead.vld
211  pcMem.io.raddr(pcMemRdIndexes("redirect").head) := redirectGen.io.redirectPcRead.ptr.value
212  redirectGen.io.redirectPcRead.data := pcMem.io.rdata(pcMemRdIndexes("redirect").head).getPc(RegEnable(redirectGen.io.redirectPcRead.offset, redirectGen.io.redirectPcRead.vld))
213  pcMem.io.ren.get(pcMemRdIndexes("memPred").head) := redirectGen.io.memPredPcRead.vld
214  pcMem.io.raddr(pcMemRdIndexes("memPred").head) := redirectGen.io.memPredPcRead.ptr.value
215  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(pcMemRdIndexes("memPred").head).getPc(RegEnable(redirectGen.io.memPredPcRead.offset, redirectGen.io.memPredPcRead.vld))
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).vld
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).vld))
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).vld
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).vld))
229  }
230
231  if (EnableStorePrefetchSMS) {
232    for ((pcMemIdx, i) <- pcMemRdIndexes("store").zipWithIndex) {
233      pcMem.io.ren.get(pcMemIdx) := io.memStPcRead(i).vld
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).vld))
236    }
237  } else {
238    io.memStPcRead.foreach(_.data := 0.U)
239  }
240
241  redirectGen.io.hartId := io.fromTop.hartId
242  redirectGen.io.exuRedirect := exuRedirects.toSeq
243  redirectGen.io.exuOutPredecode := exuPredecode // guarded by exuRedirect.valid
244  redirectGen.io.loadReplay <> loadReplay
245
246  redirectGen.io.robFlush := s1_robFlushRedirect.valid
247
248  val s5_flushFromRobValidAhead = DelayN(s1_robFlushRedirect.valid, 4)
249  val s6_flushFromRobValid = GatedValidRegNext(s5_flushFromRobValidAhead)
250  val frontendFlushBits = RegEnable(s1_robFlushRedirect.bits, s1_robFlushRedirect.valid) // ??
251  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
252  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
253  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
254  for (i <- 0 until CommitWidth) {
255    // why flushOut: instructions with flushPipe are not commited to frontend
256    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
257    val s1_isCommit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !s0_robFlushRedirect.valid
258    io.frontend.toFtq.rob_commits(i).valid := GatedValidRegNext(s1_isCommit)
259    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), s1_isCommit)
260  }
261  io.frontend.toFtq.redirect.valid := s6_flushFromRobValid || s3_redirectGen.valid
262  io.frontend.toFtq.redirect.bits := Mux(s6_flushFromRobValid, frontendFlushBits, s3_redirectGen.bits)
263  io.frontend.toFtq.ftqIdxSelOH.valid := s6_flushFromRobValid || redirectGen.io.stage2Redirect.valid
264  io.frontend.toFtq.ftqIdxSelOH.bits := Cat(s6_flushFromRobValid, redirectGen.io.stage2oldestOH & Fill(NumRedirect + 1, !s6_flushFromRobValid))
265
266  //jmp/brh
267  for (i <- 0 until NumRedirect) {
268    io.frontend.toFtq.ftqIdxAhead(i).valid := exuRedirects(i).valid && exuRedirects(i).bits.cfiUpdate.isMisPred && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
269    io.frontend.toFtq.ftqIdxAhead(i).bits := exuRedirects(i).bits.ftqIdx
270  }
271  //loadreplay
272  io.frontend.toFtq.ftqIdxAhead(NumRedirect).valid := loadReplay.valid && !s1_robFlushRedirect.valid && !s5_flushFromRobValidAhead
273  io.frontend.toFtq.ftqIdxAhead(NumRedirect).bits := loadReplay.bits.ftqIdx
274  //exception
275  io.frontend.toFtq.ftqIdxAhead.last.valid := s5_flushFromRobValidAhead
276  io.frontend.toFtq.ftqIdxAhead.last.bits := frontendFlushBits.ftqIdx
277
278  io.frontend.canAccept := decode.io.canAccept
279
280  // Be careful here:
281  // T0: rob.io.flushOut, s0_robFlushRedirect
282  // T1: s1_robFlushRedirect, rob.io.exception.valid
283  // T2: csr.redirect.valid
284  // T3: csr.exception.valid
285  // T4: csr.trapTarget
286  // T5: ctrlBlock.trapTarget
287  // T6: io.frontend.toFtq.stage2Redirect.valid
288  val s2_robFlushPc = RegEnable(Mux(s1_robFlushRedirect.bits.flushItself(),
289    s1_robFlushPc, // replay inst
290    s1_robFlushPc + Mux(s1_robFlushRedirect.bits.isRVC, 2.U, 4.U) // flush pipe
291  ), s1_robFlushRedirect.valid)
292  private val s5_csrIsTrap = DelayN(rob.io.exception.valid, 4)
293  private val s5_trapTargetFromCsr = io.robio.csr.trapTarget
294
295  val flushTarget = Mux(s5_csrIsTrap, s5_trapTargetFromCsr, s2_robFlushPc)
296  when (s6_flushFromRobValid) {
297    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
298    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegEnable(flushTarget, s5_flushFromRobValidAhead)
299  }
300
301  for (i <- 0 until DecodeWidth) {
302    gpaMem.io.fromIFU := io.frontend.fromIfu
303    gpaMem.io.exceptionReadAddr.valid := rob.io.readGPAMemAddr.valid
304    gpaMem.io.exceptionReadAddr.bits.ftqPtr := rob.io.readGPAMemAddr.bits.ftqPtr
305    gpaMem.io.exceptionReadAddr.bits.ftqOffset := rob.io.readGPAMemAddr.bits.ftqOffset
306  }
307
308  // vtype commit
309  decode.io.fromCSR := io.fromCSR.toDecode
310  decode.io.isResumeVType := rob.io.toDecode.isResumeVType
311  decode.io.commitVType := rob.io.toDecode.commitVType
312  decode.io.walkVType := rob.io.toDecode.walkVType
313
314  decode.io.redirect := s1_s3_redirect.valid || s2_s4_pendingRedirectValid
315  decode.io.vtypeRedirect := s1_s3_redirect.valid
316
317  decode.io.in.zip(io.frontend.cfVec).foreach { case (decodeIn, frontendCf) =>
318    decodeIn.valid := frontendCf.valid
319    frontendCf.ready := decodeIn.ready
320    decodeIn.bits.connectCtrlFlow(frontendCf.bits)
321  }
322  decode.io.csrCtrl := RegNext(io.csrCtrl)
323  decode.io.intRat <> rat.io.intReadPorts
324  decode.io.fpRat <> rat.io.fpReadPorts
325  decode.io.vecRat <> rat.io.vecReadPorts
326  decode.io.v0Rat <> rat.io.v0ReadPorts
327  decode.io.vlRat <> rat.io.vlReadPorts
328  decode.io.fusion := 0.U.asTypeOf(decode.io.fusion) // Todo
329  decode.io.stallReason.in <> io.frontend.stallReason
330
331  // snapshot check
332  class CFIRobIdx extends Bundle {
333    val robIdx = Vec(RenameWidth, new RobPtr)
334    val isCFI = Vec(RenameWidth, Bool())
335  }
336  val genSnapshot = Cat(rename.io.out.map(out => out.fire && out.bits.snapshot)).orR
337  val snpt = Module(new SnapshotGenerator(0.U.asTypeOf(new CFIRobIdx)))
338  snpt.io.enq := genSnapshot
339  snpt.io.enqData.robIdx := rename.io.out.map(_.bits.robIdx)
340  snpt.io.enqData.isCFI := rename.io.out.map(_.bits.snapshot)
341  snpt.io.deq := snpt.io.valids(snpt.io.deqPtr.value) && rob.io.commits.isCommit &&
342    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
343  snpt.io.redirect := s1_s3_redirect.valid
344  val flushVec = VecInit(snpt.io.snapshots.map { snapshot =>
345    val notCFIMask = snapshot.isCFI.map(~_)
346    val shouldFlush = snapshot.robIdx.map(robIdx => robIdx >= s1_s3_redirect.bits.robIdx || robIdx.value === s1_s3_redirect.bits.robIdx.value)
347    val shouldFlushMask = (1 to RenameWidth).map(shouldFlush take _ reduce (_ || _))
348    s1_s3_redirect.valid && Cat(shouldFlushMask.zip(notCFIMask).map(x => x._1 | x._2)).andR
349  })
350  val flushVecNext = flushVec zip snpt.io.valids map (x => GatedValidRegNext(x._1 && x._2, false.B))
351  snpt.io.flushVec := flushVecNext
352
353  val useSnpt = VecInit.tabulate(RenameSnapshotNum)(idx =>
354    snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
355      !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head)
356  ).reduceTree(_ || _)
357  val snptSelect = MuxCase(
358    0.U(log2Ceil(RenameSnapshotNum).W),
359    (1 to RenameSnapshotNum).map(i => (snpt.io.enqPtr - i.U).value).map(idx =>
360      (snpt.io.valids(idx) && (s1_s3_redirect.bits.robIdx > snpt.io.snapshots(idx).robIdx.head ||
361        !s1_s3_redirect.bits.flushItself() && s1_s3_redirect.bits.robIdx === snpt.io.snapshots(idx).robIdx.head), idx)
362    )
363  )
364
365  rob.io.snpt.snptEnq := DontCare
366  rob.io.snpt.snptDeq := snpt.io.deq
367  rob.io.snpt.useSnpt := useSnpt
368  rob.io.snpt.snptSelect := snptSelect
369  rob.io.snpt.flushVec := flushVecNext
370  rat.io.snpt.snptEnq := genSnapshot
371  rat.io.snpt.snptDeq := snpt.io.deq
372  rat.io.snpt.useSnpt := useSnpt
373  rat.io.snpt.snptSelect := snptSelect
374  rat.io.snpt.flushVec := flushVec
375
376  val decodeHasException = decode.io.out.map(x => x.bits.exceptionVec(instrPageFault) || x.bits.exceptionVec(instrAccessFault))
377  // fusion decoder
378  for (i <- 0 until DecodeWidth) {
379    fusionDecoder.io.in(i).valid := decode.io.out(i).valid && !(decodeHasException(i) || disableFusion)
380    fusionDecoder.io.in(i).bits := decode.io.out(i).bits.instr
381    if (i > 0) {
382      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
383    }
384  }
385
386  private val decodePipeRename = Wire(Vec(RenameWidth, DecoupledIO(new DecodedInst)))
387
388  for (i <- 0 until RenameWidth) {
389    PipelineConnect(decode.io.out(i), decodePipeRename(i), rename.io.in(i).ready,
390      s1_s3_redirect.valid || s2_s4_pendingRedirectValid, moduleName = Some("decodePipeRenameModule"))
391
392    decodePipeRename(i).ready := rename.io.in(i).ready
393    rename.io.in(i).valid := decodePipeRename(i).valid && !fusionDecoder.io.clear(i)
394    rename.io.in(i).bits := decodePipeRename(i).bits
395  }
396
397  for (i <- 0 until RenameWidth - 1) {
398    fusionDecoder.io.dec(i) := decodePipeRename(i).bits
399    rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
400
401    // update the first RenameWidth - 1 instructions
402    decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
403    when (fusionDecoder.io.out(i).valid) {
404      fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits)
405      // TODO: remove this dirty code for ftq update
406      val sameFtqPtr = rename.io.in(i).bits.ftqPtr.value === rename.io.in(i + 1).bits.ftqPtr.value
407      val ftqOffset0 = rename.io.in(i).bits.ftqOffset
408      val ftqOffset1 = rename.io.in(i + 1).bits.ftqOffset
409      val ftqOffsetDiff = ftqOffset1 - ftqOffset0
410      val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
411      val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
412      val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
413      val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
414      rename.io.in(i).bits.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
415      XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
416    }
417
418  }
419
420  // memory dependency predict
421  // when decode, send fold pc to mdp
422  private val mdpFlodPcVecVld = Wire(Vec(DecodeWidth, Bool()))
423  private val mdpFlodPcVec = Wire(Vec(DecodeWidth, UInt(MemPredPCWidth.W)))
424  for (i <- 0 until DecodeWidth) {
425    mdpFlodPcVecVld(i) := decode.io.out(i).fire || GatedValidRegNext(decode.io.out(i).fire)
426    mdpFlodPcVec(i) := Mux(
427      decode.io.out(i).fire,
428      decode.io.in(i).bits.foldpc,
429      rename.io.in(i).bits.foldpc
430    )
431  }
432
433  // currently, we only update mdp info when isReplay
434  memCtrl.io.redirect := s1_s3_redirect
435  memCtrl.io.csrCtrl := io.csrCtrl                          // RegNext in memCtrl
436  memCtrl.io.stIn := io.fromMem.stIn                        // RegNext in memCtrl
437  memCtrl.io.memPredUpdate := redirectGen.io.memPredUpdate  // RegNext in memCtrl
438  memCtrl.io.mdpFoldPcVecVld := mdpFlodPcVecVld
439  memCtrl.io.mdpFlodPcVec := mdpFlodPcVec
440  memCtrl.io.dispatchLFSTio <> dispatch.io.lfst
441
442  rat.io.redirect := s1_s3_redirect.valid
443  rat.io.rabCommits := rob.io.rabCommits
444  rat.io.diffCommits.foreach(_ := rob.io.diffCommits.get)
445  rat.io.intRenamePorts := rename.io.intRenamePorts
446  rat.io.fpRenamePorts := rename.io.fpRenamePorts
447  rat.io.vecRenamePorts := rename.io.vecRenamePorts
448  rat.io.v0RenamePorts := rename.io.v0RenamePorts
449  rat.io.vlRenamePorts := rename.io.vlRenamePorts
450
451  rename.io.redirect := s1_s3_redirect
452  rename.io.rabCommits := rob.io.rabCommits
453  rename.io.waittable := (memCtrl.io.waitTable2Rename zip decode.io.out).map{ case(waittable2rename, decodeOut) =>
454    RegEnable(waittable2rename, decodeOut.fire)
455  }
456  rename.io.ssit := memCtrl.io.ssit2Rename
457  rename.io.intReadPorts := VecInit(rat.io.intReadPorts.map(x => VecInit(x.map(_.data))))
458  rename.io.fpReadPorts := VecInit(rat.io.fpReadPorts.map(x => VecInit(x.map(_.data))))
459  rename.io.vecReadPorts := VecInit(rat.io.vecReadPorts.map(x => VecInit(x.map(_.data))))
460  rename.io.v0ReadPorts := VecInit(rat.io.v0ReadPorts.map(x => VecInit(x.data)))
461  rename.io.vlReadPorts := VecInit(rat.io.vlReadPorts.map(x => VecInit(x.data)))
462  rename.io.int_need_free := rat.io.int_need_free
463  rename.io.int_old_pdest := rat.io.int_old_pdest
464  rename.io.fp_old_pdest := rat.io.fp_old_pdest
465  rename.io.vec_old_pdest := rat.io.vec_old_pdest
466  rename.io.v0_old_pdest := rat.io.v0_old_pdest
467  rename.io.vl_old_pdest := rat.io.vl_old_pdest
468  rename.io.debug_int_rat.foreach(_ := rat.io.debug_int_rat.get)
469  rename.io.debug_fp_rat.foreach(_ := rat.io.debug_fp_rat.get)
470  rename.io.debug_vec_rat.foreach(_ := rat.io.debug_vec_rat.get)
471  rename.io.debug_v0_rat.foreach(_ := rat.io.debug_v0_rat.get)
472  rename.io.debug_vl_rat.foreach(_ := rat.io.debug_vl_rat.get)
473  rename.io.stallReason.in <> decode.io.stallReason.out
474  rename.io.snpt.snptEnq := DontCare
475  rename.io.snpt.snptDeq := snpt.io.deq
476  rename.io.snpt.useSnpt := useSnpt
477  rename.io.snpt.snptSelect := snptSelect
478  rename.io.snptIsFull := snpt.io.valids.asUInt.andR
479  rename.io.snpt.flushVec := flushVecNext
480  rename.io.snptLastEnq.valid := !isEmpty(snpt.io.enqPtr, snpt.io.deqPtr)
481  rename.io.snptLastEnq.bits := snpt.io.snapshots((snpt.io.enqPtr - 1.U).value).robIdx.head
482
483  val renameOut = Wire(chiselTypeOf(rename.io.out))
484  renameOut <> rename.io.out
485  // pass all snapshot in the first element for correctness of blockBackward
486  renameOut.tail.foreach(_.bits.snapshot := false.B)
487  renameOut.head.bits.snapshot := Mux(isFull(snpt.io.enqPtr, snpt.io.deqPtr),
488    false.B,
489    Cat(rename.io.out.map(out => out.valid && out.bits.snapshot)).orR
490  )
491
492  // pipeline between rename and dispatch
493  PipeGroupConnect(renameOut, dispatch.io.fromRename, s1_s3_redirect.valid, dispatch.io.toRenameAllFire, "renamePipeDispatch")
494  dispatch.io.intIQValidNumVec := io.intIQValidNumVec
495  dispatch.io.fpIQValidNumVec := io.fpIQValidNumVec
496  dispatch.io.fromIntDQ.intDQ0ValidDeq0Num := intDq0.io.validDeq0Num
497  dispatch.io.fromIntDQ.intDQ0ValidDeq1Num := intDq0.io.validDeq1Num
498  dispatch.io.fromIntDQ.intDQ1ValidDeq0Num := intDq1.io.validDeq0Num
499  dispatch.io.fromIntDQ.intDQ1ValidDeq1Num := intDq1.io.validDeq1Num
500
501  dispatch.io.hartId := io.fromTop.hartId
502  dispatch.io.redirect := s1_s3_redirect
503  dispatch.io.enqRob <> rob.io.enq
504  dispatch.io.robHead := rob.io.debugRobHead
505  dispatch.io.stallReason <> rename.io.stallReason.out
506  dispatch.io.lqCanAccept := io.lqCanAccept
507  dispatch.io.sqCanAccept := io.sqCanAccept
508  dispatch.io.robHeadNotReady := rob.io.headNotReady
509  dispatch.io.robFull := rob.io.robFull
510  dispatch.io.singleStep := GatedValidRegNext(io.csrCtrl.singlestep)
511
512  intDq0.io.enq <> dispatch.io.toIntDq0
513  intDq0.io.redirect <> s2_s4_redirect
514  intDq1.io.enq <> dispatch.io.toIntDq1
515  intDq1.io.redirect <> s2_s4_redirect
516
517  fpDq.io.enq <> dispatch.io.toFpDq
518  fpDq.io.redirect <> s2_s4_redirect
519
520  vecDq.io.enq <> dispatch.io.toVecDq
521  vecDq.io.redirect <> s2_s4_redirect
522
523  lsDq.io.enq <> dispatch.io.toLsDq
524  lsDq.io.redirect <> s2_s4_redirect
525
526  io.toIssueBlock.intUops <> (intDq0.io.deq :++ intDq1.io.deq)
527  io.toIssueBlock.fpUops <> fpDq.io.deq
528  io.toIssueBlock.vfUops  <> vecDq.io.deq
529  io.toIssueBlock.memUops <> lsDq.io.deq
530  io.toIssueBlock.allocPregs <> dispatch.io.allocPregs
531  io.toIssueBlock.flush   <> s2_s4_redirect
532
533  pcMem.io.wen.head   := GatedValidRegNext(io.frontend.fromFtq.pc_mem_wen)
534  pcMem.io.waddr.head := RegEnable(io.frontend.fromFtq.pc_mem_waddr.value, io.frontend.fromFtq.pc_mem_wen)
535  pcMem.io.wdata.head := RegEnable(io.frontend.fromFtq.pc_mem_wdata, io.frontend.fromFtq.pc_mem_wen)
536
537  io.toDataPath.flush := s2_s4_redirect
538  io.toExuBlock.flush := s2_s4_redirect
539
540
541  rob.io.hartId := io.fromTop.hartId
542  rob.io.redirect := s1_s3_redirect
543  rob.io.writeback := delayedNotFlushedWriteBack
544  rob.io.exuWriteback := delayedWriteBack
545  rob.io.writebackNums := VecInit(delayedNotFlushedWriteBackNums)
546  rob.io.writebackNeedFlush := delayedNotFlushedWriteBackNeedFlush
547  rob.io.readGPAMemData := gpaMem.io.exceptionReadData
548
549  io.redirect := s1_s3_redirect
550
551  // rob to int block
552  io.robio.csr <> rob.io.csr
553  // When wfi is disabled, it will not block ROB commit.
554  rob.io.csr.wfiEvent := io.robio.csr.wfiEvent
555  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
556
557  io.toTop.cpuHalt := DelayN(rob.io.cpu_halt, 5)
558
559  io.robio.csr.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
560  io.robio.exception := rob.io.exception
561  io.robio.exception.bits.pc := s1_robFlushPc
562
563  // rob to mem block
564  io.robio.lsq <> rob.io.lsq
565
566  io.debug_int_rat    .foreach(_ := rat.io.diff_int_rat.get)
567  io.debug_fp_rat     .foreach(_ := rat.io.diff_fp_rat.get)
568  io.debug_vec_rat    .foreach(_ := rat.io.diff_vec_rat.get)
569  io.debug_v0_rat.foreach(_ := rat.io.diff_v0_rat.get)
570  io.debug_vl_rat.foreach(_ := rat.io.diff_vl_rat.get)
571
572  rob.io.debug_ls := io.robio.debug_ls
573  rob.io.debugHeadLsIssue := io.robio.robHeadLsIssue
574  rob.io.lsTopdownInfo := io.robio.lsTopdownInfo
575  rob.io.debugEnqLsq := io.debugEnqLsq
576
577  io.robio.robDeqPtr := rob.io.robDeqPtr
578
579  // rob to backend
580  io.robio.commitVType := rob.io.toDecode.commitVType
581  // exu block to decode
582  decode.io.vsetvlVType := io.toDecode.vsetvlVType
583  // backend to decode
584  decode.io.vstart := io.toDecode.vstart
585  // backend to rob
586  rob.io.vstartIsZero := io.toDecode.vstart === 0.U
587
588  io.debugTopDown.fromRob := rob.io.debugTopDown.toCore
589  dispatch.io.debugTopDown.fromRob := rob.io.debugTopDown.toDispatch
590  dispatch.io.debugTopDown.fromCore := io.debugTopDown.fromCore
591  io.debugRolling := rob.io.debugRolling
592
593  io.perfInfo.ctrlInfo.robFull := GatedValidRegNext(rob.io.robFull)
594  io.perfInfo.ctrlInfo.intdqFull := GatedValidRegNext(intDq0.io.dqFull || intDq1.io.dqFull)
595  io.perfInfo.ctrlInfo.fpdqFull := GatedValidRegNext(vecDq.io.dqFull)
596  io.perfInfo.ctrlInfo.lsdqFull := GatedValidRegNext(lsDq.io.dqFull)
597
598  val perfEvents = Seq(decode, rename, dispatch, intDq0, intDq1, vecDq, lsDq, rob).flatMap(_.getPerfEvents)
599  generatePerfEvent()
600}
601
602class CtrlBlockIO()(implicit p: Parameters, params: BackendParams) extends XSBundle {
603  val fromTop = new Bundle {
604    val hartId = Input(UInt(8.W))
605  }
606  val toTop = new Bundle {
607    val cpuHalt = Output(Bool())
608  }
609  val frontend = Flipped(new FrontendToCtrlIO())
610  val fromCSR = new Bundle{
611    val toDecode = Input(new CSRToDecode)
612  }
613  val toIssueBlock = new Bundle {
614    val flush = ValidIO(new Redirect)
615    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
616    val intUops = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new DynInst))
617    val vfUops = Vec(dpParams.VecDqDeqWidth, DecoupledIO(new DynInst))
618    val fpUops = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new DynInst))
619    val memUops = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new DynInst))
620  }
621  val toDataPath = new Bundle {
622    val flush = ValidIO(new Redirect)
623  }
624  val toExuBlock = new Bundle {
625    val flush = ValidIO(new Redirect)
626  }
627  val intIQValidNumVec = Input(MixedVec(params.genIntIQValidNumBundle))
628  val fpIQValidNumVec = Input(MixedVec(params.genFpIQValidNumBundle))
629  val fromWB = new Bundle {
630    val wbData = Flipped(MixedVec(params.genWrite2CtrlBundles))
631  }
632  val redirect = ValidIO(new Redirect)
633  val fromMem = new Bundle {
634    val stIn = Vec(params.StaExuCnt, Flipped(ValidIO(new DynInst))) // use storeSetHit, ssid, robIdx
635    val violation = Flipped(ValidIO(new Redirect))
636  }
637  val memLdPcRead = Vec(params.LduCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
638  val memStPcRead = Vec(params.StaCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
639  val memHyPcRead = Vec(params.HyuCnt, Flipped(new FtqRead(UInt(VAddrBits.W))))
640
641  val csrCtrl = Input(new CustomCSRCtrlIO)
642  val robio = new Bundle {
643    val csr = new RobCSRIO
644    val exception = ValidIO(new ExceptionInfo)
645    val lsq = new RobLsqIO
646    val lsTopdownInfo = Vec(params.LduCnt + params.HyuCnt, Input(new LsTopdownInfo))
647    val debug_ls = Input(new DebugLSIO())
648    val robHeadLsIssue = Input(Bool())
649    val robDeqPtr = Output(new RobPtr)
650    val commitVType = new Bundle {
651      val vtype = Output(ValidIO(VType()))
652      val hasVsetvl = Output(Bool())
653    }
654  }
655
656  val toDecode = new Bundle {
657    val vsetvlVType = Input(VType())
658    val vstart = Input(Vl())
659  }
660
661  val perfInfo = Output(new Bundle{
662    val ctrlInfo = new Bundle {
663      val robFull   = Bool()
664      val intdqFull = Bool()
665      val fpdqFull  = Bool()
666      val lsdqFull  = Bool()
667    }
668  })
669  val debug_int_rat     = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
670  val debug_fp_rat      = if (params.debugEn) Some(Vec(32, Output(UInt(PhyRegIdxWidth.W)))) else None
671  val debug_vec_rat     = if (params.debugEn) Some(Vec(31, Output(UInt(PhyRegIdxWidth.W)))) else None
672  val debug_v0_rat      = if (params.debugEn) Some(Vec(1, Output(UInt(PhyRegIdxWidth.W)))) else None
673  val debug_vl_rat      = if (params.debugEn) Some(Vec(1, Output(UInt(PhyRegIdxWidth.W)))) else None
674
675  val sqCanAccept = Input(Bool())
676  val lqCanAccept = Input(Bool())
677
678  val debugTopDown = new Bundle {
679    val fromRob = new RobCoreTopDownIO
680    val fromCore = new CoreDispatchTopDownIO
681  }
682  val debugRolling = new RobDebugRollingIO
683  val debugEnqLsq = Input(new LsqEnqIO)
684}
685
686class NamedIndexes(namedCnt: Seq[(String, Int)]) {
687  require(namedCnt.map(_._1).distinct.size == namedCnt.size, "namedCnt should not have the same name")
688
689  val maxIdx = namedCnt.map(_._2).sum
690  val nameRangeMap: Map[String, (Int, Int)] = namedCnt.indices.map { i =>
691    val begin = namedCnt.slice(0, i).map(_._2).sum
692    val end = begin + namedCnt(i)._2
693    (namedCnt(i)._1, (begin, end))
694  }.toMap
695
696  def apply(name: String): Seq[Int] = {
697    require(nameRangeMap.contains(name))
698    nameRangeMap(name)._1 until nameRangeMap(name)._2
699  }
700}
701