xref: /XiangShan/src/main/scala/xiangshan/backend/rob/Rob.scala (revision d2b20d1a96e238e36a849bd253f65ec7b6a5db38)
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.rob
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import difftest._
23import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
24import utils._
25import utility._
26import xiangshan._
27import xiangshan.backend.exu.ExuConfig
28import xiangshan.frontend.FtqPtr
29import xiangshan.mem.{LsqEnqIO, LqPtr}
30
31class DebugMdpInfo(implicit p: Parameters) extends XSBundle{
32  val ssid = UInt(SSIDWidth.W)
33  val waitAllStore = Bool()
34}
35
36class DebugLsInfo(implicit p: Parameters) extends XSBundle {
37  val s1 = new Bundle {
38    val isTlbFirstMiss = Bool() // in s1
39    val isBankConflict = Bool() // in s1
40    val isLoadToLoadForward = Bool()
41    val isReplayFast = Bool()
42  }
43  val s2 = new Bundle{
44    val isDcacheFirstMiss = Bool() // in s2 (predicted result is in s1 when using WPU, real result is in s2)
45    val isForwardFail = Bool() // in s2
46    val isReplaySlow = Bool()
47    val isLoadReplayTLBMiss = Bool()
48    val isLoadReplayCacheMiss = Bool()
49  }
50  val replayCnt = UInt(XLEN.W)
51
52  def s1SignalEnable(ena: DebugLsInfo) = {
53    when(ena.s1.isTlbFirstMiss) { s1.isTlbFirstMiss := true.B }
54    when(ena.s1.isBankConflict) { s1.isBankConflict := true.B }
55    when(ena.s1.isLoadToLoadForward) { s1.isLoadToLoadForward := true.B }
56    when(ena.s1.isReplayFast) {
57      s1.isReplayFast := true.B
58      replayCnt := replayCnt + 1.U
59    }
60  }
61
62  def s2SignalEnable(ena: DebugLsInfo) = {
63    when(ena.s2.isDcacheFirstMiss) { s2.isDcacheFirstMiss := true.B }
64    when(ena.s2.isForwardFail) { s2.isForwardFail := true.B }
65    when(ena.s2.isLoadReplayTLBMiss) { s2.isLoadReplayTLBMiss := true.B }
66    when(ena.s2.isLoadReplayCacheMiss) { s2.isLoadReplayCacheMiss := true.B }
67    when(ena.s2.isReplaySlow) {
68      s2.isReplaySlow := true.B
69      replayCnt := replayCnt + 1.U
70    }
71  }
72
73}
74object DebugLsInfo {
75  def init(implicit p: Parameters): DebugLsInfo = {
76    val lsInfo = Wire(new DebugLsInfo)
77    lsInfo.s1.isTlbFirstMiss := false.B
78    lsInfo.s1.isBankConflict := false.B
79    lsInfo.s1.isLoadToLoadForward := false.B
80    lsInfo.s1.isReplayFast := false.B
81    lsInfo.s2.isDcacheFirstMiss := false.B
82    lsInfo.s2.isForwardFail := false.B
83    lsInfo.s2.isReplaySlow := false.B
84    lsInfo.s2.isLoadReplayTLBMiss := false.B
85    lsInfo.s2.isLoadReplayCacheMiss := false.B
86    lsInfo.replayCnt := 0.U
87    lsInfo
88  }
89
90}
91class DebugLsInfoBundle(implicit p: Parameters) extends DebugLsInfo {
92  // unified processing at the end stage of load/store  ==> s2  ==> bug that will write error robIdx data
93  val s1_robIdx = UInt(log2Ceil(RobSize).W)
94  val s2_robIdx = UInt(log2Ceil(RobSize).W)
95}
96class DebugLSIO(implicit p: Parameters) extends XSBundle {
97  val debugLsInfo = Vec(exuParameters.LduCnt + exuParameters.StuCnt, Output(new DebugLsInfoBundle))
98}
99
100class LsTopdownInfo(implicit p: Parameters) extends XSBundle {
101  val s1 = new Bundle {
102    val robIdx = UInt(log2Ceil(RobSize).W)
103    val vaddr_valid = Bool()
104    val vaddr_bits = UInt(VAddrBits.W)
105  }
106  val s2 = new Bundle {
107    val robIdx = UInt(log2Ceil(RobSize).W)
108    val paddr_valid = Bool()
109    val paddr_bits = UInt(PAddrBits.W)
110  }
111
112  def s1SignalEnable(ena: LsTopdownInfo) = {
113    when(ena.s1.vaddr_valid) {
114      s1.vaddr_valid := true.B
115      s1.vaddr_bits := ena.s1.vaddr_bits
116    }
117  }
118
119  def s2SignalEnable(ena: LsTopdownInfo) = {
120    when(ena.s2.paddr_valid) {
121      s2.paddr_valid := true.B
122      s2.paddr_bits := ena.s2.paddr_bits
123    }
124  }
125}
126
127object LsTopdownInfo {
128  def init(implicit p: Parameters): LsTopdownInfo = 0.U.asTypeOf(new LsTopdownInfo)
129}
130
131class RobPtr(implicit p: Parameters) extends CircularQueuePtr[RobPtr](
132  p => p(XSCoreParamsKey).RobSize
133) with HasCircularQueuePtrHelper {
134
135  def needFlush(redirect: Valid[Redirect]): Bool = {
136    val flushItself = redirect.bits.flushItself() && this === redirect.bits.robIdx
137    redirect.valid && (flushItself || isAfter(this, redirect.bits.robIdx))
138  }
139
140  def needFlush(redirect: Seq[Valid[Redirect]]): Bool = VecInit(redirect.map(needFlush)).asUInt.orR
141}
142
143object RobPtr {
144  def apply(f: Bool, v: UInt)(implicit p: Parameters): RobPtr = {
145    val ptr = Wire(new RobPtr)
146    ptr.flag := f
147    ptr.value := v
148    ptr
149  }
150}
151
152class RobCSRIO(implicit p: Parameters) extends XSBundle {
153  val intrBitSet = Input(Bool())
154  val trapTarget = Input(UInt(VAddrBits.W))
155  val isXRet     = Input(Bool())
156  val wfiEvent   = Input(Bool())
157
158  val fflags     = Output(Valid(UInt(5.W)))
159  val dirty_fs   = Output(Bool())
160  val perfinfo   = new Bundle {
161    val retiredInstr = Output(UInt(3.W))
162  }
163}
164
165class RobLsqIO(implicit p: Parameters) extends XSBundle {
166  val lcommit = Output(UInt(log2Up(CommitWidth + 1).W))
167  val scommit = Output(UInt(log2Up(CommitWidth + 1).W))
168  val pendingld = Output(Bool())
169  val pendingst = Output(Bool())
170  val commit = Output(Bool())
171  val pendingPtr = Output(new RobPtr)
172
173  val mmio = Input(Vec(LoadPipelineWidth, Bool()))
174  val uop = Input(Vec(LoadPipelineWidth, new MicroOp))
175}
176
177class RobEnqIO(implicit p: Parameters) extends XSBundle {
178  val canAccept = Output(Bool())
179  val isEmpty = Output(Bool())
180  // valid vector, for robIdx gen and walk
181  val needAlloc = Vec(RenameWidth, Input(Bool()))
182  val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
183  val resp = Vec(RenameWidth, Output(new RobPtr))
184}
185
186class RobDeqPtrWrapper(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
187  val io = IO(new Bundle {
188    // for commits/flush
189    val state = Input(UInt(2.W))
190    val deq_v = Vec(CommitWidth, Input(Bool()))
191    val deq_w = Vec(CommitWidth, Input(Bool()))
192    val exception_state = Flipped(ValidIO(new RobExceptionInfo))
193    // for flush: when exception occurs, reset deqPtrs to range(0, CommitWidth)
194    val intrBitSetReg = Input(Bool())
195    val hasNoSpecExec = Input(Bool())
196    val interrupt_safe = Input(Bool())
197    val blockCommit = Input(Bool())
198    // output: the CommitWidth deqPtr
199    val out = Vec(CommitWidth, Output(new RobPtr))
200    val next_out = Vec(CommitWidth, Output(new RobPtr))
201  })
202
203  val deqPtrVec = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new RobPtr))))
204
205  // for exceptions (flushPipe included) and interrupts:
206  // only consider the first instruction
207  val intrEnable = io.intrBitSetReg && !io.hasNoSpecExec && io.interrupt_safe
208  val exceptionEnable = io.deq_w(0) && io.exception_state.valid && io.exception_state.bits.not_commit && io.exception_state.bits.robIdx === deqPtrVec(0)
209  val redirectOutValid = io.state === 0.U && io.deq_v(0) && (intrEnable || exceptionEnable)
210
211  // for normal commits: only to consider when there're no exceptions
212  // we don't need to consider whether the first instruction has exceptions since it wil trigger exceptions.
213  val commit_exception = io.exception_state.valid && !isAfter(io.exception_state.bits.robIdx, deqPtrVec.last)
214  val canCommit = VecInit((0 until CommitWidth).map(i => io.deq_v(i) && io.deq_w(i)))
215  val normalCommitCnt = PriorityEncoder(canCommit.map(c => !c) :+ true.B)
216  // when io.intrBitSetReg or there're possible exceptions in these instructions,
217  // only one instruction is allowed to commit
218  val allowOnlyOne = commit_exception || io.intrBitSetReg
219  val commitCnt = Mux(allowOnlyOne, canCommit(0), normalCommitCnt)
220
221  val commitDeqPtrVec = VecInit(deqPtrVec.map(_ + commitCnt))
222  val deqPtrVec_next = Mux(io.state === 0.U && !redirectOutValid && !io.blockCommit, commitDeqPtrVec, deqPtrVec)
223
224  deqPtrVec := deqPtrVec_next
225
226  io.next_out := deqPtrVec_next
227  io.out      := deqPtrVec
228
229  when (io.state === 0.U) {
230    XSInfo(io.state === 0.U && commitCnt > 0.U, "retired %d insts\n", commitCnt)
231  }
232
233}
234
235class RobEnqPtrWrapper(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
236  val io = IO(new Bundle {
237    // for input redirect
238    val redirect = Input(Valid(new Redirect))
239    // for enqueue
240    val allowEnqueue = Input(Bool())
241    val hasBlockBackward = Input(Bool())
242    val enq = Vec(RenameWidth, Input(Bool()))
243    val out = Output(Vec(RenameWidth, new RobPtr))
244  })
245
246  val enqPtrVec = RegInit(VecInit.tabulate(RenameWidth)(_.U.asTypeOf(new RobPtr)))
247
248  // enqueue
249  val canAccept = io.allowEnqueue && !io.hasBlockBackward
250  val dispatchNum = Mux(canAccept, PopCount(io.enq), 0.U)
251
252  for ((ptr, i) <- enqPtrVec.zipWithIndex) {
253    when(io.redirect.valid) {
254      ptr := Mux(io.redirect.bits.flushItself(), io.redirect.bits.robIdx + i.U, io.redirect.bits.robIdx + (i + 1).U)
255    }.otherwise {
256      ptr := ptr + dispatchNum
257    }
258  }
259
260  io.out := enqPtrVec
261
262}
263
264class RobExceptionInfo(implicit p: Parameters) extends XSBundle {
265  // val valid = Bool()
266  val robIdx = new RobPtr
267  val exceptionVec = ExceptionVec()
268  val flushPipe = Bool()
269  val replayInst = Bool() // redirect to that inst itself
270  val singleStep = Bool() // TODO add frontend hit beneath
271  val crossPageIPFFix = Bool()
272  val trigger = new TriggerCf
273
274//  def trigger_before = !trigger.getTimingBackend && trigger.getHitBackend
275//  def trigger_after = trigger.getTimingBackend && trigger.getHitBackend
276  def has_exception = exceptionVec.asUInt.orR || flushPipe || singleStep || replayInst || trigger.hit
277  def not_commit = exceptionVec.asUInt.orR || singleStep || replayInst || trigger.hit
278  // only exceptions are allowed to writeback when enqueue
279  def can_writeback = exceptionVec.asUInt.orR || singleStep || trigger.hit
280}
281
282class ExceptionGen(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
283  val io = IO(new Bundle {
284    val redirect = Input(Valid(new Redirect))
285    val flush = Input(Bool())
286    val enq = Vec(RenameWidth, Flipped(ValidIO(new RobExceptionInfo)))
287    val wb = Vec(1 + LoadPipelineWidth + StorePipelineWidth, Flipped(ValidIO(new RobExceptionInfo)))
288    val out = ValidIO(new RobExceptionInfo)
289    val state = ValidIO(new RobExceptionInfo)
290  })
291
292  def getOldest(valid: Seq[Bool], bits: Seq[RobExceptionInfo]): (Seq[Bool], Seq[RobExceptionInfo]) = {
293    assert(valid.length == bits.length)
294    assert(isPow2(valid.length))
295    if (valid.length == 1) {
296      (valid, bits)
297    } else if (valid.length == 2) {
298      val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0)))))
299      for (i <- res.indices) {
300        res(i).valid := valid(i)
301        res(i).bits := bits(i)
302      }
303      val oldest = Mux(!valid(1) || valid(0) && isAfter(bits(1).robIdx, bits(0).robIdx), res(0), res(1))
304      (Seq(oldest.valid), Seq(oldest.bits))
305    } else {
306      val left = getOldest(valid.take(valid.length / 2), bits.take(valid.length / 2))
307      val right = getOldest(valid.takeRight(valid.length / 2), bits.takeRight(valid.length / 2))
308      getOldest(left._1 ++ right._1, left._2 ++ right._2)
309    }
310  }
311
312  val currentValid = RegInit(false.B)
313  val current = Reg(new RobExceptionInfo)
314
315  // orR the exceptionVec
316  val lastCycleFlush = RegNext(io.flush)
317  val in_enq_valid = VecInit(io.enq.map(e => e.valid && e.bits.has_exception && !lastCycleFlush))
318  val in_wb_valid = io.wb.map(w => w.valid && w.bits.has_exception && !lastCycleFlush)
319
320  // s0: compare wb(1)~wb(LoadPipelineWidth) and wb(1 + LoadPipelineWidth)~wb(LoadPipelineWidth + StorePipelineWidth)
321  val wb_valid = in_wb_valid.zip(io.wb.map(_.bits)).map{ case (v, bits) => v && !(bits.robIdx.needFlush(io.redirect) || io.flush) }
322  val csr_wb_bits = io.wb(0).bits
323  val load_wb_bits = getOldest(in_wb_valid.slice(1, 1 + LoadPipelineWidth), io.wb.map(_.bits).slice(1, 1 + LoadPipelineWidth))._2(0)
324  val store_wb_bits = getOldest(in_wb_valid.slice(1 + LoadPipelineWidth, 1 + LoadPipelineWidth + StorePipelineWidth), io.wb.map(_.bits).slice(1 + LoadPipelineWidth, 1 + LoadPipelineWidth + StorePipelineWidth))._2(0)
325  val s0_out_valid = RegNext(VecInit(Seq(wb_valid(0), wb_valid.slice(1, 1 + LoadPipelineWidth).reduce(_ || _), wb_valid.slice(1 + LoadPipelineWidth, 1 + LoadPipelineWidth + StorePipelineWidth).reduce(_ || _))))
326  val s0_out_bits = RegNext(VecInit(Seq(csr_wb_bits, load_wb_bits, store_wb_bits)))
327
328  // s1: compare last four and current flush
329  val s1_valid = VecInit(s0_out_valid.zip(s0_out_bits).map{ case (v, b) => v && !(b.robIdx.needFlush(io.redirect) || io.flush) })
330  val compare_01_valid = s0_out_valid(0) || s0_out_valid(1)
331  val compare_01_bits = Mux(!s0_out_valid(0) || s0_out_valid(1) && isAfter(s0_out_bits(0).robIdx, s0_out_bits(1).robIdx), s0_out_bits(1), s0_out_bits(0))
332  val compare_bits = Mux(!s0_out_valid(2) || compare_01_valid && isAfter(s0_out_bits(2).robIdx, compare_01_bits.robIdx), compare_01_bits, s0_out_bits(2))
333  val s1_out_bits = RegNext(compare_bits)
334  val s1_out_valid = RegNext(s1_valid.asUInt.orR)
335
336  val enq_valid = RegNext(in_enq_valid.asUInt.orR && !io.redirect.valid && !io.flush)
337  val enq_bits = RegNext(ParallelPriorityMux(in_enq_valid, io.enq.map(_.bits)))
338
339  // s2: compare the input exception with the current one
340  // priorities:
341  // (1) system reset
342  // (2) current is valid: flush, remain, merge, update
343  // (3) current is not valid: s1 or enq
344  val current_flush = current.robIdx.needFlush(io.redirect) || io.flush
345  val s1_flush = s1_out_bits.robIdx.needFlush(io.redirect) || io.flush
346  when (currentValid) {
347    when (current_flush) {
348      currentValid := Mux(s1_flush, false.B, s1_out_valid)
349    }
350    when (s1_out_valid && !s1_flush) {
351      when (isAfter(current.robIdx, s1_out_bits.robIdx)) {
352        current := s1_out_bits
353      }.elsewhen (current.robIdx === s1_out_bits.robIdx) {
354        current.exceptionVec := (s1_out_bits.exceptionVec.asUInt | current.exceptionVec.asUInt).asTypeOf(ExceptionVec())
355        current.flushPipe := s1_out_bits.flushPipe || current.flushPipe
356        current.replayInst := s1_out_bits.replayInst || current.replayInst
357        current.singleStep := s1_out_bits.singleStep || current.singleStep
358        current.trigger := (s1_out_bits.trigger.asUInt | current.trigger.asUInt).asTypeOf(new TriggerCf)
359      }
360    }
361  }.elsewhen (s1_out_valid && !s1_flush) {
362    currentValid := true.B
363    current := s1_out_bits
364  }.elsewhen (enq_valid && !(io.redirect.valid || io.flush)) {
365    currentValid := true.B
366    current := enq_bits
367  }
368
369  io.out.valid   := s1_out_valid || enq_valid && enq_bits.can_writeback
370  io.out.bits    := Mux(s1_out_valid, s1_out_bits, enq_bits)
371  io.state.valid := currentValid
372  io.state.bits  := current
373
374}
375
376class RobFlushInfo(implicit p: Parameters) extends XSBundle {
377  val ftqIdx = new FtqPtr
378  val robIdx = new RobPtr
379  val ftqOffset = UInt(log2Up(PredictWidth).W)
380  val replayInst = Bool()
381}
382
383class Rob(implicit p: Parameters) extends LazyModule with HasWritebackSink with HasXSParameter {
384
385  lazy val module = new RobImp(this)
386
387  override def generateWritebackIO(
388    thisMod: Option[HasWritebackSource] = None,
389    thisModImp: Option[HasWritebackSourceImp] = None
390  ): Unit = {
391    val sources = writebackSinksImp(thisMod, thisModImp)
392    module.io.writeback.zip(sources).foreach(x => x._1 := x._2)
393  }
394}
395
396class RobImp(outer: Rob)(implicit p: Parameters) extends LazyModuleImp(outer)
397  with HasXSParameter with HasCircularQueuePtrHelper with HasPerfEvents {
398  val wbExuConfigs = outer.writebackSinksParams.map(_.exuConfigs)
399  val numWbPorts = wbExuConfigs.map(_.length)
400
401  val io = IO(new Bundle() {
402    val hartId = Input(UInt(8.W))
403    val redirect = Input(Valid(new Redirect))
404    val enq = new RobEnqIO
405    val flushOut = ValidIO(new Redirect)
406    val exception = ValidIO(new ExceptionInfo)
407    // exu + brq
408    val writeback = MixedVec(numWbPorts.map(num => Vec(num, Flipped(ValidIO(new ExuOutput)))))
409    val commits = Output(new RobCommitIO)
410    val lsq = new RobLsqIO
411    val robDeqPtr = Output(new RobPtr)
412    val csr = new RobCSRIO
413    val robFull = Output(Bool())
414    val headNotReady = Output(Bool())
415    val cpu_halt = Output(Bool())
416    val wfi_enable = Input(Bool())
417    val debug_ls = Flipped(new DebugLSIO)
418    val debugRobHead = Output(new MicroOp)
419    val debugEnqLsq = Input(new LsqEnqIO)
420    val debugHeadLsIssue = Input(Bool())
421    val lsTopdownInfo = Vec(exuParameters.LduCnt, Input(new LsTopdownInfo))
422  })
423
424  def selectWb(index: Int, func: Seq[ExuConfig] => Boolean): Seq[(Seq[ExuConfig], ValidIO[ExuOutput])] = {
425    wbExuConfigs(index).zip(io.writeback(index)).filter(x => func(x._1))
426  }
427  val exeWbSel = outer.selWritebackSinks(_.exuConfigs.length)
428  val fflagsWbSel = outer.selWritebackSinks(_.exuConfigs.count(_.exists(_.writeFflags)))
429  val fflagsPorts = selectWb(fflagsWbSel, _.exists(_.writeFflags))
430  val exceptionWbSel = outer.selWritebackSinks(_.exuConfigs.count(_.exists(_.needExceptionGen)))
431  val exceptionPorts = selectWb(fflagsWbSel, _.exists(_.needExceptionGen))
432  val exuWbPorts = selectWb(exeWbSel, _.forall(_ != StdExeUnitCfg))
433  val stdWbPorts = selectWb(exeWbSel, _.contains(StdExeUnitCfg))
434  println(s"Rob: size $RobSize, numWbPorts: $numWbPorts, commitwidth: $CommitWidth")
435  println(s"exuPorts: ${exuWbPorts.map(_._1.map(_.name))}")
436  println(s"stdPorts: ${stdWbPorts.map(_._1.map(_.name))}")
437  println(s"fflags: ${fflagsPorts.map(_._1.map(_.name))}")
438
439
440  val exuWriteback = exuWbPorts.map(_._2)
441  val stdWriteback = stdWbPorts.map(_._2)
442
443  // instvalid field
444  val valid = RegInit(VecInit(Seq.fill(RobSize)(false.B)))
445  // writeback status
446  val writebacked = Mem(RobSize, Bool())
447  val store_data_writebacked = Mem(RobSize, Bool())
448  val mmio = RegInit(VecInit(Seq.fill(RobSize)(false.B)))
449  // data for redirect, exception, etc.
450  val flagBkup = Mem(RobSize, Bool())
451  // some instructions are not allowed to trigger interrupts
452  // They have side effects on the states of the processor before they write back
453  val interrupt_safe = Mem(RobSize, Bool())
454
455  // data for debug
456  // Warn: debug_* prefix should not exist in generated verilog.
457  val debug_microOp = Mem(RobSize, new MicroOp)
458  val debug_exuData = Reg(Vec(RobSize, UInt(XLEN.W)))//for debug
459  val debug_exuDebug = Reg(Vec(RobSize, new DebugBundle))//for debug
460  val debug_lsInfo = RegInit(VecInit(Seq.fill(RobSize)(DebugLsInfo.init)))
461  val debug_lsTopdownInfo = RegInit(VecInit(Seq.fill(RobSize)(LsTopdownInfo.init)))
462  val debug_lqIdxValid = RegInit(VecInit.fill(RobSize)(false.B))
463  val debug_lsIssued = RegInit(VecInit.fill(RobSize)(false.B))
464
465  // pointers
466  // For enqueue ptr, we don't duplicate it since only enqueue needs it.
467  val enqPtrVec = Wire(Vec(RenameWidth, new RobPtr))
468  val deqPtrVec = Wire(Vec(CommitWidth, new RobPtr))
469
470  val walkPtrVec = Reg(Vec(CommitWidth, new RobPtr))
471  val allowEnqueue = RegInit(true.B)
472
473  val enqPtr = enqPtrVec.head
474  val deqPtr = deqPtrVec(0)
475  val walkPtr = walkPtrVec(0)
476
477  val isEmpty = enqPtr === deqPtr
478  val isReplaying = io.redirect.valid && RedirectLevel.flushItself(io.redirect.bits.level)
479
480  val debug_lsIssue = WireDefault(debug_lsIssued)
481  debug_lsIssue(deqPtr.value) := io.debugHeadLsIssue
482
483  /**
484    * states of Rob
485    */
486  val s_idle :: s_walk :: Nil = Enum(2)
487  val state = RegInit(s_idle)
488
489  /**
490    * Data Modules
491    *
492    * CommitDataModule: data from dispatch
493    * (1) read: commits/walk/exception
494    * (2) write: enqueue
495    *
496    * WritebackData: data from writeback
497    * (1) read: commits/walk/exception
498    * (2) write: write back from exe units
499    */
500  val dispatchData = Module(new SyncDataModuleTemplate(new RobCommitInfo, RobSize, CommitWidth, RenameWidth))
501  val dispatchDataRead = dispatchData.io.rdata
502
503  val exceptionGen = Module(new ExceptionGen)
504  val exceptionDataRead = exceptionGen.io.state
505  val fflagsDataRead = Wire(Vec(CommitWidth, UInt(5.W)))
506
507  io.robDeqPtr := deqPtr
508  io.debugRobHead := debug_microOp(deqPtr.value)
509
510  /**
511    * Enqueue (from dispatch)
512    */
513  // special cases
514  val hasBlockBackward = RegInit(false.B)
515  val hasNoSpecExec = RegInit(false.B)
516  val doingSvinval = RegInit(false.B)
517  // When blockBackward instruction leaves Rob (commit or walk), hasBlockBackward should be set to false.B
518  // To reduce registers usage, for hasBlockBackward cases, we allow enqueue after ROB is empty.
519  when (isEmpty) { hasBlockBackward:= false.B }
520  // When any instruction commits, hasNoSpecExec should be set to false.B
521  when (io.commits.hasWalkInstr || io.commits.hasCommitInstr) { hasNoSpecExec:= false.B }
522
523  // The wait-for-interrupt (WFI) instruction waits in the ROB until an interrupt might need servicing.
524  // io.csr.wfiEvent will be asserted if the WFI can resume execution, and we change the state to s_wfi_idle.
525  // It does not affect how interrupts are serviced. Note that WFI is noSpecExec and it does not trigger interrupts.
526  val hasWFI = RegInit(false.B)
527  io.cpu_halt := hasWFI
528  // WFI Timeout: 2^20 = 1M cycles
529  val wfi_cycles = RegInit(0.U(20.W))
530  when (hasWFI) {
531    wfi_cycles := wfi_cycles + 1.U
532  }.elsewhen (!hasWFI && RegNext(hasWFI)) {
533    wfi_cycles := 0.U
534  }
535  val wfi_timeout = wfi_cycles.andR
536  when (RegNext(RegNext(io.csr.wfiEvent)) || io.flushOut.valid || wfi_timeout) {
537    hasWFI := false.B
538  }
539
540  val allocatePtrVec = VecInit((0 until RenameWidth).map(i => enqPtrVec(PopCount(io.enq.needAlloc.take(i)))))
541  io.enq.canAccept := allowEnqueue && !hasBlockBackward
542  io.enq.resp      := allocatePtrVec
543  val canEnqueue = VecInit(io.enq.req.map(_.valid && io.enq.canAccept))
544  val timer = GTimer()
545  for (i <- 0 until RenameWidth) {
546    // we don't check whether io.redirect is valid here since redirect has higher priority
547    when (canEnqueue(i)) {
548      val enqUop = io.enq.req(i).bits
549      val enqIndex = allocatePtrVec(i).value
550      // store uop in data module and debug_microOp Vec
551      debug_microOp(enqIndex) := enqUop
552      debug_microOp(enqIndex).debugInfo.dispatchTime := timer
553      debug_microOp(enqIndex).debugInfo.enqRsTime := timer
554      debug_microOp(enqIndex).debugInfo.selectTime := timer
555      debug_microOp(enqIndex).debugInfo.issueTime := timer
556      debug_microOp(enqIndex).debugInfo.writebackTime := timer
557      debug_microOp(enqIndex).debugInfo.tlbFirstReqTime := timer
558      debug_microOp(enqIndex).debugInfo.tlbRespTime := timer
559      debug_lsInfo(enqIndex) := DebugLsInfo.init
560      debug_lsTopdownInfo(enqIndex) := LsTopdownInfo.init
561      debug_lqIdxValid(enqIndex) := false.B
562      debug_lsIssued(enqIndex) := false.B
563      when (enqUop.ctrl.blockBackward) {
564        hasBlockBackward := true.B
565      }
566      when (enqUop.ctrl.noSpecExec) {
567        hasNoSpecExec := true.B
568      }
569      val enqHasTriggerHit = io.enq.req(i).bits.cf.trigger.getHitFrontend
570      val enqHasException = ExceptionNO.selectFrontend(enqUop.cf.exceptionVec).asUInt.orR
571      // the begin instruction of Svinval enqs so mark doingSvinval as true to indicate this process
572      when(!enqHasTriggerHit && !enqHasException && FuType.isSvinvalBegin(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe))
573      {
574        doingSvinval := true.B
575      }
576      // the end instruction of Svinval enqs so clear doingSvinval
577      when(!enqHasTriggerHit && !enqHasException && FuType.isSvinvalEnd(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe))
578      {
579        doingSvinval := false.B
580      }
581      // when we are in the process of Svinval software code area , only Svinval.vma and end instruction of Svinval can appear
582      assert(!doingSvinval || (FuType.isSvinval(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe) ||
583        FuType.isSvinvalEnd(enqUop.ctrl.fuType, enqUop.ctrl.fuOpType, enqUop.ctrl.flushPipe)))
584      when (enqUop.ctrl.isWFI && !enqHasException && !enqHasTriggerHit) {
585        hasWFI := true.B
586      }
587
588      mmio(enqIndex) := false.B
589    }
590  }
591  val dispatchNum = Mux(io.enq.canAccept, PopCount(io.enq.req.map(_.valid)), 0.U)
592  io.enq.isEmpty   := RegNext(isEmpty && !VecInit(io.enq.req.map(_.valid)).asUInt.orR)
593
594  when (!io.wfi_enable) {
595    hasWFI := false.B
596  }
597
598  // lqEnq
599  io.debugEnqLsq.needAlloc.map(_(0)).zip(io.debugEnqLsq.req).foreach { case (alloc, req) =>
600    when(io.debugEnqLsq.canAccept && alloc && req.valid) {
601      debug_microOp(req.bits.robIdx.value).lqIdx := req.bits.lqIdx
602      debug_lqIdxValid(req.bits.robIdx.value) := true.B
603    }
604  }
605
606  // lsIssue
607  when(io.debugHeadLsIssue) {
608    debug_lsIssued(deqPtr.value) := true.B
609  }
610
611  /**
612    * Writeback (from execution units)
613    */
614  for (wb <- exuWriteback) {
615    when (wb.valid) {
616      val wbIdx = wb.bits.uop.robIdx.value
617      debug_exuData(wbIdx) := wb.bits.data
618      debug_exuDebug(wbIdx) := wb.bits.debug
619      debug_microOp(wbIdx).debugInfo.enqRsTime := wb.bits.uop.debugInfo.enqRsTime
620      debug_microOp(wbIdx).debugInfo.selectTime := wb.bits.uop.debugInfo.selectTime
621      debug_microOp(wbIdx).debugInfo.issueTime := wb.bits.uop.debugInfo.issueTime
622      debug_microOp(wbIdx).debugInfo.writebackTime := wb.bits.uop.debugInfo.writebackTime
623      debug_microOp(wbIdx).debugInfo.tlbFirstReqTime := wb.bits.uop.debugInfo.tlbFirstReqTime
624      debug_microOp(wbIdx).debugInfo.tlbRespTime := wb.bits.uop.debugInfo.tlbRespTime
625
626      // debug for lqidx and sqidx
627      debug_microOp(wbIdx).lqIdx := wb.bits.uop.lqIdx
628      debug_microOp(wbIdx).sqIdx := wb.bits.uop.sqIdx
629
630      val debug_Uop = debug_microOp(wbIdx)
631      XSInfo(true.B,
632        p"writebacked pc 0x${Hexadecimal(debug_Uop.cf.pc)} wen ${debug_Uop.ctrl.rfWen} " +
633        p"data 0x${Hexadecimal(wb.bits.data)} ldst ${debug_Uop.ctrl.ldest} pdst ${debug_Uop.pdest} " +
634        p"skip ${wb.bits.debug.isMMIO} robIdx: ${wb.bits.uop.robIdx}\n"
635      )
636    }
637  }
638  val writebackNum = PopCount(exuWriteback.map(_.valid))
639  XSInfo(writebackNum =/= 0.U, "writebacked %d insts\n", writebackNum)
640
641  for (i <- 0 until LoadPipelineWidth) {
642    when (RegNext(io.lsq.mmio(i))) {
643      mmio(RegNext(io.lsq.uop(i).robIdx).value) := true.B
644    }
645  }
646
647  /**
648    * RedirectOut: Interrupt and Exceptions
649    */
650  val deqDispatchData = dispatchDataRead(0)
651  val debug_deqUop = debug_microOp(deqPtr.value)
652
653  val intrBitSetReg = RegNext(io.csr.intrBitSet)
654  val intrEnable = intrBitSetReg && !hasNoSpecExec && interrupt_safe(deqPtr.value)
655  val deqHasExceptionOrFlush = exceptionDataRead.valid && exceptionDataRead.bits.robIdx === deqPtr
656  val deqHasException = deqHasExceptionOrFlush && (exceptionDataRead.bits.exceptionVec.asUInt.orR ||
657    exceptionDataRead.bits.singleStep || exceptionDataRead.bits.trigger.hit)
658  val deqHasFlushPipe = deqHasExceptionOrFlush && exceptionDataRead.bits.flushPipe
659  val deqHasReplayInst = deqHasExceptionOrFlush && exceptionDataRead.bits.replayInst
660  val exceptionEnable = writebacked(deqPtr.value) && deqHasException
661
662  XSDebug(deqHasException && exceptionDataRead.bits.singleStep, "Debug Mode: Deq has singlestep exception\n")
663  XSDebug(deqHasException && exceptionDataRead.bits.trigger.getHitFrontend, "Debug Mode: Deq has frontend trigger exception\n")
664  XSDebug(deqHasException && exceptionDataRead.bits.trigger.getHitBackend, "Debug Mode: Deq has backend trigger exception\n")
665
666  val isFlushPipe = writebacked(deqPtr.value) && (deqHasFlushPipe || deqHasReplayInst)
667
668  // io.flushOut will trigger redirect at the next cycle.
669  // Block any redirect or commit at the next cycle.
670  val lastCycleFlush = RegNext(io.flushOut.valid)
671
672  io.flushOut.valid := (state === s_idle) && valid(deqPtr.value) && (intrEnable || exceptionEnable || isFlushPipe) && !lastCycleFlush
673  io.flushOut.bits := DontCare
674  io.flushOut.bits.robIdx := deqPtr
675  io.flushOut.bits.ftqIdx := deqDispatchData.ftqIdx
676  io.flushOut.bits.ftqOffset := deqDispatchData.ftqOffset
677  io.flushOut.bits.level := Mux(deqHasReplayInst || intrEnable || exceptionEnable, RedirectLevel.flush, RedirectLevel.flushAfter) // TODO use this to implement "exception next"
678  io.flushOut.bits.interrupt := true.B
679  XSPerfAccumulate("interrupt_num", io.flushOut.valid && intrEnable)
680  XSPerfAccumulate("exception_num", io.flushOut.valid && exceptionEnable)
681  XSPerfAccumulate("flush_pipe_num", io.flushOut.valid && isFlushPipe)
682  XSPerfAccumulate("replay_inst_num", io.flushOut.valid && isFlushPipe && deqHasReplayInst)
683
684  val exceptionHappen = (state === s_idle) && valid(deqPtr.value) && (intrEnable || exceptionEnable) && !lastCycleFlush
685  io.exception.valid := RegNext(exceptionHappen)
686  io.exception.bits.uop := RegEnable(debug_deqUop, exceptionHappen)
687  io.exception.bits.uop.ctrl.commitType := RegEnable(deqDispatchData.commitType, exceptionHappen)
688  io.exception.bits.uop.cf.exceptionVec := RegEnable(exceptionDataRead.bits.exceptionVec, exceptionHappen)
689  io.exception.bits.uop.ctrl.singleStep := RegEnable(exceptionDataRead.bits.singleStep, exceptionHappen)
690  io.exception.bits.uop.cf.crossPageIPFFix := RegEnable(exceptionDataRead.bits.crossPageIPFFix, exceptionHappen)
691  io.exception.bits.isInterrupt := RegEnable(intrEnable, exceptionHappen)
692  io.exception.bits.uop.cf.trigger := RegEnable(exceptionDataRead.bits.trigger, exceptionHappen)
693
694  XSDebug(io.flushOut.valid,
695    p"generate redirect: pc 0x${Hexadecimal(io.exception.bits.uop.cf.pc)} intr $intrEnable " +
696    p"excp $exceptionEnable flushPipe $isFlushPipe " +
697    p"Trap_target 0x${Hexadecimal(io.csr.trapTarget)} exceptionVec ${Binary(exceptionDataRead.bits.exceptionVec.asUInt)}\n")
698
699
700  /**
701    * Commits (and walk)
702    * They share the same width.
703    */
704  val walkCounter = Reg(UInt(log2Up(RobSize + 1).W))
705  val shouldWalkVec = VecInit((0 until CommitWidth).map(_.U < walkCounter))
706  val walkFinished = walkCounter <= CommitWidth.U
707
708  require(RenameWidth <= CommitWidth)
709
710  // wiring to csr
711  val (wflags, fpWen) = (0 until CommitWidth).map(i => {
712    val v = io.commits.commitValid(i)
713    val info = io.commits.info(i)
714    (v & info.wflags, v & info.fpWen)
715  }).unzip
716  val fflags = Wire(Valid(UInt(5.W)))
717  fflags.valid := io.commits.isCommit && VecInit(wflags).asUInt.orR
718  fflags.bits := wflags.zip(fflagsDataRead).map({
719    case (w, f) => Mux(w, f, 0.U)
720  }).reduce(_|_)
721  val dirty_fs = io.commits.isCommit && VecInit(fpWen).asUInt.orR
722
723  // when mispredict branches writeback, stop commit in the next 2 cycles
724  // TODO: don't check all exu write back
725  val misPredWb = Cat(VecInit(exuWriteback.map(wb =>
726    wb.bits.redirect.cfiUpdate.isMisPred && wb.bits.redirectValid
727  ))).orR
728  val misPredBlockCounter = Reg(UInt(3.W))
729  misPredBlockCounter := Mux(misPredWb,
730    "b111".U,
731    misPredBlockCounter >> 1.U
732  )
733  val misPredBlock = misPredBlockCounter(0)
734  val blockCommit = misPredBlock || isReplaying || lastCycleFlush || hasWFI
735
736  io.commits.isWalk := state === s_walk
737  io.commits.isCommit := state === s_idle && !blockCommit
738  val walk_v = VecInit(walkPtrVec.map(ptr => valid(ptr.value)))
739  val commit_v = VecInit(deqPtrVec.map(ptr => valid(ptr.value)))
740  // store will be commited iff both sta & std have been writebacked
741  val commit_w = VecInit(deqPtrVec.map(ptr => writebacked(ptr.value) && store_data_writebacked(ptr.value)))
742  val commit_exception = exceptionDataRead.valid && !isAfter(exceptionDataRead.bits.robIdx, deqPtrVec.last)
743  val commit_block = VecInit((0 until CommitWidth).map(i => !commit_w(i)))
744  val allowOnlyOneCommit = commit_exception || intrBitSetReg
745  // for instructions that may block others, we don't allow them to commit
746  for (i <- 0 until CommitWidth) {
747    // defaults: state === s_idle and instructions commit
748    // when intrBitSetReg, allow only one instruction to commit at each clock cycle
749    val isBlocked = if (i != 0) Cat(commit_block.take(i)).orR || allowOnlyOneCommit else intrEnable || deqHasException || deqHasReplayInst
750    io.commits.commitValid(i) := commit_v(i) && commit_w(i) && !isBlocked
751    io.commits.info(i)  := dispatchDataRead(i)
752
753    when (state === s_walk) {
754      io.commits.walkValid(i) := shouldWalkVec(i)
755      when (io.commits.isWalk && state === s_walk && shouldWalkVec(i)) {
756        XSError(!walk_v(i), s"why not $i???\n")
757      }
758    }
759
760    XSInfo(io.commits.isCommit && io.commits.commitValid(i),
761      "retired pc %x wen %d ldest %d pdest %x old_pdest %x data %x fflags: %b\n",
762      debug_microOp(deqPtrVec(i).value).cf.pc,
763      io.commits.info(i).rfWen,
764      io.commits.info(i).ldest,
765      io.commits.info(i).pdest,
766      io.commits.info(i).old_pdest,
767      debug_exuData(deqPtrVec(i).value),
768      fflagsDataRead(i)
769    )
770    XSInfo(state === s_walk && io.commits.walkValid(i), "walked pc %x wen %d ldst %d data %x\n",
771      debug_microOp(walkPtrVec(i).value).cf.pc,
772      io.commits.info(i).rfWen,
773      io.commits.info(i).ldest,
774      debug_exuData(walkPtrVec(i).value)
775    )
776  }
777  if (env.EnableDifftest) {
778    io.commits.info.map(info => dontTouch(info.pc))
779  }
780
781  // sync fflags/dirty_fs to csr
782  io.csr.fflags := RegNext(fflags)
783  io.csr.dirty_fs := RegNext(dirty_fs)
784
785  // commit load/store to lsq
786  val ldCommitVec = VecInit((0 until CommitWidth).map(i => io.commits.commitValid(i) && io.commits.info(i).commitType === CommitType.LOAD))
787  val stCommitVec = VecInit((0 until CommitWidth).map(i => io.commits.commitValid(i) && io.commits.info(i).commitType === CommitType.STORE))
788  io.lsq.lcommit := RegNext(Mux(io.commits.isCommit, PopCount(ldCommitVec), 0.U))
789  io.lsq.scommit := RegNext(Mux(io.commits.isCommit, PopCount(stCommitVec), 0.U))
790  // indicate a pending load or store
791  io.lsq.pendingld := RegNext(io.commits.isCommit && io.commits.info(0).commitType === CommitType.LOAD && valid(deqPtr.value) && mmio(deqPtr.value))
792  io.lsq.pendingst := RegNext(io.commits.isCommit && io.commits.info(0).commitType === CommitType.STORE && valid(deqPtr.value))
793  io.lsq.commit := RegNext(io.commits.isCommit && io.commits.commitValid(0))
794  io.lsq.pendingPtr := RegNext(deqPtr)
795
796  /**
797    * state changes
798    * (1) redirect: switch to s_walk
799    * (2) walk: when walking comes to the end, switch to s_idle
800    */
801  val state_next = Mux(io.redirect.valid, s_walk, Mux(state === s_walk && walkFinished, s_idle, state))
802  XSPerfAccumulate("s_idle_to_idle",            state === s_idle && state_next === s_idle)
803  XSPerfAccumulate("s_idle_to_walk",            state === s_idle && state_next === s_walk)
804  XSPerfAccumulate("s_walk_to_idle",            state === s_walk && state_next === s_idle)
805  XSPerfAccumulate("s_walk_to_walk",            state === s_walk && state_next === s_walk)
806  state := state_next
807
808  /**
809    * pointers and counters
810    */
811  val deqPtrGenModule = Module(new RobDeqPtrWrapper)
812  deqPtrGenModule.io.state := state
813  deqPtrGenModule.io.deq_v := commit_v
814  deqPtrGenModule.io.deq_w := commit_w
815  deqPtrGenModule.io.exception_state := exceptionDataRead
816  deqPtrGenModule.io.intrBitSetReg := intrBitSetReg
817  deqPtrGenModule.io.hasNoSpecExec := hasNoSpecExec
818  deqPtrGenModule.io.interrupt_safe := interrupt_safe(deqPtr.value)
819  deqPtrGenModule.io.blockCommit := blockCommit
820  deqPtrVec := deqPtrGenModule.io.out
821  val deqPtrVec_next = deqPtrGenModule.io.next_out
822
823  val enqPtrGenModule = Module(new RobEnqPtrWrapper)
824  enqPtrGenModule.io.redirect := io.redirect
825  enqPtrGenModule.io.allowEnqueue := allowEnqueue
826  enqPtrGenModule.io.hasBlockBackward := hasBlockBackward
827  enqPtrGenModule.io.enq := VecInit(io.enq.req.map(_.valid))
828  enqPtrVec := enqPtrGenModule.io.out
829
830  val thisCycleWalkCount = Mux(walkFinished, walkCounter, CommitWidth.U)
831  // next walkPtrVec:
832  // (1) redirect occurs: update according to state
833  // (2) walk: move forwards
834  val walkPtrVec_next = Mux(io.redirect.valid,
835    deqPtrVec_next,
836    Mux(state === s_walk, VecInit(walkPtrVec.map(_ + CommitWidth.U)), walkPtrVec)
837  )
838  walkPtrVec := walkPtrVec_next
839
840  val numValidEntries = distanceBetween(enqPtr, deqPtr)
841  val commitCnt = PopCount(io.commits.commitValid)
842
843  allowEnqueue := numValidEntries + dispatchNum <= (RobSize - RenameWidth).U
844
845  val currentWalkPtr = Mux(state === s_walk, walkPtr, deqPtrVec_next(0))
846  val redirectWalkDistance = distanceBetween(io.redirect.bits.robIdx, deqPtrVec_next(0))
847  when (io.redirect.valid) {
848    // full condition:
849    // +& is used here because:
850    // When rob is full and the tail instruction causes a misprediction,
851    // the redirect robIdx is the deqPtr - 1. In this case, redirectWalkDistance
852    // is RobSize - 1.
853    // Since misprediction does not flush the instruction itself, flushItSelf is false.B.
854    // Previously we use `+` to count the walk distance and it causes overflows
855    // when RobSize is power of 2. We change it to `+&` to allow walkCounter to be RobSize.
856    // The width of walkCounter also needs to be changed.
857    // empty condition:
858    // When the last instruction in ROB commits and causes a flush, a redirect
859    // will be raised later. In such circumstances, the redirect robIdx is before
860    // the deqPtrVec_next(0) and will cause underflow.
861    walkCounter := Mux(isBefore(io.redirect.bits.robIdx, deqPtrVec_next(0)), 0.U,
862                       redirectWalkDistance +& !io.redirect.bits.flushItself())
863  }.elsewhen (state === s_walk) {
864    walkCounter := walkCounter - thisCycleWalkCount
865    XSInfo(p"rolling back: $enqPtr $deqPtr walk $walkPtr walkcnt $walkCounter\n")
866  }
867
868
869  /**
870    * States
871    * We put all the stage bits changes here.
872
873    * All events: (1) enqueue (dispatch); (2) writeback; (3) cancel; (4) dequeue (commit);
874    * All states: (1) valid; (2) writebacked; (3) flagBkup
875    */
876  val commitReadAddr = Mux(state === s_idle, VecInit(deqPtrVec.map(_.value)), VecInit(walkPtrVec.map(_.value)))
877
878  // redirect logic writes 6 valid
879  val redirectHeadVec = Reg(Vec(RenameWidth, new RobPtr))
880  val redirectTail = Reg(new RobPtr)
881  val redirectIdle :: redirectBusy :: Nil = Enum(2)
882  val redirectState = RegInit(redirectIdle)
883  val invMask = redirectHeadVec.map(redirectHead => isBefore(redirectHead, redirectTail))
884  when(redirectState === redirectBusy) {
885    redirectHeadVec.foreach(redirectHead => redirectHead := redirectHead + RenameWidth.U)
886    redirectHeadVec zip invMask foreach {
887      case (redirectHead, inv) => when(inv) {
888        valid(redirectHead.value) := false.B
889      }
890    }
891    when(!invMask.last) {
892      redirectState := redirectIdle
893    }
894  }
895  when(io.redirect.valid) {
896    redirectState := redirectBusy
897    when(redirectState === redirectIdle) {
898      redirectTail := enqPtr
899    }
900    redirectHeadVec.zipWithIndex.foreach { case (redirectHead, i) =>
901      redirectHead := Mux(io.redirect.bits.flushItself(), io.redirect.bits.robIdx + i.U, io.redirect.bits.robIdx + (i + 1).U)
902    }
903  }
904  // enqueue logic writes 6 valid
905  for (i <- 0 until RenameWidth) {
906    when (canEnqueue(i) && !io.redirect.valid) {
907      valid(allocatePtrVec(i).value) := true.B
908    }
909  }
910  // dequeue logic writes 6 valid
911  for (i <- 0 until CommitWidth) {
912    val commitValid = io.commits.isCommit && io.commits.commitValid(i)
913    when (commitValid) {
914      valid(commitReadAddr(i)) := false.B
915    }
916  }
917
918  // debug_inst update
919  for(i <- 0 until (exuParameters.LduCnt + exuParameters.StuCnt)) {
920    debug_lsInfo(io.debug_ls.debugLsInfo(i).s1_robIdx).s1SignalEnable(io.debug_ls.debugLsInfo(i))
921    debug_lsInfo(io.debug_ls.debugLsInfo(i).s2_robIdx).s2SignalEnable(io.debug_ls.debugLsInfo(i))
922  }
923  for (i <- 0 until exuParameters.LduCnt) {
924    debug_lsTopdownInfo(io.lsTopdownInfo(i).s1.robIdx).s1SignalEnable(io.lsTopdownInfo(i))
925    debug_lsTopdownInfo(io.lsTopdownInfo(i).s2.robIdx).s2SignalEnable(io.lsTopdownInfo(i))
926  }
927
928  // status field: writebacked
929  // enqueue logic set 6 writebacked to false
930  for (i <- 0 until RenameWidth) {
931    when (canEnqueue(i)) {
932      val enqHasException = ExceptionNO.selectFrontend(io.enq.req(i).bits.cf.exceptionVec).asUInt.orR
933      val enqHasTriggerHit = io.enq.req(i).bits.cf.trigger.getHitFrontend
934      val enqIsWritebacked = io.enq.req(i).bits.eliminatedMove
935      writebacked(allocatePtrVec(i).value) := enqIsWritebacked && !enqHasException && !enqHasTriggerHit
936      val isStu = io.enq.req(i).bits.ctrl.fuType === FuType.stu
937      store_data_writebacked(allocatePtrVec(i).value) := !isStu
938    }
939  }
940  when (exceptionGen.io.out.valid) {
941    val wbIdx = exceptionGen.io.out.bits.robIdx.value
942    writebacked(wbIdx) := true.B
943    store_data_writebacked(wbIdx) := true.B
944  }
945  // writeback logic set numWbPorts writebacked to true
946  for ((wb, cfgs) <- exuWriteback.zip(wbExuConfigs(exeWbSel))) {
947    when (wb.valid) {
948      val wbIdx = wb.bits.uop.robIdx.value
949      val wbHasException = ExceptionNO.selectByExu(wb.bits.uop.cf.exceptionVec, cfgs).asUInt.orR
950      val wbHasTriggerHit = wb.bits.uop.cf.trigger.getHitBackend
951      val wbHasFlushPipe = cfgs.exists(_.flushPipe).B && wb.bits.uop.ctrl.flushPipe
952      val wbHasReplayInst = cfgs.exists(_.replayInst).B && wb.bits.uop.ctrl.replayInst
953      val block_wb = wbHasException || wbHasFlushPipe || wbHasReplayInst || wbHasTriggerHit
954      writebacked(wbIdx) := !block_wb
955    }
956  }
957  // store data writeback logic mark store as data_writebacked
958  for (wb <- stdWriteback) {
959    when(RegNext(wb.valid)) {
960      store_data_writebacked(RegNext(wb.bits.uop.robIdx.value)) := true.B
961    }
962  }
963
964  // flagBkup
965  // enqueue logic set 6 flagBkup at most
966  for (i <- 0 until RenameWidth) {
967    when (canEnqueue(i)) {
968      flagBkup(allocatePtrVec(i).value) := allocatePtrVec(i).flag
969    }
970  }
971
972  // interrupt_safe
973  for (i <- 0 until RenameWidth) {
974    // We RegNext the updates for better timing.
975    // Note that instructions won't change the system's states in this cycle.
976    when (RegNext(canEnqueue(i))) {
977      // For now, we allow non-load-store instructions to trigger interrupts
978      // For MMIO instructions, they should not trigger interrupts since they may
979      // be sent to lower level before it writes back.
980      // However, we cannot determine whether a load/store instruction is MMIO.
981      // Thus, we don't allow load/store instructions to trigger an interrupt.
982      // TODO: support non-MMIO load-store instructions to trigger interrupts
983      val allow_interrupts = !CommitType.isLoadStore(io.enq.req(i).bits.ctrl.commitType)
984      interrupt_safe(RegNext(allocatePtrVec(i).value)) := RegNext(allow_interrupts)
985    }
986  }
987
988  /**
989    * read and write of data modules
990    */
991  val commitReadAddr_next = Mux(state_next === s_idle,
992    VecInit(deqPtrVec_next.map(_.value)),
993    VecInit(walkPtrVec_next.map(_.value))
994  )
995  // NOTE: dispatch info will record the uop of inst
996  dispatchData.io.wen := canEnqueue
997  dispatchData.io.waddr := allocatePtrVec.map(_.value)
998  dispatchData.io.wdata.zip(io.enq.req.map(_.bits)).foreach{ case (wdata, req) =>
999    wdata.ldest := req.ctrl.ldest
1000    wdata.rfWen := req.ctrl.rfWen
1001    wdata.fpWen := req.ctrl.fpWen
1002    wdata.wflags := req.ctrl.fpu.wflags
1003    wdata.commitType := req.ctrl.commitType
1004    wdata.pdest := req.pdest
1005    wdata.old_pdest := req.old_pdest
1006    wdata.ftqIdx := req.cf.ftqPtr
1007    wdata.ftqOffset := req.cf.ftqOffset
1008    wdata.isMove := req.eliminatedMove
1009    wdata.pc := req.cf.pc
1010  }
1011  dispatchData.io.raddr := commitReadAddr_next
1012
1013  exceptionGen.io.redirect <> io.redirect
1014  exceptionGen.io.flush := io.flushOut.valid
1015  for (i <- 0 until RenameWidth) {
1016    exceptionGen.io.enq(i).valid := canEnqueue(i)
1017    exceptionGen.io.enq(i).bits.robIdx := io.enq.req(i).bits.robIdx
1018    exceptionGen.io.enq(i).bits.exceptionVec := ExceptionNO.selectFrontend(io.enq.req(i).bits.cf.exceptionVec)
1019    exceptionGen.io.enq(i).bits.flushPipe := io.enq.req(i).bits.ctrl.flushPipe
1020    exceptionGen.io.enq(i).bits.replayInst := false.B
1021    XSError(canEnqueue(i) && io.enq.req(i).bits.ctrl.replayInst, "enq should not set replayInst")
1022    exceptionGen.io.enq(i).bits.singleStep := io.enq.req(i).bits.ctrl.singleStep
1023    exceptionGen.io.enq(i).bits.crossPageIPFFix := io.enq.req(i).bits.cf.crossPageIPFFix
1024    exceptionGen.io.enq(i).bits.trigger.clear()
1025    exceptionGen.io.enq(i).bits.trigger.frontendHit := io.enq.req(i).bits.cf.trigger.frontendHit
1026  }
1027
1028  println(s"ExceptionGen:")
1029  val exceptionCases = exceptionPorts.map(_._1.flatMap(_.exceptionOut).distinct.sorted)
1030  require(exceptionCases.length == exceptionGen.io.wb.length)
1031  for ((((configs, wb), exc_wb), i) <- exceptionPorts.zip(exceptionGen.io.wb).zipWithIndex) {
1032    exc_wb.valid                := wb.valid
1033    exc_wb.bits.robIdx          := wb.bits.uop.robIdx
1034    exc_wb.bits.exceptionVec    := ExceptionNO.selectByExu(wb.bits.uop.cf.exceptionVec, configs)
1035    exc_wb.bits.flushPipe       := configs.exists(_.flushPipe).B && wb.bits.uop.ctrl.flushPipe
1036    exc_wb.bits.replayInst      := configs.exists(_.replayInst).B && wb.bits.uop.ctrl.replayInst
1037    exc_wb.bits.singleStep      := false.B
1038    exc_wb.bits.crossPageIPFFix := false.B
1039    // TODO: make trigger configurable
1040    exc_wb.bits.trigger.clear()
1041    exc_wb.bits.trigger.backendHit := wb.bits.uop.cf.trigger.backendHit
1042    println(s"  [$i] ${configs.map(_.name)}: exception ${exceptionCases(i)}, " +
1043      s"flushPipe ${configs.exists(_.flushPipe)}, " +
1044      s"replayInst ${configs.exists(_.replayInst)}")
1045  }
1046
1047  val fflags_wb = fflagsPorts.map(_._2)
1048  val fflagsDataModule = Module(new SyncDataModuleTemplate(
1049    UInt(5.W), RobSize, CommitWidth, fflags_wb.size)
1050  )
1051  for(i <- fflags_wb.indices){
1052    fflagsDataModule.io.wen  (i) := fflags_wb(i).valid
1053    fflagsDataModule.io.waddr(i) := fflags_wb(i).bits.uop.robIdx.value
1054    fflagsDataModule.io.wdata(i) := fflags_wb(i).bits.fflags
1055  }
1056  fflagsDataModule.io.raddr := VecInit(deqPtrVec_next.map(_.value))
1057  fflagsDataRead := fflagsDataModule.io.rdata
1058
1059  val instrCntReg = RegInit(0.U(64.W))
1060  val fuseCommitCnt = PopCount(io.commits.commitValid.zip(io.commits.info).map{ case (v, i) => RegNext(v && CommitType.isFused(i.commitType)) })
1061  val trueCommitCnt = RegNext(commitCnt) +& fuseCommitCnt
1062  val retireCounter = Mux(RegNext(io.commits.isCommit), trueCommitCnt, 0.U)
1063  val instrCnt = instrCntReg + retireCounter
1064  instrCntReg := instrCnt
1065  io.csr.perfinfo.retiredInstr := retireCounter
1066  io.robFull := !allowEnqueue
1067  io.headNotReady := commit_v.head && !commit_w.head
1068
1069  /**
1070    * debug info
1071    */
1072  XSDebug(p"enqPtr ${enqPtr} deqPtr ${deqPtr}\n")
1073  XSDebug("")
1074  for(i <- 0 until RobSize){
1075    XSDebug(false, !valid(i), "-")
1076    XSDebug(false, valid(i) && writebacked(i), "w")
1077    XSDebug(false, valid(i) && !writebacked(i), "v")
1078  }
1079  XSDebug(false, true.B, "\n")
1080
1081  for(i <- 0 until RobSize) {
1082    if(i % 4 == 0) XSDebug("")
1083    XSDebug(false, true.B, "%x ", debug_microOp(i).cf.pc)
1084    XSDebug(false, !valid(i), "- ")
1085    XSDebug(false, valid(i) && writebacked(i), "w ")
1086    XSDebug(false, valid(i) && !writebacked(i), "v ")
1087    if(i % 4 == 3) XSDebug(false, true.B, "\n")
1088  }
1089
1090  def ifCommit(counter: UInt): UInt = Mux(io.commits.isCommit, counter, 0.U)
1091  def ifCommitReg(counter: UInt): UInt = Mux(RegNext(io.commits.isCommit), counter, 0.U)
1092
1093  val commitDebugExu = deqPtrVec.map(_.value).map(debug_exuDebug(_))
1094  val commitDebugUop = deqPtrVec.map(_.value).map(debug_microOp(_))
1095  val commitDebugLsInfo = deqPtrVec.map(_.value).map(debug_lsInfo(_))
1096  XSPerfAccumulate("clock_cycle", 1.U)
1097  QueuePerf(RobSize, PopCount((0 until RobSize).map(valid(_))), !allowEnqueue)
1098  XSPerfAccumulate("commitUop", ifCommit(commitCnt))
1099  XSPerfAccumulate("commitInstr", ifCommitReg(trueCommitCnt))
1100  val commitIsMove = commitDebugUop.map(_.ctrl.isMove)
1101  XSPerfAccumulate("commitInstrMove", ifCommit(PopCount(io.commits.commitValid.zip(commitIsMove).map{ case (v, m) => v && m })))
1102  val commitMoveElim = commitDebugUop.map(_.debugInfo.eliminatedMove)
1103  XSPerfAccumulate("commitInstrMoveElim", ifCommit(PopCount(io.commits.commitValid zip commitMoveElim map { case (v, e) => v && e })))
1104  XSPerfAccumulate("commitInstrFused", ifCommitReg(fuseCommitCnt))
1105  val commitIsLoad = io.commits.info.map(_.commitType).map(_ === CommitType.LOAD)
1106  val commitLoadValid = io.commits.commitValid.zip(commitIsLoad).map{ case (v, t) => v && t }
1107  XSPerfAccumulate("commitInstrLoad", ifCommit(PopCount(commitLoadValid)))
1108  val commitIsBranch = io.commits.info.map(_.commitType).map(_ === CommitType.BRANCH)
1109  val commitBranchValid = io.commits.commitValid.zip(commitIsBranch).map{ case (v, t) => v && t }
1110  XSPerfAccumulate("commitInstrBranch", ifCommit(PopCount(commitBranchValid)))
1111  val commitLoadWaitBit = commitDebugUop.map(_.cf.loadWaitBit)
1112  XSPerfAccumulate("commitInstrLoadWait", ifCommit(PopCount(commitLoadValid.zip(commitLoadWaitBit).map{ case (v, w) => v && w })))
1113  val commitIsStore = io.commits.info.map(_.commitType).map(_ === CommitType.STORE)
1114  XSPerfAccumulate("commitInstrStore", ifCommit(PopCount(io.commits.commitValid.zip(commitIsStore).map{ case (v, t) => v && t })))
1115  XSPerfAccumulate("writeback", PopCount((0 until RobSize).map(i => valid(i) && writebacked(i))))
1116  // XSPerfAccumulate("enqInstr", PopCount(io.dp1Req.map(_.fire)))
1117  // XSPerfAccumulate("d2rVnR", PopCount(io.dp1Req.map(p => p.valid && !p.ready)))
1118  XSPerfAccumulate("walkInstr", Mux(io.commits.isWalk, PopCount(io.commits.walkValid), 0.U))
1119  XSPerfAccumulate("walkCycle", state === s_walk)
1120  val deqNotWritebacked = valid(deqPtr.value) && !writebacked(deqPtr.value)
1121  val deqUopCommitType = io.commits.info(0).commitType
1122  XSPerfAccumulate("waitNormalCycle", deqNotWritebacked && deqUopCommitType === CommitType.NORMAL)
1123  XSPerfAccumulate("waitBranchCycle", deqNotWritebacked && deqUopCommitType === CommitType.BRANCH)
1124  XSPerfAccumulate("waitLoadCycle", deqNotWritebacked && deqUopCommitType === CommitType.LOAD)
1125  XSPerfAccumulate("waitStoreCycle", deqNotWritebacked && deqUopCommitType === CommitType.STORE)
1126  XSPerfAccumulate("robHeadPC", io.commits.info(0).pc)
1127  val dispatchLatency = commitDebugUop.map(uop => uop.debugInfo.dispatchTime - uop.debugInfo.renameTime)
1128  val enqRsLatency = commitDebugUop.map(uop => uop.debugInfo.enqRsTime - uop.debugInfo.dispatchTime)
1129  val selectLatency = commitDebugUop.map(uop => uop.debugInfo.selectTime - uop.debugInfo.enqRsTime)
1130  val issueLatency = commitDebugUop.map(uop => uop.debugInfo.issueTime - uop.debugInfo.selectTime)
1131  val executeLatency = commitDebugUop.map(uop => uop.debugInfo.writebackTime - uop.debugInfo.issueTime)
1132  val rsFuLatency = commitDebugUop.map(uop => uop.debugInfo.writebackTime - uop.debugInfo.enqRsTime)
1133  val commitLatency = commitDebugUop.map(uop => timer - uop.debugInfo.writebackTime)
1134  val accessLatency = commitDebugUop.map(uop => uop.debugInfo.writebackTime - uop.debugInfo.issueTime)
1135  val tlbLatency = commitDebugUop.map(uop => uop.debugInfo.tlbRespTime - uop.debugInfo.tlbFirstReqTime)
1136  def latencySum(cond: Seq[Bool], latency: Seq[UInt]): UInt = {
1137    cond.zip(latency).map(x => Mux(x._1, x._2, 0.U)).reduce(_ +& _)
1138  }
1139  for (fuType <- FuType.functionNameMap.keys) {
1140    val fuName = FuType.functionNameMap(fuType)
1141    val commitIsFuType = io.commits.commitValid.zip(commitDebugUop).map(x => x._1 && x._2.ctrl.fuType === fuType.U )
1142    XSPerfAccumulate(s"${fuName}_instr_cnt", ifCommit(PopCount(commitIsFuType)))
1143    XSPerfAccumulate(s"${fuName}_latency_dispatch", ifCommit(latencySum(commitIsFuType, dispatchLatency)))
1144    XSPerfAccumulate(s"${fuName}_latency_enq_rs", ifCommit(latencySum(commitIsFuType, enqRsLatency)))
1145    XSPerfAccumulate(s"${fuName}_latency_select", ifCommit(latencySum(commitIsFuType, selectLatency)))
1146    XSPerfAccumulate(s"${fuName}_latency_issue", ifCommit(latencySum(commitIsFuType, issueLatency)))
1147    XSPerfAccumulate(s"${fuName}_latency_execute", ifCommit(latencySum(commitIsFuType, executeLatency)))
1148    XSPerfAccumulate(s"${fuName}_latency_enq_rs_execute", ifCommit(latencySum(commitIsFuType, rsFuLatency)))
1149    XSPerfAccumulate(s"${fuName}_latency_commit", ifCommit(latencySum(commitIsFuType, commitLatency)))
1150    if (fuType == FuType.fmac.litValue) {
1151      val commitIsFma = commitIsFuType.zip(commitDebugUop).map(x => x._1 && x._2.ctrl.fpu.ren3 )
1152      XSPerfAccumulate(s"${fuName}_instr_cnt_fma", ifCommit(PopCount(commitIsFma)))
1153      XSPerfAccumulate(s"${fuName}_latency_enq_rs_execute_fma", ifCommit(latencySum(commitIsFma, rsFuLatency)))
1154      XSPerfAccumulate(s"${fuName}_latency_execute_fma", ifCommit(latencySum(commitIsFma, executeLatency)))
1155    }
1156  }
1157
1158  val sourceVaddr = Wire(Valid(UInt(VAddrBits.W)))
1159  sourceVaddr.valid := debug_lsTopdownInfo(deqPtr.value).s1.vaddr_valid
1160  sourceVaddr.bits  := debug_lsTopdownInfo(deqPtr.value).s1.vaddr_bits
1161  val sourcePaddr = Wire(Valid(UInt(PAddrBits.W)))
1162  sourcePaddr.valid := debug_lsTopdownInfo(deqPtr.value).s2.paddr_valid
1163  sourcePaddr.bits  := debug_lsTopdownInfo(deqPtr.value).s2.paddr_bits
1164  val sourceLqIdx = Wire(Valid(new LqPtr))
1165  sourceLqIdx.valid := debug_lqIdxValid(deqPtr.value)
1166  sourceLqIdx.bits  := debug_microOp(deqPtr.value).lqIdx
1167  val sourceHeadLsIssue = WireDefault(debug_lsIssue(deqPtr.value))
1168  ExcitingUtils.addSource(sourceVaddr, s"rob_head_vaddr_${coreParams.HartId}", ExcitingUtils.Perf, true)
1169  ExcitingUtils.addSource(sourcePaddr, s"rob_head_paddr_${coreParams.HartId}", ExcitingUtils.Perf, true)
1170  ExcitingUtils.addSource(sourceLqIdx, s"rob_head_lqIdx_${coreParams.HartId}", ExcitingUtils.Perf, true)
1171  ExcitingUtils.addSource(sourceHeadLsIssue, s"rob_head_ls_issue_${coreParams.HartId}", ExcitingUtils.Perf, true)
1172  // dummy sink
1173  ExcitingUtils.addSink(WireDefault(sourceLqIdx), s"rob_head_lqIdx_${coreParams.HartId}", ExcitingUtils.Perf)
1174
1175  /**
1176    * DataBase info:
1177    * log trigger is at writeback valid
1178    * */
1179  if(!env.FPGAPlatform){
1180    val isWriteInstInfoTable = WireInit(Constantin.createRecord("isWriteInstInfoTable" + p(XSCoreParamsKey).HartId.toString))
1181    val instTableName = "InstTable" + p(XSCoreParamsKey).HartId.toString
1182    val instSiteName = "Rob" + p(XSCoreParamsKey).HartId.toString
1183    val debug_instTable = ChiselDB.createTable(instTableName, new InstInfoEntry)
1184    // FIXME lyq: only get inst (alu, bj, ls) in exuWriteback
1185    for (wb <- exuWriteback) {
1186      when(wb.valid) {
1187        val debug_instData = Wire(new InstInfoEntry)
1188        val idx = wb.bits.uop.robIdx.value
1189        debug_instData.globalID := wb.bits.uop.ctrl.debug_globalID
1190        debug_instData.robIdx := idx
1191        debug_instData.instType := wb.bits.uop.ctrl.fuType
1192        debug_instData.ivaddr := wb.bits.uop.cf.pc
1193        debug_instData.dvaddr := wb.bits.debug.vaddr
1194        debug_instData.dpaddr := wb.bits.debug.paddr
1195        debug_instData.tlbLatency := wb.bits.uop.debugInfo.tlbRespTime - wb.bits.uop.debugInfo.tlbFirstReqTime
1196        debug_instData.accessLatency := wb.bits.uop.debugInfo.writebackTime - wb.bits.uop.debugInfo.issueTime
1197        debug_instData.executeLatency := wb.bits.uop.debugInfo.writebackTime - wb.bits.uop.debugInfo.issueTime
1198        debug_instData.issueLatency := wb.bits.uop.debugInfo.issueTime - wb.bits.uop.debugInfo.selectTime
1199        debug_instData.exceptType := Cat(wb.bits.uop.cf.exceptionVec)
1200        debug_instData.lsInfo := debug_lsInfo(idx)
1201        debug_instData.mdpInfo.ssid := wb.bits.uop.cf.ssid
1202        debug_instData.mdpInfo.waitAllStore := wb.bits.uop.cf.loadWaitStrict && wb.bits.uop.cf.loadWaitBit
1203        debug_instData.issueTime := wb.bits.uop.debugInfo.issueTime
1204        debug_instData.writebackTime := wb.bits.uop.debugInfo.writebackTime
1205        debug_instTable.log(
1206          data = debug_instData,
1207          en = wb.valid,
1208          site = instSiteName,
1209          clock = clock,
1210          reset = reset
1211        )
1212      }
1213    }
1214  }
1215
1216
1217  //difftest signals
1218  val firstValidCommit = (deqPtr + PriorityMux(io.commits.commitValid, VecInit(List.tabulate(CommitWidth)(_.U(log2Up(CommitWidth).W))))).value
1219
1220  val wdata = Wire(Vec(CommitWidth, UInt(XLEN.W)))
1221  val wpc = Wire(Vec(CommitWidth, UInt(XLEN.W)))
1222
1223  for(i <- 0 until CommitWidth) {
1224    val idx = deqPtrVec(i).value
1225    wdata(i) := debug_exuData(idx)
1226    wpc(i) := SignExt(commitDebugUop(i).cf.pc, XLEN)
1227  }
1228
1229  if (env.EnableDifftest) {
1230    for (i <- 0 until CommitWidth) {
1231      val difftest = Module(new DifftestInstrCommit)
1232      // assgin default value
1233      difftest.io := DontCare
1234
1235      difftest.io.clock    := clock
1236      difftest.io.coreid   := io.hartId
1237      difftest.io.index    := i.U
1238
1239      val ptr = deqPtrVec(i).value
1240      val uop = commitDebugUop(i)
1241      val exuOut = debug_exuDebug(ptr)
1242      val exuData = debug_exuData(ptr)
1243      difftest.io.valid    := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.isCommit)))
1244      difftest.io.pc       := RegNext(RegNext(RegNext(SignExt(uop.cf.pc, XLEN))))
1245      difftest.io.instr    := RegNext(RegNext(RegNext(uop.cf.instr)))
1246      difftest.io.robIdx   := RegNext(RegNext(RegNext(ZeroExt(ptr, 10))))
1247      difftest.io.lqIdx    := RegNext(RegNext(RegNext(ZeroExt(uop.lqIdx.value, 7))))
1248      difftest.io.sqIdx    := RegNext(RegNext(RegNext(ZeroExt(uop.sqIdx.value, 7))))
1249      difftest.io.isLoad   := RegNext(RegNext(RegNext(io.commits.info(i).commitType === CommitType.LOAD)))
1250      difftest.io.isStore  := RegNext(RegNext(RegNext(io.commits.info(i).commitType === CommitType.STORE)))
1251      difftest.io.special  := RegNext(RegNext(RegNext(CommitType.isFused(io.commits.info(i).commitType))))
1252      // when committing an eliminated move instruction,
1253      // we must make sure that skip is properly set to false (output from EXU is random value)
1254      difftest.io.skip     := RegNext(RegNext(RegNext(Mux(uop.eliminatedMove, false.B, exuOut.isMMIO || exuOut.isPerfCnt))))
1255      difftest.io.isRVC    := RegNext(RegNext(RegNext(uop.cf.pd.isRVC)))
1256      difftest.io.rfwen    := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.info(i).rfWen && io.commits.info(i).ldest =/= 0.U)))
1257      difftest.io.fpwen    := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.info(i).fpWen)))
1258      difftest.io.wpdest   := RegNext(RegNext(RegNext(io.commits.info(i).pdest)))
1259      difftest.io.wdest    := RegNext(RegNext(RegNext(io.commits.info(i).ldest)))
1260
1261      // // runahead commit hint
1262      // val runahead_commit = Module(new DifftestRunaheadCommitEvent)
1263      // runahead_commit.io.clock := clock
1264      // runahead_commit.io.coreid := io.hartId
1265      // runahead_commit.io.index := i.U
1266      // runahead_commit.io.valid := difftest.io.valid &&
1267      //   (commitBranchValid(i) || commitIsStore(i))
1268      // // TODO: is branch or store
1269      // runahead_commit.io.pc    := difftest.io.pc
1270    }
1271  }
1272  else if (env.AlwaysBasicDiff) {
1273    // These are the structures used by difftest only and should be optimized after synthesis.
1274    val dt_eliminatedMove = Mem(RobSize, Bool())
1275    val dt_isRVC = Mem(RobSize, Bool())
1276    val dt_exuDebug = Reg(Vec(RobSize, new DebugBundle))
1277    for (i <- 0 until RenameWidth) {
1278      when (canEnqueue(i)) {
1279        dt_eliminatedMove(allocatePtrVec(i).value) := io.enq.req(i).bits.eliminatedMove
1280        dt_isRVC(allocatePtrVec(i).value) := io.enq.req(i).bits.cf.pd.isRVC
1281      }
1282    }
1283    for (wb <- exuWriteback) {
1284      when (wb.valid) {
1285        val wbIdx = wb.bits.uop.robIdx.value
1286        dt_exuDebug(wbIdx) := wb.bits.debug
1287      }
1288    }
1289    // Always instantiate basic difftest modules.
1290    for (i <- 0 until CommitWidth) {
1291      val commitInfo = io.commits.info(i)
1292      val ptr = deqPtrVec(i).value
1293      val exuOut = dt_exuDebug(ptr)
1294      val eliminatedMove = dt_eliminatedMove(ptr)
1295      val isRVC = dt_isRVC(ptr)
1296
1297      val difftest = Module(new DifftestBasicInstrCommit)
1298      difftest.io.clock   := clock
1299      difftest.io.coreid  := io.hartId
1300      difftest.io.index   := i.U
1301      difftest.io.valid   := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.isCommit)))
1302      difftest.io.special := RegNext(RegNext(RegNext(CommitType.isFused(commitInfo.commitType))))
1303      difftest.io.skip    := RegNext(RegNext(RegNext(Mux(eliminatedMove, false.B, exuOut.isMMIO || exuOut.isPerfCnt))))
1304      difftest.io.isRVC   := RegNext(RegNext(RegNext(isRVC)))
1305      difftest.io.rfwen   := RegNext(RegNext(RegNext(io.commits.commitValid(i) && commitInfo.rfWen && commitInfo.ldest =/= 0.U)))
1306      difftest.io.fpwen   := RegNext(RegNext(RegNext(io.commits.commitValid(i) && commitInfo.fpWen)))
1307      difftest.io.wpdest  := RegNext(RegNext(RegNext(commitInfo.pdest)))
1308      difftest.io.wdest   := RegNext(RegNext(RegNext(commitInfo.ldest)))
1309    }
1310  }
1311
1312  if (env.EnableDifftest) {
1313    for (i <- 0 until CommitWidth) {
1314      val difftest = Module(new DifftestLoadEvent)
1315      difftest.io.clock  := clock
1316      difftest.io.coreid := io.hartId
1317      difftest.io.index  := i.U
1318
1319      val ptr = deqPtrVec(i).value
1320      val uop = commitDebugUop(i)
1321      val exuOut = debug_exuDebug(ptr)
1322      difftest.io.valid  := RegNext(RegNext(RegNext(io.commits.commitValid(i) && io.commits.isCommit)))
1323      difftest.io.paddr  := RegNext(RegNext(RegNext(exuOut.paddr)))
1324      difftest.io.opType := RegNext(RegNext(RegNext(uop.ctrl.fuOpType)))
1325      difftest.io.fuType := RegNext(RegNext(RegNext(uop.ctrl.fuType)))
1326    }
1327  }
1328
1329  // Always instantiate basic difftest modules.
1330  if (env.EnableDifftest) {
1331    val dt_isXSTrap = Mem(RobSize, Bool())
1332    for (i <- 0 until RenameWidth) {
1333      when (canEnqueue(i)) {
1334        dt_isXSTrap(allocatePtrVec(i).value) := io.enq.req(i).bits.ctrl.isXSTrap
1335      }
1336    }
1337    val trapVec = io.commits.commitValid.zip(deqPtrVec).map{ case (v, d) => io.commits.isCommit && v && dt_isXSTrap(d.value) }
1338    val hitTrap = trapVec.reduce(_||_)
1339    val trapCode = PriorityMux(wdata.zip(trapVec).map(x => x._2 -> x._1))
1340    val trapPC = SignExt(PriorityMux(wpc.zip(trapVec).map(x => x._2 ->x._1)), XLEN)
1341    val difftest = Module(new DifftestTrapEvent)
1342    difftest.io.clock    := clock
1343    difftest.io.coreid   := io.hartId
1344    difftest.io.valid    := hitTrap
1345    difftest.io.code     := trapCode
1346    difftest.io.pc       := trapPC
1347    difftest.io.cycleCnt := timer
1348    difftest.io.instrCnt := instrCnt
1349    difftest.io.hasWFI   := hasWFI
1350  }
1351  else if (env.AlwaysBasicDiff) {
1352    val dt_isXSTrap = Mem(RobSize, Bool())
1353    for (i <- 0 until RenameWidth) {
1354      when (canEnqueue(i)) {
1355        dt_isXSTrap(allocatePtrVec(i).value) := io.enq.req(i).bits.ctrl.isXSTrap
1356      }
1357    }
1358    val trapVec = io.commits.commitValid.zip(deqPtrVec).map{ case (v, d) => io.commits.isCommit && v && dt_isXSTrap(d.value) }
1359    val hitTrap = trapVec.reduce(_||_)
1360    val difftest = Module(new DifftestBasicTrapEvent)
1361    difftest.io.clock    := clock
1362    difftest.io.coreid   := io.hartId
1363    difftest.io.valid    := hitTrap
1364    difftest.io.cycleCnt := timer
1365    difftest.io.instrCnt := instrCnt
1366  }
1367
1368  val validEntriesBanks = (0 until (RobSize + 63) / 64).map(i => RegNext(PopCount(valid.drop(i * 64).take(64))))
1369  val validEntries = RegNext(ParallelOperation(validEntriesBanks, (a: UInt, b: UInt) => a +& b))
1370  val commitMoveVec = VecInit(io.commits.commitValid.zip(commitIsMove).map{ case (v, m) => v && m })
1371  val commitLoadVec = VecInit(commitLoadValid)
1372  val commitBranchVec = VecInit(commitBranchValid)
1373  val commitLoadWaitVec = VecInit(commitLoadValid.zip(commitLoadWaitBit).map{ case (v, w) => v && w })
1374  val commitStoreVec = VecInit(io.commits.commitValid.zip(commitIsStore).map{ case (v, t) => v && t })
1375  val perfEvents = Seq(
1376    ("rob_interrupt_num      ", io.flushOut.valid && intrEnable                                       ),
1377    ("rob_exception_num      ", io.flushOut.valid && exceptionEnable                                  ),
1378    ("rob_flush_pipe_num     ", io.flushOut.valid && isFlushPipe                                      ),
1379    ("rob_replay_inst_num    ", io.flushOut.valid && isFlushPipe && deqHasReplayInst                  ),
1380    ("rob_commitUop          ", ifCommit(commitCnt)                                                   ),
1381    ("rob_commitInstr        ", ifCommitReg(trueCommitCnt)                                            ),
1382    ("rob_commitInstrMove    ", ifCommitReg(PopCount(RegNext(commitMoveVec)))                         ),
1383    ("rob_commitInstrFused   ", ifCommitReg(fuseCommitCnt)                                            ),
1384    ("rob_commitInstrLoad    ", ifCommitReg(PopCount(RegNext(commitLoadVec)))                         ),
1385    ("rob_commitInstrBranch  ", ifCommitReg(PopCount(RegNext(commitBranchVec)))                       ),
1386    ("rob_commitInstrLoadWait", ifCommitReg(PopCount(RegNext(commitLoadWaitVec)))                     ),
1387    ("rob_commitInstrStore   ", ifCommitReg(PopCount(RegNext(commitStoreVec)))                        ),
1388    ("rob_walkInstr          ", Mux(io.commits.isWalk, PopCount(io.commits.walkValid), 0.U)           ),
1389    ("rob_walkCycle          ", (state === s_walk)                                                    ),
1390    ("rob_1_4_valid          ", validEntries <= (RobSize / 4).U                                       ),
1391    ("rob_2_4_valid          ", validEntries >  (RobSize / 4).U && validEntries <= (RobSize / 2).U    ),
1392    ("rob_3_4_valid          ", validEntries >  (RobSize / 2).U && validEntries <= (RobSize * 3 / 4).U),
1393    ("rob_4_4_valid          ", validEntries >  (RobSize * 3 / 4).U                                   ),
1394  )
1395  generatePerfEvent()
1396}
1397