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