xref: /XiangShan/src/main/scala/xiangshan/Bundle.scala (revision 2866a42b48570efd2f7ec32b954dfee6561b000f)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan
18
19import chisel3._
20import chisel3.util._
21import xiangshan.backend.roq.RoqPtr
22import xiangshan.backend.decode.{ImmUnion, XDecode}
23import xiangshan.mem.{LqPtr, SqPtr}
24import xiangshan.frontend.PreDecodeInfoForDebug
25import xiangshan.frontend.PreDecodeInfo
26import xiangshan.frontend.HasBPUParameter
27import xiangshan.frontend.PreDecodeInfo
28import xiangshan.frontend.HasTageParameter
29import xiangshan.frontend.HasSCParameter
30import xiangshan.frontend.HasIFUConst
31import xiangshan.frontend.GlobalHistory
32import xiangshan.frontend.RASEntry
33import xiangshan.frontend.BPUCtrl
34import utils._
35
36import scala.math.max
37import Chisel.experimental.chiselName
38import chipsalliance.rocketchip.config.Parameters
39import xiangshan.backend.ftq.FtqPtr
40
41// Fetch FetchWidth x 32-bit insts from Icache
42class FetchPacket(implicit p: Parameters) extends XSBundle {
43  val instrs = Vec(PredictWidth, UInt(32.W))
44  val mask = UInt(PredictWidth.W)
45  val pdmask = UInt(PredictWidth.W)
46  // val pc = UInt(VAddrBits.W)
47  val pc = Vec(PredictWidth, UInt(VAddrBits.W))
48  val foldpc = Vec(PredictWidth, UInt(MemPredPCWidth.W))
49  val pd = Vec(PredictWidth, new PreDecodeInfo)
50  val ipf = Bool()
51  val acf = Bool()
52  val crossPageIPFFix = Bool()
53  val pred_taken = UInt(PredictWidth.W)
54  val ftqPtr = new FtqPtr
55}
56
57class ValidUndirectioned[T <: Data](gen: T) extends Bundle {
58  val valid = Bool()
59  val bits = gen.cloneType.asInstanceOf[T]
60
61  override def cloneType = new ValidUndirectioned(gen).asInstanceOf[this.type]
62}
63
64object ValidUndirectioned {
65  def apply[T <: Data](gen: T) = {
66    new ValidUndirectioned[T](gen)
67  }
68}
69
70object RSFeedbackType {
71  val tlbMiss = 0.U(2.W)
72  val mshrFull = 1.U(2.W)
73  val dataInvalid = 2.U(2.W)
74
75  def apply() = UInt(2.W)
76}
77
78class SCMeta(val useSC: Boolean)(implicit p: Parameters) extends XSBundle with HasSCParameter {
79  val tageTaken = if (useSC) Bool() else UInt(0.W)
80  val scUsed = if (useSC) Bool() else UInt(0.W)
81  val scPred = if (useSC) Bool() else UInt(0.W)
82  // Suppose ctrbits of all tables are identical
83  val ctrs = if (useSC) Vec(SCNTables, SInt(SCCtrBits.W)) else Vec(SCNTables, SInt(0.W))
84}
85
86class TageMeta(implicit p: Parameters) extends XSBundle with HasTageParameter {
87  val provider = ValidUndirectioned(UInt(log2Ceil(TageNTables).W))
88  val altDiffers = Bool()
89  val providerU = UInt(2.W)
90  val providerCtr = UInt(3.W)
91  val allocate = ValidUndirectioned(UInt(log2Ceil(TageNTables).W))
92  val taken = Bool()
93  val scMeta = new SCMeta(EnableSC)
94}
95
96@chiselName
97class BranchPrediction(implicit p: Parameters) extends XSBundle with HasIFUConst {
98  // val redirect = Bool()
99  val takens = UInt(PredictWidth.W)
100  // val jmpIdx = UInt(log2Up(PredictWidth).W)
101  val brMask = UInt(PredictWidth.W)
102  val jalMask = UInt(PredictWidth.W)
103  val targets = Vec(PredictWidth, UInt(VAddrBits.W))
104
105  // half RVI could only start at the end of a packet
106  val hasHalfRVI = Bool()
107
108  def brNotTakens = (~takens & brMask)
109
110  def sawNotTakenBr = VecInit((0 until PredictWidth).map(i =>
111    (if (i == 0) false.B else ParallelORR(brNotTakens(i - 1, 0)))))
112
113  // if not taken before the half RVI inst
114  def saveHalfRVI = hasHalfRVI && !(ParallelORR(takens(PredictWidth - 2, 0)))
115
116  // could get PredictWidth-1 when only the first bank is valid
117  def jmpIdx = ParallelPriorityEncoder(takens)
118
119  // only used when taken
120  def target = {
121    val generator = new PriorityMuxGenerator[UInt]
122    generator.register(takens.asBools, targets, List.fill(PredictWidth)(None))
123    generator()
124  }
125
126  def taken = ParallelORR(takens)
127
128  def takenOnBr = taken && ParallelPriorityMux(takens, brMask.asBools)
129
130  def hasNotTakenBrs = Mux(taken, ParallelPriorityMux(takens, sawNotTakenBr), ParallelORR(brNotTakens))
131}
132
133class PredictorAnswer(implicit p: Parameters) extends XSBundle {
134  val hit    = if (!env.FPGAPlatform) Bool() else UInt(0.W)
135  val taken  = if (!env.FPGAPlatform) Bool() else UInt(0.W)
136  val target = if (!env.FPGAPlatform) UInt(VAddrBits.W) else UInt(0.W)
137}
138
139class BpuMeta(implicit p: Parameters) extends XSBundle with HasBPUParameter {
140  val btbWriteWay = UInt(log2Up(BtbWays).W)
141  val btbHit = Bool()
142  val bimCtr = UInt(2.W)
143  val tageMeta = new TageMeta
144  // for global history
145
146  val debug_ubtb_cycle = if (EnableBPUTimeRecord) UInt(64.W) else UInt(0.W)
147  val debug_btb_cycle = if (EnableBPUTimeRecord) UInt(64.W) else UInt(0.W)
148  val debug_tage_cycle = if (EnableBPUTimeRecord) UInt(64.W) else UInt(0.W)
149
150  val predictor = if (BPUDebug) UInt(log2Up(4).W) else UInt(0.W) // Mark which component this prediction comes from {ubtb, btb, tage, loopPredictor}
151
152  val ubtbHit = if (BPUDebug) UInt(1.W) else UInt(0.W)
153
154  val ubtbAns = new PredictorAnswer
155  val btbAns = new PredictorAnswer
156  val tageAns = new PredictorAnswer
157  val rasAns = new PredictorAnswer
158  val loopAns = new PredictorAnswer
159
160  // def apply(histPtr: UInt, tageMeta: TageMeta, rasSp: UInt, rasTopCtr: UInt) = {
161  //   this.histPtr := histPtr
162  //   this.tageMeta := tageMeta
163  //   this.rasSp := rasSp
164  //   this.rasTopCtr := rasTopCtr
165  //   this.asUInt
166  // }
167  def size = 0.U.asTypeOf(this).getWidth
168
169  def fromUInt(x: UInt) = x.asTypeOf(this)
170}
171
172class Predecode(implicit p: Parameters) extends XSBundle with HasIFUConst {
173  val hasLastHalfRVI = Bool()
174  val mask = UInt(PredictWidth.W)
175  val lastHalf = Bool()
176  val pd = Vec(PredictWidth, (new PreDecodeInfo))
177}
178
179class CfiUpdateInfo(implicit p: Parameters) extends XSBundle with HasBPUParameter {
180  // from backend
181  val pc = UInt(VAddrBits.W)
182  // frontend -> backend -> frontend
183  val pd = new PreDecodeInfo
184  val rasSp = UInt(log2Up(RasSize).W)
185  val rasEntry = new RASEntry
186  val hist = new GlobalHistory
187  val predHist = new GlobalHistory
188  val specCnt = Vec(PredictWidth, UInt(10.W))
189  // need pipeline update
190  val sawNotTakenBranch = Bool()
191  val predTaken = Bool()
192  val target = UInt(VAddrBits.W)
193  val taken = Bool()
194  val isMisPred = Bool()
195}
196
197// Dequeue DecodeWidth insts from Ibuffer
198class CtrlFlow(implicit p: Parameters) extends XSBundle {
199  val instr = UInt(32.W)
200  val pc = UInt(VAddrBits.W)
201  val foldpc = UInt(MemPredPCWidth.W)
202  val exceptionVec = ExceptionVec()
203  val intrVec = Vec(12, Bool())
204  val pd = new PreDecodeInfo
205  val pred_taken = Bool()
206  val crossPageIPFFix = Bool()
207  val storeSetHit = Bool() // inst has been allocated an store set
208  val loadWaitBit = Bool() // load inst should not be executed until all former store addr calcuated
209  val ssid = UInt(SSIDWidth.W)
210  val ftqPtr = new FtqPtr
211  val ftqOffset = UInt(log2Up(PredictWidth).W)
212  // This inst will flush all the pipe when it is the oldest inst in ROB,
213  // then replay from this inst itself
214  val replayInst = Bool()
215}
216
217class FtqEntry(implicit p: Parameters) extends XSBundle {
218  // fetch pc, pc of each inst could be generated by concatenation
219  val ftqPC = UInt(VAddrBits.W)
220  val lastPacketPC = ValidUndirectioned(UInt(VAddrBits.W))
221  // prediction metas
222  val hist = new GlobalHistory
223  val predHist = new GlobalHistory
224  val rasSp = UInt(log2Ceil(RasSize).W)
225  val rasTop = new RASEntry()
226  val specCnt = Vec(PredictWidth, UInt(10.W))
227  val metas = Vec(PredictWidth, new BpuMeta)
228
229  val cfiIsCall, cfiIsRet, cfiIsJalr, cfiIsRVC = Bool()
230  val rvc_mask = Vec(PredictWidth, Bool())
231  val br_mask = Vec(PredictWidth, Bool())
232  val cfiIndex = ValidUndirectioned(UInt(log2Up(PredictWidth).W))
233  val valids = Vec(PredictWidth, Bool())
234
235  // backend update
236  val mispred = Vec(PredictWidth, Bool())
237  val target = UInt(VAddrBits.W)
238
239  // For perf counters
240  val pd = Vec(PredictWidth, new PreDecodeInfoForDebug(!env.FPGAPlatform))
241
242  def takens = VecInit((0 until PredictWidth).map(i => cfiIndex.valid && cfiIndex.bits === i.U))
243  def hasLastPrev = lastPacketPC.valid
244
245  override def toPrintable: Printable = {
246    p"ftqPC: ${Hexadecimal(ftqPC)} lastPacketPC: ${Hexadecimal(lastPacketPC.bits)} hasLastPrev:$hasLastPrev " +
247      p"rasSp:$rasSp specCnt:$specCnt brmask:${Binary(Cat(br_mask))} rvcmask:${Binary(Cat(rvc_mask))} " +
248      p"valids:${Binary(valids.asUInt())} cfi valid: ${cfiIndex.valid} " +
249      p"cfi index: ${cfiIndex.bits} isCall:$cfiIsCall isRet:$cfiIsRet isJalr:$cfiIsJalr, isRvc:$cfiIsRVC " +
250      p"mispred:${Binary(Cat(mispred))} target:${Hexadecimal(target)}\n"
251  }
252
253}
254
255
256class FPUCtrlSignals(implicit p: Parameters) extends XSBundle {
257  val isAddSub = Bool() // swap23
258  val typeTagIn = UInt(1.W)
259  val typeTagOut = UInt(1.W)
260  val fromInt = Bool()
261  val wflags = Bool()
262  val fpWen = Bool()
263  val fmaCmd = UInt(2.W)
264  val div = Bool()
265  val sqrt = Bool()
266  val fcvt = Bool()
267  val typ = UInt(2.W)
268  val fmt = UInt(2.W)
269  val ren3 = Bool() //TODO: remove SrcType.fp
270  val rm = UInt(3.W)
271}
272
273// Decode DecodeWidth insts at Decode Stage
274class CtrlSignals(implicit p: Parameters) extends XSBundle {
275  val srcType = Vec(3, SrcType())
276  val lsrc = Vec(3, UInt(5.W))
277  val ldest = UInt(5.W)
278  val fuType = FuType()
279  val fuOpType = FuOpType()
280  val rfWen = Bool()
281  val fpWen = Bool()
282  val isXSTrap = Bool()
283  val noSpecExec = Bool() // wait forward
284  val blockBackward = Bool() // block backward
285  val flushPipe = Bool() // This inst will flush all the pipe when commit, like exception but can commit
286  val isRVF = Bool()
287  val selImm = SelImm()
288  val imm = UInt(ImmUnion.maxLen.W)
289  val commitType = CommitType()
290  val fpu = new FPUCtrlSignals
291  val isMove = Bool()
292  val singleStep = Bool()
293
294  def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]) = {
295    val decoder = freechips.rocketchip.rocket.DecodeLogic(inst, XDecode.decodeDefault, table)
296    val signals =
297      Seq(srcType(0), srcType(1), srcType(2), fuType, fuOpType, rfWen, fpWen,
298        isXSTrap, noSpecExec, blockBackward, flushPipe, isRVF, selImm)
299    signals zip decoder map { case (s, d) => s := d }
300    commitType := DontCare
301    this
302  }
303}
304
305class CfCtrl(implicit p: Parameters) extends XSBundle {
306  val cf = new CtrlFlow
307  val ctrl = new CtrlSignals
308}
309
310class PerfDebugInfo(implicit p: Parameters) extends XSBundle {
311  val eliminatedMove = Bool()
312  // val fetchTime = UInt(64.W)
313  val renameTime = UInt(64.W)
314  val dispatchTime = UInt(64.W)
315  val issueTime = UInt(64.W)
316  val writebackTime = UInt(64.W)
317  // val commitTime = UInt(64.W)
318}
319
320// Separate LSQ
321class LSIdx(implicit p: Parameters) extends XSBundle {
322  val lqIdx = new LqPtr
323  val sqIdx = new SqPtr
324}
325
326// CfCtrl -> MicroOp at Rename Stage
327class MicroOp(implicit p: Parameters) extends CfCtrl {
328  val srcState = Vec(3, SrcState())
329  val psrc = Vec(3, UInt(PhyRegIdxWidth.W))
330  val pdest = UInt(PhyRegIdxWidth.W)
331  val old_pdest = UInt(PhyRegIdxWidth.W)
332  val roqIdx = new RoqPtr
333  val lqIdx = new LqPtr
334  val sqIdx = new SqPtr
335  val diffTestDebugLrScValid = Bool()
336  val eliminatedMove = Bool()
337  val debugInfo = new PerfDebugInfo
338  def needRfRPort(index: Int, rfType: Int, ignoreState: Boolean = true) : Bool = {
339    (index, rfType) match {
340      case (0, 0) => ctrl.srcType(0) === SrcType.reg && ctrl.lsrc(0) =/= 0.U && (srcState(0) === SrcState.rdy || ignoreState.B)
341      case (1, 0) => ctrl.srcType(1) === SrcType.reg && ctrl.lsrc(1) =/= 0.U && (srcState(1) === SrcState.rdy || ignoreState.B)
342      case (0, 1) => ctrl.srcType(0) === SrcType.fp && (srcState(0) === SrcState.rdy || ignoreState.B)
343      case (1, 1) => ctrl.srcType(1) === SrcType.fp && (srcState(1) === SrcState.rdy || ignoreState.B)
344      case (2, 1) => ctrl.srcType(2) === SrcType.fp && (srcState(2) === SrcState.rdy || ignoreState.B)
345      case _ => false.B
346    }
347  }
348  def srcIsReady: Vec[Bool] = {
349    VecInit(ctrl.srcType.zip(srcState).map{ case (t, s) => SrcType.isPcImm(t) || s === SrcState.rdy })
350  }
351  def doWriteIntRf: Bool = ctrl.rfWen && ctrl.ldest =/= 0.U
352  def doWriteFpRf: Bool = ctrl.fpWen
353}
354
355class MicroOpRbExt(implicit p: Parameters) extends XSBundle {
356  val uop = new MicroOp
357  val flag = UInt(1.W)
358}
359
360class Redirect(implicit p: Parameters) extends XSBundle {
361  val roqIdx = new RoqPtr
362  val ftqIdx = new FtqPtr
363  val ftqOffset = UInt(log2Up(PredictWidth).W)
364  val level = RedirectLevel()
365  val interrupt = Bool()
366  val cfiUpdate = new CfiUpdateInfo
367
368  val stFtqIdx = new FtqPtr // for load violation predict
369  val stFtqOffset = UInt(log2Up(PredictWidth).W)
370
371  // def isUnconditional() = RedirectLevel.isUnconditional(level)
372  def flushItself() = RedirectLevel.flushItself(level)
373  // def isException() = RedirectLevel.isException(level)
374}
375
376class Dp1ToDp2IO(implicit p: Parameters) extends XSBundle {
377  val intDqToDp2 = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
378  val fpDqToDp2 = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new MicroOp))
379  val lsDqToDp2 = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new MicroOp))
380}
381
382class ReplayPregReq(implicit p: Parameters) extends XSBundle {
383  // NOTE: set isInt and isFp both to 'false' when invalid
384  val isInt = Bool()
385  val isFp = Bool()
386  val preg = UInt(PhyRegIdxWidth.W)
387}
388
389class DebugBundle(implicit p: Parameters) extends XSBundle {
390  val isMMIO = Bool()
391  val isPerfCnt = Bool()
392  val paddr = UInt(PAddrBits.W)
393}
394
395class ExuInput(implicit p: Parameters) extends XSBundle {
396  val uop = new MicroOp
397  val src = Vec(3, UInt(XLEN.W))
398}
399
400class ExuOutput(implicit p: Parameters) extends XSBundle {
401  val uop = new MicroOp
402  val data = UInt(XLEN.W)
403  val fflags = UInt(5.W)
404  val redirectValid = Bool()
405  val redirect = new Redirect
406  val debug = new DebugBundle
407}
408
409class ExternalInterruptIO(implicit p: Parameters) extends XSBundle {
410  val mtip = Input(Bool())
411  val msip = Input(Bool())
412  val meip = Input(Bool())
413  val debug = Input(Bool())
414}
415
416class CSRSpecialIO(implicit p: Parameters) extends XSBundle {
417  val exception = Flipped(ValidIO(new MicroOp))
418  val isInterrupt = Input(Bool())
419  val memExceptionVAddr = Input(UInt(VAddrBits.W))
420  val trapTarget = Output(UInt(VAddrBits.W))
421  val externalInterrupt = new ExternalInterruptIO
422  val interrupt = Output(Bool())
423}
424
425class ExceptionInfo(implicit p: Parameters) extends XSBundle {
426  val uop = new MicroOp
427  val isInterrupt = Bool()
428}
429
430class RoqCommitInfo(implicit p: Parameters) extends XSBundle {
431  val ldest = UInt(5.W)
432  val rfWen = Bool()
433  val fpWen = Bool()
434  val wflags = Bool()
435  val commitType = CommitType()
436  val eliminatedMove = Bool()
437  val pdest = UInt(PhyRegIdxWidth.W)
438  val old_pdest = UInt(PhyRegIdxWidth.W)
439  val ftqIdx = new FtqPtr
440  val ftqOffset = UInt(log2Up(PredictWidth).W)
441
442  // these should be optimized for synthesis verilog
443  val pc = UInt(VAddrBits.W)
444}
445
446class RoqCommitIO(implicit p: Parameters) extends XSBundle {
447  val isWalk = Output(Bool())
448  val valid = Vec(CommitWidth, Output(Bool()))
449  val info = Vec(CommitWidth, Output(new RoqCommitInfo))
450
451  def hasWalkInstr = isWalk && valid.asUInt.orR
452
453  def hasCommitInstr = !isWalk && valid.asUInt.orR
454}
455
456class RSFeedback(implicit p: Parameters) extends XSBundle {
457  val rsIdx = UInt(log2Up(IssQueSize).W)
458  val hit = Bool()
459  val flushState = Bool()
460  val sourceType = RSFeedbackType()
461}
462
463class FrontendToBackendIO(implicit p: Parameters) extends XSBundle {
464  // to backend end
465  val cfVec = Vec(DecodeWidth, DecoupledIO(new CtrlFlow))
466  val fetchInfo = DecoupledIO(new FtqEntry)
467  // from backend
468  val redirect_cfiUpdate = Flipped(ValidIO(new Redirect))
469  val commit_cfiUpdate = Flipped(ValidIO(new FtqEntry))
470  val ftqEnqPtr = Input(new FtqPtr)
471  val ftqLeftOne = Input(Bool())
472}
473
474class TlbCsrBundle(implicit p: Parameters) extends XSBundle {
475  val satp = new Bundle {
476    val mode = UInt(4.W) // TODO: may change number to parameter
477    val asid = UInt(16.W)
478    val ppn = UInt(44.W) // just use PAddrBits - 3 - vpnnLen
479  }
480  val priv = new Bundle {
481    val mxr = Bool()
482    val sum = Bool()
483    val imode = UInt(2.W)
484    val dmode = UInt(2.W)
485  }
486
487  override def toPrintable: Printable = {
488    p"Satp mode:0x${Hexadecimal(satp.mode)} asid:0x${Hexadecimal(satp.asid)} ppn:0x${Hexadecimal(satp.ppn)} " +
489      p"Priv mxr:${priv.mxr} sum:${priv.sum} imode:${priv.imode} dmode:${priv.dmode}"
490  }
491}
492
493class SfenceBundle(implicit p: Parameters) extends XSBundle {
494  val valid = Bool()
495  val bits = new Bundle {
496    val rs1 = Bool()
497    val rs2 = Bool()
498    val addr = UInt(VAddrBits.W)
499  }
500
501  override def toPrintable: Printable = {
502    p"valid:0x${Hexadecimal(valid)} rs1:${bits.rs1} rs2:${bits.rs2} addr:${Hexadecimal(bits.addr)}"
503  }
504}
505
506// Bundle for load violation predictor updating
507class MemPredUpdateReq(implicit p: Parameters) extends XSBundle  {
508  val valid = Bool()
509
510  // wait table update
511  val waddr = UInt(MemPredPCWidth.W)
512  val wdata = Bool() // true.B by default
513
514  // store set update
515  // by default, ldpc/stpc should be xor folded
516  val ldpc = UInt(MemPredPCWidth.W)
517  val stpc = UInt(MemPredPCWidth.W)
518}
519
520class CustomCSRCtrlIO(implicit p: Parameters) extends XSBundle {
521  // Prefetcher
522  val l1plus_pf_enable = Output(Bool())
523  val l2_pf_enable = Output(Bool())
524  // Labeled XiangShan
525  val dsid = Output(UInt(8.W)) // TODO: DsidWidth as parameter
526  // Load violation predictor
527  val lvpred_disable = Output(Bool())
528  val no_spec_load = Output(Bool())
529  val waittable_timeout = Output(UInt(5.W))
530  // Branch predictor
531  val bp_ctrl = Output(new BPUCtrl)
532  // Memory Block
533  val sbuffer_threshold = Output(UInt(4.W))
534  // Rename
535  val move_elim_enable = Output(Bool())
536}
537