xref: /XiangShan/src/main/scala/xiangshan/backend/CtrlBlock.scala (revision 9ab1568e215c540ca0554308577ff4d1813bfa8c)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
23import utils._
24import utility._
25import xiangshan._
26import xiangshan.backend.decode.{DecodeStage, FusionDecoder, ImmUnion}
27import xiangshan.backend.dispatch.{Dispatch, Dispatch2Rs, DispatchQueue}
28import xiangshan.backend.fu.PFEvent
29import xiangshan.backend.rename.{Rename, RenameTableWrapper}
30import xiangshan.backend.rob.{Rob, RobCSRIO, RobLsqIO}
31import xiangshan.frontend.{FtqRead, Ftq_RF_Components}
32import xiangshan.mem.mdp.{LFST, SSIT, WaitTable}
33import xiangshan.ExceptionNO._
34import xiangshan.backend.exu.ExuConfig
35import xiangshan.mem.{LsqEnqCtrl, LsqEnqIO}
36
37class CtrlToFtqIO(implicit p: Parameters) extends XSBundle {
38  def numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
39  val rob_commits = Vec(CommitWidth, Valid(new RobCommitInfo))
40  val redirect = Valid(new Redirect)
41}
42
43class RedirectGenerator(implicit p: Parameters) extends XSModule
44  with HasCircularQueuePtrHelper {
45
46  class RedirectGeneratorIO(implicit p: Parameters) extends XSBundle {
47    def numRedirect = exuParameters.JmpCnt + exuParameters.AluCnt
48    val hartId = Input(UInt(8.W))
49    val exuMispredict = Vec(numRedirect, Flipped(ValidIO(new ExuOutput)))
50    val loadReplay = Flipped(ValidIO(new Redirect))
51    val flush = Input(Bool())
52    val redirectPcRead = new FtqRead(UInt(VAddrBits.W))
53    val stage2Redirect = ValidIO(new Redirect)
54    val stage3Redirect = ValidIO(new Redirect)
55    val memPredUpdate = Output(new MemPredUpdateReq)
56    val memPredPcRead = new FtqRead(UInt(VAddrBits.W)) // read req send form stage 2
57    val isMisspreRedirect = Output(Bool())
58  }
59  val io = IO(new RedirectGeneratorIO)
60  /*
61        LoadQueue  Jump  ALU0  ALU1  ALU2  ALU3   exception    Stage1
62          |         |      |    |     |     |         |
63          |============= reg & compare =====|         |       ========
64                            |                         |
65                            |                         |
66                            |                         |        Stage2
67                            |                         |
68                    redirect (flush backend)          |
69                    |                                 |
70               === reg ===                            |       ========
71                    |                                 |
72                    |----- mux (exception first) -----|        Stage3
73                            |
74                redirect (send to frontend)
75   */
76  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
77    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
78    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
79      (if (j < i) !xs(j).valid || compareVec(i)(j)
80      else if (j == i) xs(i).valid
81      else !xs(j).valid || !compareVec(j)(i))
82    )).andR))
83    resultOnehot
84  }
85
86  def getRedirect(exuOut: Valid[ExuOutput]): ValidIO[Redirect] = {
87    val redirect = Wire(Valid(new Redirect))
88    redirect.valid := exuOut.valid && exuOut.bits.redirect.cfiUpdate.isMisPred
89    redirect.bits := exuOut.bits.redirect
90    redirect
91  }
92
93  val jumpOut = io.exuMispredict.head
94  val allRedirect = VecInit(io.exuMispredict.map(x => getRedirect(x)) :+ io.loadReplay)
95  val oldestOneHot = selectOldestRedirect(allRedirect)
96  val needFlushVec = VecInit(allRedirect.map(_.bits.robIdx.needFlush(io.stage2Redirect) || io.flush))
97  val oldestValid = VecInit(oldestOneHot.zip(needFlushVec).map{ case (v, f) => v && !f }).asUInt.orR
98  val oldestExuOutput = Mux1H(io.exuMispredict.indices.map(oldestOneHot), io.exuMispredict)
99  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
100  io.isMisspreRedirect := VecInit(io.exuMispredict.map(x => getRedirect(x).valid)).asUInt.orR
101  io.redirectPcRead.ptr := oldestRedirect.bits.ftqIdx
102  io.redirectPcRead.offset := oldestRedirect.bits.ftqOffset
103
104  val s1_jumpTarget = RegEnable(jumpOut.bits.redirect.cfiUpdate.target, jumpOut.valid)
105  val s1_imm12_reg = RegNext(oldestExuOutput.bits.uop.ctrl.imm(11, 0))
106  val s1_pd = RegNext(oldestExuOutput.bits.uop.cf.pd)
107  val s1_redirect_bits_reg = RegNext(oldestRedirect.bits)
108  val s1_redirect_valid_reg = RegNext(oldestValid)
109  val s1_redirect_onehot = RegNext(oldestOneHot)
110
111  // stage1 -> stage2
112  io.stage2Redirect.valid := s1_redirect_valid_reg && !io.flush
113  io.stage2Redirect.bits := s1_redirect_bits_reg
114
115  val s1_isReplay = s1_redirect_onehot.last
116  val s1_isJump = s1_redirect_onehot.head
117  val real_pc = io.redirectPcRead.data
118  val brTarget = real_pc + SignExt(ImmUnion.B.toImm32(s1_imm12_reg), XLEN)
119  val snpc = real_pc + Mux(s1_pd.isRVC, 2.U, 4.U)
120  val target = Mux(s1_isReplay,
121    real_pc, // replay from itself
122    Mux(s1_redirect_bits_reg.cfiUpdate.taken,
123      Mux(s1_isJump, s1_jumpTarget, brTarget),
124      snpc
125    )
126  )
127
128  val stage2CfiUpdate = io.stage2Redirect.bits.cfiUpdate
129  stage2CfiUpdate.pc := real_pc
130  stage2CfiUpdate.pd := s1_pd
131  // stage2CfiUpdate.predTaken := s1_redirect_bits_reg.cfiUpdate.predTaken
132  stage2CfiUpdate.target := target
133  // stage2CfiUpdate.taken := s1_redirect_bits_reg.cfiUpdate.taken
134  // stage2CfiUpdate.isMisPred := s1_redirect_bits_reg.cfiUpdate.isMisPred
135
136  val s2_target = RegEnable(target, s1_redirect_valid_reg)
137  val s2_pc = RegEnable(real_pc, s1_redirect_valid_reg)
138  val s2_redirect_bits_reg = RegEnable(s1_redirect_bits_reg, s1_redirect_valid_reg)
139  val s2_redirect_valid_reg = RegNext(s1_redirect_valid_reg && !io.flush, init = false.B)
140
141  io.stage3Redirect.valid := s2_redirect_valid_reg
142  io.stage3Redirect.bits := s2_redirect_bits_reg
143
144  // get pc from ftq
145  // valid only if redirect is caused by load violation
146  // store_pc is used to update store set
147  val store_pc = io.memPredPcRead(s1_redirect_bits_reg.stFtqIdx, s1_redirect_bits_reg.stFtqOffset)
148
149  // update load violation predictor if load violation redirect triggered
150  io.memPredUpdate.valid := RegNext(s1_isReplay && s1_redirect_valid_reg, init = false.B)
151  // update wait table
152  io.memPredUpdate.waddr := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
153  io.memPredUpdate.wdata := true.B
154  // update store set
155  io.memPredUpdate.ldpc := RegNext(XORFold(real_pc(VAddrBits-1, 1), MemPredPCWidth))
156  // store pc is ready 1 cycle after s1_isReplay is judged
157  io.memPredUpdate.stpc := XORFold(store_pc(VAddrBits-1, 1), MemPredPCWidth)
158
159  // // recover runahead checkpoint if redirect
160  // if (!env.FPGAPlatform) {
161  //   val runahead_redirect = Module(new DifftestRunaheadRedirectEvent)
162  //   runahead_redirect.io.clock := clock
163  //   runahead_redirect.io.coreid := io.hartId
164  //   runahead_redirect.io.valid := io.stage3Redirect.valid
165  //   runahead_redirect.io.pc :=  s2_pc // for debug only
166  //   runahead_redirect.io.target_pc := s2_target // for debug only
167  //   runahead_redirect.io.checkpoint_id := io.stage3Redirect.bits.debug_runahead_checkpoint_id // make sure it is right
168  // }
169}
170
171class CtrlBlock(dpExuConfigs: Seq[Seq[Seq[ExuConfig]]])(implicit p: Parameters) extends LazyModule
172  with HasWritebackSink with HasWritebackSource {
173  val rob = LazyModule(new Rob)
174
175  override def addWritebackSink(source: Seq[HasWritebackSource], index: Option[Seq[Int]]): HasWritebackSink = {
176    rob.addWritebackSink(Seq(this), Some(Seq(writebackSinks.length)))
177    super.addWritebackSink(source, index)
178  }
179
180  // duplicated dispatch2 here to avoid cross-module timing path loop.
181  val dispatch2 = dpExuConfigs.map(c => LazyModule(new Dispatch2Rs(c)))
182  lazy val module = new CtrlBlockImp(this)
183
184  override lazy val writebackSourceParams: Seq[WritebackSourceParams] = {
185    writebackSinksParams
186  }
187  override lazy val writebackSourceImp: HasWritebackSourceImp = module
188
189  override def generateWritebackIO(
190    thisMod: Option[HasWritebackSource] = None,
191    thisModImp: Option[HasWritebackSourceImp] = None
192  ): Unit = {
193    module.io.writeback.zip(writebackSinksImp(thisMod, thisModImp)).foreach(x => x._1 := x._2)
194  }
195}
196
197class CtrlBlockImp(outer: CtrlBlock)(implicit p: Parameters) extends LazyModuleImp(outer)
198  with HasXSParameter
199  with HasCircularQueuePtrHelper
200  with HasWritebackSourceImp
201  with HasPerfEvents
202{
203  val writebackLengths = outer.writebackSinksParams.map(_.length)
204
205  val io = IO(new Bundle {
206    val hartId = Input(UInt(8.W))
207    val cpu_halt = Output(Bool())
208    val frontend = Flipped(new FrontendToCtrlIO)
209    // to exu blocks
210    val allocPregs = Vec(RenameWidth, Output(new ResetPregStateReq))
211    val dispatch = Vec(3*dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
212    val rsReady = Vec(outer.dispatch2.map(_.module.io.out.length).sum, Input(Bool()))
213    val enqLsq = Flipped(new LsqEnqIO)
214    val lqCancelCnt = Input(UInt(log2Up(LoadQueueSize + 1).W))
215    val sqCancelCnt = Input(UInt(log2Up(StoreQueueSize + 1).W))
216    val sqDeq = Input(UInt(log2Ceil(EnsbufferWidth + 1).W))
217    // from int block
218    val exuRedirect = Vec(exuParameters.AluCnt + exuParameters.JmpCnt, Flipped(ValidIO(new ExuOutput)))
219    val stIn = Vec(exuParameters.StuCnt, Flipped(ValidIO(new ExuInput)))
220    val memoryViolation = Flipped(ValidIO(new Redirect))
221    val jumpPc = Output(UInt(VAddrBits.W))
222    val jalr_target = Output(UInt(VAddrBits.W))
223    val robio = new Bundle {
224      // to int block
225      val toCSR = new RobCSRIO
226      val exception = ValidIO(new ExceptionInfo)
227      // to mem block
228      val lsq = new RobLsqIO
229    }
230    val csrCtrl = Input(new CustomCSRCtrlIO)
231    val perfInfo = Output(new Bundle{
232      val ctrlInfo = new Bundle {
233        val robFull   = Input(Bool())
234        val intdqFull = Input(Bool())
235        val fpdqFull  = Input(Bool())
236        val lsdqFull  = Input(Bool())
237      }
238    })
239    val writeback = MixedVec(writebackLengths.map(num => Vec(num, Flipped(ValidIO(new ExuOutput)))))
240    // redirect out
241    val redirect = ValidIO(new Redirect)
242    val debug_int_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
243    val debug_fp_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W)))
244    val debug_vec_rat = Vec(32, Output(UInt(PhyRegIdxWidth.W))) // TODO: use me
245    val debug_vconfig_rat = Output(UInt(PhyRegIdxWidth.W)) // TODO: use me
246  })
247
248  override def writebackSource: Option[Seq[Seq[Valid[ExuOutput]]]] = {
249    Some(io.writeback.map(writeback => {
250      val exuOutput = WireInit(writeback)
251      val timer = GTimer()
252      for ((wb_next, wb) <- exuOutput.zip(writeback)) {
253        wb_next.valid := RegNext(wb.valid && !wb.bits.uop.robIdx.needFlush(Seq(stage2Redirect, redirectForExu)))
254        wb_next.bits := RegNext(wb.bits)
255        wb_next.bits.uop.debugInfo.writebackTime := timer
256      }
257      exuOutput
258    }))
259  }
260
261  val decode = Module(new DecodeStage)
262  val fusionDecoder = Module(new FusionDecoder)
263  val rat = Module(new RenameTableWrapper)
264  val ssit = Module(new SSIT)
265  val waittable = Module(new WaitTable)
266  val rename = Module(new Rename)
267  val dispatch = Module(new Dispatch)
268  val intDq = Module(new DispatchQueue(dpParams.IntDqSize, RenameWidth, dpParams.IntDqDeqWidth))
269  val fpDq = Module(new DispatchQueue(dpParams.FpDqSize, RenameWidth, dpParams.FpDqDeqWidth))
270  val lsDq = Module(new DispatchQueue(dpParams.LsDqSize, RenameWidth, dpParams.LsDqDeqWidth))
271  val redirectGen = Module(new RedirectGenerator)
272  // jumpPc (2) + redirects (1) + loadPredUpdate (1) + jalr_target (1) + robFlush (1)
273  val pcMem = Module(new SyncDataModuleTemplate(new Ftq_RF_Components, FtqSize, 6, 1, "BackendPC"))
274  val rob = outer.rob.module
275
276  pcMem.io.wen.head   := RegNext(io.frontend.fromFtq.pc_mem_wen)
277  pcMem.io.waddr.head := RegNext(io.frontend.fromFtq.pc_mem_waddr)
278  pcMem.io.wdata.head := RegNext(io.frontend.fromFtq.pc_mem_wdata)
279
280  pcMem.io.raddr.last := rob.io.flushOut.bits.ftqIdx.value
281  val flushPC = pcMem.io.rdata.last.getPc(RegNext(rob.io.flushOut.bits.ftqOffset))
282
283  val flushRedirect = Wire(Valid(new Redirect))
284  flushRedirect.valid := RegNext(rob.io.flushOut.valid)
285  flushRedirect.bits := RegEnable(rob.io.flushOut.bits, rob.io.flushOut.valid)
286
287  val flushRedirectReg = Wire(Valid(new Redirect))
288  flushRedirectReg.valid := RegNext(flushRedirect.valid, init = false.B)
289  flushRedirectReg.bits := RegEnable(flushRedirect.bits, flushRedirect.valid)
290
291  val stage2Redirect = Mux(flushRedirect.valid, flushRedirect, redirectGen.io.stage2Redirect)
292  // Redirect will be RegNext at ExuBlocks.
293  val redirectForExu = RegNextWithEnable(stage2Redirect)
294
295  val exuRedirect = io.exuRedirect.map(x => {
296    val valid = x.valid && x.bits.redirectValid
297    val killedByOlder = x.bits.uop.robIdx.needFlush(Seq(stage2Redirect, redirectForExu))
298    val delayed = Wire(Valid(new ExuOutput))
299    delayed.valid := RegNext(valid && !killedByOlder, init = false.B)
300    delayed.bits := RegEnable(x.bits, x.valid)
301    delayed
302  })
303  val loadReplay = Wire(Valid(new Redirect))
304  loadReplay.valid := RegNext(io.memoryViolation.valid &&
305    !io.memoryViolation.bits.robIdx.needFlush(Seq(stage2Redirect, redirectForExu)),
306    init = false.B
307  )
308  loadReplay.bits := RegEnable(io.memoryViolation.bits, io.memoryViolation.valid)
309  pcMem.io.raddr(2) := redirectGen.io.redirectPcRead.ptr.value
310  redirectGen.io.redirectPcRead.data := pcMem.io.rdata(2).getPc(RegNext(redirectGen.io.redirectPcRead.offset))
311  pcMem.io.raddr(3) := redirectGen.io.memPredPcRead.ptr.value
312  redirectGen.io.memPredPcRead.data := pcMem.io.rdata(3).getPc(RegNext(redirectGen.io.memPredPcRead.offset))
313  redirectGen.io.hartId := io.hartId
314  redirectGen.io.exuMispredict <> exuRedirect
315  redirectGen.io.loadReplay <> loadReplay
316  redirectGen.io.flush := flushRedirect.valid
317
318  val frontendFlushValid = DelayN(flushRedirect.valid, 5)
319  val frontendFlushBits = RegEnable(flushRedirect.bits, flushRedirect.valid)
320  // When ROB commits an instruction with a flush, we notify the frontend of the flush without the commit.
321  // Flushes to frontend may be delayed by some cycles and commit before flush causes errors.
322  // Thus, we make all flush reasons to behave the same as exceptions for frontend.
323  for (i <- 0 until CommitWidth) {
324    // why flushOut: instructions with flushPipe are not commited to frontend
325    // If we commit them to frontend, it will cause flush after commit, which is not acceptable by frontend.
326    val is_commit = rob.io.commits.commitValid(i) && rob.io.commits.isCommit && !rob.io.flushOut.valid
327    io.frontend.toFtq.rob_commits(i).valid := RegNext(is_commit)
328    io.frontend.toFtq.rob_commits(i).bits := RegEnable(rob.io.commits.info(i), is_commit)
329  }
330  io.frontend.toFtq.redirect.valid := frontendFlushValid || redirectGen.io.stage2Redirect.valid
331  io.frontend.toFtq.redirect.bits := Mux(frontendFlushValid, frontendFlushBits, redirectGen.io.stage2Redirect.bits)
332  // Be careful here:
333  // T0: flushRedirect.valid, exception.valid
334  // T1: csr.redirect.valid
335  // T2: csr.exception.valid
336  // T3: csr.trapTarget
337  // T4: ctrlBlock.trapTarget
338  // T5: io.frontend.toFtq.stage2Redirect.valid
339  val pc_from_csr = io.robio.toCSR.isXRet || DelayN(rob.io.exception.valid, 4)
340  val rob_flush_pc = RegEnable(Mux(flushRedirect.bits.flushItself(),
341    flushPC, // replay inst
342    flushPC + 4.U // flush pipe
343  ), flushRedirect.valid)
344  val flushTarget = Mux(pc_from_csr, io.robio.toCSR.trapTarget, rob_flush_pc)
345  when (frontendFlushValid) {
346    io.frontend.toFtq.redirect.bits.level := RedirectLevel.flush
347    io.frontend.toFtq.redirect.bits.cfiUpdate.target := RegNext(flushTarget)
348  }
349
350
351  val pendingRedirect = RegInit(false.B)
352  when (stage2Redirect.valid) {
353    pendingRedirect := true.B
354  }.elsewhen (RegNext(io.frontend.toFtq.redirect.valid)) {
355    pendingRedirect := false.B
356  }
357
358  if (env.EnableTopDown) {
359    val stage2Redirect_valid_when_pending = pendingRedirect && stage2Redirect.valid
360
361    val stage2_redirect_cycles = RegInit(false.B)                                         // frontend_bound->fetch_lantency->stage2_redirect
362    val MissPredPending = RegInit(false.B); val branch_resteers_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->branch_resteers
363    val RobFlushPending = RegInit(false.B); val robFlush_bubble_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->robflush_bubble
364    val LdReplayPending = RegInit(false.B); val ldReplay_bubble_cycles = RegInit(false.B) // frontend_bound->fetch_lantency->stage2_redirect->ldReplay_bubble
365
366    when(redirectGen.io.isMisspreRedirect) { MissPredPending := true.B }
367    when(flushRedirect.valid)              { RobFlushPending := true.B }
368    when(redirectGen.io.loadReplay.valid)  { LdReplayPending := true.B }
369
370    when (RegNext(io.frontend.toFtq.redirect.valid)) {
371      when(pendingRedirect) {                             stage2_redirect_cycles := true.B }
372      when(MissPredPending) { MissPredPending := false.B; branch_resteers_cycles := true.B }
373      when(RobFlushPending) { RobFlushPending := false.B; robFlush_bubble_cycles := true.B }
374      when(LdReplayPending) { LdReplayPending := false.B; ldReplay_bubble_cycles := true.B }
375    }
376
377    when(VecInit(decode.io.out.map(x => x.valid)).asUInt.orR){
378      when(stage2_redirect_cycles) { stage2_redirect_cycles := false.B }
379      when(branch_resteers_cycles) { branch_resteers_cycles := false.B }
380      when(robFlush_bubble_cycles) { robFlush_bubble_cycles := false.B }
381      when(ldReplay_bubble_cycles) { ldReplay_bubble_cycles := false.B }
382    }
383
384    XSPerfAccumulate("stage2_redirect_cycles", stage2_redirect_cycles)
385    XSPerfAccumulate("branch_resteers_cycles", branch_resteers_cycles)
386    XSPerfAccumulate("robFlush_bubble_cycles", robFlush_bubble_cycles)
387    XSPerfAccumulate("ldReplay_bubble_cycles", ldReplay_bubble_cycles)
388    XSPerfAccumulate("s2Redirect_pend_cycles", stage2Redirect_valid_when_pending)
389  }
390
391  decode.io.in <> io.frontend.cfVec
392  decode.io.csrCtrl := RegNext(io.csrCtrl)
393  decode.io.intRat <> rat.io.intReadPorts
394  decode.io.fpRat <> rat.io.fpReadPorts
395  decode.io.vecRat <> rat.io.vecReadPorts
396
397  // memory dependency predict
398  // when decode, send fold pc to mdp
399  for (i <- 0 until DecodeWidth) {
400    val mdp_foldpc = Mux(
401      decode.io.out(i).fire,
402      decode.io.in(i).bits.foldpc,
403      rename.io.in(i).bits.cf.foldpc
404    )
405    ssit.io.raddr(i) := mdp_foldpc
406    waittable.io.raddr(i) := mdp_foldpc
407  }
408  // currently, we only update mdp info when isReplay
409  ssit.io.update <> RegNext(redirectGen.io.memPredUpdate)
410  ssit.io.csrCtrl := RegNext(io.csrCtrl)
411  waittable.io.update <> RegNext(redirectGen.io.memPredUpdate)
412  waittable.io.csrCtrl := RegNext(io.csrCtrl)
413
414  // LFST lookup and update
415  val lfst = Module(new LFST)
416  lfst.io.redirect <> RegNext(io.redirect)
417  lfst.io.storeIssue <> RegNext(io.stIn)
418  lfst.io.csrCtrl <> RegNext(io.csrCtrl)
419  lfst.io.dispatch <> dispatch.io.lfst
420
421  rat.io.redirect := stage2Redirect.valid
422  rat.io.robCommits := rob.io.commits
423  rat.io.intRenamePorts := rename.io.intRenamePorts
424  rat.io.fpRenamePorts := rename.io.fpRenamePorts
425  rat.io.vecRenamePorts := rename.io.vecRenamePorts
426
427  io.debug_int_rat := rat.io.debug_int_rat
428  io.debug_fp_rat := rat.io.debug_fp_rat
429  io.debug_vec_rat := rat.io.debug_vec_rat
430  io.debug_vconfig_rat := rat.io.debug_vconfig_rat
431
432  // pipeline between decode and rename
433  for (i <- 0 until RenameWidth) {
434    // fusion decoder
435    val decodeHasException = io.frontend.cfVec(i).bits.exceptionVec(instrPageFault) || io.frontend.cfVec(i).bits.exceptionVec(instrAccessFault)
436    val disableFusion = decode.io.csrCtrl.singlestep || !decode.io.csrCtrl.fusion_enable
437    fusionDecoder.io.in(i).valid := io.frontend.cfVec(i).valid && !(decodeHasException || disableFusion)
438    fusionDecoder.io.in(i).bits := io.frontend.cfVec(i).bits.instr
439    if (i > 0) {
440      fusionDecoder.io.inReady(i - 1) := decode.io.out(i).ready
441    }
442
443    // Pipeline
444    val renamePipe = PipelineNext(decode.io.out(i), rename.io.in(i).ready,
445      stage2Redirect.valid || pendingRedirect)
446    renamePipe.ready := rename.io.in(i).ready
447    rename.io.in(i).valid := renamePipe.valid && !fusionDecoder.io.clear(i)
448    rename.io.in(i).bits := renamePipe.bits
449    rename.io.intReadPorts(i) := rat.io.intReadPorts(i).map(_.data)
450    rename.io.fpReadPorts(i) := rat.io.fpReadPorts(i).map(_.data)
451    rename.io.vecReadPorts(i) := rat.io.vecReadPorts(i).map(_.data)
452    rename.io.waittable(i) := RegEnable(waittable.io.rdata(i), decode.io.out(i).fire)
453
454    if (i < RenameWidth - 1) {
455      // fusion decoder sees the raw decode info
456      fusionDecoder.io.dec(i) := renamePipe.bits.ctrl
457      rename.io.fusionInfo(i) := fusionDecoder.io.info(i)
458
459      // update the first RenameWidth - 1 instructions
460      decode.io.fusion(i) := fusionDecoder.io.out(i).valid && rename.io.out(i).fire
461      when (fusionDecoder.io.out(i).valid) {
462        fusionDecoder.io.out(i).bits.update(rename.io.in(i).bits.ctrl)
463        // TODO: remove this dirty code for ftq update
464        val sameFtqPtr = rename.io.in(i).bits.cf.ftqPtr.value === rename.io.in(i + 1).bits.cf.ftqPtr.value
465        val ftqOffset0 = rename.io.in(i).bits.cf.ftqOffset
466        val ftqOffset1 = rename.io.in(i + 1).bits.cf.ftqOffset
467        val ftqOffsetDiff = ftqOffset1 - ftqOffset0
468        val cond1 = sameFtqPtr && ftqOffsetDiff === 1.U
469        val cond2 = sameFtqPtr && ftqOffsetDiff === 2.U
470        val cond3 = !sameFtqPtr && ftqOffset1 === 0.U
471        val cond4 = !sameFtqPtr && ftqOffset1 === 1.U
472        rename.io.in(i).bits.ctrl.commitType := Mux(cond1, 4.U, Mux(cond2, 5.U, Mux(cond3, 6.U, 7.U)))
473        XSError(!cond1 && !cond2 && !cond3 && !cond4, p"new condition $sameFtqPtr $ftqOffset0 $ftqOffset1\n")
474      }
475    }
476  }
477
478  rename.io.redirect <> stage2Redirect
479  rename.io.robCommits <> rob.io.commits
480  rename.io.ssit <> ssit.io.rdata
481  rename.io.debug_int_rat <> rat.io.debug_int_rat
482  rename.io.debug_fp_rat <> rat.io.debug_fp_rat
483
484  // pipeline between rename and dispatch
485  for (i <- 0 until RenameWidth) {
486    PipelineConnect(rename.io.out(i), dispatch.io.fromRename(i), dispatch.io.recv(i), stage2Redirect.valid)
487  }
488
489  dispatch.io.hartId := io.hartId
490  dispatch.io.redirect <> stage2Redirect
491  dispatch.io.enqRob <> rob.io.enq
492  dispatch.io.toIntDq <> intDq.io.enq
493  dispatch.io.toFpDq <> fpDq.io.enq
494  dispatch.io.toLsDq <> lsDq.io.enq
495  dispatch.io.allocPregs <> io.allocPregs
496  dispatch.io.singleStep := RegNext(io.csrCtrl.singlestep)
497
498  intDq.io.redirect <> redirectForExu
499  fpDq.io.redirect <> redirectForExu
500  lsDq.io.redirect <> redirectForExu
501
502  val dpqOut = intDq.io.deq ++ lsDq.io.deq ++ fpDq.io.deq
503  io.dispatch <> dpqOut
504
505  for (dp2 <- outer.dispatch2.map(_.module.io)) {
506    dp2.redirect := redirectForExu
507    if (dp2.readFpState.isDefined) {
508      dp2.readFpState.get := DontCare
509    }
510    if (dp2.readIntState.isDefined) {
511      dp2.readIntState.get := DontCare
512    }
513    if (dp2.enqLsq.isDefined) {
514      val lsqCtrl = Module(new LsqEnqCtrl)
515      lsqCtrl.io.redirect <> redirectForExu
516      lsqCtrl.io.enq <> dp2.enqLsq.get
517      lsqCtrl.io.lcommit := rob.io.lsq.lcommit
518      lsqCtrl.io.scommit := io.sqDeq
519      lsqCtrl.io.lqCancelCnt := io.lqCancelCnt
520      lsqCtrl.io.sqCancelCnt := io.sqCancelCnt
521      io.enqLsq <> lsqCtrl.io.enqLsq
522    }
523  }
524  for ((dp2In, i) <- outer.dispatch2.flatMap(_.module.io.in).zipWithIndex) {
525    dp2In.valid := dpqOut(i).valid
526    dp2In.bits := dpqOut(i).bits
527    // override ready here to avoid cross-module loop path
528    dpqOut(i).ready := dp2In.ready
529  }
530  for ((dp2Out, i) <- outer.dispatch2.flatMap(_.module.io.out).zipWithIndex) {
531    dp2Out.ready := io.rsReady(i)
532  }
533
534  val pingpong = RegInit(false.B)
535  pingpong := !pingpong
536  pcMem.io.raddr(0) := intDq.io.deqNext(0).cf.ftqPtr.value
537  pcMem.io.raddr(1) := intDq.io.deqNext(2).cf.ftqPtr.value
538  val jumpPcRead0 = pcMem.io.rdata(0).getPc(RegNext(intDq.io.deqNext(0).cf.ftqOffset))
539  val jumpPcRead1 = pcMem.io.rdata(1).getPc(RegNext(intDq.io.deqNext(2).cf.ftqOffset))
540  io.jumpPc := Mux(pingpong && (exuParameters.AluCnt > 2).B, jumpPcRead1, jumpPcRead0)
541  val jalrTargetReadPtr = Mux(pingpong && (exuParameters.AluCnt > 2).B,
542    io.dispatch(2).bits.cf.ftqPtr,
543    io.dispatch(0).bits.cf.ftqPtr)
544  pcMem.io.raddr(4) := (jalrTargetReadPtr + 1.U).value
545  val jalrTargetRead = pcMem.io.rdata(4).startAddr
546  val read_from_newest_entry = RegNext(jalrTargetReadPtr) === RegNext(io.frontend.fromFtq.newest_entry_ptr)
547  io.jalr_target := Mux(read_from_newest_entry, RegNext(io.frontend.fromFtq.newest_entry_target), jalrTargetRead)
548
549  rob.io.hartId := io.hartId
550  io.cpu_halt := DelayN(rob.io.cpu_halt, 5)
551  rob.io.redirect <> stage2Redirect
552  outer.rob.generateWritebackIO(Some(outer), Some(this))
553
554  io.redirect <> stage2Redirect
555
556  // rob to int block
557  io.robio.toCSR <> rob.io.csr
558  // When wfi is disabled, it will not block ROB commit.
559  rob.io.csr.wfiEvent := io.robio.toCSR.wfiEvent
560  rob.io.wfi_enable := decode.io.csrCtrl.wfi_enable
561  io.robio.toCSR.perfinfo.retiredInstr <> RegNext(rob.io.csr.perfinfo.retiredInstr)
562  io.robio.exception := rob.io.exception
563  io.robio.exception.bits.uop.cf.pc := flushPC
564
565  // rob to mem block
566  io.robio.lsq <> rob.io.lsq
567
568  io.perfInfo.ctrlInfo.robFull := RegNext(rob.io.robFull)
569  io.perfInfo.ctrlInfo.intdqFull := RegNext(intDq.io.dqFull)
570  io.perfInfo.ctrlInfo.fpdqFull := RegNext(fpDq.io.dqFull)
571  io.perfInfo.ctrlInfo.lsdqFull := RegNext(lsDq.io.dqFull)
572
573  val pfevent = Module(new PFEvent)
574  pfevent.io.distribute_csr := RegNext(io.csrCtrl.distribute_csr)
575  val csrevents = pfevent.io.hpmevent.slice(8,16)
576
577  val perfinfo = IO(new Bundle(){
578    val perfEventsRs      = Input(Vec(NumRs, new PerfEvent))
579    val perfEventsEu0     = Input(Vec(6, new PerfEvent))
580    val perfEventsEu1     = Input(Vec(6, new PerfEvent))
581  })
582
583  val allPerfEvents = Seq(decode, rename, dispatch, intDq, fpDq, lsDq, rob).flatMap(_.getPerf)
584  val hpmEvents = allPerfEvents ++ perfinfo.perfEventsEu0 ++ perfinfo.perfEventsEu1 ++ perfinfo.perfEventsRs
585  val perfEvents = HPerfMonitor(csrevents, hpmEvents).getPerfEvents
586  generatePerfEvent()
587}
588