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