xref: /XiangShan/src/main/scala/xiangshan/mem/MemCommon.scala (revision b1e920234888fd3e5463ceb2a99c9bdca087f585)
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.mem
18
19
20import org.chipsalliance.cde.config.Parameters
21import chisel3._
22import chisel3.util._
23import utility._
24import utils._
25import xiangshan._
26import xiangshan.backend.Bundles.{DynInst, MemExuInput}
27import xiangshan.backend.rob.RobPtr
28import xiangshan.cache._
29import xiangshan.backend.fu.FenceToSbuffer
30import xiangshan.cache.wpu.ReplayCarry
31import xiangshan.mem.prefetch.PrefetchReqBundle
32
33object genWmask {
34  def apply(addr: UInt, sizeEncode: UInt): UInt = {
35    (LookupTree(sizeEncode, List(
36      "b00".U -> 0x1.U, //0001 << addr(2:0)
37      "b01".U -> 0x3.U, //0011
38      "b10".U -> 0xf.U, //1111
39      "b11".U -> 0xff.U //11111111
40    )) << addr(2, 0)).asUInt
41  }
42}
43
44object genVWmask {
45  def apply(addr: UInt, sizeEncode: UInt): UInt = {
46    (LookupTree(sizeEncode, List(
47      "b00".U -> 0x1.U, //0001 << addr(2:0)
48      "b01".U -> 0x3.U, //0011
49      "b10".U -> 0xf.U, //1111
50      "b11".U -> 0xff.U //11111111
51    )) << addr(3, 0)).asUInt
52  }
53}
54
55object genWdata {
56  def apply(data: UInt, sizeEncode: UInt): UInt = {
57    LookupTree(sizeEncode, List(
58      "b00".U -> Fill(16, data(7, 0)),
59      "b01".U -> Fill(8, data(15, 0)),
60      "b10".U -> Fill(4, data(31, 0)),
61      "b11".U -> Fill(2, data(63,0))
62    ))
63  }
64}
65
66object shiftDataToLow {
67  def apply(addr: UInt,data : UInt): UInt = {
68    Mux(addr(3), (data >> 64).asUInt,data)
69  }
70}
71object shiftMaskToLow {
72  def apply(addr: UInt,mask: UInt): UInt = {
73    Mux(addr(3),(mask >> 8).asUInt,mask)
74  }
75}
76
77class LsPipelineBundle(implicit p: Parameters) extends XSBundle
78  with HasDCacheParameters
79  with HasVLSUParameters {
80  val uop = new DynInst
81  val vaddr = UInt(VAddrBits.W)
82  val paddr = UInt(PAddrBits.W)
83  // val func = UInt(6.W)
84  val mask = UInt((VLEN/8).W)
85  val data = UInt((VLEN+1).W)
86  val wlineflag = Bool() // store write the whole cache line
87
88  val miss = Bool()
89  val tlbMiss = Bool()
90  val ptwBack = Bool()
91  val mmio = Bool()
92  val atomic = Bool()
93  val rsIdx = UInt(log2Up(MemIQSizeMax).W)
94
95  val forwardMask = Vec(VLEN/8, Bool())
96  val forwardData = Vec(VLEN/8, UInt(8.W))
97
98  // prefetch
99  val isPrefetch = Bool()
100  val isHWPrefetch = Bool()
101  def isSWPrefetch = isPrefetch && !isHWPrefetch
102
103  // vector
104  val isvec = Bool()
105  val is128bit = Bool()
106  val uop_unit_stride_fof = Bool()
107  // val rob_idx_valid = Vec(2,Bool())
108  // val inner_idx = Vec(2,UInt(3.W))
109  // val rob_idx = Vec(2,new RobPtr)
110  val reg_offset = UInt(vOffsetBits.W)
111  // val offset = Vec(2,UInt(4.W))
112  val exp = Bool()
113  val is_first_ele = Bool()
114  val flowPtr = new VlflowPtr() // VLFlowQueue ptr
115  val sflowPtr = new VsFlowPtr() // VSFlowQueue ptr
116
117  // For debug usage
118  val isFirstIssue = Bool()
119  val hasROBEntry = Bool()
120
121  // For load replay
122  val isLoadReplay = Bool()
123  val isFastPath = Bool()
124  val isFastReplay = Bool()
125  val replayCarry = new ReplayCarry(nWays)
126
127  // For dcache miss load
128  val mshrid = UInt(log2Up(cfg.nMissEntries).W)
129  val handledByMSHR = Bool()
130  val replacementUpdated = Bool()
131  val missDbUpdated = Bool()
132
133  val forward_tlDchannel = Bool()
134  val dcacheRequireReplay = Bool()
135  val delayedLoadError = Bool()
136  val lateKill = Bool()
137  val feedbacked = Bool()
138  val ldCancel = ValidUndirectioned(UInt(log2Ceil(LoadPipelineWidth).W))
139  // loadQueueReplay index.
140  val schedIndex = UInt(log2Up(LoadQueueReplaySize).W)
141
142  // issue dequeue port index
143  val deqPortIdx = UInt(log2Ceil(LoadPipelineWidth).W)
144}
145
146class LdPrefetchTrainBundle(implicit p: Parameters) extends LsPipelineBundle {
147  val meta_prefetch = UInt(L1PfSourceBits.W)
148  val meta_access = Bool()
149
150  def fromLsPipelineBundle(input: LsPipelineBundle) = {
151    vaddr := input.vaddr
152    paddr := input.paddr
153    mask := input.mask
154    data := input.data
155    uop := input.uop
156    wlineflag := input.wlineflag
157    miss := input.miss
158    tlbMiss := input.tlbMiss
159    ptwBack := input.ptwBack
160    mmio := input.mmio
161    rsIdx := input.rsIdx
162    forwardMask := input.forwardMask
163    forwardData := input.forwardData
164    isPrefetch := input.isPrefetch
165    isHWPrefetch := input.isHWPrefetch
166
167    // VLSU
168    isvec := input.isvec
169    is128bit := input.is128bit
170    exp := input.exp
171    is_first_ele := input.is_first_ele
172    uop_unit_stride_fof := input.uop_unit_stride_fof
173    // rob_idx_valid := input.rob_idx_valid
174    // rob_idx := input.rob_idx
175    // inner_idx := input.inner_idx
176    reg_offset := input.reg_offset
177    // offset := input.offset
178    flowPtr := input.flowPtr
179    sflowPtr := input.sflowPtr
180    isFirstIssue := input.isFirstIssue
181    dcacheRequireReplay := input.dcacheRequireReplay
182
183    isFirstIssue := input.isFirstIssue
184    hasROBEntry := input.hasROBEntry
185    dcacheRequireReplay := input.dcacheRequireReplay
186    schedIndex := input.schedIndex
187
188    meta_prefetch := DontCare
189    meta_access := DontCare
190    forward_tlDchannel := DontCare
191    mshrid := DontCare
192    replayCarry := DontCare
193    atomic := DontCare
194    isLoadReplay := DontCare
195    isFastPath := DontCare
196    isFastReplay := DontCare
197    handledByMSHR := DontCare
198    replacementUpdated := DontCare
199    missDbUpdated := DontCare
200    delayedLoadError := DontCare
201    lateKill := DontCare
202    feedbacked := DontCare
203    deqPortIdx := DontCare
204    ldCancel := DontCare
205  }
206
207  def asPrefetchReqBundle(): PrefetchReqBundle = {
208    val res = Wire(new PrefetchReqBundle)
209    res.vaddr := this.vaddr
210    res.paddr := this.paddr
211    res.pc    := this.uop.pc
212
213    res
214  }
215}
216
217class StPrefetchTrainBundle(implicit p: Parameters) extends LdPrefetchTrainBundle {}
218
219class LqWriteBundle(implicit p: Parameters) extends LsPipelineBundle {
220  // load inst replay informations
221  val rep_info = new LoadToLsqReplayIO
222  // queue entry data, except flag bits, will be updated if writeQueue is true,
223  // valid bit in LqWriteBundle will be ignored
224  val data_wen_dup = Vec(6, Bool()) // dirty reg dup
225
226
227  def fromLsPipelineBundle(input: LsPipelineBundle) = {
228    vaddr := input.vaddr
229    paddr := input.paddr
230    mask := input.mask
231    data := input.data
232    uop := input.uop
233    wlineflag := input.wlineflag
234    miss := input.miss
235    tlbMiss := input.tlbMiss
236    ptwBack := input.ptwBack
237    mmio := input.mmio
238    atomic := input.atomic
239    rsIdx := input.rsIdx
240    forwardMask := input.forwardMask
241    forwardData := input.forwardData
242    isPrefetch := input.isPrefetch
243    isHWPrefetch := input.isHWPrefetch
244
245    //VLSU
246    isvec := input.isvec
247    is128bit := input.is128bit
248    exp := input.exp
249    uop_unit_stride_fof := input.uop_unit_stride_fof
250    // rob_idx_valid := input.rob_idx_valid
251    // rob_idx := input.rob_idx
252    // inner_idx := input.inner_idx
253    reg_offset := input.reg_offset
254    // offset := input.offset
255
256    isFirstIssue := input.isFirstIssue
257    hasROBEntry := input.hasROBEntry
258    isLoadReplay := input.isLoadReplay
259    isFastPath := input.isFastPath
260    isFastReplay := input.isFastReplay
261    mshrid := input.mshrid
262    forward_tlDchannel := input.forward_tlDchannel
263    replayCarry := input.replayCarry
264    dcacheRequireReplay := input.dcacheRequireReplay
265    schedIndex := input.schedIndex
266    handledByMSHR := input.handledByMSHR
267    replacementUpdated := input.replacementUpdated
268    missDbUpdated := input.missDbUpdated
269    delayedLoadError := input.delayedLoadError
270    lateKill := input.lateKill
271    feedbacked := input.feedbacked
272
273    rep_info := DontCare
274    data_wen_dup := DontCare
275  }
276}
277
278class LoadForwardQueryIO(implicit p: Parameters) extends XSBundle {
279  val vaddr = Output(UInt(VAddrBits.W))
280  val paddr = Output(UInt(PAddrBits.W))
281  val mask = Output(UInt((VLEN/8).W))
282  val uop = Output(new DynInst) // for replay
283  val pc = Output(UInt(VAddrBits.W)) //for debug
284  val valid = Output(Bool())
285
286  val forwardMaskFast = Input(Vec((VLEN/8), Bool())) // resp to load_s1
287  val forwardMask = Input(Vec((VLEN/8), Bool())) // resp to load_s2
288  val forwardData = Input(Vec((VLEN/8), UInt(8.W))) // resp to load_s2
289
290  // val lqIdx = Output(UInt(LoadQueueIdxWidth.W))
291  val sqIdx = Output(new SqPtr)
292
293  // dataInvalid suggests store to load forward found forward should happen,
294  // but data is not available for now. If dataInvalid, load inst should
295  // be replayed from RS. Feedback type should be RSFeedbackType.dataInvalid
296  val dataInvalid = Input(Bool()) // Addr match, but data is not valid for now
297
298  // matchInvalid suggests in store to load forward logic, paddr cam result does
299  // to equal to vaddr cam result. If matchInvalid, a microarchitectural exception
300  // should be raised to flush SQ and committed sbuffer.
301  val matchInvalid = Input(Bool()) // resp to load_s2
302
303  // addrInvalid suggests store to load forward found forward should happen,
304  // but address (SSID) is not available for now. If addrInvalid, load inst should
305  // be replayed from RS. Feedback type should be RSFeedbackType.addrInvalid
306  val addrInvalid = Input(Bool())
307}
308
309// LoadForwardQueryIO used in load pipeline
310//
311// Difference between PipeLoadForwardQueryIO and LoadForwardQueryIO:
312// PipeIO use predecoded sqIdxMask for better forward timing
313class PipeLoadForwardQueryIO(implicit p: Parameters) extends LoadForwardQueryIO {
314  // val sqIdx = Output(new SqPtr) // for debug, should not be used in pipeline for timing reasons
315  // sqIdxMask is calcuated in earlier stage for better timing
316  val sqIdxMask = Output(UInt(StoreQueueSize.W))
317
318  // dataInvalid: addr match, but data is not valid for now
319  val dataInvalidFast = Input(Bool()) // resp to load_s1
320  // val dataInvalid = Input(Bool()) // resp to load_s2
321  val dataInvalidSqIdx = Input(new SqPtr) // resp to load_s2, sqIdx
322  val addrInvalidSqIdx = Input(new SqPtr) // resp to load_s2, sqIdx
323}
324
325// Query load queue for ld-ld violation
326//
327// Req should be send in load_s1
328// Resp will be generated 1 cycle later
329//
330// Note that query req may be !ready, as dcache is releasing a block
331// If it happens, a replay from rs is needed.
332class LoadNukeQueryReq(implicit p: Parameters) extends XSBundle { // provide lqIdx
333  val uop = new DynInst
334  // mask: load's data mask.
335  val mask = UInt((VLEN/8).W)
336
337  // paddr: load's paddr.
338  val paddr      = UInt(PAddrBits.W)
339  // dataInvalid: load data is invalid.
340  val data_valid = Bool()
341}
342
343class LoadNukeQueryResp(implicit p: Parameters) extends XSBundle {
344  // rep_frm_fetch: ld-ld violation check success, replay from fetch.
345  val rep_frm_fetch = Bool()
346}
347
348class LoadNukeQueryIO(implicit p: Parameters) extends XSBundle {
349  val req    = Decoupled(new LoadNukeQueryReq)
350  val resp   = Flipped(Valid(new LoadNukeQueryResp))
351  val revoke = Output(Bool())
352}
353
354class StoreNukeQueryIO(implicit p: Parameters) extends XSBundle {
355  //  robIdx: Requestor's (a store instruction) rob index for match logic.
356  val robIdx = new RobPtr
357
358  //  paddr: requestor's (a store instruction) physical address for match logic.
359  val paddr  = UInt(PAddrBits.W)
360
361  //  mask: requestor's (a store instruction) data width mask for match logic.
362  val mask = UInt((VLEN/8).W)
363}
364
365// Store byte valid mask write bundle
366//
367// Store byte valid mask write to SQ takes 2 cycles
368class StoreMaskBundle(implicit p: Parameters) extends XSBundle {
369  val sqIdx = new SqPtr
370  val mask = UInt((VLEN/8).W)
371}
372
373class LoadDataFromDcacheBundle(implicit p: Parameters) extends DCacheBundle {
374  // old dcache: optimize data sram read fanout
375  // val bankedDcacheData = Vec(DCacheBanks, UInt(64.W))
376  // val bank_oh = UInt(DCacheBanks.W)
377
378  // new dcache
379  val respDcacheData = UInt(VLEN.W)
380  val forwardMask = Vec(VLEN/8, Bool())
381  val forwardData = Vec(VLEN/8, UInt(8.W))
382  val uop = new DynInst // for data selection, only fwen and fuOpType are used
383  val addrOffset = UInt(4.W) // for data selection
384  // forward tilelink D channel
385  val forward_D = Bool()
386  val forwardData_D = Vec(VLEN/8, UInt(8.W))
387
388  // forward mshr data
389  val forward_mshr = Bool()
390  val forwardData_mshr = Vec(VLEN/8, UInt(8.W))
391
392  val forward_result_valid = Bool()
393
394  def dcacheData(): UInt = {
395    // old dcache
396    // val dcache_data = Mux1H(bank_oh, bankedDcacheData)
397    // new dcache
398    val dcache_data = respDcacheData
399    val use_D = forward_D && forward_result_valid
400    val use_mshr = forward_mshr && forward_result_valid
401    Mux(use_D, forwardData_D.asUInt, Mux(use_mshr, forwardData_mshr.asUInt, dcache_data))
402  }
403
404  def mergedData(): UInt = {
405    val rdataVec = VecInit((0 until VLEN / 8).map(j =>
406      Mux(forwardMask(j), forwardData(j), dcacheData()(8*(j+1)-1, 8*j))
407    ))
408    rdataVec.asUInt
409  }
410}
411
412// Load writeback data from load queue (refill)
413class LoadDataFromLQBundle(implicit p: Parameters) extends XSBundle {
414  val lqData = UInt(64.W) // load queue has merged data
415  val uop = new DynInst // for data selection, only fwen and fuOpType are used
416  val addrOffset = UInt(3.W) // for data selection
417
418  def mergedData(): UInt = {
419    lqData
420  }
421}
422
423// Bundle for load / store wait waking up
424class MemWaitUpdateReq(implicit p: Parameters) extends XSBundle {
425  val robIdx = Vec(backendParams.StaCnt, ValidIO(new RobPtr))
426  val sqIdx = Vec(backendParams.StdCnt, ValidIO(new SqPtr))
427}
428
429object AddPipelineReg {
430  class PipelineRegModule[T <: Data](gen: T) extends Module {
431    val io = IO(new Bundle() {
432      val in = Flipped(DecoupledIO(gen.cloneType))
433      val out = DecoupledIO(gen.cloneType)
434      val isFlush = Input(Bool())
435    })
436
437    val valid = RegInit(false.B)
438    valid.suggestName("pipeline_reg_valid")
439    when (io.out.fire) { valid := false.B }
440    when (io.in.fire) { valid := true.B }
441    when (io.isFlush) { valid := false.B }
442
443    io.in.ready := !valid || io.out.ready
444    io.out.bits := RegEnable(io.in.bits, io.in.fire)
445    io.out.valid := valid //&& !isFlush
446  }
447
448  def apply[T <: Data]
449  (left: DecoupledIO[T], right: DecoupledIO[T], isFlush: Bool,
450   moduleName: Option[String] = None
451  ){
452    val pipelineReg = Module(new PipelineRegModule[T](left.bits.cloneType))
453    if(moduleName.nonEmpty) pipelineReg.suggestName(moduleName.get)
454    pipelineReg.io.in <> left
455    right <> pipelineReg.io.out
456    pipelineReg.io.isFlush := isFlush
457  }
458}
459