xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision a2fa0ad9374b49a289bfb9c9677adc3f6bc0db6e)
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
25import xiangshan.backend.trace._
26import utility._
27
28object Bundles {
29  /**
30   * Connect Same Name Port like bundleSource := bundleSinkBudle.
31   *
32   * There is no limit to the number of ports on both sides.
33   *
34   * Don't forget to connect the remaining ports!
35   */
36  def connectSamePort (bundleSource: Bundle, bundleSink: Bundle):Unit = {
37    bundleSource.elements.foreach { case (name, data) =>
38      if (bundleSink.elements.contains(name))
39        data := bundleSink.elements(name)
40    }
41  }
42  // frontend -> backend
43  class StaticInst(implicit p: Parameters) extends XSBundle {
44    val instr            = UInt(32.W)
45    val pc               = UInt(VAddrBits.W)
46    val foldpc           = UInt(MemPredPCWidth.W)
47    val exceptionVec     = ExceptionVec()
48    val isFetchMalAddr   = Bool()
49    val trigger          = TriggerAction()
50    val preDecodeInfo    = new PreDecodeInfo
51    val pred_taken       = Bool()
52    val crossPageIPFFix  = Bool()
53    val ftqPtr           = new FtqPtr
54    val ftqOffset        = UInt(log2Up(PredictWidth).W)
55    val isLastInFtqEntry = Bool()
56
57    def connectCtrlFlow(source: CtrlFlow): Unit = {
58      this.instr            := source.instr
59      this.pc               := source.pc
60      this.foldpc           := source.foldpc
61      this.exceptionVec     := source.exceptionVec
62      this.isFetchMalAddr   := source.backendException
63      this.trigger          := source.trigger
64      this.preDecodeInfo    := source.pd
65      this.pred_taken       := source.pred_taken
66      this.crossPageIPFFix  := source.crossPageIPFFix
67      this.ftqPtr           := source.ftqPtr
68      this.ftqOffset        := source.ftqOffset
69      this.isLastInFtqEntry := source.isLastInFtqEntry
70    }
71  }
72
73  // StaticInst --[Decode]--> DecodedInst
74  class DecodedInst(implicit p: Parameters) extends XSBundle {
75    def numSrc = backendParams.numSrc
76    // passed from StaticInst
77    val instr           = UInt(32.W)
78    val pc              = UInt(VAddrBits.W)
79    val foldpc          = UInt(MemPredPCWidth.W)
80    val exceptionVec    = ExceptionVec()
81    val isFetchMalAddr  = Bool()
82    val trigger         = TriggerAction()
83    val preDecodeInfo   = new PreDecodeInfo
84    val pred_taken      = Bool()
85    val crossPageIPFFix = Bool()
86    val ftqPtr          = new FtqPtr
87    val ftqOffset       = UInt(log2Up(PredictWidth).W)
88    // decoded
89    val srcType         = Vec(numSrc, SrcType())
90    val lsrc            = Vec(numSrc, UInt(LogicRegsWidth.W))
91    val ldest           = UInt(LogicRegsWidth.W)
92    val fuType          = FuType()
93    val fuOpType        = FuOpType()
94    val rfWen           = Bool()
95    val fpWen           = Bool()
96    val vecWen          = Bool()
97    val v0Wen           = Bool()
98    val vlWen           = Bool()
99    val isXSTrap        = Bool()
100    val waitForward     = Bool() // no speculate execution
101    val blockBackward   = Bool()
102    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
103    val canRobCompress  = Bool()
104    val selImm          = SelImm()
105    val imm             = UInt(ImmUnion.maxLen.W)
106    val fpu             = new FPUCtrlSignals
107    val vpu             = new VPUCtrlSignals
108    val vlsInstr        = Bool()
109    val wfflags         = Bool()
110    val isMove          = Bool()
111    val uopIdx          = UopIdx()
112    val uopSplitType    = UopSplitType()
113    val isVset          = Bool()
114    val firstUop        = Bool()
115    val lastUop         = Bool()
116    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
117    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
118    val commitType      = CommitType() // Todo: remove it
119    val needFrm         = new NeedFrmBundle
120
121    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
122
123    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
124      isXSTrap, waitForward, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
125
126    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
127      val decoder: Seq[UInt] = ListLookup(
128        inst, XDecode.decodeDefault.map(bitPatToUInt),
129        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
130      )
131      allSignals zip decoder foreach { case (s, d) => s := d }
132      debug_fuType.foreach(_ := fuType)
133      this
134    }
135
136    def isSoftPrefetch: Bool = {
137      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
138    }
139
140    def connectStaticInst(source: StaticInst): Unit = {
141      for ((name, data) <- this.elements) {
142        if (source.elements.contains(name)) {
143          data := source.elements(name)
144        }
145      }
146    }
147  }
148
149  class TrapInstInfo(implicit p: Parameters) extends XSBundle {
150    val instr = UInt(32.W)
151    val ftqPtr = new FtqPtr
152    val ftqOffset = UInt(log2Up(PredictWidth).W)
153
154    def needFlush(ftqPtr: FtqPtr, ftqOffset: UInt): Bool ={
155      val sameFlush = this.ftqPtr === ftqPtr && this.ftqOffset > ftqOffset
156      sameFlush || isAfter(this.ftqPtr, ftqPtr)
157    }
158
159    def fromDecodedInst(decodedInst: DecodedInst): this.type = {
160      this.instr     := decodedInst.instr
161      this.ftqPtr    := decodedInst.ftqPtr
162      this.ftqOffset := decodedInst.ftqOffset
163      this
164    }
165  }
166
167  // DecodedInst --[Rename]--> DynInst
168  class DynInst(implicit p: Parameters) extends XSBundle {
169    def numSrc          = backendParams.numSrc
170    // passed from StaticInst
171    val instr           = UInt(32.W)
172    val pc              = UInt(VAddrBits.W)
173    val foldpc          = UInt(MemPredPCWidth.W)
174    val exceptionVec    = ExceptionVec()
175    val isFetchMalAddr  = Bool()
176    val hasException    = Bool()
177    val trigger         = TriggerAction()
178    val preDecodeInfo   = new PreDecodeInfo
179    val pred_taken      = Bool()
180    val crossPageIPFFix = Bool()
181    val ftqPtr          = new FtqPtr
182    val ftqOffset       = UInt(log2Up(PredictWidth).W)
183    // passed from DecodedInst
184    val srcType         = Vec(numSrc, SrcType())
185    val ldest           = UInt(LogicRegsWidth.W)
186    val fuType          = FuType()
187    val fuOpType        = FuOpType()
188    val rfWen           = Bool()
189    val fpWen           = Bool()
190    val vecWen          = Bool()
191    val v0Wen           = Bool()
192    val vlWen           = Bool()
193    val isXSTrap        = Bool()
194    val waitForward     = Bool() // no speculate execution
195    val blockBackward   = Bool()
196    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
197    val canRobCompress  = Bool()
198    val selImm          = SelImm()
199    val imm             = UInt(32.W)
200    val fpu             = new FPUCtrlSignals
201    val vpu             = new VPUCtrlSignals
202    val vlsInstr        = Bool()
203    val wfflags         = Bool()
204    val isMove          = Bool()
205    val uopIdx          = UopIdx()
206    val isVset          = Bool()
207    val firstUop        = Bool()
208    val lastUop         = Bool()
209    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
210    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
211    val commitType      = CommitType()
212    // rename
213    val srcState        = Vec(numSrc, SrcState())
214    val srcLoadDependency  = Vec(numSrc, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
215    val psrc            = Vec(numSrc, UInt(PhyRegIdxWidth.W))
216    val pdest           = UInt(PhyRegIdxWidth.W)
217    // reg cache
218    val useRegCache     = Vec(backendParams.numIntRegSrc, Bool())
219    val regCacheIdx     = Vec(backendParams.numIntRegSrc, UInt(RegCacheIdxWidth.W))
220    val robIdx          = new RobPtr
221    val instrSize       = UInt(log2Ceil(RenameWidth + 1).W)
222    val dirtyFs         = Bool()
223    val dirtyVs         = Bool()
224    val traceBlockInPipe = new TracePipe(IretireWidthInPipe)
225
226    val eliminatedMove  = Bool()
227    // Take snapshot at this CFI inst
228    val snapshot        = Bool()
229    val debugInfo       = new PerfDebugInfo
230    val storeSetHit     = Bool() // inst has been allocated an store set
231    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
232    // Load wait is needed
233    // load inst will not be executed until former store (predicted by mdp) addr calcuated
234    val loadWaitBit     = Bool()
235    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
236    // load inst will not be executed until ALL former store addr calcuated
237    val loadWaitStrict  = Bool()
238    val ssid            = UInt(SSIDWidth.W)
239    // Todo
240    val lqIdx = new LqPtr
241    val sqIdx = new SqPtr
242    // debug module
243    val singleStep      = Bool()
244    // schedule
245    val replayInst      = Bool()
246
247    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
248
249    val numLsElem       = NumLsElem()
250
251    def getDebugFuType: UInt = debug_fuType.getOrElse(fuType)
252
253    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
254    def isLUI32: Bool = this.selImm === SelImm.IMM_LUI32
255    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
256
257    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
258    def isSvinval(flush: Bool) = FuType.isFence(fuType) &&
259      Cat(Seq(FenceOpType.sfence, FenceOpType.hfence_v, FenceOpType.hfence_g).map(_ === fuOpType)).orR && !flush
260    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
261    def isNotSvinval = !FuType.isFence(fuType)
262
263    def isHls: Bool = {
264      fuType === FuType.ldu.U && LSUOpType.isHlv(fuOpType) || fuType === FuType.stu.U && LSUOpType.isHsv(fuOpType)
265    }
266
267    def isAMOCAS: Bool = FuType.isAMO(fuType) && LSUOpType.isAMOCAS(fuOpType)
268
269    def srcIsReady: Vec[Bool] = {
270      VecInit(this.srcType.zip(this.srcState).map {
271        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
272      })
273    }
274
275    def clearExceptions(
276      exceptionBits: Seq[Int] = Seq(),
277      flushPipe    : Boolean = false,
278      replayInst   : Boolean = false
279    ): DynInst = {
280      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
281      if (!flushPipe) { this.flushPipe := false.B }
282      if (!replayInst) { this.replayInst := false.B }
283      this
284    }
285
286    def needWriteRf: Bool = rfWen || fpWen || vecWen || v0Wen || vlWen
287  }
288
289  trait BundleSource {
290    var wakeupSource = "undefined"
291    var idx = 0
292  }
293
294  /**
295    *
296    * @param pregIdxWidth index width of preg
297    * @param exuIndices exu indices of wakeup bundle
298    */
299  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int])(implicit p: Parameters) extends XSBundle {
300    val rfWen = Bool()
301    val fpWen = Bool()
302    val vecWen = Bool()
303    val v0Wen = Bool()
304    val vlWen = Bool()
305    val pdest = UInt(pregIdxWidth.W)
306
307    /**
308      * @param successor Seq[(psrc, srcType)]
309      * @return Seq[if wakeup psrc]
310      */
311    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
312      successor.map { case (thatPsrc, srcType) =>
313        val pdestMatch = pdest === thatPsrc
314        pdestMatch && (
315          SrcType.isFp(srcType) && this.fpWen ||
316            SrcType.isXp(srcType) && this.rfWen ||
317            SrcType.isVp(srcType) && this.vecWen
318          ) && valid
319      }
320    }
321    def wakeUpV0(successor: (UInt, UInt), valid: Bool): Bool = {
322      val (thatPsrc, srcType) = successor
323      val pdestMatch = pdest === thatPsrc
324      pdestMatch && (
325        SrcType.isV0(srcType) && this.v0Wen
326      ) && valid
327    }
328    def wakeUpVl(successor: (UInt, UInt), valid: Bool): Bool = {
329      val (thatPsrc, srcType) = successor
330      val pdestMatch = pdest === thatPsrc
331      pdestMatch && (
332        SrcType.isVp(srcType) && this.vlWen
333      ) && valid
334    }
335    def wakeUpFromIQ(successor: Seq[(UInt, UInt)]): Seq[Bool] = {
336      successor.map { case (thatPsrc, srcType) =>
337        val pdestMatch = pdest === thatPsrc
338        pdestMatch && (
339          SrcType.isFp(srcType) && this.fpWen ||
340            SrcType.isXp(srcType) && this.rfWen ||
341            SrcType.isVp(srcType) && this.vecWen
342          )
343      }
344    }
345    def wakeUpV0FromIQ(successor: (UInt, UInt)): Bool = {
346      val (thatPsrc, srcType) = successor
347      val pdestMatch = pdest === thatPsrc
348      pdestMatch && (
349        SrcType.isV0(srcType) && this.v0Wen
350      )
351    }
352    def wakeUpVlFromIQ(successor: (UInt, UInt)): Bool = {
353      val (thatPsrc, srcType) = successor
354      val pdestMatch = pdest === thatPsrc
355      pdestMatch && (
356        SrcType.isVp(srcType) && this.vlWen
357      )
358    }
359
360    def hasOnlyOneSource: Boolean = exuIndices.size == 1
361
362    def hasMultiSources: Boolean = exuIndices.size > 1
363
364    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
365
366    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
367
368    def exuIdx: Int = {
369      require(hasOnlyOneSource)
370      this.exuIndices.head
371    }
372  }
373
374  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams)(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
375
376  }
377
378  class IssueQueueIQWakeUpBundle(
379    exuIdx: Int,
380    backendParams: BackendParams,
381    copyWakeupOut: Boolean = false,
382    copyNum: Int = 0
383  )(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
384    val loadDependency = Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))
385    val is0Lat = Bool()
386    val params = backendParams.allExuParams.filter(_.exuIdx == exuIdx).head
387    val rcDest = OptionWrapper(params.needWriteRegCache, UInt(RegCacheIdxWidth.W))
388    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
389    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
390    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
391    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
392    val v0WenCopy = OptionWrapper(copyWakeupOut && params.needV0Wen, Vec(copyNum, Bool()))
393    val vlWenCopy = OptionWrapper(copyWakeupOut && params.needVlWen, Vec(copyNum, Bool()))
394    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
395
396    def fromExuInput(exuInput: ExuInput): Unit = {
397      this.rfWen := exuInput.rfWen.getOrElse(false.B)
398      this.fpWen := exuInput.fpWen.getOrElse(false.B)
399      this.vecWen := exuInput.vecWen.getOrElse(false.B)
400      this.v0Wen := exuInput.v0Wen.getOrElse(false.B)
401      this.vlWen := exuInput.vlWen.getOrElse(false.B)
402      this.pdest := exuInput.pdest
403    }
404  }
405
406  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
407    // vtype
408    val vill      = Bool()
409    val vma       = Bool()    // 1: agnostic, 0: undisturbed
410    val vta       = Bool()    // 1: agnostic, 0: undisturbed
411    val vsew      = VSew()
412    val vlmul     = VLmul()   // 1/8~8      --> -3~3
413
414    // spec vtype
415    val specVill  = Bool()
416    val specVma   = Bool()    // 1: agnostic, 0: undisturbed
417    val specVta   = Bool()    // 1: agnostic, 0: undisturbed
418    val specVsew  = VSew()
419    val specVlmul = VLmul()   // 1/8~8      --> -3~3
420
421    val vm        = Bool()    // 0: need v0.t
422    val vstart    = Vl()
423
424    // float rounding mode
425    val frm       = Frm()
426    // scalar float instr and vector float reduction
427    val fpu       = Fpu()
428    // vector fix int rounding mode
429    val vxrm      = Vxrm()
430    // vector uop index, exclude other non-vector uop
431    val vuopIdx   = UopIdx()
432    val lastUop   = Bool()
433    // maybe used if data dependancy
434    val vmask     = UInt(V0Data().dataWidth.W)
435    val vl        = Vl()
436
437    // vector load/store
438    val nf        = Nf()
439    val veew      = VEew()
440
441    val isReverse = Bool() // vrsub, vrdiv
442    val isExt     = Bool()
443    val isNarrow  = Bool()
444    val isDstMask = Bool() // vvm, vvvm, mmm
445    val isOpMask  = Bool() // vmand, vmnand
446    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
447
448    val isDependOldVd = Bool() // some instruction's computation depends on oldvd
449    val isWritePartVd = Bool() // some instruction's computation writes part of vd, such as vredsum
450
451    val isVleff = Bool() // vleff
452
453    def vtype: VType = {
454      val res = Wire(VType())
455      res.illegal := this.vill
456      res.vma     := this.vma
457      res.vta     := this.vta
458      res.vsew    := this.vsew
459      res.vlmul   := this.vlmul
460      res
461    }
462
463    def specVType: VType = {
464      val res = Wire(VType())
465      res.illegal := this.specVill
466      res.vma     := this.specVma
467      res.vta     := this.specVta
468      res.vsew    := this.specVsew
469      res.vlmul   := this.specVlmul
470      res
471    }
472
473    def vconfig: VConfig = {
474      val res = Wire(VConfig())
475      res.vtype := this.vtype
476      res.vl    := this.vl
477      res
478    }
479
480    def connectVType(source: VType): Unit = {
481      this.vill  := source.illegal
482      this.vma   := source.vma
483      this.vta   := source.vta
484      this.vsew  := source.vsew
485      this.vlmul := source.vlmul
486    }
487  }
488
489  class NeedFrmBundle(implicit p: Parameters) extends XSBundle {
490    val scalaNeedFrm = Bool()
491    val vectorNeedFrm = Bool()
492  }
493
494  // DynInst --[IssueQueue]--> DataPath
495  class IssueQueueIssueBundle(
496    iqParams: IssueBlockParams,
497    val exuParams: ExeUnitParams,
498  )(implicit
499    p: Parameters
500  ) extends XSBundle {
501    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
502
503    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
504      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
505        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
506      )
507    ))
508
509    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
510    val rcIdx = OptionWrapper(exuParams.needReadRegCache, Vec(exuParams.numRegSrc, UInt(RegCacheIdxWidth.W))) // used to select regcache data
511    val immType = SelImm()                         // used to select imm extractor
512    val common = new ExuInput(exuParams)
513    val addrOH = UInt(iqParams.numEntries.W)
514
515    def exuIdx = exuParams.exuIdx
516    def getSource: SchedulerType = exuParams.getWBSource
517
518    def getRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
519      rf.zip(srcType).map {
520        case (rfRd: MixedVec[RfReadPortWithConfig], t: UInt) =>
521          makeValid(issueValid, rfRd.head)
522      }.toSeq
523    }
524  }
525
526  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
527    val issueQueueParams = this.params
528    val og0resp = Valid(new EntryDeqRespBundle)
529    val og1resp = Valid(new EntryDeqRespBundle)
530  }
531
532  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
533    private val intCertainLat = params.intLatencyCertain
534    private val fpCertainLat = params.fpLatencyCertain
535    private val vfCertainLat = params.vfLatencyCertain
536    private val v0CertainLat = params.v0LatencyCertain
537    private val vlCertainLat = params.vlLatencyCertain
538    private val intLat = params.intLatencyValMax
539    private val fpLat = params.fpLatencyValMax
540    private val vfLat = params.vfLatencyValMax
541    private val v0Lat = params.v0LatencyValMax
542    private val vlLat = params.vlLatencyValMax
543
544    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
545    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
546    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
547    val v0WbBusyTable = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
548    val vlWbBusyTable = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
549    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
550    val fpDeqRespSet = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
551    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
552    val v0DeqRespSet = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
553    val vlDeqRespSet = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
554  }
555
556  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
557    private val intCertainLat = params.intLatencyCertain
558    private val fpCertainLat = params.fpLatencyCertain
559    private val vfCertainLat = params.vfLatencyCertain
560    private val v0CertainLat = params.v0LatencyCertain
561    private val vlCertainLat = params.vlLatencyCertain
562    private val intLat = params.intLatencyValMax
563    private val fpLat = params.fpLatencyValMax
564    private val vfLat = params.vfLatencyValMax
565    private val v0Lat = params.v0LatencyValMax
566    private val vlLat = params.vlLatencyValMax
567
568    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
569    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
570    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
571    val v0WbBusyTable = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
572    val vlWbBusyTable = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
573  }
574
575  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
576    private val intCertainLat = params.intLatencyCertain
577    private val fpCertainLat = params.fpLatencyCertain
578    private val vfCertainLat = params.vfLatencyCertain
579    private val v0CertainLat = params.v0LatencyCertain
580    private val vlCertainLat = params.vlLatencyCertain
581
582    val intConflict = OptionWrapper(intCertainLat, Bool())
583    val fpConflict = OptionWrapper(fpCertainLat, Bool())
584    val vfConflict = OptionWrapper(vfCertainLat, Bool())
585    val v0Conflict = OptionWrapper(v0CertainLat, Bool())
586    val vlConflict = OptionWrapper(vlCertainLat, Bool())
587  }
588
589  class ImmInfo extends Bundle {
590    val imm = UInt(32.W)
591    val immType = SelImm()
592  }
593
594  // DataPath --[ExuInput]--> Exu
595  class ExuInput(val params: ExeUnitParams, copyWakeupOut:Boolean = false, copyNum:Int = 0)(implicit p: Parameters) extends XSBundle {
596    val fuType        = FuType()
597    val fuOpType      = FuOpType()
598    val src           = Vec(params.numRegSrc, UInt(params.srcDataBitsMax.W))
599    val imm           = UInt(64.W)
600    val nextPcOffset  = OptionWrapper(params.hasBrhFu, UInt((log2Up(PredictWidth) + 1).W))
601    val robIdx        = new RobPtr
602    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
603    val isFirstIssue  = Bool()                      // Only used by store yet
604    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
605    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
606    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
607    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
608    val v0WenCopy  = OptionWrapper(copyWakeupOut && params.needV0Wen, Vec(copyNum, Bool()))
609    val vlWenCopy  = OptionWrapper(copyWakeupOut && params.needVlWen, Vec(copyNum, Bool()))
610    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
611    val pdest         = UInt(params.wbPregIdxWidth.W)
612    val rfWen         = if (params.needIntWen)    Some(Bool())                        else None
613    val fpWen         = if (params.needFpWen)     Some(Bool())                        else None
614    val vecWen        = if (params.needVecWen)    Some(Bool())                        else None
615    val v0Wen         = if (params.needV0Wen)     Some(Bool())                        else None
616    val vlWen         = if (params.needVlWen)     Some(Bool())                        else None
617    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
618    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
619    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
620    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
621    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
622    val ftqIdx        = if (params.needPc || params.replayInst || params.hasStoreAddrFu || params.hasCSR)
623                                                  Some(new FtqPtr)                    else None
624    val ftqOffset     = if (params.needPc || params.replayInst || params.hasStoreAddrFu || params.hasCSR)
625                                                  Some(UInt(log2Up(PredictWidth).W))  else None
626    val predictInfo   = if (params.needPdInfo)  Some(new Bundle {
627      val target = UInt(VAddrData().dataWidth.W)
628      val taken = Bool()
629    }) else None
630    val loadWaitBit    = OptionWrapper(params.hasLoadExu, Bool())
631    val waitForRobIdx  = OptionWrapper(params.hasLoadExu, new RobPtr) // store set predicted previous store robIdx
632    val storeSetHit    = OptionWrapper(params.hasLoadExu, Bool()) // inst has been allocated an store set
633    val loadWaitStrict = OptionWrapper(params.hasLoadExu, Bool()) // load inst will not be executed until ALL former store addr calcuated
634    val ssid           = OptionWrapper(params.hasLoadExu, UInt(SSIDWidth.W))
635    // only vector load store need
636    val numLsElem      = OptionWrapper(params.hasVecLsFu, NumLsElem())
637
638    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
639    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
640    val dataSources = Vec(params.numRegSrc, DataSource())
641    val exuSources = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuSource(params)))
642    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
643    val loadDependency = OptionWrapper(params.needLoadDependency, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
644
645    val perfDebugInfo = new PerfDebugInfo()
646
647    def exuIdx = this.params.exuIdx
648
649    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
650      // src is assigned to rfReadData
651      this.fuType        := source.common.fuType
652      this.fuOpType      := source.common.fuOpType
653      this.imm           := source.common.imm
654      this.robIdx        := source.common.robIdx
655      this.pdest         := source.common.pdest
656      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
657      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
658      this.dataSources   := source.common.dataSources
659      this.exuSources    .foreach(_ := source.common.exuSources.get)
660      this.rfWen         .foreach(_ := source.common.rfWen.get)
661      this.fpWen         .foreach(_ := source.common.fpWen.get)
662      this.vecWen        .foreach(_ := source.common.vecWen.get)
663      this.v0Wen         .foreach(_ := source.common.v0Wen.get)
664      this.vlWen         .foreach(_ := source.common.vlWen.get)
665      this.fpu           .foreach(_ := source.common.fpu.get)
666      this.vpu           .foreach(_ := source.common.vpu.get)
667      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
668      this.pc            .foreach(_ := source.common.pc.get)
669      this.preDecode     .foreach(_ := source.common.preDecode.get)
670      this.nextPcOffset  .foreach(_ := source.common.nextPcOffset.get)
671      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
672      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
673      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
674      this.loadWaitBit   .foreach(_ := source.common.loadWaitBit.get)
675      this.waitForRobIdx .foreach(_ := source.common.waitForRobIdx.get)
676      this.storeSetHit   .foreach(_ := source.common.storeSetHit.get)
677      this.loadWaitStrict.foreach(_ := source.common.loadWaitStrict.get)
678      this.ssid          .foreach(_ := source.common.ssid.get)
679      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
680      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
681      this.numLsElem     .foreach(_ := source.common.numLsElem.get)
682      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
683      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
684    }
685  }
686
687  // ExuInput --[FuncUnit]--> ExuOutput
688  class ExuOutput(
689    val params: ExeUnitParams,
690  )(implicit
691    val p: Parameters
692  ) extends Bundle with BundleSource with HasXSParameter {
693    val data         = Vec(params.wbPathNum, UInt(params.destDataBitsMax.W))
694    val pdest        = UInt(params.wbPregIdxWidth.W)
695    val robIdx       = new RobPtr
696    val intWen       = if (params.needIntWen)   Some(Bool())                  else None
697    val fpWen        = if (params.needFpWen)    Some(Bool())                  else None
698    val vecWen       = if (params.needVecWen)   Some(Bool())                  else None
699    val v0Wen        = if (params.needV0Wen)    Some(Bool())                  else None
700    val vlWen        = if (params.needVlWen)    Some(Bool())                  else None
701    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
702    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
703    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
704    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
705    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
706    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
707    val replay       = if (params.replayInst)   Some(Bool())                  else None
708    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
709    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
710                                                Some(new SqPtr())             else None
711    val trigger      = if (params.trigger)      Some(TriggerAction())           else None
712    // uop info
713    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
714    // vldu used only
715    val vls = OptionWrapper(params.hasVLoadFu, new Bundle {
716      val vpu = new VPUCtrlSignals
717      val oldVdPsrc = UInt(PhyRegIdxWidth.W)
718      val vdIdx = UInt(3.W)
719      val vdIdxInField = UInt(3.W)
720      val isIndexed = Bool()
721      val isMasked = Bool()
722      val isStrided = Bool()
723      val isWhole = Bool()
724      val isVecLoad = Bool()
725      val isVlm = Bool()
726    })
727    val debug = new DebugBundle
728    val debugInfo = new PerfDebugInfo
729  }
730
731  // ExuOutput + DynInst --> WriteBackBundle
732  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
733    val rfWen = Bool()
734    val fpWen = Bool()
735    val vecWen = Bool()
736    val v0Wen = Bool()
737    val vlWen = Bool()
738    val pdest = UInt(params.pregIdxWidth(backendParams).W)
739    val data = UInt(params.dataWidth.W)
740    val robIdx = new RobPtr()(p)
741    val flushPipe = Bool()
742    val replayInst = Bool()
743    val redirect = ValidIO(new Redirect)
744    val fflags = UInt(5.W)
745    val vxsat = Bool()
746    val exceptionVec = ExceptionVec()
747    val debug = new DebugBundle
748    val debugInfo = new PerfDebugInfo
749
750    this.wakeupSource = s"WB(${params.toString})"
751
752    def fromExuOutput(source: ExuOutput, wbType: String) = {
753      val typeMap = Map("int" -> 0, "fp" -> 1, "vf" -> 2, "v0" -> 3, "vl" -> 4)
754      this.rfWen  := source.intWen.getOrElse(false.B)
755      this.fpWen  := source.fpWen.getOrElse(false.B)
756      this.vecWen := source.vecWen.getOrElse(false.B)
757      this.v0Wen  := source.v0Wen.getOrElse(false.B)
758      this.vlWen  := source.vlWen.getOrElse(false.B)
759      this.pdest  := source.pdest
760      this.data   := source.data(source.params.wbIndex(typeMap(wbType)))
761      this.robIdx := source.robIdx
762      this.flushPipe := source.flushPipe.getOrElse(false.B)
763      this.replayInst := source.replay.getOrElse(false.B)
764      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
765      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
766      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
767      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
768      this.debug := source.debug
769      this.debugInfo := source.debugInfo
770    }
771
772    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
773      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
774      rfWrite.wen := this.rfWen && fire
775      rfWrite.addr := this.pdest
776      rfWrite.data := this.data
777      rfWrite.intWen := this.rfWen
778      rfWrite.fpWen := false.B
779      rfWrite.vecWen := false.B
780      rfWrite.v0Wen := false.B
781      rfWrite.vlWen := false.B
782      rfWrite
783    }
784
785    def asFpRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
786      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(FpData()).addrWidth)))
787      rfWrite.wen := this.fpWen && fire
788      rfWrite.addr := this.pdest
789      rfWrite.data := this.data
790      rfWrite.intWen := false.B
791      rfWrite.fpWen := this.fpWen
792      rfWrite.vecWen := false.B
793      rfWrite.v0Wen := false.B
794      rfWrite.vlWen := false.B
795      rfWrite
796    }
797
798    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
799      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
800      rfWrite.wen := this.vecWen && fire
801      rfWrite.addr := this.pdest
802      rfWrite.data := this.data
803      rfWrite.intWen := false.B
804      rfWrite.fpWen := false.B
805      rfWrite.vecWen := this.vecWen
806      rfWrite.v0Wen := false.B
807      rfWrite.vlWen := false.B
808      rfWrite
809    }
810
811    def asV0RfWriteBundle(fire: Bool): RfWritePortWithConfig = {
812      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(V0Data()).addrWidth)))
813      rfWrite.wen := this.v0Wen && fire
814      rfWrite.addr := this.pdest
815      rfWrite.data := this.data
816      rfWrite.intWen := false.B
817      rfWrite.fpWen := false.B
818      rfWrite.vecWen := false.B
819      rfWrite.v0Wen := this.v0Wen
820      rfWrite.vlWen := false.B
821      rfWrite
822    }
823
824    def asVlRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
825      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VlData()).addrWidth)))
826      rfWrite.wen := this.vlWen && fire
827      rfWrite.addr := this.pdest
828      rfWrite.data := this.data
829      rfWrite.intWen := false.B
830      rfWrite.fpWen := false.B
831      rfWrite.vecWen := false.B
832      rfWrite.v0Wen := false.B
833      rfWrite.vlWen := this.vlWen
834      rfWrite
835    }
836  }
837
838  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
839  //                                /
840  //     [IssueQueue]--> ExuInput --
841  class ExuBypassBundle(
842    val params: ExeUnitParams,
843  )(implicit p: Parameters) extends XSBundle {
844    val intWen = Bool()
845    val data   = UInt(params.destDataBitsMax.W)
846    val pdest  = UInt(params.wbPregIdxWidth.W)
847  }
848
849  class ExceptionInfo(implicit p: Parameters) extends XSBundle {
850    val pc = UInt(VAddrData().dataWidth.W)
851    val instr = UInt(32.W)
852    val commitType = CommitType()
853    val exceptionVec = ExceptionVec()
854    val isPcBkpt = Bool()
855    val isFetchMalAddr = Bool()
856    val gpaddr = UInt(XLEN.W)
857    val singleStep = Bool()
858    val crossPageIPFFix = Bool()
859    val isInterrupt = Bool()
860    val isHls = Bool()
861    val vls = Bool()
862    val trigger = TriggerAction()
863    val isForVSnonLeafPTE = Bool()
864  }
865
866  object UopIdx {
867    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
868  }
869
870  object FuLatency {
871    def apply(): UInt = UInt(width.W)
872
873    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
874  }
875
876  class ExuSource(exuNum: Int)(implicit p: Parameters) extends XSBundle {
877    val value = UInt(log2Ceil(exuNum + 1).W)
878
879    val allExuNum = p(XSCoreParamsKey).backendParams.numExu
880
881    def toExuOH(num: Int, filter: Seq[Int]): Vec[Bool] = {
882      require(num == filter.size)
883      val encodedExuOH = UIntToOH(this.value)(num, 1)
884      val ext = Module(new UIntExtractor(allExuNum, filter))
885      ext.io.in := encodedExuOH
886      VecInit(ext.io.out.asBools.zipWithIndex.map{ case(out, idx) =>
887        if (filter.contains(idx)) out
888        else false.B
889      })
890    }
891
892    def toExuOH(exuParams: ExeUnitParams): Vec[Bool] = {
893      toExuOH(exuParams.numWakeupFromIQ, exuParams.iqWakeUpSinkPairs.map(x => x.source.getExuParam(p(XSCoreParamsKey).backendParams.allExuParams).exuIdx))
894    }
895
896    def toExuOH(iqParams: IssueBlockParams): Vec[Bool] = {
897      toExuOH(iqParams.numWakeupFromIQ, iqParams.wakeUpSourceExuIdx)
898    }
899
900    def fromExuOH(iqParams: IssueBlockParams, exuOH: UInt): UInt = {
901      val comp = Module(new UIntCompressor(allExuNum, iqParams.wakeUpSourceExuIdx))
902      comp.io.in := exuOH
903      OHToUInt(Cat(comp.io.out, 0.U(1.W)))
904    }
905  }
906
907  object ExuSource {
908    def apply(exuNum: Int)(implicit p: Parameters) = new ExuSource(exuNum)
909
910    def apply(params: ExeUnitParams)(implicit p: Parameters) = new ExuSource(params.numWakeupFromIQ)
911
912    def apply()(implicit p: Parameters, params: IssueBlockParams) = new ExuSource(params.numWakeupFromIQ)
913  }
914
915  object ExuVec {
916    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
917
918    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
919
920    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
921  }
922
923  class CancelSignal(implicit p: Parameters) extends XSBundle {
924    val rfWen = Bool()
925    val fpWen = Bool()
926    val vecWen = Bool()
927    val v0Wen = Bool()
928    val vlWen = Bool()
929    val pdest = UInt(PhyRegIdxWidth.W)
930  }
931
932  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
933    val uop = new DynInst
934    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
935    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
936    val isFirstIssue = Bool()
937    val flowNum      = OptionWrapper(isVector, NumLsElem())
938
939    def src_rs1 = src(0)
940    def src_rs2 = src(1)
941    def src_stride = src(1)
942    def src_vs3 = src(2)
943    def src_mask = if (isVector) src(3) else 0.U
944    def src_vl = if (isVector) src(4) else 0.U
945  }
946
947  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
948    val uop = new DynInst
949    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
950    val mask = if (isVector) Some(UInt(VLEN.W)) else None
951    val vdIdx = if (isVector) Some(UInt(3.W)) else None // TODO: parameterize width
952    val vdIdxInField = if (isVector) Some(UInt(3.W)) else None
953    val isFromLoadUnit = Bool()
954    val debug = new DebugBundle
955
956    def isVls = FuType.isVls(uop.fuType)
957  }
958
959  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
960    val uop = new DynInst
961    val flag = UInt(1.W)
962  }
963
964  object LoadShouldCancel {
965    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
966      val ld1Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld1Cancel)).map { case (dep, cancel) => cancel && dep(0)}.reduce(_ || _))
967      val ld2Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld2Cancel)).map { case (dep, cancel) => cancel && dep(1)}.reduce(_ || _))
968      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
969    }
970  }
971}
972