xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision b52d475534795fe5ff9bc9107eb7a4d1b6966d85)
1package xiangshan.backend
2
3import chipsalliance.rocketchip.config.Parameters
4import chisel3._
5import chisel3.util.BitPat.bitPatToUInt
6import chisel3.util._
7import xiangshan._
8import xiangshan.backend.datapath.DataConfig._
9import xiangshan.backend.datapath.WbConfig.WbConfig
10import xiangshan.backend.decode.{ImmUnion, XDecode}
11import xiangshan.backend.exu.ExeUnitParams
12import xiangshan.backend.fu.FuType
13import xiangshan.backend.fu.vector.Bundles.VType
14import xiangshan.backend.issue.{IssueBlockParams, IssueQueueJumpBundle, SchedulerType, StatusArrayDeqRespBundle}
15import xiangshan.backend.regfile.{RfReadPortWithConfig, RfWritePortWithConfig}
16import xiangshan.backend.rob.RobPtr
17import xiangshan.frontend._
18import xiangshan.mem.{LqPtr, SqPtr}
19
20object Bundles {
21
22  // frontend -> backend
23  class StaticInst(implicit p: Parameters) extends XSBundle {
24    val instr           = UInt(32.W)
25    val pc              = UInt(VAddrBits.W)
26    val foldpc          = UInt(MemPredPCWidth.W)
27    val exceptionVec    = ExceptionVec()
28    val trigger         = new TriggerCf
29    val preDecodeInfo   = new PreDecodeInfo
30    val pred_taken      = Bool()
31    val crossPageIPFFix = Bool()
32    val ftqPtr          = new FtqPtr
33    val ftqOffset       = UInt(log2Up(PredictWidth).W)
34
35    def connectCtrlFlow(source: CtrlFlow): Unit = {
36      this.instr            := source.instr
37      this.pc               := source.pc
38      this.foldpc           := source.foldpc
39      this.exceptionVec     := source.exceptionVec
40      this.trigger          := source.trigger
41      this.preDecodeInfo    := source.pd
42      this.pred_taken       := source.pred_taken
43      this.crossPageIPFFix  := source.crossPageIPFFix
44      this.ftqPtr           := source.ftqPtr
45      this.ftqOffset        := source.ftqOffset
46    }
47  }
48
49  // StaticInst --[Decode]--> DecodedInst
50  class DecodedInst(implicit p: Parameters) extends XSBundle {
51    def numPSrc = 5
52    def numLSrc = 3
53    // passed from StaticInst
54    val instr           = UInt(32.W)
55    val pc              = UInt(VAddrBits.W)
56    val foldpc          = UInt(MemPredPCWidth.W)
57    val exceptionVec    = ExceptionVec()
58    val trigger         = new TriggerCf
59    val preDecodeInfo   = new PreDecodeInfo
60    val pred_taken      = Bool()
61    val crossPageIPFFix = Bool()
62    val ftqPtr          = new FtqPtr
63    val ftqOffset       = UInt(log2Up(PredictWidth).W)
64    // decoded
65    val srcType       = Vec(numLSrc, SrcType())
66    val lsrc          = Vec(numLSrc, UInt(6.W))
67    val ldest         = UInt(6.W)
68    val fuType        = FuType()
69    val fuOpType      = FuOpType()
70    val rfWen         = Bool()
71    val fpWen         = Bool()
72    val vecWen        = Bool()
73    val isXSTrap      = Bool()
74    val waitForward   = Bool() // no speculate execution
75    val blockBackward = Bool()
76    val flushPipe     = Bool() // This inst will flush all the pipe when commit, like exception but can commit
77    val selImm        = SelImm()
78    val imm           = UInt(ImmUnion.maxLen.W)
79    val fpu           = new FPUCtrlSignals
80    val vpu           = new VPUCtrlSignals
81    val isMove        = Bool()
82    val uopIdx        = UInt(5.W)
83    val vtype         = new VType
84    val uopDivType    = UopDivType()
85    val isVset        = Bool()
86    val firstUop      = Bool()
87    val lastUop       = Bool()
88    val commitType    = CommitType() // Todo: remove it
89
90    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
91      isXSTrap, waitForward, blockBackward, flushPipe, uopDivType, selImm)
92
93    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
94      val decoder: Seq[UInt] = ListLookup(
95        inst, XDecode.decodeDefault.map(bitPatToUInt),
96        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
97      )
98      allSignals zip decoder foreach { case (s, d) => s := d }
99      this
100    }
101
102    def isSoftPrefetch: Bool = {
103      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
104    }
105
106    def connectStaticInst(source: StaticInst): Unit = {
107      for ((name, data) <- this.elements) {
108        if (source.elements.contains(name)) {
109          data := source.elements(name)
110        }
111      }
112    }
113  }
114
115  // DecodedInst --[Rename]--> DynInst
116  class DynInst(implicit p: Parameters) extends XSBundle {
117    def numLSrc         = 3
118    // vector inst need vs1, vs2, vd, v0, vl&vtype, 5 psrcs
119    def numPSrc         = 5
120    // passed from StaticInst
121    val instr           = UInt(32.W)
122    val pc              = UInt(VAddrBits.W)
123    val foldpc          = UInt(MemPredPCWidth.W)
124    val exceptionVec    = ExceptionVec()
125    val trigger         = new TriggerCf
126    val preDecodeInfo   = new PreDecodeInfo
127    val pred_taken      = Bool()
128    val crossPageIPFFix = Bool()
129    val ftqPtr          = new FtqPtr
130    val ftqOffset       = UInt(log2Up(PredictWidth).W)
131    // passed from DecodedInst
132    val srcType         = Vec(numLSrc, SrcType())
133    val lsrc            = Vec(numLSrc, UInt(6.W))
134    val ldest           = UInt(6.W)
135    val fuType          = FuType()
136    val fuOpType        = FuOpType()
137    val rfWen           = Bool()
138    val fpWen           = Bool()
139    val vecWen          = Bool()
140    val isXSTrap        = Bool()
141    val waitForward     = Bool() // no speculate execution
142    val blockBackward   = Bool()
143    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
144    val selImm          = SelImm()
145    val imm             = UInt(XLEN.W) // Todo: check if it need minimized
146    val fpu             = new FPUCtrlSignals
147    val vpu             = new VPUCtrlSignals
148    val isMove          = Bool()
149    val uopIdx          = UInt(5.W)
150    val vtype           = new VType
151    val isVset          = Bool()
152    val firstUop = Bool()
153    val lastUop = Bool()
154    val commitType      = CommitType()
155    // rename
156    val srcState        = Vec(numPSrc, SrcState())
157    val psrc            = Vec(numPSrc, UInt(PhyRegIdxWidth.W))
158    val pdest           = UInt(PhyRegIdxWidth.W)
159    val oldPdest        = UInt(PhyRegIdxWidth.W)
160    val robIdx          = new RobPtr
161
162    val eliminatedMove  = Bool()
163    val debugInfo       = new PerfDebugInfo
164    val storeSetHit     = Bool() // inst has been allocated an store set
165    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
166    // Load wait is needed
167    // load inst will not be executed until former store (predicted by mdp) addr calcuated
168    val loadWaitBit     = Bool()
169    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
170    // load inst will not be executed until ALL former store addr calcuated
171    val loadWaitStrict  = Bool()
172    val ssid            = UInt(SSIDWidth.W)
173    // Todo
174    val lqIdx = new LqPtr
175    val sqIdx = new SqPtr
176    // debug module
177    val singleStep      = Bool()
178    // schedule
179    val replayInst      = Bool()
180
181    def isLUI: Bool = this.fuType === FuType.alu.U && this.selImm === SelImm.IMM_U
182    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
183
184    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
185    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
186    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
187
188    def srcIsReady: Vec[Bool] = {
189      VecInit(this.srcType.zip(this.srcState).map {
190        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
191      })
192    }
193
194    def clearExceptions(
195      exceptionBits: Seq[Int] = Seq(),
196      flushPipe    : Boolean = false,
197      replayInst   : Boolean = false
198    ): DynInst = {
199      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
200      if (!flushPipe) { this.flushPipe := false.B }
201      if (!replayInst) { this.replayInst := false.B }
202      this
203    }
204
205    def asWakeUpBundle: IssueQueueWakeUpBundle = {
206      val wakeup = Output(new IssueQueueWakeUpBundle(pdest.getWidth))
207      wakeup.rfWen := this.rfWen
208      wakeup.fpWen := this.fpWen
209      wakeup.vecWen := this.vecWen
210      wakeup.pdest := this.pdest
211      wakeup
212    }
213  }
214
215  trait BundleSource {
216    var source = "not exist"
217  }
218
219  class IssueQueueWakeUpBundle(PregIdxWidth: Int) extends Bundle with BundleSource {
220    val rfWen = Bool()
221    val fpWen = Bool()
222    val vecWen = Bool()
223    val pdest = UInt(PregIdxWidth.W)
224
225    /**
226      * @param successor Seq[(psrc, srcType)]
227      * @return Seq[if wakeup psrc]
228      */
229    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool]= {
230      successor.map { case (thatPsrc, srcType) =>
231        val pdestMatch = pdest === thatPsrc
232        pdestMatch && (
233          SrcType.isFp(srcType) && this.fpWen ||
234          SrcType.isXp(srcType) && this.rfWen ||
235          SrcType.isVp(srcType) && this.vecWen
236        ) && valid
237      }
238    }
239  }
240
241  object VsewBundle {
242    def apply()   = UInt(2.W)   // 8/16/32/64 --> 0/1/2/3
243  }
244
245  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
246    val vlmul     = SInt(3.W) // 1/8~8      --> -3~3
247    val vsew      = VsewBundle()
248    val vta       = Bool()    // 1: agnostic, 0: undisturbed
249    val vma       = Bool()    // 1: agnostic, 0: undisturbed
250    val vm        = Bool()    // 0: need v0.t
251    val vill      = Bool()
252    // vector load/store
253    val nf        = UInt(3.W)
254    val lsumop    = UInt(5.W) // lumop or sumop
255    // used for vector index load/store and vrgatherei16.vv
256    val idxEmul   = UInt(3.W)
257  }
258
259  // DynInst --[IssueQueue]--> DataPath
260  class IssueQueueIssueBundle(
261    iqParams: IssueBlockParams,
262    exuParams: ExeUnitParams,
263    addrWidth: Int,
264    vaddrBits: Int
265  )(implicit
266    p: Parameters
267  ) extends Bundle {
268    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
269
270    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
271      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
272        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, addrWidth)).toSeq)
273      )
274    ))
275    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
276    val immType = SelImm()                         // used to select imm extractor
277    val common = new ExuInput(exuParams)
278    val jmp = if (exuParams.needPc) Some(Flipped(new IssueQueueJumpBundle)) else None
279    val addrOH = UInt(iqParams.numEntries.W)
280
281    def getSource: SchedulerType = exuParams.getWBSource
282    def getIntRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readInt)
283    def getFpRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(x => x.readFp || x.readVec)
284  }
285
286  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
287    val og0resp = Valid(new StatusArrayDeqRespBundle)
288    val og1resp = Valid(new StatusArrayDeqRespBundle)
289  }
290
291  // DataPath --[ExuInput]--> Exu
292  class ExuInput(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
293    val fuType        = FuType()
294    val fuOpType      = FuOpType()
295    val src           = Vec(params.numRegSrc, UInt(params.dataBitsMax.W))
296    val imm           = UInt(XLEN.W)
297    val robIdx        = new RobPtr
298    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
299    val isFirstIssue  = Bool()                      // Only used by store yet
300    val pdest         = UInt(params.wbPregIdxWidth.W)
301    val rfWen         = if (params.writeIntRf)    Some(Bool())                        else None
302    val fpWen         = if (params.writeFpRf)     Some(Bool())                        else None
303    val vecWen        = if (params.writeVecRf)    Some(Bool())                        else None
304    val fpu           = if (params.needFPUCtrl)   Some(new FPUCtrlSignals)            else None
305    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
306    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
307    val jalrTarget    = if (params.hasJmpFu)      Some(UInt(VAddrData().dataWidth.W)) else None
308    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
309    val ftqIdx        = if (params.needPc || params.replayInst)
310                                                  Some(new FtqPtr)                    else None
311    val ftqOffset     = if (params.needPc || params.replayInst)
312                                                  Some(UInt(log2Up(PredictWidth).W))  else None
313    val predictInfo   = if (params.hasPredecode)  Some(new Bundle {
314      val target = UInt(VAddrData().dataWidth.W)
315      val taken = Bool()
316    }) else None
317    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
318    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
319
320    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
321      // src is assigned to rfReadData
322      this.fuType       := source.common.fuType
323      this.fuOpType     := source.common.fuOpType
324      this.imm          := source.common.imm
325      this.robIdx       := source.common.robIdx
326      this.pdest        := source.common.pdest
327      this.isFirstIssue := source.common.isFirstIssue // Only used by mem debug log
328      this.iqIdx        := source.common.iqIdx        // Only used by mem feedback
329      this.rfWen        .foreach(_ := source.common.rfWen.get)
330      this.fpWen        .foreach(_ := source.common.fpWen.get)
331      this.vecWen       .foreach(_ := source.common.vecWen.get)
332      this.fpu          .foreach(_ := source.common.fpu.get)
333      this.flushPipe    .foreach(_ := source.common.flushPipe.get)
334      this.pc           .foreach(_ := source.jmp.get.pc)
335      this.jalrTarget   .foreach(_ := source.jmp.get.target)
336      this.preDecode    .foreach(_ := source.common.preDecode.get)
337      this.ftqIdx       .foreach(_ := source.common.ftqIdx.get)
338      this.ftqOffset    .foreach(_ := source.common.ftqOffset.get)
339      this.predictInfo  .foreach(_ := source.common.predictInfo.get)
340      this.lqIdx        .foreach(_ := source.common.lqIdx.get)
341      this.sqIdx        .foreach(_ := source.common.sqIdx.get)
342    }
343  }
344
345  // ExuInput --[FuncUnit]--> ExuOutput
346  class ExuOutput(
347    val params: ExeUnitParams,
348  )(implicit
349    val p: Parameters
350  ) extends Bundle with BundleSource with HasXSParameter {
351    val data         = UInt(params.dataBitsMax.W)
352    val pdest        = UInt(params.wbPregIdxWidth.W)
353    val robIdx       = new RobPtr
354    val intWen       = if (params.writeIntRf)   Some(Bool())                  else None
355    val fpWen        = if (params.writeFpRf)    Some(Bool())                  else None
356    val vecWen       = if (params.writeVecRf)   Some(Bool())                  else None
357    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
358    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
359    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
360    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
361    val replay       = if (params.replayInst)   Some(Bool())                  else None
362    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
363    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
364                                                Some(new SqPtr())             else None
365    val ftqIdx       = if (params.needPc || params.replayInst)
366                                                Some(new FtqPtr)                    else None
367    val ftqOffset    = if (params.needPc || params.replayInst)
368                                                Some(UInt(log2Up(PredictWidth).W))  else None
369    // uop info
370    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
371    val debug = new DebugBundle
372    val debugInfo = new PerfDebugInfo
373  }
374
375  // ExuOutput + DynInst --> WriteBackBundle
376  class WriteBackBundle(val params: WbConfig)(implicit p: Parameters) extends Bundle with BundleSource {
377    val rfWen = Bool()
378    val fpWen = Bool()
379    val vecWen = Bool()
380    val pdest = UInt(params.pregIdxWidth.W)
381    val data = UInt(params.dataWidth.W)
382    val robIdx = new RobPtr()(p)
383    val flushPipe = Bool()
384    val replayInst = Bool()
385    val redirect = ValidIO(new Redirect)
386    val fflags = UInt(5.W)
387    val exceptionVec = ExceptionVec()
388    val debug = new DebugBundle
389    val debugInfo = new PerfDebugInfo
390
391    def fromExuOutput(source: ExuOutput) = {
392      this.rfWen  := source.intWen.getOrElse(false.B)
393      this.fpWen  := source.fpWen.getOrElse(false.B)
394      this.vecWen := source.vecWen.getOrElse(false.B)
395      this.pdest  := source.pdest
396      this.data   := source.data
397      this.robIdx := source.robIdx
398      this.flushPipe := source.flushPipe.getOrElse(false.B)
399      this.replayInst := source.replay.getOrElse(false.B)
400      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
401      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
402      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
403      this.debug := source.debug
404      this.debugInfo := source.debugInfo
405    }
406
407    def asWakeUpBundle: IssueQueueWakeUpBundle = {
408      val wakeup = Output(new IssueQueueWakeUpBundle(params.pregIdxWidth))
409      wakeup.rfWen := this.rfWen
410      wakeup.fpWen := this.fpWen
411      wakeup.vecWen := this.vecWen
412      wakeup.pdest := this.pdest
413      wakeup.source = this.source
414      wakeup
415    }
416
417    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
418      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, this.params.pregIdxWidth)))
419      rfWrite.wen := this.rfWen && fire
420      rfWrite.addr := this.pdest
421      rfWrite.data := this.data
422      rfWrite.intWen := this.rfWen
423      rfWrite.fpWen := false.B
424      rfWrite.vecWen := false.B
425      rfWrite
426    }
427
428    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
429      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, this.params.pregIdxWidth)))
430      rfWrite.wen := (this.fpWen || this.vecWen) && fire
431      rfWrite.addr := this.pdest
432      rfWrite.data := this.data
433      rfWrite.intWen := false.B
434      rfWrite.fpWen := this.fpWen
435      rfWrite.vecWen := this.vecWen
436      rfWrite
437    }
438  }
439
440  class ExceptionInfo extends Bundle {
441    val pc = UInt(VAddrData().dataWidth.W)
442    val instr = UInt(32.W)
443    val commitType = CommitType()
444    val exceptionVec = ExceptionVec()
445    val singleStep = Bool()
446    val crossPageIPFFix = Bool()
447    val isInterrupt = Bool()
448  }
449
450  class MemExuInput(implicit p: Parameters) extends XSBundle {
451    val uop = new DynInst
452    val src = Vec(3, UInt(XLEN.W))
453    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
454    val isFirstIssue = Bool()
455  }
456
457  class MemExuOutput(implicit p: Parameters) extends XSBundle {
458    val uop = new DynInst
459    val data = UInt(XLEN.W)
460    val debug = new DebugBundle
461  }
462
463  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
464    val uop = new DynInst
465    val flag = UInt(1.W)
466  }
467}
468