xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision 00f9d184d720c2934146e1d3661fc6dc93cbdf1e)
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 hasException    = Bool()
148    val trigger         = new TriggerCf
149    val preDecodeInfo   = new PreDecodeInfo
150    val pred_taken      = Bool()
151    val crossPageIPFFix = Bool()
152    val ftqPtr          = new FtqPtr
153    val ftqOffset       = UInt(log2Up(PredictWidth).W)
154    // passed from DecodedInst
155    val srcType         = Vec(numSrc, SrcType())
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(LoadDependencyWidth.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    val dirtyVs         = Bool()
190
191    val eliminatedMove  = Bool()
192    // Take snapshot at this CFI inst
193    val snapshot        = Bool()
194    val debugInfo       = new PerfDebugInfo
195    val storeSetHit     = Bool() // inst has been allocated an store set
196    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
197    // Load wait is needed
198    // load inst will not be executed until former store (predicted by mdp) addr calcuated
199    val loadWaitBit     = Bool()
200    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
201    // load inst will not be executed until ALL former store addr calcuated
202    val loadWaitStrict  = Bool()
203    val ssid            = UInt(SSIDWidth.W)
204    // Todo
205    val lqIdx = new LqPtr
206    val sqIdx = new SqPtr
207    // debug module
208    val singleStep      = Bool()
209    // schedule
210    val replayInst      = Bool()
211
212    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
213
214    val numLsElem       = NumLsElem()
215
216    def getDebugFuType: UInt = debug_fuType.getOrElse(fuType)
217
218    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
219    def isLUI32: Bool = this.selImm === SelImm.IMM_LUI32
220    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
221
222    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
223    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
224    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
225
226    def isHls: Bool = {
227      fuType === FuType.ldu.U && LSUOpType.isHlv(fuOpType) || fuType === FuType.stu.U && LSUOpType.isHsv(fuOpType)
228    }
229
230    def srcIsReady: Vec[Bool] = {
231      VecInit(this.srcType.zip(this.srcState).map {
232        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
233      })
234    }
235
236    def clearExceptions(
237      exceptionBits: Seq[Int] = Seq(),
238      flushPipe    : Boolean = false,
239      replayInst   : Boolean = false
240    ): DynInst = {
241      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
242      if (!flushPipe) { this.flushPipe := false.B }
243      if (!replayInst) { this.replayInst := false.B }
244      this
245    }
246
247    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen
248  }
249
250  trait BundleSource {
251    var wakeupSource = "undefined"
252    var idx = 0
253  }
254
255  /**
256    *
257    * @param pregIdxWidth index width of preg
258    * @param exuIndices exu indices of wakeup bundle
259    */
260  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int])(implicit p: Parameters) extends XSBundle {
261    val rfWen = Bool()
262    val fpWen = Bool()
263    val vecWen = Bool()
264    val pdest = UInt(pregIdxWidth.W)
265
266    /**
267      * @param successor Seq[(psrc, srcType)]
268      * @return Seq[if wakeup psrc]
269      */
270    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
271      successor.map { case (thatPsrc, srcType) =>
272        val pdestMatch = pdest === thatPsrc
273        pdestMatch && (
274          SrcType.isFp(srcType) && this.fpWen ||
275            SrcType.isXp(srcType) && this.rfWen ||
276            SrcType.isVp(srcType) && this.vecWen
277          ) && valid
278      }
279    }
280    def wakeUpFromIQ(successor: Seq[(UInt, UInt)]): Seq[Bool] = {
281      successor.map { case (thatPsrc, srcType) =>
282        val pdestMatch = pdest === thatPsrc
283        pdestMatch && (
284          SrcType.isFp(srcType) && this.fpWen ||
285            SrcType.isXp(srcType) && this.rfWen ||
286            SrcType.isVp(srcType) && this.vecWen
287          )
288      }
289    }
290
291    def hasOnlyOneSource: Boolean = exuIndices.size == 1
292
293    def hasMultiSources: Boolean = exuIndices.size > 1
294
295    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
296
297    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
298
299    def exuIdx: Int = {
300      require(hasOnlyOneSource)
301      this.exuIndices.head
302    }
303  }
304
305  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams)(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
306
307  }
308
309  class IssueQueueIQWakeUpBundle(
310    exuIdx: Int,
311    backendParams: BackendParams,
312    copyWakeupOut: Boolean = false,
313    copyNum: Int = 0
314  )(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
315    val loadDependency = Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))
316    val is0Lat = Bool()
317    val params = backendParams.allExuParams.filter(_.exuIdx == exuIdx).head
318    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
319    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
320    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
321    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
322    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
323    def fromExuInput(exuInput: ExuInput, l2ExuVecs: Vec[UInt]): Unit = {
324      this.rfWen := exuInput.rfWen.getOrElse(false.B)
325      this.fpWen := exuInput.fpWen.getOrElse(false.B)
326      this.vecWen := exuInput.vecWen.getOrElse(false.B)
327      this.pdest := exuInput.pdest
328    }
329
330    def fromExuInput(exuInput: ExuInput): Unit = {
331      this.rfWen := exuInput.rfWen.getOrElse(false.B)
332      this.fpWen := exuInput.fpWen.getOrElse(false.B)
333      this.vecWen := exuInput.vecWen.getOrElse(false.B)
334      this.pdest := exuInput.pdest
335    }
336  }
337
338  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
339    // vtype
340    val vill      = Bool()
341    val vma       = Bool()    // 1: agnostic, 0: undisturbed
342    val vta       = Bool()    // 1: agnostic, 0: undisturbed
343    val vsew      = VSew()
344    val vlmul     = VLmul()   // 1/8~8      --> -3~3
345
346    val vm        = Bool()    // 0: need v0.t
347    val vstart    = Vl()
348
349    // float rounding mode
350    val frm       = Frm()
351    // scalar float instr and vector float reduction
352    val fpu       = Fpu()
353    // vector fix int rounding mode
354    val vxrm      = Vxrm()
355    // vector uop index, exclude other non-vector uop
356    val vuopIdx   = UopIdx()
357    val lastUop   = Bool()
358    // maybe used if data dependancy
359    val vmask     = UInt(MaskSrcData().dataWidth.W)
360    val vl        = Vl()
361
362    // vector load/store
363    val nf        = Nf()
364    val veew      = VEew()
365
366    val isReverse = Bool() // vrsub, vrdiv
367    val isExt     = Bool()
368    val isNarrow  = Bool()
369    val isDstMask = Bool() // vvm, vvvm, mmm
370    val isOpMask  = Bool() // vmand, vmnand
371    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
372
373    val isDependOldvd = Bool() // some instruction's computation depends on oldvd
374    val isWritePartVd = Bool() // some instruction's computation writes part of vd, such as vredsum
375
376    def vtype: VType = {
377      val res = Wire(VType())
378      res.illegal := this.vill
379      res.vma     := this.vma
380      res.vta     := this.vta
381      res.vsew    := this.vsew
382      res.vlmul   := this.vlmul
383      res
384    }
385
386    def vconfig: VConfig = {
387      val res = Wire(VConfig())
388      res.vtype := this.vtype
389      res.vl    := this.vl
390      res
391    }
392
393    def connectVType(source: VType): Unit = {
394      this.vill  := source.illegal
395      this.vma   := source.vma
396      this.vta   := source.vta
397      this.vsew  := source.vsew
398      this.vlmul := source.vlmul
399    }
400  }
401
402  // DynInst --[IssueQueue]--> DataPath
403  class IssueQueueIssueBundle(
404    iqParams: IssueBlockParams,
405    val exuParams: ExeUnitParams,
406  )(implicit
407    p: Parameters
408  ) extends Bundle {
409    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
410
411    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
412      rfReadDataCfgSet.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 getFpRfReadValidBundle(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 getVfRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
442      rf.zip(srcType).map {
443        case (rfRd: MixedVec[RfReadPortWithConfig], t: UInt) =>
444          makeValid(issueValid, rfRd.head)
445      }.toSeq
446    }
447
448    def getIntRfWriteValidBundle(issueValid: Bool) = {
449
450    }
451  }
452
453  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
454    val issueQueueParams = this.params
455    val og0resp = Valid(new EntryDeqRespBundle)
456    val og1resp = Valid(new EntryDeqRespBundle)
457  }
458
459  class fuBusyRespBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
460    val respType = RSFeedbackType() // update credit if needs replay
461    val rfWen = Bool() // TODO: use params to identify IntWB/VfWB
462    val fuType = FuType()
463  }
464
465  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
466    private val intCertainLat = params.intLatencyCertain
467    private val fpCertainLat = params.fpLatencyCertain
468    private val vfCertainLat = params.vfLatencyCertain
469    private val intLat = params.intLatencyValMax
470    private val fpLat = params.fpLatencyValMax
471    private val vfLat = params.vfLatencyValMax
472
473    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
474    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
475    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
476    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
477    val fpDeqRespSet = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
478    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
479  }
480
481  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
482    private val intCertainLat = params.intLatencyCertain
483    private val fpCertainLat = params.fpLatencyCertain
484    private val vfCertainLat = params.vfLatencyCertain
485    private val intLat = params.intLatencyValMax
486    private val fpLat = params.fpLatencyValMax
487    private val vfLat = params.vfLatencyValMax
488
489    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
490    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
491    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
492  }
493
494  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
495    private val intCertainLat = params.intLatencyCertain
496    private val fpCertainLat = params.fpLatencyCertain
497    private val vfCertainLat = params.vfLatencyCertain
498
499    val intConflict = OptionWrapper(intCertainLat, Bool())
500    val fpConflict = OptionWrapper(fpCertainLat, Bool())
501    val vfConflict = OptionWrapper(vfCertainLat, Bool())
502  }
503
504  class ImmInfo extends Bundle {
505    val imm = UInt(32.W)
506    val immType = SelImm()
507  }
508
509  // DataPath --[ExuInput]--> Exu
510  class ExuInput(val params: ExeUnitParams, copyWakeupOut:Boolean = false, copyNum:Int = 0)(implicit p: Parameters) extends XSBundle {
511    val fuType        = FuType()
512    val fuOpType      = FuOpType()
513    val src           = Vec(params.numRegSrc, UInt(params.dataBitsMax.W))
514    val imm           = UInt(32.W)
515    val robIdx        = new RobPtr
516    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
517    val isFirstIssue  = Bool()                      // Only used by store yet
518    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
519    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
520    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
521    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
522    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
523    val pdest         = UInt(params.wbPregIdxWidth.W)
524    val rfWen         = if (params.needIntWen)    Some(Bool())                        else None
525    val fpWen         = if (params.needFpWen)     Some(Bool())                        else None
526    val vecWen        = if (params.needVecWen)    Some(Bool())                        else None
527    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
528    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
529    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
530    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
531    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
532    val ftqIdx        = if (params.needPc || params.replayInst || params.hasStoreAddrFu)
533                                                  Some(new FtqPtr)                    else None
534    val ftqOffset     = if (params.needPc || params.replayInst || params.hasStoreAddrFu)
535                                                  Some(UInt(log2Up(PredictWidth).W))  else None
536    val predictInfo   = if (params.needPdInfo)  Some(new Bundle {
537      val target = UInt(VAddrData().dataWidth.W)
538      val taken = Bool()
539    }) else None
540    val loadWaitBit    = OptionWrapper(params.hasLoadExu, Bool())
541    val waitForRobIdx  = OptionWrapper(params.hasLoadExu, new RobPtr) // store set predicted previous store robIdx
542    val storeSetHit    = OptionWrapper(params.hasLoadExu, Bool()) // inst has been allocated an store set
543    val loadWaitStrict = OptionWrapper(params.hasLoadExu, Bool()) // load inst will not be executed until ALL former store addr calcuated
544    val ssid           = OptionWrapper(params.hasLoadExu, UInt(SSIDWidth.W))
545    // only vector load store need
546    val numLsElem      = OptionWrapper(params.hasVecLsFu, NumLsElem())
547
548    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
549    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
550    val dataSources = Vec(params.numRegSrc, DataSource())
551    val l1ExuOH = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuOH()))
552    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
553    val loadDependency = OptionWrapper(params.isIQWakeUpSink, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
554
555    val perfDebugInfo = new PerfDebugInfo()
556
557    def exuIdx = this.params.exuIdx
558
559    def needCancel(og0CancelOH: UInt, og1CancelOH: UInt) : Bool = {
560      if (params.isIQWakeUpSink) {
561        require(
562          og0CancelOH.getWidth == l1ExuOH.get.head.getWidth,
563          s"cancelVecSize: {og0: ${og0CancelOH.getWidth}, og1: ${og1CancelOH.getWidth}}"
564        )
565        val l1Cancel: Bool = l1ExuOH.get.zip(srcTimer.get).map {
566          case(exuOH: UInt, srcTimer: UInt) =>
567            (exuOH & og0CancelOH).orR && srcTimer === 1.U
568        }.reduce(_ | _)
569        l1Cancel
570      } else {
571        false.B
572      }
573    }
574
575    def getFpWen = {
576      if (params.writeFpRf) this.fpWen
577      else None
578    }
579
580    def getVfWen = {
581      if(params.writeVecRf) this.vecWen
582      else None
583    }
584
585    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
586      // src is assigned to rfReadData
587      this.fuType        := source.common.fuType
588      this.fuOpType      := source.common.fuOpType
589      this.imm           := source.common.imm
590      this.robIdx        := source.common.robIdx
591      this.pdest         := source.common.pdest
592      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
593      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
594      this.dataSources   := source.common.dataSources
595      this.l1ExuOH       .foreach(_ := source.common.l1ExuOH.get)
596      this.rfWen         .foreach(_ := source.common.rfWen.get)
597      this.fpWen         .foreach(_ := source.common.fpWen.get)
598      this.vecWen        .foreach(_ := source.common.vecWen.get)
599      this.fpu           .foreach(_ := source.common.fpu.get)
600      this.vpu           .foreach(_ := source.common.vpu.get)
601      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
602      this.pc            .foreach(_ := source.common.pc.get)
603      this.preDecode     .foreach(_ := source.common.preDecode.get)
604      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
605      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
606      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
607      this.loadWaitBit   .foreach(_ := source.common.loadWaitBit.get)
608      this.waitForRobIdx .foreach(_ := source.common.waitForRobIdx.get)
609      this.storeSetHit   .foreach(_ := source.common.storeSetHit.get)
610      this.loadWaitStrict.foreach(_ := source.common.loadWaitStrict.get)
611      this.ssid          .foreach(_ := source.common.ssid.get)
612      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
613      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
614      this.numLsElem     .foreach(_ := source.common.numLsElem.get)
615      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
616      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
617    }
618  }
619
620  // ExuInput --[FuncUnit]--> ExuOutput
621  class ExuOutput(
622    val params: ExeUnitParams,
623  )(implicit
624    val p: Parameters
625  ) extends Bundle with BundleSource with HasXSParameter {
626    val data         = UInt(params.dataBitsMax.W)
627    val pdest        = UInt(params.wbPregIdxWidth.W)
628    val robIdx       = new RobPtr
629    val intWen       = if (params.needIntWen)   Some(Bool())                  else None
630    val fpWen        = if (params.needFpWen)    Some(Bool())                  else None
631    val vecWen       = if (params.needVecWen)   Some(Bool())                  else None
632    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
633    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
634    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
635    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
636    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
637    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
638    val replay       = if (params.replayInst)   Some(Bool())                  else None
639    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
640    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
641                                                Some(new SqPtr())             else None
642    val trigger      = if (params.trigger)      Some(new TriggerCf)           else None
643    // uop info
644    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
645    // vldu used only
646    val vls = OptionWrapper(params.hasVLoadFu, new Bundle {
647      val vpu = new VPUCtrlSignals
648      val oldVdPsrc = UInt(PhyRegIdxWidth.W)
649      val vdIdx = UInt(3.W)
650      val vdIdxInField = UInt(3.W)
651      val isIndexed = Bool()
652      val isMasked = Bool()
653    })
654    val debug = new DebugBundle
655    val debugInfo = new PerfDebugInfo
656  }
657
658  // ExuOutput + DynInst --> WriteBackBundle
659  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
660    val rfWen = Bool()
661    val fpWen = Bool()
662    val vecWen = Bool()
663    val pdest = UInt(params.pregIdxWidth(backendParams).W)
664    val data = UInt(params.dataWidth.W)
665    val robIdx = new RobPtr()(p)
666    val flushPipe = Bool()
667    val replayInst = Bool()
668    val redirect = ValidIO(new Redirect)
669    val fflags = UInt(5.W)
670    val vxsat = Bool()
671    val exceptionVec = ExceptionVec()
672    val debug = new DebugBundle
673    val debugInfo = new PerfDebugInfo
674
675    this.wakeupSource = s"WB(${params.toString})"
676
677    def fromExuOutput(source: ExuOutput) = {
678      this.rfWen  := source.intWen.getOrElse(false.B)
679      this.fpWen  := source.fpWen.getOrElse(false.B)
680      this.vecWen := source.vecWen.getOrElse(false.B)
681      this.pdest  := source.pdest
682      this.data   := source.data
683      this.robIdx := source.robIdx
684      this.flushPipe := source.flushPipe.getOrElse(false.B)
685      this.replayInst := source.replay.getOrElse(false.B)
686      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
687      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
688      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
689      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
690      this.debug := source.debug
691      this.debugInfo := source.debugInfo
692    }
693
694    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
695      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
696      rfWrite.wen := this.rfWen && fire
697      rfWrite.addr := this.pdest
698      rfWrite.data := this.data
699      rfWrite.intWen := this.rfWen
700      rfWrite.fpWen := false.B
701      rfWrite.vecWen := false.B
702      rfWrite
703    }
704
705    def asFpRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
706      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(FpData()).addrWidth)))
707      rfWrite.wen := this.fpWen && fire
708      rfWrite.addr := this.pdest
709      rfWrite.data := this.data
710      rfWrite.intWen := false.B
711      rfWrite.fpWen := this.fpWen
712      rfWrite.vecWen := false.B
713      rfWrite
714    }
715
716    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
717      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
718      rfWrite.wen := this.vecWen && fire
719      rfWrite.addr := this.pdest
720      rfWrite.data := this.data
721      rfWrite.intWen := false.B
722      rfWrite.fpWen := false.B
723      rfWrite.vecWen := this.vecWen
724      rfWrite
725    }
726  }
727
728  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
729  //                                /
730  //     [IssueQueue]--> ExuInput --
731  class ExuBypassBundle(
732    val params: ExeUnitParams,
733  )(implicit
734    val p: Parameters
735  ) extends Bundle {
736    val data  = UInt(params.dataBitsMax.W)
737    val pdest = UInt(params.wbPregIdxWidth.W)
738  }
739
740  class ExceptionInfo(implicit p: Parameters) extends XSBundle {
741    val pc = UInt(VAddrData().dataWidth.W)
742    val instr = UInt(32.W)
743    val commitType = CommitType()
744    val exceptionVec = ExceptionVec()
745    val gpaddr = UInt(GPAddrBits.W)
746    val singleStep = Bool()
747    val crossPageIPFFix = Bool()
748    val isInterrupt = Bool()
749    val isHls = Bool()
750    val vls = Bool()
751    val trigger  = new TriggerCf
752  }
753
754  object UopIdx {
755    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
756  }
757
758  object FuLatency {
759    def apply(): UInt = UInt(width.W)
760
761    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
762  }
763
764  object ExuOH {
765    def apply(exuNum: Int): UInt = UInt(exuNum.W)
766
767    def apply()(implicit p: Parameters): UInt = UInt(width.W)
768
769    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
770  }
771
772  object ExuVec {
773    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
774
775    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
776
777    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
778  }
779
780  class CancelSignal(implicit p: Parameters) extends XSBundle {
781    val rfWen = Bool()
782    val fpWen = Bool()
783    val vecWen = Bool()
784    val pdest = UInt(PhyRegIdxWidth.W)
785
786    def needCancel(srcType: UInt, psrc: UInt, valid: Bool): Bool = {
787      val pdestMatch = pdest === psrc
788      pdestMatch && (
789        SrcType.isFp(srcType) && !this.rfWen ||
790          SrcType.isXp(srcType) && this.rfWen ||
791          SrcType.isVp(srcType) && !this.rfWen
792        ) && valid
793    }
794  }
795
796  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
797    val uop = new DynInst
798    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
799    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
800    val isFirstIssue = Bool()
801    val flowNum      = OptionWrapper(isVector, NumLsElem())
802
803    def src_rs1 = src(0)
804    def src_stride = src(1)
805    def src_vs3 = src(2)
806    def src_mask = if (isVector) src(3) else 0.U
807    def src_vl = if (isVector) src(4) else 0.U
808  }
809
810  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
811    val uop = new DynInst
812    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
813    val mask = if (isVector) Some(UInt(VLEN.W)) else None
814    val vdIdx = if (isVector) Some(UInt(3.W)) else None // TODO: parameterize width
815    val vdIdxInField = if (isVector) Some(UInt(3.W)) else None
816    val debug = new DebugBundle
817
818    def isVls = FuType.isVls(uop.fuType)
819  }
820
821  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
822    val uop = new DynInst
823    val flag = UInt(1.W)
824  }
825
826  object LoadShouldCancel {
827    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
828      val ld1Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld1Cancel)).map { case (dep, cancel) => cancel && dep(0)}.reduce(_ || _))
829      val ld2Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld2Cancel)).map { case (dep, cancel) => cancel && dep(1)}.reduce(_ || _))
830      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
831    }
832  }
833}
834