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