xref: /XiangShan/src/main/scala/xiangshan/backend/rename/Rename.scala (revision aad61829667df24ef0dc5e649eafb6bf2e747c98)
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.rename
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utility._
23import utils._
24import xiangshan._
25import xiangshan.backend.Bundles.{DecodedInst, DynInst}
26import xiangshan.backend.decode.{FusionDecodeInfo, ImmUnion, Imm_I, Imm_LUI_LOAD, Imm_U}
27import xiangshan.backend.fu.FuType
28import xiangshan.backend.rename.freelist._
29import xiangshan.backend.rob.{RobEnqIO, RobPtr}
30import xiangshan.mem.mdp._
31import xiangshan.ExceptionNO._
32import xiangshan.backend.fu.FuType._
33import xiangshan.mem.{EewLog2, GenUSWholeEmul}
34import xiangshan.mem.GenRealFlowNum
35import xiangshan.backend.trace._
36import xiangshan.backend.decode.isa.bitfield.{OPCODE5Bit, XSInstBitFields}
37import xiangshan.backend.fu.NewCSR.CSROoORead
38import yunsuan.{VfaluType, VipuType}
39
40class Rename(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper with HasPerfEvents {
41
42  // params alias
43  private val numRegSrc = backendParams.numRegSrc
44  private val numVecRegSrc = backendParams.numVecRegSrc
45  private val numVecRatPorts = numVecRegSrc
46
47  println(s"[Rename] numRegSrc: $numRegSrc")
48
49  val io = IO(new Bundle() {
50    val redirect = Flipped(ValidIO(new Redirect))
51    val rabCommits = Input(new RabCommitIO)
52    // from csr
53    val singleStep = Input(Bool())
54    // from decode
55    val in = Vec(RenameWidth, Flipped(DecoupledIO(new DecodedInst)))
56    val fusionInfo = Vec(DecodeWidth - 1, Flipped(new FusionDecodeInfo))
57    // ssit read result
58    val ssit = Flipped(Vec(RenameWidth, Output(new SSITEntry)))
59    // waittable read result
60    val waittable = Flipped(Vec(RenameWidth, Output(Bool())))
61    // to rename table
62    val intReadPorts = Vec(RenameWidth, Vec(2, Input(UInt(PhyRegIdxWidth.W))))
63    val fpReadPorts = Vec(RenameWidth, Vec(3, Input(UInt(PhyRegIdxWidth.W))))
64    val vecReadPorts = Vec(RenameWidth, Vec(numVecRatPorts, Input(UInt(PhyRegIdxWidth.W))))
65    val v0ReadPorts = Vec(RenameWidth, Vec(1, Input(UInt(PhyRegIdxWidth.W))))
66    val vlReadPorts = Vec(RenameWidth, Vec(1, Input(UInt(PhyRegIdxWidth.W))))
67    val intRenamePorts = Vec(RenameWidth, Output(new RatWritePort(log2Ceil(IntLogicRegs))))
68    val fpRenamePorts = Vec(RenameWidth, Output(new RatWritePort(log2Ceil(FpLogicRegs))))
69    val vecRenamePorts = Vec(RenameWidth, Output(new RatWritePort(log2Ceil(VecLogicRegs))))
70    val v0RenamePorts = Vec(RenameWidth, Output(new RatWritePort(log2Ceil(V0LogicRegs))))
71    val vlRenamePorts = Vec(RenameWidth, Output(new RatWritePort(log2Ceil(VlLogicRegs))))
72    // from rename table
73    val int_old_pdest = Vec(RabCommitWidth, Input(UInt(PhyRegIdxWidth.W)))
74    val fp_old_pdest = Vec(RabCommitWidth, Input(UInt(PhyRegIdxWidth.W)))
75    val vec_old_pdest = Vec(RabCommitWidth, Input(UInt(PhyRegIdxWidth.W)))
76    val v0_old_pdest = Vec(RabCommitWidth, Input(UInt(PhyRegIdxWidth.W)))
77    val vl_old_pdest = Vec(RabCommitWidth, Input(UInt(PhyRegIdxWidth.W)))
78    val int_need_free = Vec(RabCommitWidth, Input(Bool()))
79    // to dispatch1
80    val out = Vec(RenameWidth, DecoupledIO(new DynInst))
81    // for snapshots
82    val snpt = Input(new SnapshotPort)
83    val snptLastEnq = Flipped(ValidIO(new RobPtr))
84    val snptIsFull= Input(Bool())
85    // debug arch ports
86    val debug_int_rat = if (backendParams.debugEn) Some(Vec(32, Input(UInt(PhyRegIdxWidth.W)))) else None
87    val debug_fp_rat  = if (backendParams.debugEn) Some(Vec(32, Input(UInt(PhyRegIdxWidth.W)))) else None
88    val debug_vec_rat = if (backendParams.debugEn) Some(Vec(31, Input(UInt(PhyRegIdxWidth.W)))) else None
89    val debug_v0_rat  = if (backendParams.debugEn) Some(Vec(1, Input(UInt(PhyRegIdxWidth.W)))) else None
90    val debug_vl_rat  = if (backendParams.debugEn) Some(Vec(1, Input(UInt(PhyRegIdxWidth.W)))) else None
91    // perf only
92    val stallReason = new Bundle {
93      val in = Flipped(new StallReasonIO(RenameWidth))
94      val out = new StallReasonIO(RenameWidth)
95    }
96  })
97
98  // io alias
99  private val dispatchCanAcc = io.out.head.ready
100
101  val compressUnit = Module(new CompressUnit())
102  // create free list and rat
103  val intFreeList = Module(new MEFreeList(IntPhyRegs))
104  val fpFreeList = Module(new StdFreeList(FpPhyRegs - FpLogicRegs, FpLogicRegs, Reg_F))
105  val vecFreeList = Module(new StdFreeList(VfPhyRegs - VecLogicRegs, VecLogicRegs, Reg_V, 31))
106  val v0FreeList = Module(new StdFreeList(V0PhyRegs - V0LogicRegs, V0LogicRegs, Reg_V0, 1))
107  val vlFreeList = Module(new StdFreeList(VlPhyRegs - VlLogicRegs, VlLogicRegs, Reg_Vl, 1))
108
109
110  intFreeList.io.commit    <> io.rabCommits
111  intFreeList.io.debug_rat.foreach(_ <> io.debug_int_rat.get)
112  fpFreeList.io.commit     <> io.rabCommits
113  fpFreeList.io.debug_rat.foreach(_ <> io.debug_fp_rat.get)
114  vecFreeList.io.commit    <> io.rabCommits
115  vecFreeList.io.debug_rat.foreach(_ <> io.debug_vec_rat.get)
116  v0FreeList.io.commit <> io.rabCommits
117  v0FreeList.io.debug_rat.foreach(_ <> io.debug_v0_rat.get)
118  vlFreeList.io.commit <> io.rabCommits
119  vlFreeList.io.debug_rat.foreach(_ <> io.debug_vl_rat.get)
120
121  // decide if given instruction needs allocating a new physical register (CfCtrl: from decode; RobCommitInfo: from rob)
122  def needDestReg[T <: DecodedInst](reg_t: RegType, x: T): Bool = reg_t match {
123    case Reg_I => x.rfWen
124    case Reg_F => x.fpWen
125    case Reg_V => x.vecWen
126    case Reg_V0 => x.v0Wen
127    case Reg_Vl => x.vlWen
128  }
129  def needDestRegCommit[T <: RabCommitInfo](reg_t: RegType, x: T): Bool = {
130    reg_t match {
131      case Reg_I => x.rfWen
132      case Reg_F => x.fpWen
133      case Reg_V => x.vecWen
134      case Reg_V0 => x.v0Wen
135      case Reg_Vl => x.vlWen
136    }
137  }
138  def needDestRegWalk[T <: RabCommitInfo](reg_t: RegType, x: T): Bool = {
139    reg_t match {
140      case Reg_I => x.rfWen
141      case Reg_F => x.fpWen
142      case Reg_V => x.vecWen
143      case Reg_V0 => x.v0Wen
144      case Reg_Vl => x.vlWen
145    }
146  }
147
148  // connect [redirect + walk] ports for fp & vec & int free list
149  Seq(fpFreeList, vecFreeList, intFreeList, v0FreeList, vlFreeList).foreach { case fl =>
150    fl.io.redirect := io.redirect.valid
151    fl.io.walk := io.rabCommits.isWalk
152  }
153  // only when all free list and dispatch1 has enough space can we do allocation
154  // when isWalk, freelist can definitely allocate
155  intFreeList.io.doAllocate := fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && dispatchCanAcc || io.rabCommits.isWalk
156  fpFreeList.io.doAllocate := intFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && dispatchCanAcc || io.rabCommits.isWalk
157  vecFreeList.io.doAllocate := intFreeList.io.canAllocate && fpFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && dispatchCanAcc || io.rabCommits.isWalk
158  v0FreeList.io.doAllocate := intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && vlFreeList.io.canAllocate && dispatchCanAcc || io.rabCommits.isWalk
159  vlFreeList.io.doAllocate := intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && dispatchCanAcc || io.rabCommits.isWalk
160
161  //           dispatch1 ready ++ float point free list ready ++ int free list ready ++ vec free list ready     ++ not walk
162  val canOut = dispatchCanAcc && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !io.rabCommits.isWalk
163
164  compressUnit.io.in.zip(io.in).foreach{ case(sink, source) =>
165    sink.valid := source.valid && !io.singleStep
166    sink.bits := source.bits
167  }
168  val needRobFlags = compressUnit.io.out.needRobFlags
169  val instrSizesVec = compressUnit.io.out.instrSizes
170  val compressMasksVec = compressUnit.io.out.masks
171
172  // speculatively assign the instruction with an robIdx
173  val validCount = PopCount(io.in.zip(needRobFlags).map{ case(in, needRobFlag) => in.valid && in.bits.lastUop && needRobFlag}) // number of instructions waiting to enter rob (from decode)
174  val robIdxHead = RegInit(0.U.asTypeOf(new RobPtr))
175  val lastCycleMisprediction = GatedValidRegNext(io.redirect.valid && !io.redirect.bits.flushItself())
176  val robIdxHeadNext = Mux(io.redirect.valid, io.redirect.bits.robIdx, // redirect: move ptr to given rob index
177         Mux(lastCycleMisprediction, robIdxHead + 1.U, // mis-predict: not flush robIdx itself
178           Mux(canOut, robIdxHead + validCount, // instructions successfully entered next stage: increase robIdx
179                      /* default */  robIdxHead))) // no instructions passed by this cycle: stick to old value
180  robIdxHead := robIdxHeadNext
181
182  /**
183    * Rename: allocate free physical register and update rename table
184    */
185  val uops = Wire(Vec(RenameWidth, new DynInst))
186  uops.foreach( uop => {
187    uop.srcState      := DontCare
188    uop.debugInfo     := DontCare
189    uop.lqIdx         := DontCare
190    uop.sqIdx         := DontCare
191    uop.waitForRobIdx := DontCare
192    uop.singleStep    := DontCare
193    uop.snapshot      := DontCare
194    uop.srcLoadDependency := DontCare
195    uop.numLsElem       :=  DontCare
196    uop.hasException  :=  DontCare
197    uop.useRegCache   := DontCare
198    uop.regCacheIdx   := DontCare
199    uop.traceBlockInPipe := DontCare
200    uop.isDropAmocasSta := DontCare
201  })
202  private val inst         = Wire(Vec(RenameWidth, new XSInstBitFields))
203  private val isCsr        = Wire(Vec(RenameWidth, Bool()))
204  private val isCsrr       = Wire(Vec(RenameWidth, Bool()))
205  private val isRoCsrr     = Wire(Vec(RenameWidth, Bool()))
206  private val fuType       = uops.map(_.fuType)
207  private val fuOpType     = uops.map(_.fuOpType)
208  private val vtype        = uops.map(_.vpu.vtype)
209  private val sew          = vtype.map(_.vsew)
210  private val lmul         = vtype.map(_.vlmul)
211  private val eew          = uops.map(_.vpu.veew)
212  private val mop          = fuOpType.map(fuOpTypeItem => LSUOpType.getVecLSMop(fuOpTypeItem))
213  private val isVlsType    = fuType.map(fuTypeItem => isVls(fuTypeItem))
214  private val isSegment    = fuType.map(fuTypeItem => isVsegls(fuTypeItem))
215  private val isUnitStride = fuOpType.map(fuOpTypeItem => LSUOpType.isAllUS(fuOpTypeItem))
216  private val nf           = fuOpType.zip(uops.map(_.vpu.nf)).map { case (fuOpTypeItem, nfItem) => Mux(LSUOpType.isWhole(fuOpTypeItem), 0.U, nfItem) }
217  private val mulBits      = 3 // dirty code
218  private val emul         = fuOpType.zipWithIndex.map { case (fuOpTypeItem, index) =>
219    Mux(
220      LSUOpType.isWhole(fuOpTypeItem),
221      GenUSWholeEmul(nf(index)),
222      Mux(
223        LSUOpType.isMasked(fuOpTypeItem),
224        0.U(mulBits.W),
225        EewLog2(eew(index)) - sew(index) + lmul(index)
226      )
227    )
228  }
229  private val isVecUnitType = isVlsType.zip(isUnitStride).map { case (isVlsTypeItme, isUnitStrideItem) =>
230    isVlsTypeItme && isUnitStrideItem
231  }
232  private val isfofFixVlUop   = uops.map{x => x.vpu.isVleff && x.lastUop}
233  private val instType = isSegment.zip(mop).map { case (isSegementItem, mopItem) => Cat(isSegementItem, mopItem) }
234  // There is no way to calculate the 'flow' for 'unit-stride' exactly:
235  //  Whether 'unit-stride' needs to be split can only be known after obtaining the address.
236  // For scalar instructions, this is not handled here, and different assignments are done later according to the situation.
237  private val numLsElem = instType.zipWithIndex.map { case (instTypeItem, index) =>
238    Mux(
239      isVecUnitType(index),
240      VecMemUnitStrideMaxFlowNum.U,
241      GenRealFlowNum(instTypeItem, emul(index), lmul(index), eew(index), sew(index))
242    )
243  }
244  uops.zipWithIndex.map { case(u, i) =>
245    u.numLsElem := Mux(io.in(i).valid & isVlsType(i) && !isfofFixVlUop(i), numLsElem(i), 0.U)
246  }
247
248  val needVecDest    = Wire(Vec(RenameWidth, Bool()))
249  val needFpDest     = Wire(Vec(RenameWidth, Bool()))
250  val needIntDest    = Wire(Vec(RenameWidth, Bool()))
251  val needV0Dest     = Wire(Vec(RenameWidth, Bool()))
252  val needVlDest     = Wire(Vec(RenameWidth, Bool()))
253  private val inHeadValid = io.in.head.valid
254
255  val isMove = Wire(Vec(RenameWidth, Bool()))
256  isMove zip io.in.map(_.bits) foreach {
257    case (move, in) => move := Mux(in.exceptionVec.asUInt.orR, false.B, in.isMove)
258  }
259
260  val walkNeedIntDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
261  val walkNeedFpDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
262  val walkNeedVecDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
263  val walkNeedV0Dest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
264  val walkNeedVlDest = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
265  val walkIsMove = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
266
267  val intSpecWen = Wire(Vec(RenameWidth, Bool()))
268  val fpSpecWen  = Wire(Vec(RenameWidth, Bool()))
269  val vecSpecWen = Wire(Vec(RenameWidth, Bool()))
270  val v0SpecWen = Wire(Vec(RenameWidth, Bool()))
271  val vlSpecWen = Wire(Vec(RenameWidth, Bool()))
272
273  val walkIntSpecWen = WireDefault(VecInit(Seq.fill(RenameWidth)(false.B)))
274
275  val walkPdest = Wire(Vec(RenameWidth, UInt(PhyRegIdxWidth.W)))
276
277  // uop calculation
278  for (i <- 0 until RenameWidth) {
279    (uops(i): Data).waiveAll :<= (io.in(i).bits: Data).waiveAll
280
281    // read only CSRR instruction support: remove blockBackward and waitForward
282    inst(i) := uops(i).instr.asTypeOf(new XSInstBitFields)
283    isCsr(i) := inst(i).OPCODE5Bit === OPCODE5Bit.SYSTEM && inst(i).FUNCT3(1, 0) =/= 0.U
284    isCsrr(i) := isCsr(i) && inst(i).FUNCT3 === BitPat("b?1?") && inst(i).RS1 === 0.U
285    isRoCsrr(i) := isCsrr(i) && LookupTreeDefault(
286      inst(i).CSRIDX, true.B, CSROoORead.inOrderCsrReadList.map(_.U -> false.B))
287
288    /*
289     * For most CSRs, CSRR instructions do not need to wait forward instructions.
290     *
291     * For All CSRs, CSRR instructions do not need to block backward instructions.
292     *
293     * Signal "isCsrr" contains not only "CSRR", but also other CSR instructions that do not require writing to CSR.
294     */
295    uops(i).waitForward := io.in(i).bits.waitForward && !isRoCsrr(i)
296    uops(i).blockBackward := io.in(i).bits.blockBackward && !isCsrr(i)
297
298    // update cf according to ssit result
299    uops(i).storeSetHit := io.ssit(i).valid
300    uops(i).loadWaitStrict := io.ssit(i).strict && io.ssit(i).valid
301    uops(i).ssid := io.ssit(i).ssid
302
303    // update cf according to waittable result
304    uops(i).loadWaitBit := io.waittable(i)
305
306    uops(i).replayInst := false.B // set by IQ or MemQ
307    // alloc a new phy reg
308    needV0Dest(i) := io.in(i).valid && needDestReg(Reg_V0, io.in(i).bits)
309    needVlDest(i) := io.in(i).valid && needDestReg(Reg_Vl, io.in(i).bits)
310    needVecDest(i) := io.in(i).valid && needDestReg(Reg_V, io.in(i).bits)
311    needFpDest(i) := io.in(i).valid && needDestReg(Reg_F, io.in(i).bits)
312    needIntDest(i) := io.in(i).valid && needDestReg(Reg_I, io.in(i).bits)
313    if (i < RabCommitWidth) {
314      walkNeedIntDest(i) := io.rabCommits.walkValid(i) && needDestRegWalk(Reg_I, io.rabCommits.info(i))
315      walkNeedFpDest(i) := io.rabCommits.walkValid(i) && needDestRegWalk(Reg_F, io.rabCommits.info(i))
316      walkNeedVecDest(i) := io.rabCommits.walkValid(i) && needDestRegWalk(Reg_V, io.rabCommits.info(i))
317      walkNeedV0Dest(i) := io.rabCommits.walkValid(i) && needDestRegWalk(Reg_V0, io.rabCommits.info(i))
318      walkNeedVlDest(i) := io.rabCommits.walkValid(i) && needDestRegWalk(Reg_Vl, io.rabCommits.info(i))
319      walkIsMove(i) := io.rabCommits.info(i).isMove
320    }
321    fpFreeList.io.allocateReq(i) := needFpDest(i)
322    fpFreeList.io.walkReq(i) := walkNeedFpDest(i)
323    vecFreeList.io.allocateReq(i) := needVecDest(i)
324    vecFreeList.io.walkReq(i) := walkNeedVecDest(i)
325    v0FreeList.io.allocateReq(i) := needV0Dest(i)
326    v0FreeList.io.walkReq(i) := walkNeedV0Dest(i)
327    vlFreeList.io.allocateReq(i) := needVlDest(i)
328    vlFreeList.io.walkReq(i) := walkNeedVlDest(i)
329    intFreeList.io.allocateReq(i) := needIntDest(i) && !isMove(i)
330    intFreeList.io.walkReq(i) := walkNeedIntDest(i) && !walkIsMove(i)
331
332    // no valid instruction from decode stage || all resources (dispatch1 + both free lists) ready
333    io.in(i).ready := !io.in(0).valid || canOut
334
335    uops(i).robIdx := robIdxHead + PopCount(io.in.zip(needRobFlags).take(i).map{ case(in, needRobFlag) => in.valid && in.bits.lastUop && needRobFlag})
336    uops(i).instrSize := instrSizesVec(i)
337    val hasExceptionExceptFlushPipe = Cat(selectFrontend(uops(i).exceptionVec) :+ uops(i).exceptionVec(illegalInstr) :+ uops(i).exceptionVec(virtualInstr)).orR || TriggerAction.isDmode(uops(i).trigger)
338    when(isMove(i) || hasExceptionExceptFlushPipe) {
339      uops(i).numUops := 0.U
340      uops(i).numWB := 0.U
341    }
342    if (i > 0) {
343      when(!needRobFlags(i - 1)) {
344        uops(i).firstUop := false.B
345        uops(i).ftqPtr := uops(i - 1).ftqPtr
346        uops(i).ftqOffset := uops(i - 1).ftqOffset
347        uops(i).numUops := instrSizesVec(i) - PopCount(compressMasksVec(i) & Cat(isMove.reverse))
348        uops(i).numWB := instrSizesVec(i) - PopCount(compressMasksVec(i) & Cat(isMove.reverse))
349      }
350    }
351    when(!needRobFlags(i)) {
352      uops(i).lastUop := false.B
353      uops(i).numUops := instrSizesVec(i) - PopCount(compressMasksVec(i) & Cat(isMove.reverse))
354      uops(i).numWB := instrSizesVec(i) - PopCount(compressMasksVec(i) & Cat(isMove.reverse))
355    }
356    uops(i).wfflags := (compressMasksVec(i) & Cat(io.in.map(_.bits.wfflags).reverse)).orR
357    uops(i).dirtyFs := (compressMasksVec(i) & Cat(io.in.map(_.bits.fpWen).reverse)).orR
358    uops(i).dirtyVs := (
359      compressMasksVec(i) & Cat(io.in.map(in =>
360        // vector instructions' uopSplitType cannot be UopSplitType.SCA_SIM
361        in.bits.uopSplitType =/= UopSplitType.SCA_SIM &&
362        !UopSplitType.isAMOCAS(in.bits.uopSplitType) &&
363        // vfmv.f.s, vcpop.m, vfirst.m and vmv.x.s don't change vector state
364        !Seq(
365          (FuType.vfalu, VfaluType.vfmv_f_s), // vfmv.f.s
366          (FuType.vipu, VipuType.vcpop_m),    // vcpop.m
367          (FuType.vipu, VipuType.vfirst_m),   // vfirst.m
368          (FuType.vipu, VipuType.vmv_x_s)     // vmv.x.s
369        ).map(x => FuTypeOrR(in.bits.fuType, x._1) && in.bits.fuOpType === x._2).reduce(_ || _)
370      ).reverse)
371    ).orR
372    // psrc0,psrc1,psrc2 don't require v0ReadPorts because their srcType can distinguish whether they are V0 or not
373    uops(i).psrc(0) := Mux1H(uops(i).srcType(0)(2, 0), Seq(io.intReadPorts(i)(0), io.fpReadPorts(i)(0), io.vecReadPorts(i)(0)))
374    uops(i).psrc(1) := Mux1H(uops(i).srcType(1)(2, 0), Seq(io.intReadPorts(i)(1), io.fpReadPorts(i)(1), io.vecReadPorts(i)(1)))
375    uops(i).psrc(2) := Mux1H(uops(i).srcType(2)(2, 1), Seq(io.fpReadPorts(i)(2), io.vecReadPorts(i)(2)))
376    uops(i).psrc(3) := io.v0ReadPorts(i)(0)
377    uops(i).psrc(4) := io.vlReadPorts(i)(0)
378
379    // int psrc2 should be bypassed from next instruction if it is fused
380    if (i < RenameWidth - 1) {
381      when (io.fusionInfo(i).rs2FromRs2 || io.fusionInfo(i).rs2FromRs1) {
382        uops(i).psrc(1) := Mux(io.fusionInfo(i).rs2FromRs2, io.intReadPorts(i + 1)(1), io.intReadPorts(i + 1)(0))
383      }.elsewhen(io.fusionInfo(i).rs2FromZero) {
384        uops(i).psrc(1) := 0.U
385      }
386    }
387    uops(i).eliminatedMove := isMove(i)
388
389    // update pdest
390    uops(i).pdest := MuxCase(0.U, Seq(
391      needIntDest(i)    ->  intFreeList.io.allocatePhyReg(i),
392      needFpDest(i)     ->  fpFreeList.io.allocatePhyReg(i),
393      needVecDest(i)    ->  vecFreeList.io.allocatePhyReg(i),
394      needV0Dest(i)    ->  v0FreeList.io.allocatePhyReg(i),
395      needVlDest(i)    ->  vlFreeList.io.allocatePhyReg(i),
396    ))
397
398    // Assign performance counters
399    uops(i).debugInfo.renameTime := GTimer()
400
401    io.out(i).valid := io.in(i).valid && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !io.rabCommits.isWalk
402    io.out(i).bits := uops(i)
403    // dirty code
404    if (i == 0) {
405      io.out(i).bits.psrc(0) := Mux(io.out(i).bits.isLUI, 0.U, uops(i).psrc(0))
406    }
407    // Todo: move these shit in decode stage
408    // dirty code for fence. The lsrc is passed by imm.
409    when (io.out(i).bits.fuType === FuType.fence.U) {
410      io.out(i).bits.imm := Cat(io.in(i).bits.lsrc(1), io.in(i).bits.lsrc(0))
411    }
412
413    // dirty code for SoftPrefetch (prefetch.r/prefetch.w)
414//    when (io.in(i).bits.isSoftPrefetch) {
415//      io.out(i).bits.fuType := FuType.ldu.U
416//      io.out(i).bits.fuOpType := Mux(io.in(i).bits.lsrc(1) === 1.U, LSUOpType.prefetch_r, LSUOpType.prefetch_w)
417//      io.out(i).bits.selImm := SelImm.IMM_S
418//      io.out(i).bits.imm := Cat(io.in(i).bits.imm(io.in(i).bits.imm.getWidth - 1, 5), 0.U(5.W))
419//    }
420
421    // dirty code for lui+addi(w) fusion
422    if (i < RenameWidth - 1) {
423      val fused_lui32 = io.in(i).bits.selImm === SelImm.IMM_LUI32 && io.in(i).bits.fuType === FuType.alu.U
424      when (fused_lui32) {
425        val lui_imm = io.in(i).bits.imm(19, 0)
426        val add_imm = io.in(i + 1).bits.imm(11, 0)
427        require(io.out(i).bits.imm.getWidth >= lui_imm.getWidth + add_imm.getWidth)
428        io.out(i).bits.imm := Cat(lui_imm, add_imm)
429      }
430    }
431
432    // write speculative rename table
433    // we update rat later inside commit code
434    intSpecWen(i) := needIntDest(i) && intFreeList.io.canAllocate && intFreeList.io.doAllocate && !io.rabCommits.isWalk && !io.redirect.valid
435    fpSpecWen(i)  := needFpDest(i)  && fpFreeList.io.canAllocate  && fpFreeList.io.doAllocate  && !io.rabCommits.isWalk && !io.redirect.valid
436    vecSpecWen(i) := needVecDest(i) && vecFreeList.io.canAllocate && vecFreeList.io.doAllocate && !io.rabCommits.isWalk && !io.redirect.valid
437    v0SpecWen(i) := needV0Dest(i) && v0FreeList.io.canAllocate && v0FreeList.io.doAllocate && !io.rabCommits.isWalk && !io.redirect.valid
438    vlSpecWen(i) := needVlDest(i) && vlFreeList.io.canAllocate && vlFreeList.io.doAllocate && !io.rabCommits.isWalk && !io.redirect.valid
439
440
441    if (i < RabCommitWidth) {
442      walkIntSpecWen(i) := walkNeedIntDest(i) && !io.redirect.valid
443      walkPdest(i) := io.rabCommits.info(i).pdest
444    } else {
445      walkPdest(i) := io.out(i).bits.pdest
446    }
447  }
448
449  /**
450   * trace begin
451   */
452  // note: fusionInst can't robcompress
453  val inVec = io.in.map(_.bits)
454  val isRVCVec = inVec.map(_.preDecodeInfo.isRVC)
455  val isFusionVec = inVec.map(_.commitType).map(ctype => CommitType.isFused(ctype))
456
457  val canRobCompressVec = compressUnit.io.out.canCompressVec
458  val iLastSizeVec = isRVCVec.map(isRVC => Mux(isRVC, Ilastsize.HalfWord, Ilastsize.Word))
459  val halfWordNumVec = isRVCVec.map(isRVC => Mux(isRVC, 1.U, 2.U))
460  val halfWordNumMatrix = (0 until RenameWidth).map(
461    i => compressMasksVec(i).asBools.zipWithIndex.map{ case(mask, j) =>
462      Mux(mask, halfWordNumVec(j), 0.U)
463    }
464  )
465
466  for (i <- 0 until RenameWidth) {
467    // iretire
468    uops(i).traceBlockInPipe.iretire := Mux(canRobCompressVec(i),
469      halfWordNumMatrix(i).reduce(_ +& _),
470      (if(i < RenameWidth -1) Mux(isFusionVec(i), halfWordNumVec(i+1), 0.U) else 0.U) +& halfWordNumVec(i)
471    )
472
473    // ilastsize
474    val tmp = i
475    val lastIsRVC = WireInit(false.B)
476    (tmp until RenameWidth).map { j =>
477      when(compressMasksVec(i)(j)) {
478        lastIsRVC := io.in(j).bits.preDecodeInfo.isRVC
479      }
480    }
481    uops(i).traceBlockInPipe.ilastsize := Mux(canRobCompressVec(i),
482      Mux(lastIsRVC, Ilastsize.HalfWord, Ilastsize.Word),
483      (if(i < RenameWidth -1) Mux(isFusionVec(i), iLastSizeVec(i+1), iLastSizeVec(i)) else iLastSizeVec(i))
484    )
485
486    // itype
487    uops(i).traceBlockInPipe.itype := Itype.jumpTypeGen(inVec(i).preDecodeInfo.brType, inVec(i).ldest.asTypeOf(new OpRegType), inVec(i).lsrc(0).asTypeOf((new OpRegType)))
488  }
489  /**
490   * trace end
491   */
492
493  /**
494    * How to set psrc:
495    * - bypass the pdest to psrc if previous instructions write to the same ldest as lsrc
496    * - default: psrc from RAT
497    * How to set pdest:
498    * - Mux(isMove, psrc, pdest_from_freelist).
499    *
500    * The critical path of rename lies here:
501    * When move elimination is enabled, we need to update the rat with psrc.
502    * However, psrc maybe comes from previous instructions' pdest, which comes from freelist.
503    *
504    * If we expand these logic for pdest(N):
505    * pdest(N) = Mux(isMove(N), psrc(N), freelist_out(N))
506    *          = Mux(isMove(N), Mux(bypass(N, N - 1), pdest(N - 1),
507    *                           Mux(bypass(N, N - 2), pdest(N - 2),
508    *                           ...
509    *                           Mux(bypass(N, 0),     pdest(0),
510    *                                                 rat_out(N))...)),
511    *                           freelist_out(N))
512    */
513  // a simple functional model for now
514  io.out(0).bits.pdest := Mux(isMove(0), uops(0).psrc.head, uops(0).pdest)
515
516  // psrc(n) + pdest(1)
517  val bypassCond: Vec[MixedVec[UInt]] = Wire(Vec(numRegSrc, MixedVec(List.tabulate(RenameWidth-1)(i => UInt((i+1).W)))))
518  require(io.in(0).bits.srcType.size == io.in(0).bits.numSrc)
519  private val pdestLoc = io.in.head.bits.srcType.size // 2 vector src: v0, vl&vtype
520  println(s"[Rename] idx of pdest in bypassCond $pdestLoc")
521  for (i <- 1 until RenameWidth) {
522    val v0Cond = io.in(i).bits.srcType.zipWithIndex.map{ case (s, i) =>
523      if (i == 3) (s === SrcType.vp) || (s === SrcType.v0)
524      else false.B
525    }
526    val vlCond = io.in(i).bits.srcType.zipWithIndex.map{ case (s, i) =>
527      if (i == 4) s === SrcType.vp
528      else false.B
529    }
530    val vecCond = io.in(i).bits.srcType.map(_ === SrcType.vp)
531    val fpCond  = io.in(i).bits.srcType.map(_ === SrcType.fp)
532    val intCond = io.in(i).bits.srcType.map(_ === SrcType.xp)
533    val target = io.in(i).bits.lsrc
534    for ((((((cond1, (condV0, condVl)), cond2), cond3), t), j) <- vecCond.zip(v0Cond.zip(vlCond)).zip(fpCond).zip(intCond).zip(target).zipWithIndex) {
535      val destToSrc = io.in.take(i).zipWithIndex.map { case (in, j) =>
536        val indexMatch = in.bits.ldest === t
537        val writeMatch =  cond3 && needIntDest(j) || cond2 && needFpDest(j) || cond1 && needVecDest(j)
538        val v0vlMatch = condV0 && needV0Dest(j) || condVl && needVlDest(j)
539        indexMatch && writeMatch || v0vlMatch
540      }
541      bypassCond(j)(i - 1) := VecInit(destToSrc).asUInt
542    }
543    // For the LUI instruction: psrc(0) is from register file and should always be zero.
544    io.out(i).bits.psrc(0) := Mux(io.out(i).bits.isLUI, 0.U, io.out.take(i).map(_.bits.pdest).zip(bypassCond(0)(i-1).asBools).foldLeft(uops(i).psrc(0)) {
545      (z, next) => Mux(next._2, next._1, z)
546    })
547    io.out(i).bits.psrc(1) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(1)(i-1).asBools).foldLeft(uops(i).psrc(1)) {
548      (z, next) => Mux(next._2, next._1, z)
549    }
550    io.out(i).bits.psrc(2) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(2)(i-1).asBools).foldLeft(uops(i).psrc(2)) {
551      (z, next) => Mux(next._2, next._1, z)
552    }
553    io.out(i).bits.psrc(3) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(3)(i-1).asBools).foldLeft(uops(i).psrc(3)) {
554      (z, next) => Mux(next._2, next._1, z)
555    }
556    io.out(i).bits.psrc(4) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(4)(i-1).asBools).foldLeft(uops(i).psrc(4)) {
557      (z, next) => Mux(next._2, next._1, z)
558    }
559    io.out(i).bits.pdest := Mux(isMove(i), io.out(i).bits.psrc(0), uops(i).pdest)
560
561    // Todo: better implementation for fields reuse
562    // For fused-lui-load, load.src(0) is replaced by the imm.
563    val last_is_lui = io.in(i - 1).bits.selImm === SelImm.IMM_U && io.in(i - 1).bits.srcType(0) =/= SrcType.pc
564    val this_is_load = io.in(i).bits.fuType === FuType.ldu.U
565    val lui_to_load = io.in(i - 1).valid && io.in(i - 1).bits.rfWen && io.in(i - 1).bits.ldest === io.in(i).bits.lsrc(0)
566    val fused_lui_load = last_is_lui && this_is_load && lui_to_load
567    when (fused_lui_load) {
568      // The first LOAD operand (base address) is replaced by LUI-imm and stored in imm
569      val lui_imm = io.in(i - 1).bits.imm(ImmUnion.U.len - 1, 0)
570      val ld_imm = io.in(i).bits.imm(ImmUnion.I.len - 1, 0)
571      require(io.out(i).bits.imm.getWidth >= lui_imm.getWidth + ld_imm.getWidth)
572      io.out(i).bits.srcType(0) := SrcType.imm
573      io.out(i).bits.imm := Cat(lui_imm, ld_imm)
574    }
575
576  }
577
578  val genSnapshot = Cat(io.out.map(out => out.fire && out.bits.snapshot)).orR
579  val lastCycleCreateSnpt = RegInit(false.B)
580  lastCycleCreateSnpt := genSnapshot && !io.snptIsFull
581  val sameSnptDistance = (RobCommitWidth * 4).U
582  // notInSameSnpt: 1.robidxHead - snapLastEnq >= sameSnptDistance 2.no snap
583  val notInSameSnpt = GatedValidRegNext(distanceBetween(robIdxHeadNext, io.snptLastEnq.bits) >= sameSnptDistance || !io.snptLastEnq.valid)
584  val allowSnpt = if (EnableRenameSnapshot) notInSameSnpt && !lastCycleCreateSnpt && io.in.head.bits.firstUop else false.B
585  io.out.zip(io.in).foreach{ case (out, in) => out.bits.snapshot := allowSnpt && (!in.bits.preDecodeInfo.notCFI || FuType.isJump(in.bits.fuType)) && in.fire }
586  io.out.map{ x =>
587    x.bits.hasException := Cat(selectFrontend(x.bits.exceptionVec) :+ x.bits.exceptionVec(illegalInstr) :+ x.bits.exceptionVec(virtualInstr)).orR || TriggerAction.isDmode(x.bits.trigger)
588  }
589  if(backendParams.debugEn){
590    dontTouch(robIdxHeadNext)
591    dontTouch(notInSameSnpt)
592    dontTouch(genSnapshot)
593  }
594  intFreeList.io.snpt := io.snpt
595  fpFreeList.io.snpt := io.snpt
596  vecFreeList.io.snpt := io.snpt
597  v0FreeList.io.snpt := io.snpt
598  vlFreeList.io.snpt := io.snpt
599  intFreeList.io.snpt.snptEnq := genSnapshot
600  fpFreeList.io.snpt.snptEnq := genSnapshot
601  vecFreeList.io.snpt.snptEnq := genSnapshot
602  v0FreeList.io.snpt.snptEnq := genSnapshot
603  vlFreeList.io.snpt.snptEnq := genSnapshot
604
605  /**
606    * Instructions commit: update freelist and rename table
607    */
608  for (i <- 0 until RabCommitWidth) {
609    val commitValid = io.rabCommits.isCommit && io.rabCommits.commitValid(i)
610    val walkValid = io.rabCommits.isWalk && io.rabCommits.walkValid(i)
611
612    // I. RAT Update
613    // When redirect happens (mis-prediction), don't update the rename table
614    io.intRenamePorts(i).wen  := intSpecWen(i)
615    io.intRenamePorts(i).addr := uops(i).ldest(log2Ceil(IntLogicRegs) - 1, 0)
616    io.intRenamePorts(i).data := io.out(i).bits.pdest
617
618    io.fpRenamePorts(i).wen  := fpSpecWen(i)
619    io.fpRenamePorts(i).addr := uops(i).ldest(log2Ceil(FpLogicRegs) - 1, 0)
620    io.fpRenamePorts(i).data := fpFreeList.io.allocatePhyReg(i)
621
622    io.vecRenamePorts(i).wen := vecSpecWen(i)
623    io.vecRenamePorts(i).addr := uops(i).ldest(log2Ceil(VecLogicRegs) - 1, 0)
624    io.vecRenamePorts(i).data := vecFreeList.io.allocatePhyReg(i)
625
626    io.v0RenamePorts(i).wen := v0SpecWen(i)
627    io.v0RenamePorts(i).addr := uops(i).ldest(log2Ceil(V0LogicRegs) - 1, 0)
628    io.v0RenamePorts(i).data := v0FreeList.io.allocatePhyReg(i)
629
630    io.vlRenamePorts(i).wen := vlSpecWen(i)
631    io.vlRenamePorts(i).addr := uops(i).ldest(log2Ceil(VlLogicRegs) - 1, 0)
632    io.vlRenamePorts(i).data := vlFreeList.io.allocatePhyReg(i)
633
634    // II. Free List Update
635    intFreeList.io.freeReq(i) := io.int_need_free(i)
636    intFreeList.io.freePhyReg(i) := RegNext(io.int_old_pdest(i))
637    fpFreeList.io.freeReq(i)  := GatedValidRegNext(commitValid && needDestRegCommit(Reg_F, io.rabCommits.info(i)))
638    fpFreeList.io.freePhyReg(i) := io.fp_old_pdest(i)
639    vecFreeList.io.freeReq(i)  := GatedValidRegNext(commitValid && needDestRegCommit(Reg_V, io.rabCommits.info(i)))
640    vecFreeList.io.freePhyReg(i) := io.vec_old_pdest(i)
641    v0FreeList.io.freeReq(i) := GatedValidRegNext(commitValid && needDestRegCommit(Reg_V0, io.rabCommits.info(i)))
642    v0FreeList.io.freePhyReg(i) := io.v0_old_pdest(i)
643    vlFreeList.io.freeReq(i) := GatedValidRegNext(commitValid && needDestRegCommit(Reg_Vl, io.rabCommits.info(i)))
644    vlFreeList.io.freePhyReg(i) := io.vl_old_pdest(i)
645  }
646
647  /*
648  Debug and performance counters
649   */
650  def printRenameInfo(in: DecoupledIO[DecodedInst], out: DecoupledIO[DynInst]) = {
651    XSInfo(out.fire, p"pc:${Hexadecimal(in.bits.pc)} in(${in.valid},${in.ready}) " +
652      p"lsrc(0):${in.bits.lsrc(0)} -> psrc(0):${out.bits.psrc(0)} " +
653      p"lsrc(1):${in.bits.lsrc(1)} -> psrc(1):${out.bits.psrc(1)} " +
654      p"lsrc(2):${in.bits.lsrc(2)} -> psrc(2):${out.bits.psrc(2)} " +
655      p"ldest:${in.bits.ldest} -> pdest:${out.bits.pdest}\n"
656    )
657  }
658
659  for ((x,y) <- io.in.zip(io.out)) {
660    printRenameInfo(x, y)
661  }
662
663  io.out.map { case x =>
664    when(x.valid && x.bits.rfWen){
665      assert(x.bits.ldest =/= 0.U, "rfWen cannot be 1 when Int regfile ldest is 0")
666    }
667  }
668  val debugRedirect = RegEnable(io.redirect.bits, io.redirect.valid)
669  // bad speculation
670  val recStall = io.redirect.valid || io.rabCommits.isWalk
671  val ctrlRecStall = Mux(io.redirect.valid, io.redirect.bits.debugIsCtrl, io.rabCommits.isWalk && debugRedirect.debugIsCtrl)
672  val mvioRecStall = Mux(io.redirect.valid, io.redirect.bits.debugIsMemVio, io.rabCommits.isWalk && debugRedirect.debugIsMemVio)
673  val otherRecStall = recStall && !(ctrlRecStall || mvioRecStall)
674  XSPerfAccumulate("recovery_stall", recStall)
675  XSPerfAccumulate("control_recovery_stall", ctrlRecStall)
676  XSPerfAccumulate("mem_violation_recovery_stall", mvioRecStall)
677  XSPerfAccumulate("other_recovery_stall", otherRecStall)
678  // freelist stall
679  val notRecStall = !io.out.head.valid && !recStall
680  val intFlStall = notRecStall && inHeadValid && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !intFreeList.io.canAllocate
681  val fpFlStall = notRecStall && inHeadValid && intFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !fpFreeList.io.canAllocate
682  val vecFlStall = notRecStall && inHeadValid && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !vecFreeList.io.canAllocate
683  val v0FlStall = notRecStall && inHeadValid && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && vlFreeList.io.canAllocate && !v0FreeList.io.canAllocate
684  val vlFlStall = notRecStall && inHeadValid && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && !vlFreeList.io.canAllocate
685  val multiFlStall = notRecStall && inHeadValid && (PopCount(Cat(
686    !intFreeList.io.canAllocate,
687    !fpFreeList.io.canAllocate,
688    !vecFreeList.io.canAllocate,
689    !v0FreeList.io.canAllocate,
690    !vlFreeList.io.canAllocate,
691  )) > 1.U)
692  // other stall
693  val otherStall = notRecStall && !intFlStall && !fpFlStall && !vecFlStall && !v0FlStall && !vlFlStall && !multiFlStall
694
695  io.stallReason.in.backReason.valid := io.stallReason.out.backReason.valid || !io.in.head.ready
696  io.stallReason.in.backReason.bits := Mux(io.stallReason.out.backReason.valid, io.stallReason.out.backReason.bits,
697    MuxCase(TopDownCounters.OtherCoreStall.id.U, Seq(
698      ctrlRecStall  -> TopDownCounters.ControlRecoveryStall.id.U,
699      mvioRecStall  -> TopDownCounters.MemVioRecoveryStall.id.U,
700      otherRecStall -> TopDownCounters.OtherRecoveryStall.id.U,
701      intFlStall    -> TopDownCounters.IntFlStall.id.U,
702      fpFlStall     -> TopDownCounters.FpFlStall.id.U,
703      vecFlStall    -> TopDownCounters.VecFlStall.id.U,
704      v0FlStall     -> TopDownCounters.V0FlStall.id.U,
705      vlFlStall     -> TopDownCounters.VlFlStall.id.U,
706      multiFlStall  -> TopDownCounters.MultiFlStall.id.U,
707    )
708  ))
709  io.stallReason.out.reason.zip(io.stallReason.in.reason).zip(io.in.map(_.valid)).foreach { case ((out, in), valid) =>
710    out := Mux(io.stallReason.in.backReason.valid, io.stallReason.in.backReason.bits, in)
711  }
712
713  XSDebug(io.rabCommits.isWalk, p"Walk Recovery Enabled\n")
714  XSDebug(io.rabCommits.isWalk, p"validVec:${Binary(io.rabCommits.walkValid.asUInt)}\n")
715  for (i <- 0 until RabCommitWidth) {
716    val info = io.rabCommits.info(i)
717    XSDebug(io.rabCommits.isWalk && io.rabCommits.walkValid(i), p"[#$i walk info] " +
718      p"ldest:${info.ldest} rfWen:${info.rfWen} fpWen:${info.fpWen} vecWen:${info.vecWen} v0Wen:${info.v0Wen} vlWen:${info.vlWen}")
719  }
720
721  XSDebug(p"inValidVec: ${Binary(Cat(io.in.map(_.valid)))}\n")
722
723  XSPerfAccumulate("in_valid_count", PopCount(io.in.map(_.valid)))
724  XSPerfAccumulate("in_fire_count", PopCount(io.in.map(_.fire)))
725  XSPerfAccumulate("in_valid_not_ready_count", PopCount(io.in.map(x => x.valid && !x.ready)))
726  XSPerfAccumulate("wait_cycle", !io.in.head.valid && dispatchCanAcc)
727
728  // These stall reasons could overlap each other, but we configure the priority as fellows.
729  // walk stall > dispatch stall > int freelist stall > fp freelist stall
730  private val inHeadStall = io.in.head match { case x => x.valid && !x.ready }
731  private val stallForWalk      = inHeadValid &&  io.rabCommits.isWalk
732  private val stallForDispatch  = inHeadValid && !io.rabCommits.isWalk && !dispatchCanAcc
733  private val stallForIntFL     = inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !intFreeList.io.canAllocate
734  private val stallForFpFL      = inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !fpFreeList.io.canAllocate
735  private val stallForVecFL     = inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !vecFreeList.io.canAllocate
736  private val stallForV0FL      = inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && vlFreeList.io.canAllocate && !v0FreeList.io.canAllocate
737  private val stallForVlFL      = inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && !vlFreeList.io.canAllocate
738  XSPerfAccumulate("stall_cycle",          inHeadStall)
739  XSPerfAccumulate("stall_cycle_walk",     stallForWalk)
740  XSPerfAccumulate("stall_cycle_dispatch", stallForDispatch)
741  XSPerfAccumulate("stall_cycle_int",      stallForIntFL)
742  XSPerfAccumulate("stall_cycle_fp",       stallForFpFL)
743  XSPerfAccumulate("stall_cycle_vec",      stallForVecFL)
744  XSPerfAccumulate("stall_cycle_vec",      stallForV0FL)
745  XSPerfAccumulate("stall_cycle_vec",      stallForVlFL)
746
747  XSPerfHistogram("in_valid_range",  PopCount(io.in.map(_.valid)),  true.B, 0, DecodeWidth + 1, 1)
748  XSPerfHistogram("in_fire_range",   PopCount(io.in.map(_.fire)),   true.B, 0, DecodeWidth + 1, 1)
749  XSPerfHistogram("out_valid_range", PopCount(io.out.map(_.valid)), true.B, 0, DecodeWidth + 1, 1)
750  XSPerfHistogram("out_fire_range",  PopCount(io.out.map(_.fire)),  true.B, 0, DecodeWidth + 1, 1)
751
752  XSPerfAccumulate("move_instr_count", PopCount(io.out.map(out => out.fire && out.bits.isMove)))
753  val is_fused_lui_load = io.out.map(o => o.fire && o.bits.fuType === FuType.ldu.U && o.bits.srcType(0) === SrcType.imm)
754  XSPerfAccumulate("fused_lui_load_instr_count", PopCount(is_fused_lui_load))
755
756  val renamePerf = Seq(
757    ("rename_in                  ", PopCount(io.in.map(_.valid & io.in(0).ready ))),
758    ("rename_waitinstr           ", PopCount((0 until RenameWidth).map(i => io.in(i).valid && !io.in(i).ready))),
759    ("rename_stall               ", inHeadStall),
760    ("rename_stall_cycle_walk    ", inHeadValid &&  io.rabCommits.isWalk),
761    ("rename_stall_cycle_dispatch", inHeadValid && !io.rabCommits.isWalk && !dispatchCanAcc),
762    ("rename_stall_cycle_int     ", inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !intFreeList.io.canAllocate),
763    ("rename_stall_cycle_fp      ", inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !fpFreeList.io.canAllocate),
764    ("rename_stall_cycle_vec     ", inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && v0FreeList.io.canAllocate && vlFreeList.io.canAllocate && !vecFreeList.io.canAllocate),
765    ("rename_stall_cycle_v0      ", inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && vlFreeList.io.canAllocate && !v0FreeList.io.canAllocate),
766    ("rename_stall_cycle_vl      ", inHeadValid && !io.rabCommits.isWalk && dispatchCanAcc && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && vecFreeList.io.canAllocate && v0FreeList.io.canAllocate && !vlFreeList.io.canAllocate),
767  )
768  val intFlPerf = intFreeList.getPerfEvents
769  val fpFlPerf = fpFreeList.getPerfEvents
770  val vecFlPerf = vecFreeList.getPerfEvents
771  val v0FlPerf = v0FreeList.getPerfEvents
772  val vlFlPerf = vlFreeList.getPerfEvents
773  val perfEvents = renamePerf ++ intFlPerf ++ fpFlPerf ++ vecFlPerf ++ v0FlPerf ++ vlFlPerf
774  generatePerfEvent()
775}
776