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