xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision 9b8ed6d695628a488377ef8eb908efd1908f8f27)
1package xiangshan.backend
2
3import chipsalliance.rocketchip.config.Parameters
4import chisel3._
5import chisel3.util.BitPat.bitPatToUInt
6import chisel3.util._
7import utils.BundleUtils.makeValid
8import utils.OptionWrapper
9import xiangshan._
10import xiangshan.backend.datapath.DataConfig._
11import xiangshan.backend.datapath.DataSource
12import xiangshan.backend.datapath.WbConfig.PregWB
13import xiangshan.backend.decode.{ImmUnion, XDecode}
14import xiangshan.backend.exu.ExeUnitParams
15import xiangshan.backend.fu.FuType
16import xiangshan.backend.fu.fpu.Bundles.Frm
17import xiangshan.backend.fu.vector.Bundles._
18import xiangshan.backend.issue.{IssueBlockParams, IssueQueueDeqRespBundle, IssueQueueJumpBundle, SchedulerType, EntryDeqRespBundle}
19import xiangshan.backend.regfile.{RfReadPortWithConfig, RfWritePortWithConfig}
20import xiangshan.backend.rob.RobPtr
21import xiangshan.frontend._
22import xiangshan.mem.{LqPtr, SqPtr}
23
24object Bundles {
25
26  // frontend -> backend
27  class StaticInst(implicit p: Parameters) extends XSBundle {
28    val instr           = UInt(32.W)
29    val pc              = UInt(VAddrBits.W)
30    val foldpc          = UInt(MemPredPCWidth.W)
31    val exceptionVec    = ExceptionVec()
32    val trigger         = new TriggerCf
33    val preDecodeInfo   = new PreDecodeInfo
34    val pred_taken      = Bool()
35    val crossPageIPFFix = Bool()
36    val ftqPtr          = new FtqPtr
37    val ftqOffset       = UInt(log2Up(PredictWidth).W)
38
39    def connectCtrlFlow(source: CtrlFlow): Unit = {
40      this.instr            := source.instr
41      this.pc               := source.pc
42      this.foldpc           := source.foldpc
43      this.exceptionVec     := source.exceptionVec
44      this.trigger          := source.trigger
45      this.preDecodeInfo    := source.pd
46      this.pred_taken       := source.pred_taken
47      this.crossPageIPFFix  := source.crossPageIPFFix
48      this.ftqPtr           := source.ftqPtr
49      this.ftqOffset        := source.ftqOffset
50    }
51  }
52
53  // StaticInst --[Decode]--> DecodedInst
54  class DecodedInst(implicit p: Parameters) extends XSBundle {
55    def numSrc = backendParams.numSrc
56    // passed from StaticInst
57    val instr           = UInt(32.W)
58    val pc              = UInt(VAddrBits.W)
59    val foldpc          = UInt(MemPredPCWidth.W)
60    val exceptionVec    = ExceptionVec()
61    val trigger         = new TriggerCf
62    val preDecodeInfo   = new PreDecodeInfo
63    val pred_taken      = Bool()
64    val crossPageIPFFix = Bool()
65    val ftqPtr          = new FtqPtr
66    val ftqOffset       = UInt(log2Up(PredictWidth).W)
67    // decoded
68    val srcType         = Vec(numSrc, SrcType())
69    val lsrc            = Vec(numSrc, UInt(6.W))
70    val ldest           = UInt(6.W)
71    val fuType          = FuType()
72    val fuOpType        = FuOpType()
73    val rfWen           = Bool()
74    val fpWen           = Bool()
75    val vecWen          = Bool()
76    val isXSTrap        = Bool()
77    val waitForward     = Bool() // no speculate execution
78    val blockBackward   = Bool()
79    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
80    val canRobCompress  = Bool()
81    val selImm          = SelImm()
82    val imm             = UInt(ImmUnion.maxLen.W)
83    val fpu             = new FPUCtrlSignals
84    val vpu             = new VPUCtrlSignals
85    val wfflags         = Bool()
86    val isMove          = Bool()
87    val uopIdx          = UInt(5.W)
88    val uopSplitType    = UopSplitType()
89    val isVset          = Bool()
90    val firstUop        = Bool()
91    val lastUop         = Bool()
92    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
93    val commitType      = CommitType() // Todo: remove it
94
95    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
96      isXSTrap, waitForward, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
97
98    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
99      val decoder: Seq[UInt] = ListLookup(
100        inst, XDecode.decodeDefault.map(bitPatToUInt),
101        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
102      )
103      allSignals zip decoder foreach { case (s, d) => s := d }
104      this
105    }
106
107    def isSoftPrefetch: Bool = {
108      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
109    }
110
111    def connectStaticInst(source: StaticInst): Unit = {
112      for ((name, data) <- this.elements) {
113        if (source.elements.contains(name)) {
114          data := source.elements(name)
115        }
116      }
117    }
118  }
119
120  // DecodedInst --[Rename]--> DynInst
121  class DynInst(implicit p: Parameters) extends XSBundle {
122    def numSrc          = backendParams.numSrc
123    // passed from StaticInst
124    val instr           = UInt(32.W)
125    val pc              = UInt(VAddrBits.W)
126    val foldpc          = UInt(MemPredPCWidth.W)
127    val exceptionVec    = ExceptionVec()
128    val trigger         = new TriggerCf
129    val preDecodeInfo   = new PreDecodeInfo
130    val pred_taken      = Bool()
131    val crossPageIPFFix = Bool()
132    val ftqPtr          = new FtqPtr
133    val ftqOffset       = UInt(log2Up(PredictWidth).W)
134    // passed from DecodedInst
135    val srcType         = Vec(numSrc, SrcType())
136    val lsrc            = Vec(numSrc, UInt(6.W))
137    val ldest           = UInt(6.W)
138    val fuType          = FuType()
139    val fuOpType        = FuOpType()
140    val rfWen           = Bool()
141    val fpWen           = Bool()
142    val vecWen          = Bool()
143    val isXSTrap        = Bool()
144    val waitForward     = Bool() // no speculate execution
145    val blockBackward   = Bool()
146    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
147    val canRobCompress  = Bool()
148    val selImm          = SelImm()
149    val imm             = UInt(XLEN.W) // Todo: check if it need minimized
150    val fpu             = new FPUCtrlSignals
151    val vpu             = new VPUCtrlSignals
152    val wfflags         = Bool()
153    val isMove          = Bool()
154    val uopIdx          = UInt(5.W)
155    val isVset          = Bool()
156    val firstUop        = Bool()
157    val lastUop         = Bool()
158    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
159    val commitType      = CommitType()
160    // rename
161    val srcState        = Vec(numSrc, SrcState())
162    val dataSource      = Vec(numSrc, DataSource())
163    val l1ExuOH         = Vec(numSrc, ExuVec())
164    val psrc            = Vec(numSrc, UInt(PhyRegIdxWidth.W))
165    val pdest           = UInt(PhyRegIdxWidth.W)
166    val robIdx          = new RobPtr
167    val instrSize       = UInt(log2Ceil(RenameWidth + 1).W)
168
169    val eliminatedMove  = Bool()
170    // Take snapshot at this CFI inst
171    val snapshot        = Bool()
172    val debugInfo       = new PerfDebugInfo
173    val storeSetHit     = Bool() // inst has been allocated an store set
174    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
175    // Load wait is needed
176    // load inst will not be executed until former store (predicted by mdp) addr calcuated
177    val loadWaitBit     = Bool()
178    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
179    // load inst will not be executed until ALL former store addr calcuated
180    val loadWaitStrict  = Bool()
181    val ssid            = UInt(SSIDWidth.W)
182    // Todo
183    val lqIdx = new LqPtr
184    val sqIdx = new SqPtr
185    // debug module
186    val singleStep      = Bool()
187    // schedule
188    val replayInst      = Bool()
189
190    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
191    def isLUI32: Bool = this.fuType === FuType.alu.U && this.selImm === SelImm.IMM_LUI32
192    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
193
194    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
195    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
196    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
197
198    def srcIsReady: Vec[Bool] = {
199      VecInit(this.srcType.zip(this.srcState).map {
200        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
201      })
202    }
203
204    def clearExceptions(
205      exceptionBits: Seq[Int] = Seq(),
206      flushPipe    : Boolean = false,
207      replayInst   : Boolean = false
208    ): DynInst = {
209      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
210      if (!flushPipe) { this.flushPipe := false.B }
211      if (!replayInst) { this.replayInst := false.B }
212      this
213    }
214
215    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen
216  }
217
218  trait BundleSource {
219    var wakeupSource = "undefined"
220    var idx = 0
221  }
222
223  /**
224    *
225    * @param pregIdxWidth index width of preg
226    * @param exuIndices exu indices of wakeup bundle
227    */
228  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int]) extends Bundle {
229    val rfWen = Bool()
230    val fpWen = Bool()
231    val vecWen = Bool()
232    val pdest = UInt(pregIdxWidth.W)
233
234    /**
235      * @param successor Seq[(psrc, srcType)]
236      * @return Seq[if wakeup psrc]
237      */
238    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
239      successor.map { case (thatPsrc, srcType) =>
240        val pdestMatch = pdest === thatPsrc
241        pdestMatch && (
242          SrcType.isFp(srcType) && this.fpWen ||
243            SrcType.isXp(srcType) && this.rfWen ||
244            SrcType.isVp(srcType) && this.vecWen
245          ) && valid
246      }
247    }
248
249    def hasOnlyOneSource: Boolean = exuIndices.size == 1
250
251    def hasMultiSources: Boolean = exuIndices.size > 1
252
253    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
254
255    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
256
257    def exuIdx: Int = {
258      require(hasOnlyOneSource)
259      this.exuIndices.head
260    }
261  }
262
263  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
264
265  }
266
267  class IssueQueueIQWakeUpBundle(exuIdx: Int, backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
268    val loadDependency = Vec(backendParams.LduCnt, UInt(3.W))
269    def fromExuInput(exuInput: ExuInput, l2ExuVecs: Vec[Vec[Bool]]): Unit = {
270      this.rfWen := exuInput.rfWen.getOrElse(false.B)
271      this.fpWen := exuInput.fpWen.getOrElse(false.B)
272      this.vecWen := exuInput.vecWen.getOrElse(false.B)
273      this.pdest := exuInput.pdest
274    }
275
276    def fromExuInput(exuInput: ExuInput): Unit = {
277      this.rfWen := exuInput.rfWen.getOrElse(false.B)
278      this.fpWen := exuInput.fpWen.getOrElse(false.B)
279      this.vecWen := exuInput.vecWen.getOrElse(false.B)
280      this.pdest := exuInput.pdest
281    }
282  }
283
284  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
285    // vtype
286    val vill      = Bool()
287    val vma       = Bool()    // 1: agnostic, 0: undisturbed
288    val vta       = Bool()    // 1: agnostic, 0: undisturbed
289    val vsew      = VSew()
290    val vlmul     = VLmul()   // 1/8~8      --> -3~3
291
292    val vm        = Bool()    // 0: need v0.t
293    val vstart    = Vl()
294
295    // float rounding mode
296    val frm       = Frm()
297    // scalar float instr and vector float reduction
298    val fpu       = Fpu()
299    // vector fix int rounding mode
300    val vxrm      = Vxrm()
301    // vector uop index, exclude other non-vector uop
302    val vuopIdx   = UopIdx()
303    // maybe used if data dependancy
304    val vmask     = UInt(MaskSrcData().dataWidth.W)
305    val vl        = Vl()
306
307    // vector load/store
308    val nf        = Nf()
309
310    val needScalaSrc       = Bool()
311    val permImmTruncate    = Bool() // opivi
312
313    val isReverse = Bool() // vrsub, vrdiv
314    val isExt     = Bool()
315    val isNarrow  = Bool()
316    val isDstMask = Bool() // vvm, vvvm, mmm
317    val isOpMask  = Bool() // vmand, vmnand
318    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
319
320    def vtype: VType = {
321      val res = Wire(VType())
322      res.illegal := this.vill
323      res.vma     := this.vma
324      res.vta     := this.vta
325      res.vsew    := this.vsew
326      res.vlmul   := this.vlmul
327      res
328    }
329
330    def vconfig: VConfig = {
331      val res = Wire(VConfig())
332      res.vtype := this.vtype
333      res.vl    := this.vl
334      res
335    }
336  }
337
338  // DynInst --[IssueQueue]--> DataPath
339  class IssueQueueIssueBundle(
340    iqParams: IssueBlockParams,
341    val exuParams: ExeUnitParams,
342  )(implicit
343    p: Parameters
344  ) extends Bundle {
345    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
346
347    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
348      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
349        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
350      )
351    ))
352
353    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
354    val immType = SelImm()                         // used to select imm extractor
355    val common = new ExuInput(exuParams)
356    val addrOH = UInt(iqParams.numEntries.W)
357
358    def exuIdx = exuParams.exuIdx
359    def getSource: SchedulerType = exuParams.getWBSource
360    def getIntWbBusyBundle = common.rfWen.toSeq
361    def getVfWbBusyBundle = common.getVfWen.toSeq
362    def getIntRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readInt)
363    def getVfRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readVf)
364
365    def getIntRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
366      getIntRfReadBundle.zip(srcType).map {
367        case (rfRd: RfReadPortWithConfig, t: UInt) =>
368          makeValid(issueValid && SrcType.isXp(t), rfRd)
369      }
370    }
371
372    def getVfRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
373      getVfRfReadBundle.zip(srcType).map {
374        case (rfRd: RfReadPortWithConfig, t: UInt) =>
375          makeValid(issueValid && SrcType.isVfp(t), rfRd)
376      }
377    }
378
379    def getIntRfWriteValidBundle(issueValid: Bool) = {
380
381    }
382  }
383
384  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
385    val issueQueueParams = this.params
386    val og0resp = Valid(new EntryDeqRespBundle)
387    val og1resp = Valid(new EntryDeqRespBundle)
388  }
389
390  class fuBusyRespBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
391    val respType = RSFeedbackType() // update credit if needs replay
392    val rfWen = Bool() // TODO: use params to identify IntWB/VfWB
393    val fuType = FuType()
394  }
395
396  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
397    private val intCertainLat = params.intLatencyCertain
398    private val vfCertainLat = params.vfLatencyCertain
399    private val intLat = params.intLatencyValMax
400    private val vfLat = params.vfLatencyValMax
401
402    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
403    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
404    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
405    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
406  }
407
408  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
409    private val intCertainLat = params.intLatencyCertain
410    private val vfCertainLat = params.vfLatencyCertain
411    private val intLat = params.intLatencyValMax
412    private val vfLat = params.vfLatencyValMax
413
414    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
415    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
416  }
417
418  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
419    private val intCertainLat = params.intLatencyCertain
420    private val vfCertainLat = params.vfLatencyCertain
421
422    val intConflict = OptionWrapper(intCertainLat, Bool())
423    val vfConflict = OptionWrapper(vfCertainLat, Bool())
424  }
425
426  // DataPath --[ExuInput]--> Exu
427  class ExuInput(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
428    val fuType        = FuType()
429    val fuOpType      = FuOpType()
430    val src           = Vec(params.numRegSrc, UInt(params.dataBitsMax.W))
431    val imm           = UInt(XLEN.W)
432    val robIdx        = new RobPtr
433    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
434    val isFirstIssue  = Bool()                      // Only used by store yet
435    val pdest         = UInt(params.wbPregIdxWidth.W)
436    val rfWen         = if (params.writeIntRf)    Some(Bool())                        else None
437    val fpWen         = if (params.writeFpRf)     Some(Bool())                        else None
438    val vecWen        = if (params.writeVecRf)    Some(Bool())                        else None
439    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
440    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
441    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
442    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
443    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
444    val ftqIdx        = if (params.needPc || params.replayInst)
445                                                  Some(new FtqPtr)                    else None
446    val ftqOffset     = if (params.needPc || params.replayInst)
447                                                  Some(UInt(log2Up(PredictWidth).W))  else None
448    val predictInfo   = if (params.hasPredecode)  Some(new Bundle {
449      val target = UInt(VAddrData().dataWidth.W)
450      val taken = Bool()
451    }) else None
452    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
453    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
454    val dataSources = Vec(params.numRegSrc, DataSource())
455    val l1ExuVec = Vec(params.numRegSrc, ExuVec())
456    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
457    val loadDependency = OptionWrapper(params.isIQWakeUpSink, Vec(LoadPipelineWidth, UInt(3.W)))
458    val deqPortIdx = OptionWrapper(params.hasLoadFu, UInt(log2Ceil(LoadPipelineWidth).W))
459
460    val perfDebugInfo = new PerfDebugInfo()
461
462    def exuIdx = this.params.exuIdx
463
464    def needCancel(og0CancelVec: Vec[Bool], og1CancelVec: Vec[Bool]) : Bool = {
465      if (params.isIQWakeUpSink) {
466        require(
467          og0CancelVec.size == l1ExuVec.head.size,
468          s"cancelVecSize: {og0: ${og0CancelVec.size}, og1: ${og1CancelVec.size}}"
469        )
470        val l1Cancel: Bool = l1ExuVec.zip(srcTimer.get).map {
471          case(exuOH: Vec[Bool], srcTimer: UInt) =>
472            (exuOH.asUInt & og0CancelVec.asUInt).orR && srcTimer === 1.U
473        }.reduce(_ | _)
474        l1Cancel
475      } else {
476        false.B
477      }
478    }
479
480    def getVfWen = {
481      if (params.writeFpRf) this.fpWen
482      else if(params.writeVecRf) this.vecWen
483      else None
484    }
485
486    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
487      // src is assigned to rfReadData
488      this.fuType        := source.common.fuType
489      this.fuOpType      := source.common.fuOpType
490      this.imm           := source.common.imm
491      this.robIdx        := source.common.robIdx
492      this.pdest         := source.common.pdest
493      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
494      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
495      this.dataSources   := source.common.dataSources
496      this.l1ExuVec     := source.common.l1ExuVec
497      this.rfWen         .foreach(_ := source.common.rfWen.get)
498      this.fpWen         .foreach(_ := source.common.fpWen.get)
499      this.vecWen        .foreach(_ := source.common.vecWen.get)
500      this.fpu           .foreach(_ := source.common.fpu.get)
501      this.vpu           .foreach(_ := source.common.vpu.get)
502      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
503      this.pc            .foreach(_ := source.common.pc.get)
504      this.preDecode     .foreach(_ := source.common.preDecode.get)
505      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
506      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
507      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
508      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
509      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
510      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
511      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
512      this.deqPortIdx    .foreach(_ := source.common.deqPortIdx.get)
513    }
514  }
515
516  // ExuInput --[FuncUnit]--> ExuOutput
517  class ExuOutput(
518    val params: ExeUnitParams,
519  )(implicit
520    val p: Parameters
521  ) extends Bundle with BundleSource with HasXSParameter {
522    val data         = UInt(params.dataBitsMax.W)
523    val pdest        = UInt(params.wbPregIdxWidth.W)
524    val robIdx       = new RobPtr
525    val intWen       = if (params.writeIntRf)   Some(Bool())                  else None
526    val fpWen        = if (params.writeFpRf)    Some(Bool())                  else None
527    val vecWen       = if (params.writeVecRf)   Some(Bool())                  else None
528    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
529    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
530    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
531    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
532    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
533    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
534    val replay       = if (params.replayInst)   Some(Bool())                  else None
535    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
536    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
537                                                Some(new SqPtr())             else None
538    // uop info
539    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
540    val debug = new DebugBundle
541    val debugInfo = new PerfDebugInfo
542  }
543
544  // ExuOutput + DynInst --> WriteBackBundle
545  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
546    val rfWen = Bool()
547    val fpWen = Bool()
548    val vecWen = Bool()
549    val pdest = UInt(params.pregIdxWidth(backendParams).W)
550    val data = UInt(params.dataWidth.W)
551    val robIdx = new RobPtr()(p)
552    val flushPipe = Bool()
553    val replayInst = Bool()
554    val redirect = ValidIO(new Redirect)
555    val fflags = UInt(5.W)
556    val vxsat = Bool()
557    val exceptionVec = ExceptionVec()
558    val debug = new DebugBundle
559    val debugInfo = new PerfDebugInfo
560
561    this.wakeupSource = s"WB(${params.toString})"
562
563    def fromExuOutput(source: ExuOutput) = {
564      this.rfWen  := source.intWen.getOrElse(false.B)
565      this.fpWen  := source.fpWen.getOrElse(false.B)
566      this.vecWen := source.vecWen.getOrElse(false.B)
567      this.pdest  := source.pdest
568      this.data   := source.data
569      this.robIdx := source.robIdx
570      this.flushPipe := source.flushPipe.getOrElse(false.B)
571      this.replayInst := source.replay.getOrElse(false.B)
572      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
573      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
574      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
575      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
576      this.debug := source.debug
577      this.debugInfo := source.debugInfo
578    }
579
580    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
581      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
582      rfWrite.wen := this.rfWen && fire
583      rfWrite.addr := this.pdest
584      rfWrite.data := this.data
585      rfWrite.intWen := this.rfWen
586      rfWrite.fpWen := false.B
587      rfWrite.vecWen := false.B
588      rfWrite
589    }
590
591    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
592      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
593      rfWrite.wen := (this.fpWen || this.vecWen) && fire
594      rfWrite.addr := this.pdest
595      rfWrite.data := this.data
596      rfWrite.intWen := false.B
597      rfWrite.fpWen := this.fpWen
598      rfWrite.vecWen := this.vecWen
599      rfWrite
600    }
601  }
602
603  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
604  //                                /
605  //     [IssueQueue]--> ExuInput --
606  class ExuBypassBundle(
607    val params: ExeUnitParams,
608  )(implicit
609    val p: Parameters
610  ) extends Bundle {
611    val data  = UInt(params.dataBitsMax.W)
612    val pdest = UInt(params.wbPregIdxWidth.W)
613  }
614
615  class ExceptionInfo extends Bundle {
616    val pc = UInt(VAddrData().dataWidth.W)
617    val instr = UInt(32.W)
618    val commitType = CommitType()
619    val exceptionVec = ExceptionVec()
620    val singleStep = Bool()
621    val crossPageIPFFix = Bool()
622    val isInterrupt = Bool()
623  }
624
625  object UopIdx {
626    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
627  }
628
629  object FuLatency {
630    def apply(): UInt = UInt(width.W)
631
632    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
633  }
634
635  object ExuVec {
636    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
637
638    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
639
640    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
641  }
642
643  class CancelSignal(implicit p: Parameters) extends XSBundle {
644    val rfWen = Bool()
645    val fpWen = Bool()
646    val vecWen = Bool()
647    val pdest = UInt(PhyRegIdxWidth.W)
648
649    def needCancel(srcType: UInt, psrc: UInt, valid: Bool): Bool = {
650      val pdestMatch = pdest === psrc
651      pdestMatch && (
652        SrcType.isFp(srcType) && !this.rfWen ||
653          SrcType.isXp(srcType) && this.rfWen ||
654          SrcType.isVp(srcType) && !this.rfWen
655        ) && valid
656    }
657  }
658
659  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
660    val uop = new DynInst
661    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
662    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
663    val isFirstIssue = Bool()
664    val deqPortIdx = UInt(log2Ceil(LoadPipelineWidth).W)
665  }
666
667  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
668    val uop = new DynInst
669    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
670    val debug = new DebugBundle
671  }
672
673  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
674    val uop = new DynInst
675    val flag = UInt(1.W)
676  }
677
678  object LoadShouldCancel {
679    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
680      val ld1Cancel = loadDependency.map(deps =>
681        deps.zipWithIndex.map { case (dep, ldPortIdx) =>
682          ldCancel.map(_.ld1Cancel).map(cancel => cancel.fire && dep(1) && cancel.bits === ldPortIdx.U).reduce(_ || _)
683        }.reduce(_ || _)
684      )
685      val ld2Cancel = loadDependency.map(deps =>
686        deps.zipWithIndex.map { case (dep, ldPortIdx) =>
687          ldCancel.map(_.ld2Cancel).map(cancel => cancel.fire && dep(2) && cancel.bits === ldPortIdx.U).reduce(_ || _)
688        }.reduce(_ || _)
689      )
690      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
691    }
692  }
693}
694