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