xref: /XiangShan/src/main/scala/xiangshan/Bundle.scala (revision e3f759ae573d6f4fabbfe9e4dcf7987b1d32d06d)
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  // This inst is ld, can be load to load fast forwarded
216  // TODO: this is dirty
217  val fastfwd = Bool()
218}
219
220class FtqEntry(implicit p: Parameters) extends XSBundle {
221  // fetch pc, pc of each inst could be generated by concatenation
222  val ftqPC = UInt(VAddrBits.W)
223  val lastPacketPC = ValidUndirectioned(UInt(VAddrBits.W))
224  // prediction metas
225  val hist = new GlobalHistory
226  val predHist = new GlobalHistory
227  val rasSp = UInt(log2Ceil(RasSize).W)
228  val rasTop = new RASEntry()
229  val specCnt = Vec(PredictWidth, UInt(10.W))
230  val metas = Vec(PredictWidth, new BpuMeta)
231
232  val cfiIsCall, cfiIsRet, cfiIsJalr, cfiIsRVC = Bool()
233  val rvc_mask = Vec(PredictWidth, Bool())
234  val br_mask = Vec(PredictWidth, Bool())
235  val cfiIndex = ValidUndirectioned(UInt(log2Up(PredictWidth).W))
236  val valids = Vec(PredictWidth, Bool())
237
238  // backend update
239  val mispred = Vec(PredictWidth, Bool())
240  val target = UInt(VAddrBits.W)
241
242  // For perf counters
243  val pd = Vec(PredictWidth, new PreDecodeInfoForDebug(!env.FPGAPlatform))
244
245  def takens = VecInit((0 until PredictWidth).map(i => cfiIndex.valid && cfiIndex.bits === i.U))
246  def hasLastPrev = lastPacketPC.valid
247
248  override def toPrintable: Printable = {
249    p"ftqPC: ${Hexadecimal(ftqPC)} lastPacketPC: ${Hexadecimal(lastPacketPC.bits)} hasLastPrev:$hasLastPrev " +
250      p"rasSp:$rasSp specCnt:$specCnt brmask:${Binary(Cat(br_mask))} rvcmask:${Binary(Cat(rvc_mask))} " +
251      p"valids:${Binary(valids.asUInt())} cfi valid: ${cfiIndex.valid} " +
252      p"cfi index: ${cfiIndex.bits} isCall:$cfiIsCall isRet:$cfiIsRet isJalr:$cfiIsJalr, isRvc:$cfiIsRVC " +
253      p"mispred:${Binary(Cat(mispred))} target:${Hexadecimal(target)}\n"
254  }
255
256}
257
258
259class FPUCtrlSignals(implicit p: Parameters) extends XSBundle {
260  val isAddSub = Bool() // swap23
261  val typeTagIn = UInt(2.W)
262  val typeTagOut = UInt(2.W)
263  val fromInt = Bool()
264  val wflags = Bool()
265  val fpWen = Bool()
266  val fmaCmd = UInt(2.W)
267  val div = Bool()
268  val sqrt = Bool()
269  val fcvt = Bool()
270  val typ = UInt(2.W)
271  val fmt = UInt(2.W)
272  val ren3 = Bool() //TODO: remove SrcType.fp
273  val rm = UInt(3.W)
274}
275
276// Decode DecodeWidth insts at Decode Stage
277class CtrlSignals(implicit p: Parameters) extends XSBundle {
278  val srcType = Vec(3, SrcType())
279  val lsrc = Vec(3, UInt(5.W))
280  val ldest = UInt(5.W)
281  val fuType = FuType()
282  val fuOpType = FuOpType()
283  val rfWen = Bool()
284  val fpWen = Bool()
285  val isXSTrap = Bool()
286  val noSpecExec = Bool() // wait forward
287  val blockBackward = Bool() // block backward
288  val flushPipe = Bool() // This inst will flush all the pipe when commit, like exception but can commit
289  val isRVF = Bool()
290  val selImm = SelImm()
291  val imm = UInt(ImmUnion.maxLen.W)
292  val commitType = CommitType()
293  val fpu = new FPUCtrlSignals
294  val isMove = Bool()
295
296  def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]) = {
297    val decoder = freechips.rocketchip.rocket.DecodeLogic(inst, XDecode.decodeDefault, table)
298    val signals =
299      Seq(srcType(0), srcType(1), srcType(2), fuType, fuOpType, rfWen, fpWen,
300        isXSTrap, noSpecExec, blockBackward, flushPipe, isRVF, selImm)
301    signals zip decoder map { case (s, d) => s := d }
302    commitType := DontCare
303    this
304  }
305}
306
307class CfCtrl(implicit p: Parameters) extends XSBundle {
308  val cf = new CtrlFlow
309  val ctrl = new CtrlSignals
310}
311
312class PerfDebugInfo(implicit p: Parameters) extends XSBundle {
313  val src1MoveElim = Bool()
314  val src2MoveElim = Bool()
315  // val fetchTime = UInt(64.W)
316  val renameTime = UInt(64.W)
317  val dispatchTime = UInt(64.W)
318  val issueTime = UInt(64.W)
319  val writebackTime = UInt(64.W)
320  // val commitTime = UInt(64.W)
321}
322
323// Separate LSQ
324class LSIdx(implicit p: Parameters) extends XSBundle {
325  val lqIdx = new LqPtr
326  val sqIdx = new SqPtr
327}
328
329// CfCtrl -> MicroOp at Rename Stage
330class MicroOp(implicit p: Parameters) extends CfCtrl {
331  val srcState = Vec(3, SrcState())
332  val psrc = Vec(3, UInt(PhyRegIdxWidth.W))
333  val pdest = UInt(PhyRegIdxWidth.W)
334  val old_pdest = UInt(PhyRegIdxWidth.W)
335  val roqIdx = new RoqPtr
336  val lqIdx = new LqPtr
337  val sqIdx = new SqPtr
338  val diffTestDebugLrScValid = Bool()
339  val debugInfo = new PerfDebugInfo
340  def needRfRPort(index: Int, rfType: Int, ignoreState: Boolean = true) : Bool = {
341    (index, rfType) match {
342      case (0, 0) => ctrl.srcType(0) === SrcType.reg && ctrl.lsrc(0) =/= 0.U && (srcState(0) === SrcState.rdy || ignoreState.B)
343      case (1, 0) => ctrl.srcType(1) === SrcType.reg && ctrl.lsrc(1) =/= 0.U && (srcState(1) === SrcState.rdy || ignoreState.B)
344      case (0, 1) => ctrl.srcType(0) === SrcType.fp && (srcState(0) === SrcState.rdy || ignoreState.B)
345      case (1, 1) => ctrl.srcType(1) === SrcType.fp && (srcState(1) === SrcState.rdy || ignoreState.B)
346      case (2, 1) => ctrl.srcType(2) === SrcType.fp && (srcState(2) === SrcState.rdy || ignoreState.B)
347      case _ => false.B
348    }
349  }
350  def srcIsReady: Vec[Bool] = {
351    VecInit(ctrl.srcType.zip(srcState).map{ case (t, s) => SrcType.isPcImm(t) || s === SrcState.rdy })
352  }
353  def doWriteIntRf: Bool = ctrl.rfWen && ctrl.ldest =/= 0.U
354  def doWriteFpRf: Bool = ctrl.fpWen
355}
356
357class MicroOpRbExt(implicit p: Parameters) extends XSBundle {
358  val uop = new MicroOp
359  val flag = UInt(1.W)
360}
361
362class Redirect(implicit p: Parameters) extends XSBundle {
363  val roqIdx = new RoqPtr
364  val ftqIdx = new FtqPtr
365  val ftqOffset = UInt(log2Up(PredictWidth).W)
366  val level = RedirectLevel()
367  val interrupt = Bool()
368  val cfiUpdate = new CfiUpdateInfo
369
370  val stFtqIdx = new FtqPtr // for load violation predict
371  val stFtqOffset = UInt(log2Up(PredictWidth).W)
372
373  // def isUnconditional() = RedirectLevel.isUnconditional(level)
374  def flushItself() = RedirectLevel.flushItself(level)
375  // def isException() = RedirectLevel.isException(level)
376}
377
378class Dp1ToDp2IO(implicit p: Parameters) extends XSBundle {
379  val intDqToDp2 = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
380  val fpDqToDp2 = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new MicroOp))
381  val lsDqToDp2 = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new MicroOp))
382}
383
384class ReplayPregReq(implicit p: Parameters) extends XSBundle {
385  // NOTE: set isInt and isFp both to 'false' when invalid
386  val isInt = Bool()
387  val isFp = Bool()
388  val preg = UInt(PhyRegIdxWidth.W)
389}
390
391class DebugBundle(implicit p: Parameters) extends XSBundle {
392  val isMMIO = Bool()
393  val isPerfCnt = Bool()
394  val paddr = UInt(PAddrBits.W)
395}
396
397class ExuInput(implicit p: Parameters) extends XSBundle {
398  val uop = new MicroOp
399  val src = Vec(3, UInt((XLEN + 1).W))
400}
401
402class ExuOutput(implicit p: Parameters) extends XSBundle {
403  val uop = new MicroOp
404  val data = UInt((XLEN + 1).W)
405  val fflags = UInt(5.W)
406  val redirectValid = Bool()
407  val redirect = new Redirect
408  val debug = new DebugBundle
409}
410
411class ExternalInterruptIO(implicit p: Parameters) extends XSBundle {
412  val mtip = Input(Bool())
413  val msip = Input(Bool())
414  val meip = Input(Bool())
415}
416
417class CSRSpecialIO(implicit p: Parameters) extends XSBundle {
418  val exception = Flipped(ValidIO(new MicroOp))
419  val isInterrupt = Input(Bool())
420  val memExceptionVAddr = Input(UInt(VAddrBits.W))
421  val trapTarget = Output(UInt(VAddrBits.W))
422  val externalInterrupt = new ExternalInterruptIO
423  val interrupt = Output(Bool())
424}
425
426class ExceptionInfo(implicit p: Parameters) extends XSBundle {
427  val uop = new MicroOp
428  val isInterrupt = Bool()
429}
430
431class RoqCommitInfo(implicit p: Parameters) extends XSBundle {
432  val ldest = UInt(5.W)
433  val rfWen = Bool()
434  val fpWen = Bool()
435  val wflags = Bool()
436  val commitType = CommitType()
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