xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/HybridUnit.scala (revision 7531c765d87d92e3c772b0d55aa810c2041ba3e3)
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
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan.ExceptionNO._
25import xiangshan._
26import xiangshan.backend.Bundles.{DynInst, MemExuInput, MemExuOutput}
27import xiangshan.backend.fu.PMPRespBundle
28import xiangshan.backend.fu.FuConfig._
29import xiangshan.backend.ctrlblock.{DebugLsInfoBundle, LsTopdownInfo}
30import xiangshan.backend.rob.RobPtr
31import xiangshan.backend.fu._
32import xiangshan.cache._
33import xiangshan.cache.wpu.ReplayCarry
34import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
35import xiangshan.mem.mdp._
36
37class HybridUnit(implicit p: Parameters) extends XSModule
38  with HasLoadHelper
39  with HasPerfEvents
40  with HasDCacheParameters
41  with HasCircularQueuePtrHelper
42{
43  val io = IO(new Bundle() {
44    // control
45    val redirect      = Flipped(ValidIO(new Redirect))
46    val csrCtrl       = Flipped(new CustomCSRCtrlIO)
47
48    // flow in
49    val lsin          = Flipped(Decoupled(new MemExuInput))
50
51    // flow out
52    val ldout = DecoupledIO(new MemExuOutput)
53    val stout = DecoupledIO(new MemExuOutput)
54
55    val ldu_io = new Bundle() {
56      // dcache
57      val dcache        = new DCacheLoadIO
58
59      // data path
60      val sbuffer       = new LoadForwardQueryIO
61      val lsq           = new LoadToLsqIO
62      val tl_d_channel  = Input(new DcacheToLduForwardIO)
63      val forward_mshr  = Flipped(new LduToMissqueueForwardIO)
64      val refill        = Flipped(ValidIO(new Refill))
65      val l2_hint       = Input(Valid(new L2ToL1Hint))
66
67      // fast wakeup
68      val fast_uop = ValidIO(new DynInst) // early wakeup signal generated in load_s1, send to RS in load_s2
69
70      // trigger
71      val trigger = Vec(3, new LoadUnitTriggerIO)
72
73      // load to load fast path
74      val l2l_fwd_in    = Input(new LoadToLoadIO)
75      val l2l_fwd_out   = Output(new LoadToLoadIO)
76
77      val ld_fast_match    = Input(Bool())
78      val ld_fast_fuOpType = Input(UInt())
79      val ld_fast_imm      = Input(UInt(12.W))
80
81      // hardware prefetch to l1 cache req
82      val prefetch_req    = Flipped(ValidIO(new L1PrefetchReq))
83
84      // iq cancel
85      val ldCancel = Output(new LoadCancelIO()) // use to cancel the uops waked by this load, and cancel load
86
87      // load ecc error
88      val s3_dly_ld_err = Output(Bool()) // Note that io.s3_dly_ld_err and io.lsq.s3_dly_ld_err is different
89
90      // schedule error query
91      val stld_nuke_query = Flipped(Vec(StorePipelineWidth, Valid(new StoreNukeQueryIO)))
92
93      // queue-based replay
94      val replay       = Flipped(Decoupled(new LsPipelineBundle))
95      val lq_rep_full  = Input(Bool())
96
97      // misc
98      val s2_ptr_chasing = Output(Bool()) // provide right pc for hw prefetch
99
100      // Load fast replay path
101      val fast_rep_in  = Flipped(Decoupled(new LqWriteBundle))
102      val fast_rep_out = Decoupled(new LqWriteBundle)
103
104      // perf
105      val debug_ls         = Output(new DebugLsInfoBundle)
106      val lsTopdownInfo    = Output(new LsTopdownInfo)
107    }
108
109    val stu_io = new Bundle() {
110      val dcache          = new DCacheStoreIO
111      val prefetch_req    = Flipped(DecoupledIO(new StorePrefetchReq))
112      val issue           = Valid(new MemExuInput)
113      val lsq             = ValidIO(new LsPipelineBundle)
114      val lsq_replenish   = Output(new LsPipelineBundle())
115      val stld_nuke_query = Valid(new StoreNukeQueryIO)
116      val st_mask_out     = Valid(new StoreMaskBundle)
117      val debug_ls        = Output(new DebugLsInfoBundle)
118    }
119
120    // prefetch
121    val prefetch_train            = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to sms
122    val prefetch_train_l1         = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to stream & stride
123    val canAcceptLowConfPrefetch  = Output(Bool())
124    val canAcceptHighConfPrefetch = Output(Bool())
125    val correctMissTrain          = Input(Bool())
126
127    // data path
128    val tlb           = new TlbRequestIO(2)
129    val pmp           = Flipped(new PMPRespBundle()) // arrive same to tlb now
130
131
132    // rs feedback
133    val feedback_fast = ValidIO(new RSFeedback) // stage 2
134    val feedback_slow = ValidIO(new RSFeedback) // stage 3
135  })
136
137  val StorePrefetchL1Enabled = EnableStorePrefetchAtCommit || EnableStorePrefetchAtIssue || EnableStorePrefetchSPB
138  val s1_ready, s2_ready, s3_ready, sx_can_go = WireInit(false.B)
139
140  // Pipeline
141  // --------------------------------------------------------------------------------
142  // stage 0
143  // --------------------------------------------------------------------------------
144  // generate addr, use addr to query DCache and DTLB
145  val s0_valid         = Wire(Bool())
146  val s0_dcache_ready  = Wire(Bool())
147  val s0_kill          = Wire(Bool())
148  val s0_vaddr         = Wire(UInt(VAddrBits.W))
149  val s0_mask          = Wire(UInt((VLEN/8).W))
150  val s0_uop           = Wire(new DynInst)
151  val s0_has_rob_entry = Wire(Bool())
152  val s0_rsIdx         = Wire(UInt(log2Up(MemIQSizeMax).W))
153  val s0_mshrid        = Wire(UInt())
154  val s0_try_l2l       = Wire(Bool())
155  val s0_rep_carry     = Wire(new ReplayCarry(nWays))
156  val s0_isFirstIssue  = Wire(Bool())
157  val s0_fast_rep      = Wire(Bool())
158  val s0_ld_rep        = Wire(Bool())
159  val s0_l2l_fwd       = Wire(Bool())
160  val s0_sched_idx     = Wire(UInt())
161  val s0_deqPortIdx    = Wire(UInt(log2Ceil(LoadPipelineWidth).W))
162  val s0_can_go        = s1_ready
163  val s0_fire          = s0_valid && s0_dcache_ready && s0_can_go
164  val s0_out           = Wire(new LqWriteBundle)
165
166  // load flow select/gen
167  // src0: super load replayed by LSQ (cache miss replay) (io.ldu_io.replay)
168  // src1: fast load replay (io.ldu_io.fast_rep_in)
169  // src2: load replayed by LSQ (io.ldu_io.replay)
170  // src3: hardware prefetch from prefetchor (high confidence) (io.prefetch)
171  // src4: int read / software prefetch first issue from RS (io.in)
172  // src5: vec read first issue from RS (TODO)
173  // src6: load try pointchaising when no issued or replayed load (io.fastpath)
174  // src7: hardware prefetch from prefetchor (high confidence) (io.prefetch)
175  // priority: high to low
176  val s0_ld_flow             = FuType.isLoad(s0_uop.fuType)
177  val s0_rep_stall           = io.lsin.valid && isAfter(io.ldu_io.replay.bits.uop.robIdx, io.lsin.bits.uop.robIdx)
178  val s0_super_ld_rep_valid  = io.ldu_io.replay.valid && io.ldu_io.replay.bits.forward_tlDchannel
179  val s0_ld_fast_rep_valid   = io.ldu_io.fast_rep_in.valid
180  val s0_ld_rep_valid        = io.ldu_io.replay.valid && !io.ldu_io.replay.bits.forward_tlDchannel && !s0_rep_stall
181  val s0_high_conf_prf_valid = io.ldu_io.prefetch_req.valid && io.ldu_io.prefetch_req.bits.confidence > 0.U
182  val s0_int_iss_valid       = io.lsin.valid // int flow first issue or software prefetch
183  val s0_vec_iss_valid       = WireInit(false.B) // TODO
184  val s0_l2l_fwd_valid       = io.ldu_io.l2l_fwd_in.valid && io.ldu_io.ld_fast_match
185  val s0_low_conf_prf_valid  = io.ldu_io.prefetch_req.valid && io.ldu_io.prefetch_req.bits.confidence === 0.U
186  dontTouch(s0_super_ld_rep_valid)
187  dontTouch(s0_ld_fast_rep_valid)
188  dontTouch(s0_ld_rep_valid)
189  dontTouch(s0_high_conf_prf_valid)
190  dontTouch(s0_int_iss_valid)
191  dontTouch(s0_vec_iss_valid)
192  dontTouch(s0_l2l_fwd_valid)
193  dontTouch(s0_low_conf_prf_valid)
194
195  // load flow source ready
196  val s0_super_ld_rep_ready  = WireInit(true.B)
197  val s0_ld_fast_rep_ready   = !s0_super_ld_rep_valid
198  val s0_ld_rep_ready        = !s0_super_ld_rep_valid &&
199                               !s0_ld_fast_rep_valid
200  val s0_high_conf_prf_ready = !s0_super_ld_rep_valid &&
201                               !s0_ld_fast_rep_valid &&
202                               !s0_ld_rep_valid
203
204  val s0_int_iss_ready       = !s0_super_ld_rep_valid &&
205                               !s0_ld_fast_rep_valid &&
206                               !s0_ld_rep_valid &&
207                               !s0_high_conf_prf_valid
208
209  val s0_vec_iss_ready       = !s0_super_ld_rep_valid &&
210                               !s0_ld_fast_rep_valid &&
211                               !s0_ld_rep_valid &&
212                               !s0_high_conf_prf_valid &&
213                               !s0_int_iss_valid
214
215  val s0_l2l_fwd_ready       = !s0_super_ld_rep_valid &&
216                               !s0_ld_fast_rep_valid &&
217                               !s0_ld_rep_valid &&
218                               !s0_high_conf_prf_valid &&
219                               !s0_int_iss_valid &&
220                               !s0_vec_iss_valid
221
222  val s0_low_conf_prf_ready  = !s0_super_ld_rep_valid &&
223                               !s0_ld_fast_rep_valid &&
224                               !s0_ld_rep_valid &&
225                               !s0_high_conf_prf_valid &&
226                               !s0_int_iss_valid &&
227                               !s0_vec_iss_valid &&
228                               !s0_l2l_fwd_valid
229  dontTouch(s0_super_ld_rep_ready)
230  dontTouch(s0_ld_fast_rep_ready)
231  dontTouch(s0_ld_rep_ready)
232  dontTouch(s0_high_conf_prf_ready)
233  dontTouch(s0_int_iss_ready)
234  dontTouch(s0_vec_iss_ready)
235  dontTouch(s0_l2l_fwd_ready)
236  dontTouch(s0_low_conf_prf_ready)
237
238  // load flow source select (OH)
239  val s0_super_ld_rep_select = s0_super_ld_rep_valid && s0_super_ld_rep_ready
240  val s0_ld_fast_rep_select  = s0_ld_fast_rep_valid && s0_ld_fast_rep_ready
241  val s0_ld_rep_select       = s0_ld_rep_valid && s0_ld_rep_ready
242  val s0_hw_prf_select       = s0_high_conf_prf_ready && s0_high_conf_prf_valid ||
243                               s0_low_conf_prf_ready && s0_low_conf_prf_valid
244  val s0_int_iss_select      = s0_int_iss_ready && s0_int_iss_valid
245  val s0_vec_iss_select      = s0_vec_iss_ready && s0_vec_iss_valid
246  val s0_l2l_fwd_select      = s0_l2l_fwd_ready && s0_l2l_fwd_valid
247  assert(!s0_vec_iss_select) // to be added
248  dontTouch(s0_super_ld_rep_select)
249  dontTouch(s0_ld_fast_rep_select)
250  dontTouch(s0_ld_rep_select)
251  dontTouch(s0_hw_prf_select)
252  dontTouch(s0_int_iss_select)
253  dontTouch(s0_vec_iss_select)
254  dontTouch(s0_l2l_fwd_select)
255
256  s0_valid := (s0_super_ld_rep_valid ||
257               s0_ld_fast_rep_valid ||
258               s0_ld_rep_valid ||
259               s0_high_conf_prf_valid ||
260               s0_int_iss_valid ||
261               s0_vec_iss_valid ||
262               s0_l2l_fwd_valid ||
263               s0_low_conf_prf_valid) && !s0_kill
264
265  // which is S0's out is ready and dcache is ready
266  val s0_try_ptr_chasing      = s0_l2l_fwd_select
267  val s0_do_try_ptr_chasing   = s0_try_ptr_chasing && s0_can_go && io.ldu_io.dcache.req.ready
268  val s0_ptr_chasing_vaddr    = io.ldu_io.l2l_fwd_in.data(5, 0) +& io.ldu_io.ld_fast_imm(5, 0)
269  val s0_ptr_chasing_canceled = WireInit(false.B)
270  s0_kill := s0_ptr_chasing_canceled || (s0_out.uop.robIdx.needFlush(io.redirect) && !s0_try_ptr_chasing)
271
272  // prefetch related ctrl signal
273  val s0_prf    = Wire(Bool())
274  val s0_prf_rd = Wire(Bool())
275  val s0_prf_wr = Wire(Bool())
276  val s0_hw_prf = s0_hw_prf_select
277
278  io.canAcceptLowConfPrefetch  := s0_low_conf_prf_ready
279  io.canAcceptHighConfPrefetch := s0_high_conf_prf_ready
280
281  if (StorePrefetchL1Enabled) {
282    s0_dcache_ready := Mux(s0_ld_flow, io.ldu_io.dcache.req.ready, io.stu_io.dcache.req.ready)
283  } else {
284    s0_dcache_ready := Mux(s0_ld_flow, io.ldu_io.dcache.req.ready, true.B)
285  }
286
287  // query DTLB
288  io.tlb.req.valid                   := s0_valid && s0_dcache_ready
289  io.tlb.req.bits.cmd                := Mux(s0_prf,
290                                         Mux(s0_prf_wr, TlbCmd.write, TlbCmd.read),
291                                         Mux(s0_ld_flow, TlbCmd.read, TlbCmd.write)
292                                       )
293  io.tlb.req.bits.vaddr              := Mux(s0_hw_prf_select, io.ldu_io.prefetch_req.bits.paddr, s0_vaddr)
294  io.tlb.req.bits.size               := LSUOpType.size(s0_uop.fuOpType)
295  io.tlb.req.bits.kill               := s0_kill
296  io.tlb.req.bits.memidx.is_ld       := s0_ld_flow
297  io.tlb.req.bits.memidx.is_st       := !s0_ld_flow
298  io.tlb.req.bits.memidx.idx         := s0_uop.lqIdx.value
299  io.tlb.req.bits.debug.robIdx       := s0_uop.robIdx
300  io.tlb.req.bits.no_translate       := s0_hw_prf_select  // hw b.reqetch addr does not need to be translated
301  io.tlb.req.bits.debug.pc           := s0_uop.pc
302  io.tlb.req.bits.debug.isFirstIssue := s0_isFirstIssue
303
304  // query DCache
305  // for load
306  io.ldu_io.dcache.req.valid             := s0_valid && s0_dcache_ready && s0_ld_flow
307  io.ldu_io.dcache.req.bits.cmd          :=  Mux(s0_prf_rd, MemoryOpConstants.M_PFR,
308                                              Mux(s0_prf_wr, MemoryOpConstants.M_PFW, MemoryOpConstants.M_XRD))
309  io.ldu_io.dcache.req.bits.vaddr        := s0_vaddr
310  io.ldu_io.dcache.req.bits.mask         := s0_mask
311  io.ldu_io.dcache.req.bits.data         := DontCare
312  io.ldu_io.dcache.req.bits.isFirstIssue := s0_isFirstIssue
313  io.ldu_io.dcache.req.bits.instrtype    := Mux(s0_prf, DCACHE_PREFETCH_SOURCE.U, LOAD_SOURCE.U)
314  io.ldu_io.dcache.req.bits.debug_robIdx := s0_uop.robIdx.value
315  io.ldu_io.dcache.req.bits.replayCarry  := s0_rep_carry
316  io.ldu_io.dcache.req.bits.id           := DontCare // TODO: update cache meta
317  io.ldu_io.dcache.pf_source             := Mux(s0_hw_prf_select, io.ldu_io.prefetch_req.bits.pf_source.value, L1_HW_PREFETCH_NULL)
318
319  // for store
320  io.stu_io.dcache.req.valid             := s0_valid && s0_dcache_ready && !s0_ld_flow && !s0_prf
321  io.stu_io.dcache.req.bits.cmd          := MemoryOpConstants.M_PFW
322  io.stu_io.dcache.req.bits.vaddr        := s0_vaddr
323  io.stu_io.dcache.req.bits.instrtype    := Mux(s0_prf, DCACHE_PREFETCH_SOURCE.U, STORE_SOURCE.U)
324
325  // load flow priority mux
326  def fromNullSource() = {
327    s0_vaddr         := 0.U
328    s0_mask          := 0.U
329    s0_uop           := 0.U.asTypeOf(new DynInst)
330    s0_try_l2l       := false.B
331    s0_has_rob_entry := false.B
332    s0_rsIdx         := 0.U
333    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
334    s0_mshrid        := 0.U
335    s0_isFirstIssue  := false.B
336    s0_fast_rep      := false.B
337    s0_ld_rep        := false.B
338    s0_l2l_fwd       := false.B
339    s0_prf           := false.B
340    s0_prf_rd        := false.B
341    s0_prf_wr        := false.B
342    s0_sched_idx     := 0.U
343    s0_deqPortIdx    := 0.U
344  }
345
346  def fromFastReplaySource(src: LqWriteBundle) = {
347    s0_vaddr         := src.vaddr
348    s0_mask          := src.mask
349    s0_uop           := src.uop
350    s0_try_l2l       := false.B
351    s0_has_rob_entry := src.hasROBEntry
352    s0_rep_carry     := src.rep_info.rep_carry
353    s0_mshrid        := src.rep_info.mshr_id
354    s0_rsIdx         := src.rsIdx
355    s0_isFirstIssue  := false.B
356    s0_fast_rep      := true.B
357    s0_ld_rep        := src.isLoadReplay
358    s0_l2l_fwd       := false.B
359    s0_prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
360    s0_prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
361    s0_prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
362    s0_sched_idx     := src.schedIndex
363    s0_deqPortIdx    := src.deqPortIdx
364  }
365
366  def fromNormalReplaySource(src: LsPipelineBundle) = {
367    s0_vaddr         := src.vaddr
368    s0_mask          := genVWmask(src.vaddr, src.uop.fuOpType(1, 0))
369    s0_uop           := src.uop
370    s0_try_l2l       := false.B
371    s0_has_rob_entry := true.B
372    s0_rsIdx         := src.rsIdx
373    s0_rep_carry     := src.replayCarry
374    s0_mshrid        := src.mshrid
375    s0_isFirstIssue  := false.B
376    s0_fast_rep      := false.B
377    s0_ld_rep        := true.B
378    s0_l2l_fwd       := false.B
379    s0_prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
380    s0_prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
381    s0_prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
382    s0_sched_idx     := src.schedIndex
383    s0_deqPortIdx    := src.deqPortIdx
384  }
385
386  def fromPrefetchSource(src: L1PrefetchReq) = {
387    s0_vaddr         := src.getVaddr()
388    s0_mask          := 0.U
389    s0_uop           := DontCare
390    s0_try_l2l       := false.B
391    s0_has_rob_entry := false.B
392    s0_rsIdx         := 0.U
393    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
394    s0_mshrid        := 0.U
395    s0_isFirstIssue  := false.B
396    s0_fast_rep      := false.B
397    s0_ld_rep        := false.B
398    s0_l2l_fwd       := false.B
399    s0_prf           := true.B
400    s0_prf_rd        := !src.is_store
401    s0_prf_wr        := src.is_store
402    s0_sched_idx     := 0.U
403    s0_deqPortIdx    := 0.U
404  }
405
406  def fromIntIssueSource(src: MemExuInput) = {
407    s0_vaddr         := src.src(0) + SignExt(src.uop.imm(11, 0), VAddrBits)
408    s0_mask          := genVWmask(s0_vaddr, src.uop.fuOpType(1,0))
409    s0_uop           := src.uop
410    s0_try_l2l       := false.B
411    s0_has_rob_entry := true.B
412    s0_rsIdx         := src.iqIdx
413    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
414    s0_mshrid        := 0.U
415    s0_isFirstIssue  := true.B
416    s0_fast_rep      := false.B
417    s0_ld_rep        := false.B
418    s0_l2l_fwd       := false.B
419    s0_prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
420    s0_prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
421    s0_prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
422    s0_sched_idx     := 0.U
423    s0_deqPortIdx    := src.deqPortIdx
424  }
425
426  def fromVecIssueSource() = {
427    s0_vaddr         := 0.U
428    s0_mask          := 0.U
429    s0_uop           := 0.U.asTypeOf(new DynInst)
430    s0_try_l2l       := false.B
431    s0_has_rob_entry := false.B
432    s0_rsIdx         := 0.U
433    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
434    s0_mshrid        := 0.U
435    s0_isFirstIssue  := false.B
436    s0_fast_rep      := false.B
437    s0_ld_rep        := false.B
438    s0_l2l_fwd       := false.B
439    s0_prf           := false.B
440    s0_prf_rd        := false.B
441    s0_prf_wr        := false.B
442    s0_sched_idx     := 0.U
443    s0_deqPortIdx    := 0.U
444  }
445
446  def fromLoadToLoadSource(src: LoadToLoadIO) = {
447    s0_vaddr              := Cat(src.data(XLEN-1, 6), s0_ptr_chasing_vaddr(5,0))
448    s0_mask               := genVWmask(s0_vaddr, io.ldu_io.ld_fast_fuOpType(1, 0))
449    // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
450    // Assume the pointer chasing is always ld.
451    s0_uop.fuOpType  := io.ldu_io.ld_fast_fuOpType
452    s0_try_l2l            := true.B
453    // we dont care s0_isFirstIssue and s0_rsIdx and s0_sqIdx and s0_deqPortIdx in S0 when trying pointchasing
454    // because these signals will be updated in S1
455    s0_has_rob_entry      := false.B
456    s0_rsIdx              := 0.U
457    s0_mshrid             := 0.U
458    s0_rep_carry          := 0.U.asTypeOf(s0_rep_carry.cloneType)
459    s0_isFirstIssue       := true.B
460    s0_fast_rep           := false.B
461    s0_ld_rep             := false.B
462    s0_l2l_fwd            := true.B
463    s0_prf                := false.B
464    s0_prf_rd             := false.B
465    s0_prf_wr             := false.B
466    s0_sched_idx          := 0.U
467    s0_deqPortIdx         := 0.U
468  }
469
470  // set default
471  s0_uop := DontCare
472  when (s0_super_ld_rep_select)      { fromNormalReplaySource(io.ldu_io.replay.bits)     }
473  .elsewhen (s0_ld_fast_rep_select)  { fromFastReplaySource(io.ldu_io.fast_rep_in.bits)  }
474  .elsewhen (s0_ld_rep_select)       { fromNormalReplaySource(io.ldu_io.replay.bits)     }
475  .elsewhen (s0_hw_prf_select)       { fromPrefetchSource(io.ldu_io.prefetch_req.bits)   }
476  .elsewhen (s0_int_iss_select)      { fromIntIssueSource(io.lsin.bits)           }
477  .elsewhen (s0_vec_iss_select)      { fromVecIssueSource()                       }
478  .otherwise {
479    if (EnableLoadToLoadForward) {
480      fromLoadToLoadSource(io.ldu_io.l2l_fwd_in)
481    } else {
482      fromNullSource()
483    }
484  }
485
486  // address align check
487  val s0_addr_aligned = LookupTree(s0_uop.fuOpType(1, 0), List(
488    "b00".U   -> true.B,                   //b
489    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
490    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
491    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
492  ))
493
494  // accept load flow if dcache ready (tlb is always ready)
495  // TODO: prefetch need writeback to loadQueueFlag
496  s0_out               := DontCare
497  s0_out.rsIdx         := s0_rsIdx
498  s0_out.vaddr         := s0_vaddr
499  s0_out.mask          := s0_mask
500  s0_out.uop           := s0_uop
501  s0_out.isFirstIssue  := s0_isFirstIssue
502  s0_out.hasROBEntry   := s0_has_rob_entry
503  s0_out.isPrefetch    := s0_prf
504  s0_out.isHWPrefetch  := s0_hw_prf
505  s0_out.isFastReplay  := s0_fast_rep
506  s0_out.isLoadReplay  := s0_ld_rep
507  s0_out.isFastPath    := s0_l2l_fwd
508  s0_out.mshrid        := s0_mshrid
509  s0_out.uop.exceptionVec(loadAddrMisaligned)  := !s0_addr_aligned && s0_ld_flow
510  s0_out.uop.exceptionVec(storeAddrMisaligned) := !s0_addr_aligned && !s0_ld_flow
511  s0_out.forward_tlDchannel := s0_super_ld_rep_select
512  when(io.tlb.req.valid && s0_isFirstIssue) {
513    s0_out.uop.debugInfo.tlbFirstReqTime := GTimer()
514  }.otherwise{
515    s0_out.uop.debugInfo.tlbFirstReqTime := s0_uop.debugInfo.tlbFirstReqTime
516  }
517  s0_out.schedIndex     := s0_sched_idx
518  s0_out.deqPortIdx     := s0_deqPortIdx
519
520  // load fast replay
521  io.ldu_io.fast_rep_in.ready := (s0_can_go && io.ldu_io.dcache.req.ready && s0_ld_fast_rep_ready)
522
523  // load flow source ready
524  // cache missed load has highest priority
525  // always accept cache missed load flow from load replay queue
526  io.ldu_io.replay.ready := (s0_can_go && io.ldu_io.dcache.req.ready && (s0_ld_rep_ready && !s0_rep_stall || s0_super_ld_rep_select))
527
528  // accept load flow from rs when:
529  // 1) there is no lsq-replayed load
530  // 2) there is no fast replayed load
531  // 3) there is no high confidence prefetch request
532  io.lsin.ready := (s0_can_go &&
533                    Mux(FuType.isLoad(io.lsin.bits.uop.fuType), io.ldu_io.dcache.req.ready,
534                    (if (StorePrefetchL1Enabled) io.stu_io.dcache.req.ready else true.B)) && s0_int_iss_ready)
535
536
537  // for hw prefetch load flow feedback, to be added later
538  // io.prefetch_in.ready := s0_hw_prf_select
539
540  // dcache replacement extra info
541  // TODO: should prefetch load update replacement?
542  io.ldu_io.dcache.replacementUpdated := Mux(s0_ld_rep_select || s0_super_ld_rep_select, io.ldu_io.replay.bits.replacementUpdated, false.B)
543
544  io.stu_io.prefetch_req.ready := s1_ready && io.stu_io.dcache.req.ready && !io.lsin.valid
545
546  // load debug
547  XSDebug(io.ldu_io.dcache.req.fire && s0_ld_flow,
548    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
549  )
550  XSDebug(s0_valid && s0_ld_flow,
551    p"S0: pc ${Hexadecimal(s0_out.uop.pc)}, lqIdx ${Hexadecimal(s0_out.uop.lqIdx.asUInt)}, " +
552    p"vaddr ${Hexadecimal(s0_out.vaddr)}, mask ${Hexadecimal(s0_out.mask)}\n")
553
554  // store debug
555  XSDebug(io.stu_io.dcache.req.fire && !s0_ld_flow,
556    p"[DCACHE STORE REQ] pc ${Hexadecimal(s0_uop.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
557  )
558  XSDebug(s0_valid && !s0_ld_flow,
559    p"S0: pc ${Hexadecimal(s0_out.uop.pc)}, sqIdx ${Hexadecimal(s0_out.uop.sqIdx.asUInt)}, " +
560    p"vaddr ${Hexadecimal(s0_out.vaddr)}, mask ${Hexadecimal(s0_out.mask)}\n")
561
562
563  // Pipeline
564  // --------------------------------------------------------------------------------
565  // stage 1
566  // --------------------------------------------------------------------------------
567  // TLB resp (send paddr to dcache)
568  val s1_valid      = RegInit(false.B)
569  val s1_in         = Wire(new LqWriteBundle)
570  val s1_out        = Wire(new LqWriteBundle)
571  val s1_kill       = Wire(Bool())
572  val s1_can_go     = s2_ready
573  val s1_fire       = s1_valid && !s1_kill && s1_can_go
574  val s1_ld_flow    = RegNext(s0_ld_flow)
575
576  s1_ready := !s1_valid || s1_kill || s2_ready
577  when (s0_fire) { s1_valid := true.B }
578  .elsewhen (s1_fire) { s1_valid := false.B }
579  .elsewhen (s1_kill) { s1_valid := false.B }
580  s1_in   := RegEnable(s0_out, s0_fire)
581
582  val s1_fast_rep_dly_err = RegNext(io.ldu_io.fast_rep_in.bits.delayedLoadError)
583  val s1_fast_rep_kill    = s1_fast_rep_dly_err && s1_in.isFastReplay
584  val s1_l2l_fwd_dly_err  = RegNext(io.ldu_io.l2l_fwd_in.dly_ld_err)
585  val s1_l2l_fwd_kill     = s1_l2l_fwd_dly_err && s1_in.isFastPath
586  val s1_late_kill        = s1_fast_rep_kill || s1_l2l_fwd_kill
587  val s1_vaddr_hi         = Wire(UInt())
588  val s1_vaddr_lo         = Wire(UInt())
589  val s1_vaddr            = Wire(UInt())
590  val s1_paddr_dup_lsu    = Wire(UInt())
591  val s1_paddr_dup_dcache = Wire(UInt())
592  val s1_ld_exception     = ExceptionNO.selectByFu(s1_out.uop.exceptionVec, LduCfg).asUInt.orR   // af & pf exception were modified below.
593  val s1_st_exception     = ExceptionNO.selectByFu(s1_out.uop.exceptionVec, StaCfg).asUInt.orR   // af & pf exception were modified below.
594  val s1_exception        = (s1_ld_flow && s1_ld_exception) || (!s1_ld_flow && s1_st_exception)
595  val s1_tlb_miss         = io.tlb.resp.bits.miss
596  val s1_prf              = s1_in.isPrefetch
597  val s1_hw_prf           = s1_in.isHWPrefetch
598  val s1_sw_prf           = s1_prf && !s1_hw_prf
599  val s1_tlb_memidx       = io.tlb.resp.bits.memidx
600
601  // mmio cbo decoder
602  val s1_mmio_cbo  = (s1_in.uop.fuOpType === LSUOpType.cbo_clean ||
603                      s1_in.uop.fuOpType === LSUOpType.cbo_flush ||
604                      s1_in.uop.fuOpType === LSUOpType.cbo_inval) && !s1_ld_flow && !s1_prf
605  val s1_mmio = s1_mmio_cbo
606
607  s1_vaddr_hi         := s1_in.vaddr(VAddrBits - 1, 6)
608  s1_vaddr_lo         := s1_in.vaddr(5, 0)
609  s1_vaddr            := Cat(s1_vaddr_hi, s1_vaddr_lo)
610  s1_paddr_dup_lsu    := io.tlb.resp.bits.paddr(0)
611  s1_paddr_dup_dcache := io.tlb.resp.bits.paddr(1)
612
613  when (s1_tlb_memidx.is_ld && io.tlb.resp.valid && !s1_tlb_miss &&
614        s1_tlb_memidx.idx === s1_in.uop.lqIdx.value && s1_ld_flow) {
615    // printf("Load idx = %d\n", s1_tlb_memidx.idx)
616    s1_out.uop.debugInfo.tlbRespTime := GTimer()
617  } .elsewhen(s1_tlb_memidx.is_st && io.tlb.resp.valid && !s1_tlb_miss &&
618              s1_tlb_memidx.idx === s1_out.uop.sqIdx.value && !s1_ld_flow) {
619    // printf("Store idx = %d\n", s1_tlb_memidx.idx)
620    s1_out.uop.debugInfo.tlbRespTime := GTimer()
621  }
622
623  io.tlb.req_kill   := s1_kill
624  io.tlb.resp.ready := true.B
625
626  io.ldu_io.dcache.s1_paddr_dup_lsu    <> s1_paddr_dup_lsu
627  io.ldu_io.dcache.s1_paddr_dup_dcache <> s1_paddr_dup_dcache
628  io.ldu_io.dcache.s1_kill             := s1_kill || s1_tlb_miss || s1_exception
629
630  // store to load forwarding
631  io.ldu_io.sbuffer.valid := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_fast_rep_kill || s1_prf || !s1_ld_flow)
632  io.ldu_io.sbuffer.vaddr := s1_vaddr
633  io.ldu_io.sbuffer.paddr := s1_paddr_dup_lsu
634  io.ldu_io.sbuffer.uop   := s1_in.uop
635  io.ldu_io.sbuffer.sqIdx := s1_in.uop.sqIdx
636  io.ldu_io.sbuffer.mask  := s1_in.mask
637  io.ldu_io.sbuffer.pc    := s1_in.uop.pc // FIXME: remove it
638
639  io.ldu_io.lsq.forward.valid     := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_fast_rep_kill || s1_prf || !s1_ld_flow)
640  io.ldu_io.lsq.forward.vaddr     := s1_vaddr
641  io.ldu_io.lsq.forward.paddr     := s1_paddr_dup_lsu
642  io.ldu_io.lsq.forward.uop       := s1_in.uop
643  io.ldu_io.lsq.forward.sqIdx     := s1_in.uop.sqIdx
644  io.ldu_io.lsq.forward.sqIdxMask := 0.U
645  io.ldu_io.lsq.forward.mask      := s1_in.mask
646  io.ldu_io.lsq.forward.pc        := s1_in.uop.pc // FIXME: remove it
647
648  // st-ld violation query
649  val s1_nuke = VecInit((0 until StorePipelineWidth).map(w => {
650                       io.ldu_io.stld_nuke_query(w).valid && // query valid
651                       isAfter(s1_in.uop.robIdx, io.ldu_io.stld_nuke_query(w).bits.robIdx) && // older store
652                       // TODO: Fix me when vector instruction
653                       (s1_paddr_dup_lsu(PAddrBits-1, 3) === io.ldu_io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3)) && // paddr match
654                       (s1_in.mask & io.ldu_io.stld_nuke_query(w).bits.mask).orR // data mask contain
655                      })).asUInt.orR && !s1_tlb_miss && s1_ld_flow
656
657  s1_out                   := s1_in
658  s1_out.vaddr             := s1_vaddr
659  s1_out.paddr             := s1_paddr_dup_lsu
660  s1_out.tlbMiss           := s1_tlb_miss
661  s1_out.ptwBack           := io.tlb.resp.bits.ptwBack
662  s1_out.rsIdx             := s1_in.rsIdx
663  s1_out.rep_info.debug    := s1_in.uop.debugInfo
664  s1_out.rep_info.nuke     := s1_nuke && !s1_sw_prf
665  s1_out.lateKill          := s1_late_kill
666
667  when (s1_ld_flow) {
668    when (!s1_late_kill) {
669      // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
670      // af & pf exception were modified
671      s1_out.uop.exceptionVec(loadPageFault)   := io.tlb.resp.bits.excp(0).pf.ld
672      s1_out.uop.exceptionVec(loadAccessFault) := io.tlb.resp.bits.excp(0).af.ld
673    } .otherwise {
674      s1_out.uop.exceptionVec(loadAddrMisaligned) := false.B
675      s1_out.uop.exceptionVec(loadAccessFault)    := s1_late_kill
676    }
677  } .otherwise {
678    s1_out.uop.exceptionVec(storePageFault)   := io.tlb.resp.bits.excp(0).pf.st
679    s1_out.uop.exceptionVec(storeAccessFault) := io.tlb.resp.bits.excp(0).af.st
680  }
681
682  // pointer chasing
683  val s1_try_ptr_chasing       = RegNext(s0_do_try_ptr_chasing, false.B)
684  val s1_ptr_chasing_vaddr     = RegEnable(s0_ptr_chasing_vaddr, s0_do_try_ptr_chasing)
685  val s1_fu_op_type_not_ld     = WireInit(false.B)
686  val s1_not_fast_match        = WireInit(false.B)
687  val s1_addr_mismatch         = WireInit(false.B)
688  val s1_addr_misaligned       = WireInit(false.B)
689  val s1_ptr_chasing_canceled  = WireInit(false.B)
690  val s1_cancel_ptr_chasing    = WireInit(false.B)
691
692  s1_kill := s1_late_kill ||
693             s1_cancel_ptr_chasing ||
694             s1_in.uop.robIdx.needFlush(io.redirect) ||
695             RegEnable(s0_kill, false.B, io.lsin.valid || io.ldu_io.replay.valid || io.ldu_io.l2l_fwd_in.valid || io.ldu_io.fast_rep_in.valid)
696
697  if (EnableLoadToLoadForward) {
698    // Sometimes, we need to cancel the load-load forwarding.
699    // These can be put at S0 if timing is bad at S1.
700    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
701    s1_addr_mismatch      := s1_ptr_chasing_vaddr(6) || RegEnable(io.ldu_io.ld_fast_imm(11, 6).orR, s0_do_try_ptr_chasing)
702    // Case 1: the address is misaligned, kill s1
703    s1_addr_misaligned    := LookupTree(s1_in.uop.fuOpType(1, 0), List(
704                             "b00".U   -> false.B,                  //b
705                             "b01".U   -> (s1_vaddr(0)    =/= 0.U), //h
706                             "b10".U   -> (s1_vaddr(1, 0) =/= 0.U), //w
707                             "b11".U   -> (s1_vaddr(2, 0) =/= 0.U)  //d
708                          ))
709    // Case 2: this load-load uop is cancelled
710    s1_ptr_chasing_canceled := !io.lsin.valid || FuType.isStore(io.lsin.bits.uop.fuType)
711
712    when (s1_try_ptr_chasing) {
713      s1_cancel_ptr_chasing := s1_addr_mismatch || s1_addr_misaligned || s1_ptr_chasing_canceled
714
715      s1_in.uop           := io.lsin.bits.uop
716      s1_in.rsIdx         := io.lsin.bits.iqIdx
717      s1_in.isFirstIssue  := io.lsin.bits.isFirstIssue
718      s1_vaddr_lo         := s1_ptr_chasing_vaddr(5, 0)
719      s1_paddr_dup_lsu    := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
720      s1_paddr_dup_dcache := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
721
722      // recored tlb time when get the data to ensure the correctness of the latency calculation (although it should not record in here, because it does not use tlb)
723      s1_in.uop.debugInfo.tlbFirstReqTime := GTimer()
724      s1_in.uop.debugInfo.tlbRespTime     := GTimer()
725    }
726    when (!s1_cancel_ptr_chasing) {
727      s0_ptr_chasing_canceled := s1_try_ptr_chasing && !io.ldu_io.replay.fire && !io.ldu_io.fast_rep_in.fire
728      when (s1_try_ptr_chasing) {
729        io.lsin.ready := true.B
730      }
731    }
732  }
733
734  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
735  val s1_sqIdx_mask = RegNext(UIntToMask(s0_out.uop.sqIdx.value, StoreQueueSize))
736  // to enable load-load, sqIdxMask must be calculated based on lsin.uop
737  // If the timing here is not OK, load-load forwarding has to be disabled.
738  // Or we calculate sqIdxMask at RS??
739  io.ldu_io.lsq.forward.sqIdxMask := s1_sqIdx_mask
740  if (EnableLoadToLoadForward) {
741    when (s1_try_ptr_chasing) {
742      io.ldu_io.lsq.forward.sqIdxMask := UIntToMask(io.lsin.bits.uop.sqIdx.value, StoreQueueSize)
743    }
744  }
745
746  io.ldu_io.forward_mshr.valid  := s1_valid && s1_out.forward_tlDchannel && s1_ld_flow
747  io.ldu_io.forward_mshr.mshrid := s1_out.mshrid
748  io.ldu_io.forward_mshr.paddr  := s1_out.paddr
749
750  io.stu_io.dcache.s1_kill := s1_tlb_miss || s1_exception || s1_mmio || s1_in.uop.robIdx.needFlush(io.redirect)
751  io.stu_io.dcache.s1_paddr := s1_paddr_dup_dcache
752
753
754  // load debug
755  XSDebug(s1_valid && s1_ld_flow,
756    p"S1: pc ${Hexadecimal(s1_out.uop.pc)}, lId ${Hexadecimal(s1_out.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
757    p"paddr ${Hexadecimal(s1_out.paddr)}, mmio ${s1_out.mmio}\n")
758
759  // store debug
760  XSDebug(s1_valid && !s1_ld_flow,
761    p"S1: pc ${Hexadecimal(s1_out.uop.pc)}, lId ${Hexadecimal(s1_out.uop.sqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
762    p"paddr ${Hexadecimal(s1_out.paddr)}, mmio ${s1_out.mmio}\n")
763
764  // store out
765  io.stu_io.lsq.valid         := s1_valid && !s1_ld_flow && !s1_prf
766  io.stu_io.lsq.bits          := s1_out
767  io.stu_io.lsq.bits.miss     := s1_tlb_miss
768
769  io.stu_io.st_mask_out.valid       := s1_valid && !s1_ld_flow && !s1_prf
770  io.stu_io.st_mask_out.bits.mask   := s1_out.mask
771  io.stu_io.st_mask_out.bits.sqIdx  := s1_out.uop.sqIdx
772
773  io.stu_io.issue.valid       := s1_valid && !s1_tlb_miss && !s1_ld_flow && !s1_prf
774  io.stu_io.issue.bits        := RegEnable(io.lsin.bits, io.lsin.fire)
775
776  // st-ld violation dectect request
777  io.stu_io.stld_nuke_query.valid       := s1_valid && !s1_tlb_miss && !s1_ld_flow && !s1_prf
778  io.stu_io.stld_nuke_query.bits.robIdx := s1_in.uop.robIdx
779  io.stu_io.stld_nuke_query.bits.paddr  := s1_paddr_dup_lsu
780  io.stu_io.stld_nuke_query.bits.mask   := s1_in.mask
781
782  // Pipeline
783  // --------------------------------------------------------------------------------
784  // stage 2
785  // --------------------------------------------------------------------------------
786  // s2: DCache resp
787  val s2_valid  = RegInit(false.B)
788  val s2_in     = Wire(new LqWriteBundle)
789  val s2_out    = Wire(new LqWriteBundle)
790  val s2_kill   = Wire(Bool())
791  val s2_can_go = s3_ready
792  val s2_fire   = s2_valid && !s2_kill && s2_can_go
793
794  s2_kill := s2_in.uop.robIdx.needFlush(io.redirect)
795  s2_ready := !s2_valid || s2_kill || s3_ready
796  when (s1_fire) { s2_valid := true.B }
797  .elsewhen (s2_fire) { s2_valid := false.B }
798  .elsewhen (s2_kill) { s2_valid := false.B }
799  s2_in := RegEnable(s1_out, s1_fire)
800
801  val s2_pmp = WireInit(io.pmp)
802
803  val s2_prf    = s2_in.isPrefetch
804  val s2_hw_prf = s2_in.isHWPrefetch
805  val s2_ld_flow  = RegEnable(s1_ld_flow, s1_fire)
806
807  // exception that may cause load addr to be invalid / illegal
808  // if such exception happen, that inst and its exception info
809  // will be force writebacked to rob
810  val s2_exception_vec = WireInit(s2_in.uop.exceptionVec)
811  when (s2_ld_flow) {
812    when (!s2_in.lateKill) {
813      s2_exception_vec(loadAccessFault) := s2_in.uop.exceptionVec(loadAccessFault) || s2_pmp.ld
814      // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
815      when (s2_prf || s2_in.tlbMiss) {
816        s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
817      }
818    }
819  } .otherwise {
820    s2_exception_vec(storeAccessFault) := s2_in.uop.exceptionVec(storeAccessFault) || s2_pmp.st
821    when (s2_prf || s2_in.tlbMiss) {
822      s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
823    }
824  }
825  val s2_ld_exception = ExceptionNO.selectByFu(s2_exception_vec, LduCfg).asUInt.orR && s2_ld_flow
826  val s2_st_exception = ExceptionNO.selectByFu(s2_exception_vec, StaCfg).asUInt.orR && !s2_ld_flow
827  val s2_exception    = s2_ld_exception || s2_st_exception
828
829  val (s2_fwd_frm_d_chan, s2_fwd_data_frm_d_chan) = io.ldu_io.tl_d_channel.forward(s1_valid && s1_out.forward_tlDchannel, s1_out.mshrid, s1_out.paddr)
830  val (s2_fwd_data_valid, s2_fwd_frm_mshr, s2_fwd_data_frm_mshr) = io.ldu_io.forward_mshr.forward()
831  val s2_fwd_frm_d_chan_or_mshr = s2_fwd_data_valid && (s2_fwd_frm_d_chan || s2_fwd_frm_mshr)
832
833  // writeback access fault caused by ecc error / bus error
834  // * ecc data error is slow to generate, so we will not use it until load stage 3
835  // * in load stage 3, an extra signal io.load_error will be used to
836  val s2_actually_mmio = s2_pmp.mmio
837  val s2_ld_mmio       = !s2_prf &&
838                          s2_actually_mmio &&
839                         !s2_exception &&
840                         !s2_in.tlbMiss &&
841                         s2_ld_flow
842  val s2_st_mmio       = !s2_prf &&
843                          (RegNext(s1_mmio) || s2_pmp.mmio) &&
844                         !s2_exception &&
845                         !s2_in.tlbMiss &&
846                         !s2_ld_flow
847  val s2_st_atomic     = !s2_prf &&
848                          (RegNext(s1_mmio) || s2_pmp.atomic) &&
849                         !s2_exception &&
850                         !s2_in.tlbMiss &&
851                         !s2_ld_flow
852  val s2_full_fwd      = Wire(Bool())
853  val s2_mem_amb       = s2_in.uop.storeSetHit &&
854                         io.ldu_io.lsq.forward.addrInvalid
855
856  val s2_tlb_miss      = s2_in.tlbMiss
857  val s2_fwd_fail      = io.ldu_io.lsq.forward.dataInvalid
858  val s2_dcache_miss   = io.ldu_io.dcache.resp.bits.miss &&
859                         !s2_fwd_frm_d_chan_or_mshr &&
860                         !s2_full_fwd
861
862  val s2_mq_nack       = io.ldu_io.dcache.s2_mq_nack &&
863                         !s2_fwd_frm_d_chan_or_mshr &&
864                         !s2_full_fwd
865
866  val s2_bank_conflict = io.ldu_io.dcache.s2_bank_conflict &&
867                         !s2_fwd_frm_d_chan_or_mshr &&
868                         !s2_full_fwd
869
870  val s2_wpu_pred_fail = io.ldu_io.dcache.s2_wpu_pred_fail &&
871                        !s2_fwd_frm_d_chan_or_mshr &&
872                        !s2_full_fwd
873
874  val s2_rar_nack      = io.ldu_io.lsq.ldld_nuke_query.req.valid &&
875                         !io.ldu_io.lsq.ldld_nuke_query.req.ready
876
877  val s2_raw_nack      = io.ldu_io.lsq.stld_nuke_query.req.valid &&
878                         !io.ldu_io.lsq.stld_nuke_query.req.ready
879
880  // st-ld violation query
881  //  NeedFastRecovery Valid when
882  //  1. Fast recovery query request Valid.
883  //  2. Load instruction is younger than requestors(store instructions).
884  //  3. Physical address match.
885  //  4. Data contains.
886  val s2_nuke = VecInit((0 until StorePipelineWidth).map(w => {
887                        io.ldu_io.stld_nuke_query(w).valid && // query valid
888                        isAfter(s2_in.uop.robIdx, io.ldu_io.stld_nuke_query(w).bits.robIdx) && // older store
889                        // TODO: Fix me when vector instruction
890                        (s2_in.paddr(PAddrBits-1, 3) === io.ldu_io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3)) && // paddr match
891                        (s2_in.mask & io.ldu_io.stld_nuke_query(w).bits.mask).orR // data mask contain
892                      })).asUInt.orR && s2_ld_flow || s2_in.rep_info.nuke
893
894  val s2_cache_handled   = io.ldu_io.dcache.resp.bits.handled
895  val s2_cache_tag_error = RegNext(io.csrCtrl.cache_error_enable) &&
896                           io.ldu_io.dcache.resp.bits.tag_error
897
898  val s2_troublem        = !s2_exception &&
899                           !s2_ld_mmio &&
900                           !s2_prf &&
901                           !s2_in.lateKill &&
902                           s2_ld_flow
903
904  io.ldu_io.dcache.resp.ready := true.B
905  io.stu_io.dcache.resp.ready := true.B
906  val s2_dcache_should_resp = !(s2_in.tlbMiss || s2_exception || s2_ld_mmio || s2_prf || s2_in.lateKill) && s2_ld_flow
907  assert(!(s2_valid && (s2_dcache_should_resp && !io.ldu_io.dcache.resp.valid)), "DCache response got lost")
908
909  // fast replay require
910  val s2_dcache_fast_rep = (s2_mq_nack || !s2_dcache_miss && (s2_bank_conflict || s2_wpu_pred_fail))
911  val s2_nuke_fast_rep   = !s2_mq_nack &&
912                           !s2_dcache_miss &&
913                           !s2_bank_conflict &&
914                           !s2_wpu_pred_fail &&
915                           !s2_rar_nack &&
916                           !s2_raw_nack &&
917                           s2_nuke
918
919  val s2_fast_rep = !s2_mem_amb &&
920                    !s2_tlb_miss &&
921                    !s2_fwd_fail &&
922                    (s2_dcache_fast_rep || s2_nuke_fast_rep) &&
923                    s2_troublem
924
925  // need allocate new entry
926  val s2_can_query = !s2_mem_amb &&
927                     !s2_tlb_miss  &&
928                     !s2_fwd_fail &&
929                     !s2_dcache_fast_rep &&
930                     s2_troublem
931
932  val s2_data_fwded = s2_dcache_miss && (s2_full_fwd || s2_cache_tag_error)
933
934  // ld-ld violation require
935  io.ldu_io.lsq.ldld_nuke_query.req.valid           := s2_valid && s2_can_query
936  io.ldu_io.lsq.ldld_nuke_query.req.bits.uop        := s2_in.uop
937  io.ldu_io.lsq.ldld_nuke_query.req.bits.mask       := s2_in.mask
938  io.ldu_io.lsq.ldld_nuke_query.req.bits.paddr      := s2_in.paddr
939  io.ldu_io.lsq.ldld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
940
941  // st-ld violation require
942  io.ldu_io.lsq.stld_nuke_query.req.valid           := s2_valid && s2_can_query
943  io.ldu_io.lsq.stld_nuke_query.req.bits.uop        := s2_in.uop
944  io.ldu_io.lsq.stld_nuke_query.req.bits.mask       := s2_in.mask
945  io.ldu_io.lsq.stld_nuke_query.req.bits.paddr      := s2_in.paddr
946  io.ldu_io.lsq.stld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
947
948  // merge forward result
949  // lsq has higher priority than sbuffer
950  val s2_fwd_mask = Wire(Vec((VLEN/8), Bool()))
951  val s2_fwd_data = Wire(Vec((VLEN/8), UInt(8.W)))
952  s2_full_fwd := ((~s2_fwd_mask.asUInt).asUInt & s2_in.mask) === 0.U && !io.ldu_io.lsq.forward.dataInvalid
953  // generate XLEN/8 Muxs
954  for (i <- 0 until VLEN / 8) {
955    s2_fwd_mask(i) := io.ldu_io.lsq.forward.forwardMask(i) || io.ldu_io.sbuffer.forwardMask(i)
956    s2_fwd_data(i) := Mux(io.ldu_io.lsq.forward.forwardMask(i), io.ldu_io.lsq.forward.forwardData(i), io.ldu_io.sbuffer.forwardData(i))
957  }
958
959  XSDebug(s2_fire && s2_ld_flow, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
960    s2_in.uop.pc,
961    io.ldu_io.lsq.forward.forwardData.asUInt, io.ldu_io.lsq.forward.forwardMask.asUInt,
962    s2_in.forwardData.asUInt, s2_in.forwardMask.asUInt
963  )
964
965  //
966  s2_out                  := s2_in
967  s2_out.data             := 0.U // data will be generated in load s3
968  s2_out.uop.fpWen        := s2_in.uop.fpWen && !s2_exception && s2_ld_flow
969  s2_out.mmio             := s2_ld_mmio || s2_st_mmio
970  s2_out.atomic           := s2_st_atomic
971  s2_out.uop.flushPipe    := false.B
972  s2_out.uop.exceptionVec := s2_exception_vec
973  s2_out.forwardMask      := s2_fwd_mask
974  s2_out.forwardData      := s2_fwd_data
975  s2_out.handledByMSHR    := s2_cache_handled
976  s2_out.miss             := s2_dcache_miss && s2_troublem
977  s2_out.feedbacked       := io.feedback_fast.valid && !io.feedback_fast.bits.hit
978
979  // Generate replay signal caused by:
980  // * st-ld violation check
981  // * tlb miss
982  // * dcache replay
983  // * forward data invalid
984  // * dcache miss
985  s2_out.rep_info.mem_amb         := s2_mem_amb && s2_troublem
986  s2_out.rep_info.tlb_miss        := s2_tlb_miss && s2_troublem
987  s2_out.rep_info.fwd_fail        := s2_fwd_fail && s2_troublem
988  s2_out.rep_info.dcache_rep      := s2_mq_nack && s2_troublem
989  s2_out.rep_info.dcache_miss     := s2_dcache_miss && s2_troublem
990  s2_out.rep_info.bank_conflict   := s2_bank_conflict && s2_troublem
991  s2_out.rep_info.wpu_fail        := s2_wpu_pred_fail && s2_troublem
992  s2_out.rep_info.rar_nack        := s2_rar_nack && s2_troublem
993  s2_out.rep_info.raw_nack        := s2_raw_nack && s2_troublem
994  s2_out.rep_info.nuke            := s2_nuke && s2_troublem
995  s2_out.rep_info.full_fwd        := s2_data_fwded
996  s2_out.rep_info.data_inv_sq_idx := io.ldu_io.lsq.forward.dataInvalidSqIdx
997  s2_out.rep_info.addr_inv_sq_idx := io.ldu_io.lsq.forward.addrInvalidSqIdx
998  s2_out.rep_info.rep_carry       := io.ldu_io.dcache.resp.bits.replayCarry
999  s2_out.rep_info.mshr_id         := io.ldu_io.dcache.resp.bits.mshr_id
1000  s2_out.rep_info.last_beat       := s2_in.paddr(log2Up(refillBytes))
1001  s2_out.rep_info.debug           := s2_in.uop.debugInfo
1002
1003  // if forward fail, replay this inst from fetch
1004  val debug_fwd_fail_rep = s2_fwd_fail && !s2_troublem && !s2_in.tlbMiss
1005  // if ld-ld violation is detected, replay from this inst from fetch
1006  val debug_ldld_nuke_rep = false.B // s2_ldld_violation && !s2_ld_mmio && !s2_is_prefetch && !s2_in.tlbMiss
1007  // io.out.bits.uop.replayInst := false.B
1008
1009  // to be removed
1010  val s2_ld_need_fb = !s2_in.isLoadReplay &&      // already feedbacked
1011                      io.ldu_io.lq_rep_full &&           // LoadQueueReplay is full
1012                      s2_out.rep_info.need_rep && // need replay
1013                      !s2_exception &&            // no exception is triggered
1014                      !s2_hw_prf                  // not hardware prefetch
1015  val s2_st_need_fb = !s2_ld_flow && !s2_hw_prf
1016  io.feedback_fast.valid                 := s2_valid && (s2_ld_need_fb || s2_st_need_fb)
1017  io.feedback_fast.bits.hit              := Mux(s2_ld_flow, false.B, !s2_tlb_miss)
1018  io.feedback_fast.bits.flushState       := s2_in.ptwBack
1019  io.feedback_fast.bits.robIdx           := s2_in.uop.robIdx
1020  io.feedback_fast.bits.sourceType       := Mux(s2_ld_flow, RSFeedbackType.lrqFull, RSFeedbackType.tlbMiss)
1021  io.feedback_fast.bits.dataInvalidSqIdx := DontCare
1022
1023  io.stu_io.lsq_replenish := s2_out
1024  io.stu_io.lsq_replenish.miss := io.ldu_io.dcache.resp.fire && io.ldu_io.dcache.resp.bits.miss
1025
1026  io.ldu_io.ldCancel.ld1Cancel.valid := s2_valid && (
1027    (s2_out.rep_info.need_rep && s2_out.isFirstIssue) ||                // exe fail and issued from IQ
1028    s2_ld_mmio                                                             // is mmio
1029  ) && s2_ld_flow
1030  io.ldu_io.ldCancel.ld1Cancel.bits := s2_out.deqPortIdx
1031
1032  // fast wakeup
1033  io.ldu_io.fast_uop.valid := RegNext(
1034    !io.ldu_io.dcache.s1_disable_fast_wakeup &&
1035    s1_valid &&
1036    !s1_kill &&
1037    !io.tlb.resp.bits.miss &&
1038    !io.ldu_io.lsq.forward.dataInvalidFast
1039  ) && (s2_valid && !s2_out.rep_info.need_rep && !s2_ld_mmio && s2_ld_flow)
1040  io.ldu_io.fast_uop.bits := RegNext(s1_out.uop)
1041
1042  //
1043  io.ldu_io.s2_ptr_chasing                    := RegEnable(s1_try_ptr_chasing && !s1_cancel_ptr_chasing, false.B, s1_fire)
1044
1045  // prefetch train
1046  io.prefetch_train.valid              := s2_valid && !s2_actually_mmio && !s2_in.tlbMiss
1047  io.prefetch_train.bits.fromLsPipelineBundle(s2_in)
1048  io.prefetch_train.bits.miss          := Mux(s2_ld_flow, io.ldu_io.dcache.resp.bits.miss, io.stu_io.dcache.resp.bits.miss) // TODO: use trace with bank conflict?
1049  io.prefetch_train.bits.meta_prefetch := Mux(s2_ld_flow, io.ldu_io.dcache.resp.bits.meta_prefetch, false.B)
1050  io.prefetch_train.bits.meta_access   := Mux(s2_ld_flow, io.ldu_io.dcache.resp.bits.meta_access, false.B)
1051
1052  io.prefetch_train_l1.valid              := s2_valid && !s2_actually_mmio && s2_ld_flow
1053  io.prefetch_train_l1.bits.fromLsPipelineBundle(s2_in)
1054  io.prefetch_train_l1.bits.miss          := io.ldu_io.dcache.resp.bits.miss
1055  io.prefetch_train_l1.bits.meta_prefetch := io.ldu_io.dcache.resp.bits.meta_prefetch
1056  io.prefetch_train_l1.bits.meta_access   := io.ldu_io.dcache.resp.bits.meta_access
1057  if (env.FPGAPlatform){
1058    io.ldu_io.dcache.s0_pc := DontCare
1059    io.ldu_io.dcache.s1_pc := DontCare
1060    io.ldu_io.dcache.s2_pc := DontCare
1061  }else{
1062    io.ldu_io.dcache.s0_pc := s0_out.uop.pc
1063    io.ldu_io.dcache.s1_pc := s1_out.uop.pc
1064    io.ldu_io.dcache.s2_pc := s2_out.uop.pc
1065  }
1066  io.ldu_io.dcache.s2_kill := s2_pmp.ld  || s2_actually_mmio || s2_kill
1067  io.stu_io.dcache.s2_kill := s2_pmp.st || s2_actually_mmio || s2_kill
1068  io.stu_io.dcache.s2_pc := s2_out.uop.pc
1069
1070  val s1_ld_left_fire = s1_valid && !s1_kill && s2_ready && s1_ld_flow
1071  val s2_ld_valid_dup = RegInit(0.U(6.W))
1072  s2_ld_valid_dup := 0x0.U(6.W)
1073  when (s1_ld_left_fire && !s1_out.isHWPrefetch && s1_ld_flow) { s2_ld_valid_dup := 0x3f.U(6.W) }
1074  when (s1_kill || s1_out.isHWPrefetch || !s1_ld_flow) { s2_ld_valid_dup := 0x0.U(6.W) }
1075  assert(RegNext((s2_valid === s2_ld_valid_dup(0)) || RegNext(s1_out.isHWPrefetch) || RegNext(!s1_ld_flow)))
1076
1077  // Pipeline
1078  // --------------------------------------------------------------------------------
1079  // stage 3
1080  // --------------------------------------------------------------------------------
1081  // writeback and update load queue
1082  val s3_valid        = RegNext(s2_valid && !s2_out.isHWPrefetch && !s2_out.uop.robIdx.needFlush(io.redirect))
1083  val s3_in           = RegEnable(s2_out, s2_fire)
1084  val s3_out          = Wire(Valid(new MemExuOutput))
1085  val s3_dcache_rep   = RegEnable(s2_dcache_fast_rep && s2_troublem, false.B, s2_fire)
1086  val s3_ld_valid_dup = RegEnable(s2_ld_valid_dup, s2_fire)
1087  val s3_fast_rep     = Wire(Bool())
1088  val s3_ld_flow      = RegNext(s2_ld_flow)
1089  val s3_troublem     = RegNext(s2_troublem)
1090  val s3_kill         = s3_in.uop.robIdx.needFlush(io.redirect)
1091  s3_ready := !s3_valid || s3_kill || sx_can_go
1092
1093  // forwrad last beat
1094  val (s3_fwd_frm_d_chan, s3_fwd_data_frm_d_chan) = io.ldu_io.tl_d_channel.forward(s2_valid && s2_out.forward_tlDchannel, s2_out.mshrid, s2_out.paddr)
1095  val s3_fwd_data_valid = RegEnable(s2_fwd_data_valid, false.B, s2_valid)
1096  val s3_fwd_frm_d_chan_valid = (s3_fwd_frm_d_chan && s3_fwd_data_valid) && s3_ld_flow
1097
1098
1099  // s3 load fast replay
1100  io.ldu_io.fast_rep_out.valid := s3_valid &&
1101                                  s3_fast_rep &&
1102                                  !s3_in.uop.robIdx.needFlush(io.redirect) &&
1103                                  s3_ld_flow
1104  io.ldu_io.fast_rep_out.bits := s3_in
1105
1106  io.ldu_io.lsq.ldin.valid := s3_valid &&
1107                              (!s3_fast_rep || !io.ldu_io.fast_rep_out.ready) &&
1108                              !s3_in.feedbacked &&
1109                              !s3_in.lateKill &&
1110                              s3_ld_flow
1111  io.ldu_io.lsq.ldin.bits := s3_in
1112  io.ldu_io.lsq.ldin.bits.miss := s3_in.miss && !s3_fwd_frm_d_chan_valid
1113
1114  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1115  io.ldu_io.lsq.ldin.bits.data_wen_dup := s3_ld_valid_dup.asBools
1116  io.ldu_io.lsq.ldin.bits.replacementUpdated := io.ldu_io.dcache.resp.bits.replacementUpdated
1117  io.ldu_io.lsq.ldin.bits.missDbUpdated := RegNext(s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated)
1118
1119  val s3_dly_ld_err =
1120    if (EnableAccurateLoadError) {
1121      (s3_in.lateKill || io.ldu_io.dcache.resp.bits.error_delayed) && RegNext(io.csrCtrl.cache_error_enable)
1122    } else {
1123      WireInit(false.B)
1124    }
1125  io.ldu_io.s3_dly_ld_err := false.B // s3_dly_ld_err && s3_valid
1126  io.ldu_io.fast_rep_out.bits.delayedLoadError := s3_dly_ld_err
1127  io.ldu_io.lsq.ldin.bits.dcacheRequireReplay  := s3_dcache_rep
1128
1129  val s3_vp_match_fail = RegNext(io.ldu_io.lsq.forward.matchInvalid || io.ldu_io.sbuffer.matchInvalid) && s3_troublem
1130  val s3_ldld_rep_inst =
1131      io.ldu_io.lsq.ldld_nuke_query.resp.valid &&
1132      io.ldu_io.lsq.ldld_nuke_query.resp.bits.rep_frm_fetch &&
1133      RegNext(io.csrCtrl.ldld_vio_check_enable)
1134
1135  val s3_rep_info = WireInit(s3_in.rep_info)
1136  s3_rep_info.dcache_miss   := s3_in.rep_info.dcache_miss && !s3_fwd_frm_d_chan_valid && s3_troublem
1137  val s3_rep_frm_fetch = s3_vp_match_fail || s3_ldld_rep_inst
1138  val s3_sel_rep_cause = PriorityEncoderOH(s3_rep_info.cause.asUInt)
1139  val s3_force_rep     = s3_sel_rep_cause(LoadReplayCauses.C_TM) &&
1140                         !s3_in.uop.exceptionVec(loadAddrMisaligned) &&
1141                         s3_troublem
1142
1143  val s3_ld_exception = ExceptionNO.selectByFu(s3_in.uop.exceptionVec, LduCfg).asUInt.orR && s3_ld_flow
1144  val s3_st_exception = ExceptionNO.selectByFu(s3_in.uop.exceptionVec, StaCfg).asUInt.orR && !s3_ld_flow
1145  val s3_exception    = s3_ld_exception || s3_st_exception
1146  when ((s3_ld_exception || s3_dly_ld_err || s3_rep_frm_fetch) && !s3_force_rep) {
1147    io.ldu_io.lsq.ldin.bits.rep_info.cause := 0.U.asTypeOf(s3_rep_info.cause.cloneType)
1148  } .otherwise {
1149    io.ldu_io.lsq.ldin.bits.rep_info.cause := VecInit(s3_sel_rep_cause.asBools)
1150  }
1151
1152  // Int flow, if hit, will be writebacked at s3
1153  s3_out.valid                := s3_valid &&
1154                                (!s3_ld_flow && !s3_in.feedbacked || !io.ldu_io.lsq.ldin.bits.rep_info.need_rep) && !s3_in.mmio
1155  s3_out.bits.uop             := s3_in.uop
1156  s3_out.bits.uop.exceptionVec(loadAccessFault) := (s3_dly_ld_err  || s3_in.uop.exceptionVec(loadAccessFault)) && s3_ld_flow
1157  s3_out.bits.uop.replayInst := s3_rep_frm_fetch
1158  s3_out.bits.data            := s3_in.data
1159  s3_out.bits.debug.isMMIO    := s3_in.mmio
1160  s3_out.bits.debug.isPerfCnt := false.B
1161  s3_out.bits.debug.paddr     := s3_in.paddr
1162  s3_out.bits.debug.vaddr     := s3_in.vaddr
1163
1164  when (s3_force_rep) {
1165    s3_out.bits.uop.exceptionVec := 0.U.asTypeOf(s3_in.uop.exceptionVec.cloneType)
1166  }
1167
1168  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1169  io.ldu_io.lsq.ldin.bits.uop := s3_out.bits.uop
1170
1171  val s3_revoke = s3_exception || io.ldu_io.lsq.ldin.bits.rep_info.need_rep
1172  io.ldu_io.lsq.ldld_nuke_query.revoke := s3_revoke
1173  io.ldu_io.lsq.stld_nuke_query.revoke := s3_revoke
1174
1175  // feedback slow
1176  s3_fast_rep := RegNext(s2_fast_rep) &&
1177                 !s3_in.feedbacked &&
1178                 !s3_in.lateKill &&
1179                 !s3_rep_frm_fetch &&
1180                 !s3_exception
1181
1182  val s3_fb_no_waiting = !s3_in.isLoadReplay && !(s3_fast_rep && io.ldu_io.fast_rep_out.ready) && !s3_in.feedbacked
1183
1184  //
1185  io.feedback_slow.valid                 := s3_valid && !s3_in.uop.robIdx.needFlush(io.redirect) && s3_fb_no_waiting && s3_ld_flow
1186  io.feedback_slow.bits.hit              := !io.ldu_io.lsq.ldin.bits.rep_info.need_rep || io.ldu_io.lsq.ldin.ready
1187  io.feedback_slow.bits.flushState       := s3_in.ptwBack
1188  io.feedback_slow.bits.robIdx           := s3_in.uop.robIdx
1189  io.feedback_slow.bits.sourceType       := RSFeedbackType.lrqFull
1190  io.feedback_slow.bits.dataInvalidSqIdx := DontCare
1191
1192  io.ldu_io.ldCancel.ld2Cancel.valid := s3_valid && (
1193    (io.ldu_io.lsq.ldin.bits.rep_info.need_rep && s3_in.isFirstIssue) ||
1194    s3_in.mmio
1195  ) && s3_ld_flow
1196  io.ldu_io.ldCancel.ld2Cancel.bits := s3_in.deqPortIdx
1197
1198  // data from dcache hit
1199  val s3_ld_raw_data_frm_cache = Wire(new LoadDataFromDcacheBundle)
1200  s3_ld_raw_data_frm_cache.respDcacheData       := io.ldu_io.dcache.resp.bits.data_delayed
1201  s3_ld_raw_data_frm_cache.forwardMask          := RegEnable(s2_fwd_mask, s2_valid)
1202  s3_ld_raw_data_frm_cache.forwardData          := RegEnable(s2_fwd_data, s2_valid)
1203  s3_ld_raw_data_frm_cache.uop                  := RegEnable(s2_out.uop, s2_valid)
1204  s3_ld_raw_data_frm_cache.addrOffset           := RegEnable(s2_out.paddr(3, 0), s2_valid)
1205  s3_ld_raw_data_frm_cache.forward_D            := RegEnable(s2_fwd_frm_d_chan, false.B, s2_valid) || s3_fwd_frm_d_chan_valid
1206  s3_ld_raw_data_frm_cache.forwardData_D        := Mux(s3_fwd_frm_d_chan_valid, s3_fwd_data_frm_d_chan, RegEnable(s2_fwd_data_frm_d_chan, s2_valid))
1207  s3_ld_raw_data_frm_cache.forward_mshr         := RegEnable(s2_fwd_frm_mshr, false.B, s2_valid)
1208  s3_ld_raw_data_frm_cache.forwardData_mshr     := RegEnable(s2_fwd_data_frm_mshr, s2_valid)
1209  s3_ld_raw_data_frm_cache.forward_result_valid := RegEnable(s2_fwd_data_valid, false.B, s2_valid)
1210
1211  val s3_merged_data_frm_cache = s3_ld_raw_data_frm_cache.mergedData()
1212  val s3_picked_data_frm_cache = LookupTree(s3_ld_raw_data_frm_cache.addrOffset, List(
1213    "b0000".U -> s3_merged_data_frm_cache(63,    0),
1214    "b0001".U -> s3_merged_data_frm_cache(63,    8),
1215    "b0010".U -> s3_merged_data_frm_cache(63,   16),
1216    "b0011".U -> s3_merged_data_frm_cache(63,   24),
1217    "b0100".U -> s3_merged_data_frm_cache(63,   32),
1218    "b0101".U -> s3_merged_data_frm_cache(63,   40),
1219    "b0110".U -> s3_merged_data_frm_cache(63,   48),
1220    "b0111".U -> s3_merged_data_frm_cache(63,   56),
1221    "b1000".U -> s3_merged_data_frm_cache(127,  64),
1222    "b1001".U -> s3_merged_data_frm_cache(127,  72),
1223    "b1010".U -> s3_merged_data_frm_cache(127,  80),
1224    "b1011".U -> s3_merged_data_frm_cache(127,  88),
1225    "b1100".U -> s3_merged_data_frm_cache(127,  96),
1226    "b1101".U -> s3_merged_data_frm_cache(127, 104),
1227    "b1110".U -> s3_merged_data_frm_cache(127, 112),
1228    "b1111".U -> s3_merged_data_frm_cache(127, 120)
1229  ))
1230  val s3_ld_data_frm_cache = rdataHelper(s3_ld_raw_data_frm_cache.uop, s3_picked_data_frm_cache)
1231
1232  // FIXME: add 1 cycle delay ?
1233  io.ldout.bits      := s3_out.bits
1234  io.ldout.bits.data := s3_ld_data_frm_cache
1235  io.ldout.valid     := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) && s3_ld_flow
1236
1237  // for uncache
1238  io.ldu_io.lsq.uncache.ready := true.B
1239
1240  // fast load to load forward
1241  io.ldu_io.l2l_fwd_out.valid      := s3_out.valid && !s3_in.lateKill && s3_ld_flow
1242  io.ldu_io.l2l_fwd_out.data       := s3_ld_data_frm_cache
1243  io.ldu_io.l2l_fwd_out.dly_ld_err := s3_dly_ld_err // ecc delayed error
1244
1245  // hybrid unit writeback to rob
1246  // delay params
1247  val SelectGroupSize   = RollbackGroupSize
1248  val lgSelectGroupSize = log2Ceil(SelectGroupSize)
1249  val TotalSelectCycles = scala.math.ceil(log2Ceil(LoadQueueRAWSize).toFloat / lgSelectGroupSize).toInt + 1
1250  val TotalDelayCycles  = TotalSelectCycles - 2
1251
1252  // writeback
1253  val sx_valid = Wire(Vec(TotalDelayCycles + 1, Bool()))
1254  val sx_ready = Wire(Vec(TotalDelayCycles + 1, Bool()))
1255  val sx_in    = Wire(Vec(TotalDelayCycles + 1, new MemExuOutput))
1256
1257  sx_can_go := sx_ready.head
1258  for (i <- 0 until TotalDelayCycles + 1) {
1259    if (i == 0) {
1260      sx_valid(i) := s3_valid &&
1261                    !s3_ld_flow &&
1262                    !s3_in.feedbacked &&
1263                    !s3_in.mmio
1264      sx_in(i)    := s3_out.bits
1265      sx_ready(i) := !s3_valid(i) || sx_in(i).uop.robIdx.needFlush(io.redirect) || (if (TotalDelayCycles == 0) io.stout.ready else sx_ready(i+1))
1266    } else {
1267      val cur_kill   = sx_in(i).uop.robIdx.needFlush(io.redirect)
1268      val cur_can_go = (if (i == TotalDelayCycles) io.stout.ready else sx_ready(i+1))
1269      val cur_fire   = sx_valid(i) && !cur_kill && cur_can_go
1270      val prev_fire  = sx_valid(i-1) && !sx_in(i-1).uop.robIdx.needFlush(io.redirect) && sx_ready(i)
1271
1272      sx_ready(i) := !sx_valid(i) || cur_kill || (if (i == TotalDelayCycles) io.stout.ready else sx_ready(i+1))
1273      val sx_valid_can_go = prev_fire || cur_fire || cur_kill
1274      sx_valid(i) := RegEnable(Mux(prev_fire, true.B, false.B), sx_valid_can_go)
1275      sx_in(i) := RegEnable(sx_in(i-1), prev_fire)
1276    }
1277  }
1278
1279  val sx_last_valid = sx_valid.takeRight(1).head
1280  val sx_last_ready = sx_ready.takeRight(1).head
1281  val sx_last_in    = sx_in.takeRight(1).head
1282
1283  sx_last_ready  := !sx_last_valid || sx_last_in.uop.robIdx.needFlush(io.redirect) || io.stout.ready
1284  io.stout.valid := sx_last_valid && !sx_last_in.uop.robIdx.needFlush(io.redirect)
1285  io.stout.bits  := sx_last_in
1286
1287   // trigger
1288  val ld_trigger = FuType.isLoad(io.ldout.bits.uop.fuType)
1289  val last_valid_data = RegEnable(io.ldout.bits.data, io.stout.fire)
1290  val hit_ld_addr_trig_hit_vec = Wire(Vec(3, Bool()))
1291  val lq_ld_addr_trig_hit_vec = RegNext(io.ldu_io.lsq.trigger.lqLoadAddrTriggerHitVec)
1292  (0 until 3).map{i => {
1293    val tdata2    = RegNext(RegNext(io.ldu_io.trigger(i).tdata2))
1294    val matchType = RegNext(RegNext(io.ldu_io.trigger(i).matchType))
1295    val tEnable   = RegNext(RegNext(io.ldu_io.trigger(i).tEnable))
1296
1297    hit_ld_addr_trig_hit_vec(i)        := TriggerCmp(RegNext(s3_in.vaddr), tdata2, matchType, tEnable)
1298    io.ldu_io.trigger(i).addrHit       := Mux(io.ldout.valid && ld_trigger, hit_ld_addr_trig_hit_vec(i), lq_ld_addr_trig_hit_vec(i))
1299    io.ldu_io.trigger(i).lastDataHit   := TriggerCmp(last_valid_data, tdata2, matchType, tEnable)
1300  }}
1301  io.ldu_io.lsq.trigger.hitLoadAddrTriggerHitVec := hit_ld_addr_trig_hit_vec
1302
1303  // FIXME: please move this part to LoadQueueReplay
1304  io.ldu_io.debug_ls := DontCare
1305  io.stu_io.debug_ls := DontCare
1306  io.stu_io.debug_ls.s1.isTlbFirstMiss := io.tlb.resp.valid && io.tlb.resp.bits.miss && io.tlb.resp.bits.debug.isFirstIssue && !s1_in.isHWPrefetch && !s1_ld_flow
1307  io.stu_io.debug_ls.s1_robIdx := s1_in.uop.robIdx.value
1308
1309 // Topdown
1310  io.ldu_io.lsTopdownInfo.s1.robIdx          := s1_in.uop.robIdx.value
1311  io.ldu_io.lsTopdownInfo.s1.vaddr_valid     := s1_valid && s1_in.hasROBEntry
1312  io.ldu_io.lsTopdownInfo.s1.vaddr_bits      := s1_vaddr
1313  io.ldu_io.lsTopdownInfo.s2.robIdx          := s2_in.uop.robIdx.value
1314  io.ldu_io.lsTopdownInfo.s2.paddr_valid     := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss
1315  io.ldu_io.lsTopdownInfo.s2.paddr_bits      := s2_in.paddr
1316  io.ldu_io.lsTopdownInfo.s2.first_real_miss := io.ldu_io.dcache.resp.bits.real_miss
1317  io.ldu_io.lsTopdownInfo.s2.cache_miss_en   := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated
1318
1319  // perf cnt
1320  XSPerfAccumulate("s0_in_valid",                  io.lsin.valid)
1321  XSPerfAccumulate("s0_in_block",                  io.lsin.valid && !io.lsin.fire)
1322  XSPerfAccumulate("s0_in_fire_first_issue",       s0_valid && s0_isFirstIssue)
1323  XSPerfAccumulate("s0_lsq_fire_first_issue",      io.ldu_io.replay.fire)
1324  XSPerfAccumulate("s0_ldu_fire_first_issue",      io.lsin.fire && s0_isFirstIssue)
1325  XSPerfAccumulate("s0_fast_replay_issue",         io.ldu_io.fast_rep_in.fire)
1326  XSPerfAccumulate("s0_stall_out",                 s0_valid && !s0_can_go)
1327  XSPerfAccumulate("s0_stall_ld_dcache",           s0_valid && !io.ldu_io.dcache.req.ready)
1328  XSPerfAccumulate("s0_stall_st_dcache",           s0_valid && !io.stu_io.dcache.req.ready)
1329  XSPerfAccumulate("s0_addr_spec_success",         s0_fire && s0_vaddr(VAddrBits-1, 12) === io.lsin.bits.src(0)(VAddrBits-1, 12))
1330  XSPerfAccumulate("s0_addr_spec_failed",          s0_fire && s0_vaddr(VAddrBits-1, 12) =/= io.lsin.bits.src(0)(VAddrBits-1, 12))
1331  XSPerfAccumulate("s0_addr_spec_success_once",    s0_fire && s0_vaddr(VAddrBits-1, 12) === io.lsin.bits.src(0)(VAddrBits-1, 12) && s0_isFirstIssue)
1332  XSPerfAccumulate("s0_addr_spec_failed_once",     s0_fire && s0_vaddr(VAddrBits-1, 12) =/= io.lsin.bits.src(0)(VAddrBits-1, 12) && s0_isFirstIssue)
1333  XSPerfAccumulate("s0_forward_tl_d_channel",      s0_out.forward_tlDchannel)
1334  XSPerfAccumulate("s0_hardware_prefetch_fire",    s0_fire && s0_hw_prf_select)
1335  XSPerfAccumulate("s0_software_prefetch_fire",    s0_fire && s0_prf && s0_int_iss_select)
1336  XSPerfAccumulate("s0_hardware_prefetch_blocked", io.ldu_io.prefetch_req.valid && !s0_hw_prf_select)
1337  XSPerfAccumulate("s0_hardware_prefetch_total",   io.ldu_io.prefetch_req.valid)
1338
1339  XSPerfAccumulate("s1_in_valid",                  s1_valid)
1340  XSPerfAccumulate("s1_in_fire",                   s1_fire)
1341  XSPerfAccumulate("s1_in_fire_first_issue",       s1_fire && s1_in.isFirstIssue)
1342  XSPerfAccumulate("s1_tlb_miss",                  s1_fire && s1_tlb_miss)
1343  XSPerfAccumulate("s1_tlb_miss_first_issue",      s1_fire && s1_tlb_miss && s1_in.isFirstIssue)
1344  XSPerfAccumulate("s1_stall_out",                 s1_valid && !s1_can_go)
1345  XSPerfAccumulate("s1_late_kill",                 s1_valid && s1_fast_rep_kill)
1346
1347  XSPerfAccumulate("s2_in_valid",                  s2_valid)
1348  XSPerfAccumulate("s2_in_fire",                   s2_fire)
1349  XSPerfAccumulate("s2_in_fire_first_issue",       s2_fire && s2_in.isFirstIssue)
1350  XSPerfAccumulate("s2_dcache_miss",               s2_fire && io.ldu_io.dcache.resp.bits.miss)
1351  XSPerfAccumulate("s2_dcache_miss_first_issue",   s2_fire && io.ldu_io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1352  XSPerfAccumulate("s2_dcache_real_miss_first_issue",   s2_fire && io.ldu_io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1353  XSPerfAccumulate("s2_full_forward",              s2_fire && s2_full_fwd)
1354  XSPerfAccumulate("s2_dcache_miss_full_forward",  s2_fire && s2_dcache_miss)
1355  XSPerfAccumulate("s2_fwd_frm_d_can",             s2_valid && s2_fwd_frm_d_chan)
1356  XSPerfAccumulate("s2_fwd_frm_d_chan_or_mshr",    s2_valid && s2_fwd_frm_d_chan_or_mshr)
1357  XSPerfAccumulate("s2_stall_out",                 s2_fire && !s2_can_go)
1358  XSPerfAccumulate("s2_prefetch",                  s2_fire && s2_prf)
1359  XSPerfAccumulate("s2_prefetch_ignored",          s2_fire && s2_prf && s2_mq_nack) // ignore prefetch for mshr full / miss req port conflict
1360  XSPerfAccumulate("s2_prefetch_miss",             s2_fire && s2_prf && io.ldu_io.dcache.resp.bits.miss) // prefetch req miss in l1
1361  XSPerfAccumulate("s2_prefetch_hit",              s2_fire && s2_prf && !io.ldu_io.dcache.resp.bits.miss) // prefetch req hit in l1
1362  XSPerfAccumulate("s2_prefetch_accept",           s2_fire && s2_prf && io.ldu_io.dcache.resp.bits.miss && !s2_mq_nack) // prefetch a missed line in l1, and l1 accepted it
1363  XSPerfAccumulate("s2_forward_req",               s2_fire && s2_in.forward_tlDchannel)
1364  XSPerfAccumulate("s2_successfully_forward_channel_D", s2_fire && s2_fwd_frm_d_chan && s2_fwd_data_valid)
1365  XSPerfAccumulate("s2_successfully_forward_mshr",      s2_fire && s2_fwd_frm_mshr && s2_fwd_data_valid)
1366
1367  XSPerfAccumulate("s3_fwd_frm_d_chan",            s3_valid && s3_fwd_frm_d_chan_valid)
1368
1369  XSPerfAccumulate("load_to_load_forward",                      s1_try_ptr_chasing && !s1_ptr_chasing_canceled)
1370  XSPerfAccumulate("load_to_load_forward_try",                  s1_try_ptr_chasing)
1371  XSPerfAccumulate("load_to_load_forward_fail",                 s1_cancel_ptr_chasing)
1372  XSPerfAccumulate("load_to_load_forward_fail_cancelled",       s1_cancel_ptr_chasing && s1_ptr_chasing_canceled)
1373  XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && s1_not_fast_match)
1374  XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",       s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && s1_fu_op_type_not_ld)
1375  XSPerfAccumulate("load_to_load_forward_fail_addr_align",      s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && !s1_fu_op_type_not_ld && s1_addr_misaligned)
1376  XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",    s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && !s1_fu_op_type_not_ld && !s1_addr_misaligned && s1_addr_mismatch)
1377
1378  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1379  // hardware performance counter
1380  val perfEvents = Seq(
1381    ("load_s0_in_fire         ", s0_fire                                                        ),
1382    ("load_to_load_forward    ", s1_fire && s1_try_ptr_chasing && !s1_ptr_chasing_canceled      ),
1383    ("stall_dcache            ", s0_valid && s0_can_go && !io.ldu_io.dcache.req.ready           ),
1384    ("load_s1_in_fire         ", s0_fire                                                        ),
1385    ("load_s1_tlb_miss        ", s1_fire && io.tlb.resp.bits.miss                               ),
1386    ("load_s2_in_fire         ", s1_fire                                                        ),
1387    ("load_s2_dcache_miss     ", s2_fire && io.ldu_io.dcache.resp.bits.miss                     ),
1388  )
1389  generatePerfEvent()
1390}