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