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