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