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