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