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