xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision d8aa3d57ee3367828b7a51544c0d78d331d3c295)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan.ExceptionNO._
25import xiangshan._
26import xiangshan.backend.fu.PMPRespBundle
27import xiangshan.backend.rob.DebugLsInfoBundle
28import xiangshan.cache._
29import xiangshan.cache.dcache.ReplayCarry
30import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
31
32class LoadToLsqFastIO(implicit p: Parameters) extends XSBundle {
33  val valid = Output(Bool())
34  val ld_ld_check_ok = Output(Bool())
35  val st_ld_check_ok = Output(Bool())
36  val cache_bank_no_conflict = Output(Bool())
37  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
38  val debug = Output(new PerfDebugInfo)
39
40  def needreplay: Bool = {
41    !ld_ld_check_ok || !st_ld_check_ok || !cache_bank_no_conflict
42  }
43}
44
45class LoadToLsqSlowIO(implicit p: Parameters) extends XSBundle with HasDCacheParameters {
46  val valid = Output(Bool())
47  val tlb_hited = Output(Bool())
48  val st_ld_check_ok = Output(Bool())
49  val cache_no_replay = Output(Bool())
50  val forward_data_valid = Output(Bool())
51  val cache_hited = Output(Bool())
52  val can_forward_full_data = Output(Bool())
53  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
54  val data_invalid_sq_idx = Output(UInt(log2Ceil(StoreQueueSize).W))
55  val replayCarry = Output(new ReplayCarry)
56  val miss_mshr_id = Output(UInt(log2Up(cfg.nMissEntries).W))
57  val data_in_last_beat = Output(Bool())
58  val debug = Output(new PerfDebugInfo)
59
60  def needreplay: Bool = {
61    !tlb_hited || !st_ld_check_ok || !cache_no_replay || !forward_data_valid || !cache_hited
62  }
63}
64
65class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
66  val loadIn = ValidIO(new LqWriteBundle)
67  val loadPaddrIn = ValidIO(new LqPaddrWriteBundle)
68  val loadVaddrIn = ValidIO(new LqVaddrWriteBundle)
69  val ldout = Flipped(DecoupledIO(new ExuOutput))
70  val ldRawData = Input(new LoadDataFromLQBundle)
71  val s2_load_data_forwarded = Output(Bool())
72  val s3_delayed_load_error = Output(Bool())
73  val s2_dcache_require_replay = Output(Bool())
74  val s3_replay_from_fetch = Output(Bool()) // update uop.ctrl.replayInst in load queue in s3
75  val forward = new PipeLoadForwardQueryIO
76  val loadViolationQuery = new LoadViolationQueryIO
77  val trigger = Flipped(new LqTriggerIO)
78
79  // for load replay
80  val replayFast = new LoadToLsqFastIO
81  val replaySlow = new LoadToLsqSlowIO
82}
83
84class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
85  // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
86  val data = UInt(XLEN.W)
87  val valid = Bool()
88}
89
90class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
91  val tdata2 = Input(UInt(64.W))
92  val matchType = Input(UInt(2.W))
93  val tEnable = Input(Bool()) // timing is calculated before this
94  val addrHit = Output(Bool())
95  val lastDataHit = Output(Bool())
96}
97
98// Load Pipeline Stage 0
99// Generate addr, use addr to query DCache and DTLB
100class LoadUnit_S0(implicit p: Parameters) extends XSModule with HasDCacheParameters{
101  val io = IO(new Bundle() {
102    val in = Flipped(Decoupled(new ExuInput))
103    val out = Decoupled(new LsPipelineBundle)
104    val prefetch_in = Flipped(ValidIO(new L1PrefetchReq))
105    val dtlbReq = DecoupledIO(new TlbReq)
106    val dcacheReq = DecoupledIO(new DCacheWordReq)
107    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
108    val isFirstIssue = Input(Bool())
109    val fastpath = Input(new LoadToLoadIO)
110    val s0_kill = Input(Bool())
111    // wire from lq to load pipeline
112    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
113
114    val s0_sqIdx = Output(new SqPtr)
115    // l2l
116    val l2lForward_select = Output(Bool())
117  })
118  require(LoadPipelineWidth == exuParameters.LduCnt)
119
120  val s0_vaddr = Wire(UInt(VAddrBits.W))
121  val s0_mask = Wire(UInt(8.W))
122  val s0_uop = Wire(new MicroOp)
123  val s0_isFirstIssue = Wire(Bool())
124  val s0_rsIdx = Wire(UInt(log2Up(IssQueSize).W))
125  val s0_sqIdx = Wire(new SqPtr)
126  val s0_replayCarry = Wire(new ReplayCarry) // way info for way predict related logic
127  // default value
128  s0_replayCarry.valid := false.B
129  s0_replayCarry.real_way_en := 0.U
130
131  io.s0_sqIdx := s0_sqIdx
132
133  val tryFastpath = WireInit(false.B)
134
135  // load flow select/gen
136  //
137  // src0: load replayed by LSQ (io.lsqOut)
138  // src1: hardware prefetch from prefetchor (high confidence) (io.prefetch)
139  // src2: int read / software prefetch first issue from RS (io.in)
140  // src3: vec read first issue from RS (TODO)
141  // src4: load try pointchaising when no issued or replayed load (io.fastpath)
142  // src5: hardware prefetch from prefetchor (high confidence) (io.prefetch)
143
144  // load flow source valid
145  val lfsrc0_loadReplay_valid = io.lsqOut.valid
146  val lfsrc1_highconfhwPrefetch_valid = io.prefetch_in.valid && io.prefetch_in.bits.confidence > 0.U
147  val lfsrc2_intloadFirstIssue_valid = io.in.valid // int flow first issue or software prefetch
148  val lfsrc3_vecloadFirstIssue_valid = WireInit(false.B) // TODO
149  val lfsrc4_l2lForward_valid = io.fastpath.valid
150  val lfsrc5_lowconfhwPrefetch_valid = io.prefetch_in.valid && io.prefetch_in.bits.confidence === 0.U
151  dontTouch(lfsrc0_loadReplay_valid)
152  dontTouch(lfsrc1_highconfhwPrefetch_valid)
153  dontTouch(lfsrc2_intloadFirstIssue_valid)
154  dontTouch(lfsrc3_vecloadFirstIssue_valid)
155  dontTouch(lfsrc4_l2lForward_valid)
156  dontTouch(lfsrc5_lowconfhwPrefetch_valid)
157
158  // load flow source ready
159  val lfsrc_loadReplay_ready = WireInit(true.B)
160  val lfsrc_highconfhwPrefetch_ready = !lfsrc0_loadReplay_valid
161  val lfsrc_intloadFirstIssue_ready = !lfsrc0_loadReplay_valid &&
162    !lfsrc1_highconfhwPrefetch_valid
163  val lfsrc_vecloadFirstIssue_ready = !lfsrc0_loadReplay_valid &&
164    !lfsrc1_highconfhwPrefetch_valid &&
165    !lfsrc2_intloadFirstIssue_valid
166  val lfsrc_l2lForward_ready = !lfsrc0_loadReplay_valid &&
167    !lfsrc1_highconfhwPrefetch_valid &&
168    !lfsrc2_intloadFirstIssue_valid &&
169    !lfsrc3_vecloadFirstIssue_valid
170  val lfsrc_lowconfhwPrefetch_ready = !lfsrc0_loadReplay_valid &&
171    !lfsrc1_highconfhwPrefetch_valid &&
172    !lfsrc2_intloadFirstIssue_valid &&
173    !lfsrc3_vecloadFirstIssue_valid &&
174    !lfsrc4_l2lForward_valid
175  dontTouch(lfsrc_loadReplay_ready)
176  dontTouch(lfsrc_highconfhwPrefetch_ready)
177  dontTouch(lfsrc_intloadFirstIssue_ready)
178  dontTouch(lfsrc_vecloadFirstIssue_ready)
179  dontTouch(lfsrc_l2lForward_ready)
180  dontTouch(lfsrc_lowconfhwPrefetch_ready)
181
182  // load flow source select (OH)
183  val lfsrc_loadReplay_select = lfsrc0_loadReplay_valid && lfsrc_loadReplay_ready
184  val lfsrc_hwprefetch_select = lfsrc_highconfhwPrefetch_ready && lfsrc1_highconfhwPrefetch_valid ||
185    lfsrc_lowconfhwPrefetch_ready && lfsrc5_lowconfhwPrefetch_valid
186  val lfsrc_intloadFirstIssue_select = lfsrc_intloadFirstIssue_ready && lfsrc2_intloadFirstIssue_valid
187  val lfsrc_vecloadFirstIssue_select = lfsrc_vecloadFirstIssue_ready && lfsrc3_vecloadFirstIssue_valid
188  val lfsrc_l2lForward_select = lfsrc_l2lForward_ready && lfsrc4_l2lForward_valid
189  assert(!lfsrc_vecloadFirstIssue_select) // to be added
190  dontTouch(lfsrc_loadReplay_select)
191  dontTouch(lfsrc_hwprefetch_select)
192  dontTouch(lfsrc_intloadFirstIssue_select)
193  dontTouch(lfsrc_vecloadFirstIssue_select)
194  dontTouch(lfsrc_l2lForward_select)
195
196  io.l2lForward_select := lfsrc_l2lForward_select
197
198  // s0_valid == ture iff there is a valid load flow in load_s0
199  val s0_valid = lfsrc0_loadReplay_valid ||
200    lfsrc1_highconfhwPrefetch_valid ||
201    lfsrc2_intloadFirstIssue_valid ||
202    lfsrc3_vecloadFirstIssue_valid ||
203    lfsrc4_l2lForward_valid ||
204    lfsrc5_lowconfhwPrefetch_valid
205
206  // prefetch related ctrl signal
207  val isPrefetch = WireInit(false.B)
208  val isPrefetchRead = WireInit(s0_uop.ctrl.fuOpType === LSUOpType.prefetch_r)
209  val isPrefetchWrite = WireInit(s0_uop.ctrl.fuOpType === LSUOpType.prefetch_w)
210  val isHWPrefetch = lfsrc_hwprefetch_select
211
212  // query DTLB
213  io.dtlbReq.valid := s0_valid
214  // hw prefetch addr does not need to be translated, give tlb paddr
215  io.dtlbReq.bits.vaddr := Mux(lfsrc_hwprefetch_select, io.prefetch_in.bits.paddr, s0_vaddr)
216  io.dtlbReq.bits.cmd := Mux(isPrefetch,
217    Mux(isPrefetchWrite, TlbCmd.write, TlbCmd.read),
218    TlbCmd.read
219  )
220  io.dtlbReq.bits.size := LSUOpType.size(s0_uop.ctrl.fuOpType)
221  io.dtlbReq.bits.kill := DontCare
222  io.dtlbReq.bits.memidx.is_ld := true.B
223  io.dtlbReq.bits.memidx.is_st := false.B
224  io.dtlbReq.bits.memidx.idx := s0_uop.lqIdx.value
225  io.dtlbReq.bits.debug.robIdx := s0_uop.robIdx
226  // hw prefetch addr does not need to be translated
227  io.dtlbReq.bits.no_translate := lfsrc_hwprefetch_select
228  io.dtlbReq.bits.debug.pc := s0_uop.cf.pc
229  io.dtlbReq.bits.debug.isFirstIssue := s0_isFirstIssue
230
231  // query DCache
232  io.dcacheReq.valid := s0_valid
233  when (isPrefetchRead) {
234    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFR
235  }.elsewhen (isPrefetchWrite) {
236    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFW
237  }.otherwise {
238    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_XRD
239  }
240  io.dcacheReq.bits.addr := s0_vaddr
241  io.dcacheReq.bits.mask := s0_mask
242  io.dcacheReq.bits.data := DontCare
243  when(isPrefetch) {
244    io.dcacheReq.bits.instrtype := DCACHE_PREFETCH_SOURCE.U
245  }.otherwise {
246    io.dcacheReq.bits.instrtype := LOAD_SOURCE.U
247  }
248  io.dcacheReq.bits.isFirstIssue := s0_isFirstIssue
249  io.dcacheReq.bits.replayCarry := s0_replayCarry
250  io.dcacheReq.bits.debug_robIdx := s0_uop.robIdx.value
251
252  // TODO: update cache meta
253  io.dcacheReq.bits.id := DontCare
254
255  // assign default value
256  s0_uop := DontCare
257
258  // load flow priority mux
259  when(lfsrc_loadReplay_select) {
260    s0_vaddr := io.lsqOut.bits.vaddr
261    s0_mask := io.lsqOut.bits.mask
262    s0_uop := io.lsqOut.bits.uop
263    s0_isFirstIssue := io.lsqOut.bits.isFirstIssue
264    s0_rsIdx := io.lsqOut.bits.rsIdx
265    s0_sqIdx := io.lsqOut.bits.uop.sqIdx
266    s0_replayCarry := io.lsqOut.bits.replayCarry
267    val replayUopIsPrefetch = WireInit(LSUOpType.isPrefetch(io.lsqOut.bits.uop.ctrl.fuOpType))
268    when (replayUopIsPrefetch) {
269      isPrefetch := true.B
270    }
271  }.elsewhen(lfsrc_hwprefetch_select) {
272    // vaddr based index for dcache
273    s0_vaddr := io.prefetch_in.bits.getVaddr()
274    s0_mask := 0.U
275    s0_uop := DontCare
276    s0_isFirstIssue := false.B
277    s0_rsIdx := DontCare
278    s0_sqIdx := DontCare
279    s0_replayCarry := DontCare
280    // ctrl signal
281    isPrefetch := true.B
282    isPrefetchRead := !io.prefetch_in.bits.is_store
283    isPrefetchWrite := io.prefetch_in.bits.is_store
284  }.elsewhen(lfsrc_intloadFirstIssue_select) {
285    val imm12 = io.in.bits.uop.ctrl.imm(11, 0)
286    s0_vaddr := io.in.bits.src(0) + SignExt(imm12, VAddrBits)
287    s0_mask := genWmask(s0_vaddr, io.in.bits.uop.ctrl.fuOpType(1,0))
288    s0_uop := io.in.bits.uop
289    s0_isFirstIssue := io.isFirstIssue
290    s0_rsIdx := io.rsIdx
291    s0_sqIdx := io.in.bits.uop.sqIdx
292    val issueUopIsPrefetch = WireInit(LSUOpType.isPrefetch(io.in.bits.uop.ctrl.fuOpType))
293    when (issueUopIsPrefetch) {
294      isPrefetch := true.B
295    }
296  }.otherwise {
297    if (EnableLoadToLoadForward) {
298      tryFastpath := lfsrc_l2lForward_select
299      // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
300      s0_vaddr := io.fastpath.data
301      // Assume the pointer chasing is always ld.
302      s0_uop.ctrl.fuOpType := LSUOpType.ld
303      s0_mask := genWmask(0.U, LSUOpType.ld)
304      // we dont care s0_isFirstIssue and s0_rsIdx and s0_sqIdx in S0 when trying pointchasing
305      // because these signals will be updated in S1
306      s0_isFirstIssue := true.B
307      s0_rsIdx := DontCare
308      s0_sqIdx := DontCare
309    }
310  }
311
312  // address align check
313  val addrAligned = LookupTree(s0_uop.ctrl.fuOpType(1, 0), List(
314    "b00".U   -> true.B,                   //b
315    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
316    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
317    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
318  ))
319
320  // accept load flow if dcache ready (dtlb is always ready)
321  io.out.valid := s0_valid && io.dcacheReq.ready && !io.s0_kill
322  io.out.bits := DontCare
323  io.out.bits.vaddr := s0_vaddr
324  io.out.bits.mask := s0_mask
325  io.out.bits.uop := s0_uop
326  io.out.bits.uop.cf.exceptionVec(loadAddrMisaligned) := !addrAligned
327  io.out.bits.rsIdx := s0_rsIdx
328  io.out.bits.isFirstIssue := s0_isFirstIssue
329  io.out.bits.isPrefetch := isPrefetch
330  io.out.bits.isHWPrefetch := isHWPrefetch
331  io.out.bits.isLoadReplay := io.lsqOut.valid
332  io.out.bits.mshrid := io.lsqOut.bits.mshrid
333  io.out.bits.forward_tlDchannel := io.lsqOut.valid && io.lsqOut.bits.forward_tlDchannel
334  when(io.dtlbReq.valid && s0_isFirstIssue) {
335    io.out.bits.uop.debugInfo.tlbFirstReqTime := GTimer()
336  }.otherwise{
337    io.out.bits.uop.debugInfo.tlbFirstReqTime := s0_uop.debugInfo.tlbFirstReqTime
338  }
339
340  // load flow source ready
341  // always accept load flow from load replay queue
342  // io.lsqOut has highest priority
343  io.lsqOut.ready := (io.out.ready && io.dcacheReq.ready && lfsrc_loadReplay_ready)
344
345  // accept load flow from rs when:
346  // 1) there is no lsq-replayed load
347  // 2) there is no high confidence prefetch request
348  io.in.ready := (io.out.ready && io.dcacheReq.ready && lfsrc_intloadFirstIssue_select)
349
350  // for hw prefetch load flow feedback, to be added later
351  // io.prefetch_in.ready := lfsrc_hwprefetch_select
352
353  XSDebug(io.dcacheReq.fire,
354    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.cf.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
355  )
356  XSPerfAccumulate("in_valid", io.in.valid)
357  XSPerfAccumulate("in_fire", io.in.fire)
358  XSPerfAccumulate("in_fire_first_issue", s0_valid && s0_isFirstIssue)
359  XSPerfAccumulate("lsq_fire_first_issue", io.lsqOut.valid && io.lsqOut.bits.isFirstIssue)
360  XSPerfAccumulate("ldu_fire_first_issue", io.in.valid && io.isFirstIssue)
361  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready && io.dcacheReq.ready)
362  XSPerfAccumulate("stall_dcache", io.out.valid && io.out.ready && !io.dcacheReq.ready)
363  XSPerfAccumulate("addr_spec_success", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12))
364  XSPerfAccumulate("addr_spec_failed", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12))
365  XSPerfAccumulate("addr_spec_success_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
366  XSPerfAccumulate("addr_spec_failed_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
367  XSPerfAccumulate("forward_tlDchannel", io.out.bits.forward_tlDchannel)
368  XSPerfAccumulate("hardware_prefetch_fire", io.out.fire && lfsrc_hwprefetch_select)
369  XSPerfAccumulate("software_prefetch_fire", io.out.fire && isPrefetch && lfsrc_intloadFirstIssue_select)
370  XSPerfAccumulate("hardware_prefetch_blocked", io.prefetch_in.valid && !lfsrc_hwprefetch_select)
371  XSPerfAccumulate("hardware_prefetch_total", io.prefetch_in.valid)
372}
373
374
375// Load Pipeline Stage 1
376// TLB resp (send paddr to dcache)
377class LoadUnit_S1(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
378  val io = IO(new Bundle() {
379    val in = Flipped(Decoupled(new LsPipelineBundle))
380    val s1_kill = Input(Bool())
381    val out = Decoupled(new LsPipelineBundle)
382    val dtlbResp = Flipped(DecoupledIO(new TlbResp(2)))
383    val lsuPAddr = Output(UInt(PAddrBits.W))
384    val dcachePAddr = Output(UInt(PAddrBits.W))
385    val dcacheKill = Output(Bool())
386    val dcacheBankConflict = Input(Bool())
387    val fullForwardFast = Output(Bool())
388    val sbuffer = new LoadForwardQueryIO
389    val lsq = new PipeLoadForwardQueryIO
390    val loadViolationQueryReq = Decoupled(new LoadViolationQueryReq)
391    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))
392    val rsFeedback = ValidIO(new RSFeedback)
393    val replayFast = new LoadToLsqFastIO
394    val csrCtrl = Flipped(new CustomCSRCtrlIO)
395    val needLdVioCheckRedo = Output(Bool())
396    val needReExecute = Output(Bool())
397  })
398
399  val s1_uop = io.in.bits.uop
400  val s1_paddr_dup_lsu = io.dtlbResp.bits.paddr(0)
401  val s1_paddr_dup_dcache = io.dtlbResp.bits.paddr(1)
402  // af & pf exception were modified below.
403  val s1_exception = ExceptionNO.selectByFu(io.out.bits.uop.cf.exceptionVec, lduCfg).asUInt.orR
404  val s1_tlb_miss = io.dtlbResp.bits.miss
405  val s1_mask = io.in.bits.mask
406  val s1_is_prefetch = io.in.bits.isPrefetch
407  val s1_is_hw_prefetch = io.in.bits.isHWPrefetch
408  val s1_is_sw_prefetch = s1_is_prefetch && !s1_is_hw_prefetch
409  val s1_bank_conflict = io.dcacheBankConflict
410
411  io.out.bits := io.in.bits // forwardXX field will be updated in s1
412
413  val s1_tlb_memidx = io.dtlbResp.bits.memidx
414  when(s1_tlb_memidx.is_ld && io.dtlbResp.valid && !s1_tlb_miss && s1_tlb_memidx.idx === io.out.bits.uop.lqIdx.value) {
415    // printf("load idx = %d\n", s1_tlb_memidx.idx)
416    io.out.bits.uop.debugInfo.tlbRespTime := GTimer()
417  }
418
419  io.dtlbResp.ready := true.B
420
421  io.lsuPAddr := s1_paddr_dup_lsu
422  io.dcachePAddr := s1_paddr_dup_dcache
423  //io.dcacheKill := s1_tlb_miss || s1_exception || s1_mmio
424  io.dcacheKill := s1_tlb_miss || s1_exception || io.s1_kill
425  // load forward query datapath
426  io.sbuffer.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill || s1_is_prefetch)
427  io.sbuffer.vaddr := io.in.bits.vaddr
428  io.sbuffer.paddr := s1_paddr_dup_lsu
429  io.sbuffer.uop := s1_uop
430  io.sbuffer.sqIdx := s1_uop.sqIdx
431  io.sbuffer.mask := s1_mask
432  io.sbuffer.pc := s1_uop.cf.pc // FIXME: remove it
433
434  io.lsq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill || s1_is_prefetch)
435  io.lsq.vaddr := io.in.bits.vaddr
436  io.lsq.paddr := s1_paddr_dup_lsu
437  io.lsq.uop := s1_uop
438  io.lsq.sqIdx := s1_uop.sqIdx
439  io.lsq.sqIdxMask := DontCare // will be overwritten by sqIdxMask pre-generated in s0
440  io.lsq.mask := s1_mask
441  io.lsq.pc := s1_uop.cf.pc // FIXME: remove it
442
443  // ld-ld violation query
444  io.loadViolationQueryReq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill || s1_is_prefetch)
445  io.loadViolationQueryReq.bits.paddr := s1_paddr_dup_lsu
446  io.loadViolationQueryReq.bits.uop := s1_uop
447
448  // st-ld violation query
449  val needReExecuteVec = Wire(Vec(StorePipelineWidth, Bool()))
450  val needReExecute = Wire(Bool())
451
452  for (w <- 0 until StorePipelineWidth) {
453    //  needReExecute valid when
454    //  1. ReExecute query request valid.
455    //  2. Load instruction is younger than requestors(store instructions).
456    //  3. Physical address match.
457    //  4. Data contains.
458
459    needReExecuteVec(w) := io.reExecuteQuery(w).valid &&
460                          isAfter(io.in.bits.uop.robIdx, io.reExecuteQuery(w).bits.robIdx) &&
461                          !s1_tlb_miss &&
462                          (s1_paddr_dup_lsu(PAddrBits-1, 3) === io.reExecuteQuery(w).bits.paddr(PAddrBits-1, 3)) &&
463                          (s1_mask & io.reExecuteQuery(w).bits.mask).orR
464  }
465  needReExecute := needReExecuteVec.asUInt.orR
466  io.needReExecute := needReExecute
467
468  // Generate forwardMaskFast to wake up insts earlier
469  val forwardMaskFast = io.lsq.forwardMaskFast.asUInt | io.sbuffer.forwardMaskFast.asUInt
470  io.fullForwardFast := ((~forwardMaskFast).asUInt & s1_mask) === 0.U
471
472  // Generate feedback signal caused by:
473  // * dcache bank conflict
474  // * need redo ld-ld violation check
475  val needLdVioCheckRedo = io.loadViolationQueryReq.valid &&
476    !io.loadViolationQueryReq.ready &&
477    RegNext(io.csrCtrl.ldld_vio_check_enable)
478  io.needLdVioCheckRedo := needLdVioCheckRedo
479
480  // make nanhu rs feedback port happy
481  // if a load flow comes from rs, always feedback hit (no need to replay from rs)
482  io.rsFeedback.valid := Mux(io.in.bits.isLoadReplay, false.B, io.in.valid && !io.s1_kill && !s1_is_hw_prefetch)
483  io.rsFeedback.bits.hit := true.B // we have found s1_bank_conflict / re do ld-ld violation check
484  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
485  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
486  io.rsFeedback.bits.sourceType := Mux(s1_bank_conflict, RSFeedbackType.bankConflict, RSFeedbackType.ldVioCheckRedo)
487  io.rsFeedback.bits.dataInvalidSqIdx := DontCare
488
489  // request replay from load replay queue, fast port
490  io.replayFast.valid := io.in.valid && !io.s1_kill && !s1_is_hw_prefetch
491  io.replayFast.ld_ld_check_ok := !needLdVioCheckRedo || s1_is_sw_prefetch
492  io.replayFast.st_ld_check_ok := !needReExecute || s1_is_sw_prefetch
493  io.replayFast.cache_bank_no_conflict := !s1_bank_conflict || s1_is_sw_prefetch
494  io.replayFast.ld_idx := io.in.bits.uop.lqIdx.value
495  io.replayFast.debug := io.in.bits.uop.debugInfo
496
497  // if replay is detected in load_s1,
498  // load inst will be canceled immediately
499  io.out.valid := io.in.valid && (!needLdVioCheckRedo && !s1_bank_conflict && !needReExecute || s1_is_sw_prefetch) && !io.s1_kill
500  io.out.bits.paddr := s1_paddr_dup_lsu
501  io.out.bits.tlbMiss := s1_tlb_miss
502
503  // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
504  // af & pf exception were modified
505  io.out.bits.uop.cf.exceptionVec(loadPageFault) := io.dtlbResp.bits.excp(0).pf.ld
506  io.out.bits.uop.cf.exceptionVec(loadAccessFault) := io.dtlbResp.bits.excp(0).af.ld
507
508  io.out.bits.ptwBack := io.dtlbResp.bits.ptwBack
509  io.out.bits.rsIdx := io.in.bits.rsIdx
510
511  io.in.ready := !io.in.valid || io.out.ready
512
513  XSPerfAccumulate("in_valid", io.in.valid)
514  XSPerfAccumulate("in_fire", io.in.fire)
515  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
516  XSPerfAccumulate("tlb_miss", io.in.fire && s1_tlb_miss)
517  XSPerfAccumulate("tlb_miss_first_issue", io.in.fire && s1_tlb_miss && io.in.bits.isFirstIssue)
518  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
519}
520
521// Load Pipeline Stage 2
522// DCache resp
523class LoadUnit_S2(implicit p: Parameters) extends XSModule with HasLoadHelper with HasCircularQueuePtrHelper with HasDCacheParameters {
524  val io = IO(new Bundle() {
525    val in = Flipped(Decoupled(new LsPipelineBundle))
526    val out = Decoupled(new LsPipelineBundle)
527    val rsFeedback = ValidIO(new RSFeedback)
528    val replaySlow = new LoadToLsqSlowIO
529    val dcacheResp = Flipped(DecoupledIO(new DCacheWordResp))
530    val pmpResp = Flipped(new PMPRespBundle())
531    val lsq = new LoadForwardQueryIO
532    val dataInvalidSqIdx = Input(UInt())
533    val sbuffer = new LoadForwardQueryIO
534    val dataForwarded = Output(Bool())
535    val s2_dcache_require_replay = Output(Bool())
536    val fullForward = Output(Bool())
537    val dcache_kill = Output(Bool())
538    val s3_delayed_load_error = Output(Bool())
539    val loadViolationQueryResp = Flipped(Valid(new LoadViolationQueryResp))
540    val csrCtrl = Flipped(new CustomCSRCtrlIO)
541    val sentFastUop = Input(Bool())
542    val static_pm = Input(Valid(Bool())) // valid for static, bits for mmio
543    val s2_can_replay_from_fetch = Output(Bool()) // dirty code
544    val loadDataFromDcache = Output(new LoadDataFromDcacheBundle)
545    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))
546    val needReExecute = Output(Bool())
547    // forward tilelink D channel
548    val forward_D = Input(Bool())
549    val forwardData_D = Input(Vec(8, UInt(8.W)))
550
551    // forward mshr data
552    val forward_mshr = Input(Bool())
553    val forwardData_mshr = Input(Vec(8, UInt(8.W)))
554
555    // indicate whether forward tilelink D channel or mshr data is valid
556    val forward_result_valid = Input(Bool())
557
558    val s2_forward_fail = Output(Bool())
559  })
560
561  val pmp = WireInit(io.pmpResp)
562  when (io.static_pm.valid) {
563    pmp.ld := false.B
564    pmp.st := false.B
565    pmp.instr := false.B
566    pmp.mmio := io.static_pm.bits
567  }
568
569  val s2_is_prefetch = io.in.bits.isPrefetch
570  val s2_is_hw_prefetch = io.in.bits.isHWPrefetch
571
572  val forward_D_or_mshr_valid = io.forward_result_valid && (io.forward_D || io.forward_mshr)
573
574  // assert(!reset && io.forward_D && io.forward_mshr && io.in.valid && io.in.bits.forward_tlDchannel, "forward D and mshr at the same time")
575
576  // exception that may cause load addr to be invalid / illegal
577  //
578  // if such exception happen, that inst and its exception info
579  // will be force writebacked to rob
580  val s2_exception_vec = WireInit(io.in.bits.uop.cf.exceptionVec)
581  s2_exception_vec(loadAccessFault) := io.in.bits.uop.cf.exceptionVec(loadAccessFault) || pmp.ld
582  // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
583  when (s2_is_prefetch) {
584    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
585  }
586  val s2_exception = ExceptionNO.selectByFu(s2_exception_vec, lduCfg).asUInt.orR && !io.in.bits.tlbMiss
587
588  // writeback access fault caused by ecc error / bus error
589  //
590  // * ecc data error is slow to generate, so we will not use it until load stage 3
591  // * in load stage 3, an extra signal io.load_error will be used to
592
593  // now cache ecc error will raise an access fault
594  // at the same time, error info (including error paddr) will be write to
595  // an customized CSR "CACHE_ERROR"
596  if (EnableAccurateLoadError) {
597    io.s3_delayed_load_error := io.dcacheResp.bits.error_delayed &&
598      io.csrCtrl.cache_error_enable &&
599      RegNext(io.out.valid)
600  } else {
601    io.s3_delayed_load_error := false.B
602  }
603
604  val actually_mmio = pmp.mmio
605  val s2_uop = io.in.bits.uop
606  val s2_mask = io.in.bits.mask
607  val s2_paddr = io.in.bits.paddr
608  val s2_tlb_miss = io.in.bits.tlbMiss
609  val s2_mmio = !s2_is_prefetch && actually_mmio && !s2_exception
610  val s2_cache_miss = io.dcacheResp.bits.miss && !forward_D_or_mshr_valid
611  val s2_cache_replay = io.dcacheResp.bits.replay && !forward_D_or_mshr_valid
612  val s2_cache_tag_error = io.dcacheResp.bits.tag_error
613  val s2_forward_fail = io.lsq.matchInvalid || io.sbuffer.matchInvalid
614  val s2_ldld_violation = io.loadViolationQueryResp.valid &&
615    io.loadViolationQueryResp.bits.have_violation &&
616    RegNext(io.csrCtrl.ldld_vio_check_enable)
617  val s2_data_invalid = io.lsq.dataInvalid && !s2_ldld_violation && !s2_exception
618
619  io.s2_forward_fail := s2_forward_fail
620  io.dcache_kill := pmp.ld || pmp.mmio // move pmp resp kill to outside
621  io.dcacheResp.ready := true.B
622  val dcacheShouldResp = !(s2_tlb_miss || s2_exception || s2_mmio || s2_is_prefetch)
623  assert(!(io.in.valid && (dcacheShouldResp && !io.dcacheResp.valid)), "DCache response got lost")
624
625  // merge forward result
626  // lsq has higher priority than sbuffer
627  val forwardMask = Wire(Vec(8, Bool()))
628  val forwardData = Wire(Vec(8, UInt(8.W)))
629
630  val fullForward = ((~forwardMask.asUInt).asUInt & s2_mask) === 0.U && !io.lsq.dataInvalid
631  io.lsq := DontCare
632  io.sbuffer := DontCare
633  io.fullForward := fullForward
634
635  // generate XLEN/8 Muxs
636  for (i <- 0 until XLEN / 8) {
637    forwardMask(i) := io.lsq.forwardMask(i) || io.sbuffer.forwardMask(i)
638    forwardData(i) := Mux(io.lsq.forwardMask(i), io.lsq.forwardData(i), io.sbuffer.forwardData(i))
639  }
640
641  XSDebug(io.out.fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
642    s2_uop.cf.pc,
643    io.lsq.forwardData.asUInt, io.lsq.forwardMask.asUInt,
644    io.in.bits.forwardData.asUInt, io.in.bits.forwardMask.asUInt
645  )
646
647  // data merge
648  // val rdataVec = VecInit((0 until XLEN / 8).map(j =>
649  //   Mux(forwardMask(j), forwardData(j), io.dcacheResp.bits.data(8*(j+1)-1, 8*j))
650  // )) // s2_rdataVec will be write to load queue
651  // val rdata = rdataVec.asUInt
652  // val rdataSel = LookupTree(s2_paddr(2, 0), List(
653  //   "b000".U -> rdata(63, 0),
654  //   "b001".U -> rdata(63, 8),
655  //   "b010".U -> rdata(63, 16),
656  //   "b011".U -> rdata(63, 24),
657  //   "b100".U -> rdata(63, 32),
658  //   "b101".U -> rdata(63, 40),
659  //   "b110".U -> rdata(63, 48),
660  //   "b111".U -> rdata(63, 56)
661  // ))
662  // val rdataPartialLoad = rdataHelper(s2_uop, rdataSel) // s2_rdataPartialLoad is not used
663
664  io.out.valid := io.in.valid &&
665    !s2_tlb_miss && // always request replay and cancel current flow if tlb miss
666    (!s2_data_invalid && !io.needReExecute || s2_is_prefetch) && // prefetch does not care about ld-st dependency
667    !s2_is_hw_prefetch // hardware prefetch flow should not be writebacked
668  // write_lq_safe is needed by dup logic
669  // io.write_lq_safe := !s2_tlb_miss && !s2_data_invalid
670  // Inst will be canceled in store queue / lsq,
671  // so we do not need to care about flush in load / store unit's out.valid
672  io.out.bits := io.in.bits
673  // io.out.bits.data := rdataPartialLoad
674  io.out.bits.data := 0.U // data will be generated in load_s3
675  // when exception occurs, set it to not miss and let it write back to rob (via int port)
676  if (EnableFastForward) {
677    io.out.bits.miss := s2_cache_miss &&
678      !s2_exception &&
679      !fullForward &&
680      !s2_is_prefetch
681  } else {
682    io.out.bits.miss := s2_cache_miss &&
683      !s2_exception &&
684      !s2_is_prefetch
685  }
686  io.out.bits.uop.ctrl.fpWen := io.in.bits.uop.ctrl.fpWen && !s2_exception
687
688  // val s2_loadDataFromDcache = new LoadDataFromDcacheBundle
689  // s2_loadDataFromDcache.forwardMask := forwardMask
690  // s2_loadDataFromDcache.forwardData := forwardData
691  // s2_loadDataFromDcache.uop := io.out.bits.uop
692  // s2_loadDataFromDcache.addrOffset := s2_paddr(2, 0)
693  // // forward D or mshr
694  // s2_loadDataFromDcache.forward_D := io.forward_D
695  // s2_loadDataFromDcache.forwardData_D := io.forwardData_D
696  // s2_loadDataFromDcache.forward_mshr := io.forward_mshr
697  // s2_loadDataFromDcache.forwardData_mshr := io.forwardData_mshr
698  // s2_loadDataFromDcache.forward_result_valid := io.forward_result_valid
699  // io.loadDataFromDcache := RegEnable(s2_loadDataFromDcache, io.in.valid)
700  io.loadDataFromDcache.respDcacheData := io.dcacheResp.bits.data_delayed
701  io.loadDataFromDcache.forwardMask := RegEnable(forwardMask, io.in.valid)
702  io.loadDataFromDcache.forwardData := RegEnable(forwardData, io.in.valid)
703  io.loadDataFromDcache.uop := RegEnable(io.out.bits.uop, io.in.valid)
704  io.loadDataFromDcache.addrOffset := RegEnable(s2_paddr(2, 0), io.in.valid)
705  // forward D or mshr
706  io.loadDataFromDcache.forward_D := RegEnable(io.forward_D, io.in.valid)
707  io.loadDataFromDcache.forwardData_D := RegEnable(io.forwardData_D, io.in.valid)
708  io.loadDataFromDcache.forward_mshr := RegEnable(io.forward_mshr, io.in.valid)
709  io.loadDataFromDcache.forwardData_mshr := RegEnable(io.forwardData_mshr, io.in.valid)
710  io.loadDataFromDcache.forward_result_valid := RegEnable(io.forward_result_valid, io.in.valid)
711
712  io.s2_can_replay_from_fetch := !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
713  // if forward fail, replay this inst from fetch
714  val debug_forwardFailReplay = s2_forward_fail && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
715  // if ld-ld violation is detected, replay from this inst from fetch
716  val debug_ldldVioReplay = s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
717  // io.out.bits.uop.ctrl.replayInst := false.B
718
719  io.out.bits.mmio := s2_mmio
720  io.out.bits.uop.ctrl.flushPipe := s2_mmio && io.sentFastUop
721  io.out.bits.uop.cf.exceptionVec := s2_exception_vec // cache error not included
722
723  // For timing reasons, sometimes we can not let
724  // io.out.bits.miss := s2_cache_miss && !s2_exception && !fullForward
725  // We use io.dataForwarded instead. It means:
726  // 1. Forward logic have prepared all data needed,
727  //    and dcache query is no longer needed.
728  // 2. ... or data cache tag error is detected, this kind of inst
729  //    will not update miss queue. That is to say, if miss, that inst
730  //    may not be refilled
731  // Such inst will be writebacked from load queue.
732  io.dataForwarded := s2_cache_miss && !s2_exception &&
733    (fullForward || io.csrCtrl.cache_error_enable && s2_cache_tag_error)
734  // io.out.bits.forwardX will be send to lq
735  io.out.bits.forwardMask := forwardMask
736  // data from dcache is not included in io.out.bits.forwardData
737  io.out.bits.forwardData := forwardData
738
739  io.in.ready := io.out.ready || !io.in.valid
740
741
742  // st-ld violation query
743  val needReExecuteVec = Wire(Vec(StorePipelineWidth, Bool()))
744  val needReExecute = Wire(Bool())
745
746  for (i <- 0 until StorePipelineWidth) {
747    //  NeedFastRecovery Valid when
748    //  1. Fast recovery query request Valid.
749    //  2. Load instruction is younger than requestors(store instructions).
750    //  3. Physical address match.
751    //  4. Data contains.
752    needReExecuteVec(i) := io.reExecuteQuery(i).valid &&
753                              isAfter(io.in.bits.uop.robIdx, io.reExecuteQuery(i).bits.robIdx) &&
754                              !s2_tlb_miss &&
755                              (s2_paddr(PAddrBits-1,3) === io.reExecuteQuery(i).bits.paddr(PAddrBits-1, 3)) &&
756                              (s2_mask & io.reExecuteQuery(i).bits.mask).orR
757  }
758  needReExecute := needReExecuteVec.asUInt.orR
759  io.needReExecute := needReExecute
760
761  // rs slow feedback port in nanhu is not used for now
762  io.rsFeedback.valid := false.B
763  io.rsFeedback.bits := DontCare
764
765  // request replay from load replay queue, fast port
766  io.replaySlow.valid := io.in.valid && !s2_is_hw_prefetch // hardware prefetch flow should not be reported to load replay queue
767  io.replaySlow.tlb_hited := !s2_tlb_miss
768  io.replaySlow.st_ld_check_ok := !needReExecute || s2_is_prefetch // Note: soft prefetch does not care about ld-st dependency
769  if (EnableFastForward) {
770    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || fullForward
771  }else {
772    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || io.dataForwarded
773  }
774  io.replaySlow.forward_data_valid := !s2_data_invalid || s2_is_prefetch // Note: soft prefetch does not care about ld-st dependency
775  io.replaySlow.cache_hited := !io.out.bits.miss || io.out.bits.mmio
776  io.replaySlow.can_forward_full_data := io.dataForwarded
777  io.replaySlow.ld_idx := io.in.bits.uop.lqIdx.value
778  io.replaySlow.data_invalid_sq_idx := io.dataInvalidSqIdx
779  io.replaySlow.replayCarry := io.dcacheResp.bits.replayCarry
780  io.replaySlow.miss_mshr_id := io.dcacheResp.bits.mshr_id
781  io.replaySlow.data_in_last_beat := io.in.bits.paddr(log2Up(refillBytes))
782  io.replaySlow.debug := io.in.bits.uop.debugInfo
783
784  // To be removed
785  val s2_need_replay_from_rs = Wire(Bool())
786  if (EnableFastForward) {
787    s2_need_replay_from_rs :=
788      needReExecute ||
789      s2_tlb_miss || // replay if dtlb miss
790      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !fullForward || // replay if dcache miss queue full / busy
791      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
792  } else {
793    // Note that if all parts of data are available in sq / sbuffer, replay required by dcache will not be scheduled
794    s2_need_replay_from_rs :=
795      needReExecute ||
796      s2_tlb_miss || // replay if dtlb miss
797      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !io.dataForwarded || // replay if dcache miss queue full / busy
798      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
799  }
800
801  // s2_cache_replay is quite slow to generate, send it separately to LQ
802  if (EnableFastForward) {
803    io.s2_dcache_require_replay := s2_cache_replay && !fullForward
804  } else {
805    io.s2_dcache_require_replay := s2_cache_replay &&
806      s2_need_replay_from_rs &&
807      !io.dataForwarded &&
808      !s2_is_prefetch &&
809      io.out.bits.miss
810  }
811
812  XSPerfAccumulate("in_valid", io.in.valid)
813  XSPerfAccumulate("in_fire", io.in.fire)
814  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
815  XSPerfAccumulate("dcache_miss", io.in.fire && s2_cache_miss)
816  XSPerfAccumulate("dcache_miss_first_issue", io.in.fire && s2_cache_miss && io.in.bits.isFirstIssue)
817  XSPerfAccumulate("full_forward", io.in.valid && fullForward)
818  XSPerfAccumulate("dcache_miss_full_forward", io.in.valid && s2_cache_miss && fullForward)
819  XSPerfAccumulate("replay",  io.rsFeedback.valid && !io.rsFeedback.bits.hit)
820  XSPerfAccumulate("replay_tlb_miss", io.rsFeedback.valid && !io.rsFeedback.bits.hit && s2_tlb_miss)
821  XSPerfAccumulate("replay_cache", io.rsFeedback.valid && !io.rsFeedback.bits.hit && !s2_tlb_miss && s2_cache_replay)
822  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
823  XSPerfAccumulate("replay_from_fetch_forward", io.out.valid && debug_forwardFailReplay)
824  XSPerfAccumulate("replay_from_fetch_load_vio", io.out.valid && debug_ldldVioReplay)
825  XSPerfAccumulate("replay_lq",  io.replaySlow.valid && (!io.replaySlow.tlb_hited || !io.replaySlow.cache_no_replay || !io.replaySlow.forward_data_valid))
826  XSPerfAccumulate("replay_tlb_miss_lq", io.replaySlow.valid && !io.replaySlow.tlb_hited)
827  XSPerfAccumulate("replay_sl_vio", io.replaySlow.valid && io.replaySlow.tlb_hited && !io.replaySlow.st_ld_check_ok)
828  XSPerfAccumulate("replay_cache_lq", io.replaySlow.valid && io.replaySlow.tlb_hited && io.replaySlow.st_ld_check_ok && !io.replaySlow.cache_no_replay)
829  XSPerfAccumulate("replay_cache_miss_lq", io.replaySlow.valid && !io.replaySlow.cache_hited)
830  XSPerfAccumulate("prefetch", io.in.fire && s2_is_prefetch)
831  XSPerfAccumulate("prefetch_ignored", io.in.fire && s2_is_prefetch && s2_cache_replay) // ignore prefetch for mshr full / miss req port conflict
832  XSPerfAccumulate("prefetch_miss", io.in.fire && s2_is_prefetch && s2_cache_miss) // prefetch req miss in l1
833  XSPerfAccumulate("prefetch_hit", io.in.fire && s2_is_prefetch && !s2_cache_miss) // prefetch req hit in l1
834  // prefetch a missed line in l1, and l1 accepted it
835  XSPerfAccumulate("prefetch_accept", io.in.fire && s2_is_prefetch && s2_cache_miss && !s2_cache_replay)
836}
837
838class LoadUnit(implicit p: Parameters) extends XSModule
839  with HasLoadHelper
840  with HasPerfEvents
841  with HasDCacheParameters
842{
843  val io = IO(new Bundle() {
844    val ldin = Flipped(Decoupled(new ExuInput))
845    val ldout = Decoupled(new ExuOutput)
846    val redirect = Flipped(ValidIO(new Redirect))
847    val feedbackSlow = ValidIO(new RSFeedback)
848    val feedbackFast = ValidIO(new RSFeedback)
849    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
850    val isFirstIssue = Input(Bool())
851    val dcache = new DCacheLoadIO
852    val sbuffer = new LoadForwardQueryIO
853    val lsq = new LoadToLsqIO
854    val tlDchannel = Input(new DcacheToLduForwardIO)
855    val forward_mshr = Flipped(new LduToMissqueueForwardIO)
856    val refill = Flipped(ValidIO(new Refill))
857    val fastUop = ValidIO(new MicroOp) // early wakeup signal generated in load_s1, send to RS in load_s2
858    val trigger = Vec(3, new LoadUnitTriggerIO)
859
860    val tlb = new TlbRequestIO(2)
861    val pmp = Flipped(new PMPRespBundle()) // arrive same to tlb now
862
863    // provide prefetch info
864    val prefetch_train = ValidIO(new LdPrefetchTrainBundle())
865
866    // hardware prefetch to l1 cache req
867    val prefetch_req = Flipped(ValidIO(new L1PrefetchReq))
868
869    // load to load fast path
870    val fastpathOut = Output(new LoadToLoadIO)
871    val fastpathIn = Input(new LoadToLoadIO)
872    val loadFastMatch = Input(Bool())
873    val loadFastImm = Input(UInt(12.W))
874
875    // load ecc
876    val s3_delayed_load_error = Output(Bool()) // load ecc error
877    // Note that io.s3_delayed_load_error and io.lsq.s3_delayed_load_error is different
878
879    // load unit ctrl
880    val csrCtrl = Flipped(new CustomCSRCtrlIO)
881
882    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))    // load replay
883    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
884    val debug_ls = Output(new DebugLsInfoBundle)
885    val s2IsPointerChasing = Output(Bool()) // provide right pc for hw prefetch
886  })
887
888  val load_s0 = Module(new LoadUnit_S0)
889  val load_s1 = Module(new LoadUnit_S1)
890  val load_s2 = Module(new LoadUnit_S2)
891
892  load_s0.io.lsqOut <> io.lsqOut
893
894  // load s0
895  load_s0.io.in <> io.ldin
896  load_s0.io.dtlbReq <> io.tlb.req
897  load_s0.io.dcacheReq <> io.dcache.req
898  load_s0.io.rsIdx := io.rsIdx
899  load_s0.io.isFirstIssue := io.isFirstIssue
900  load_s0.io.s0_kill := false.B
901
902  // we try pointerchasing if lfsrc_l2lForward_select condition is satisfied
903  val s0_tryPointerChasing = load_s0.io.l2lForward_select
904  val s0_pointerChasingVAddr = io.fastpathIn.data(5, 0) +& io.loadFastImm(5, 0)
905  load_s0.io.fastpath.valid := io.fastpathIn.valid
906  load_s0.io.fastpath.data := Cat(io.fastpathIn.data(XLEN-1, 6), s0_pointerChasingVAddr(5,0))
907
908  val s1_data = PipelineConnect(load_s0.io.out, load_s1.io.in, true.B,
909    load_s0.io.out.bits.uop.robIdx.needFlush(io.redirect) && !s0_tryPointerChasing).get
910
911  // load s1
912  // update s1_kill when any source has valid request
913  load_s1.io.s1_kill := RegEnable(load_s0.io.s0_kill, false.B, io.ldin.valid || io.lsqOut.valid || io.fastpathIn.valid)
914  io.tlb.req_kill := load_s1.io.s1_kill
915  load_s1.io.dtlbResp <> io.tlb.resp
916  io.dcache.s1_paddr_dup_lsu <> load_s1.io.lsuPAddr
917  io.dcache.s1_paddr_dup_dcache <> load_s1.io.dcachePAddr
918  io.dcache.s1_kill := load_s1.io.dcacheKill
919  load_s1.io.sbuffer <> io.sbuffer
920  load_s1.io.lsq <> io.lsq.forward
921  load_s1.io.loadViolationQueryReq <> io.lsq.loadViolationQuery.req
922  load_s1.io.dcacheBankConflict <> io.dcache.s1_bank_conflict
923  load_s1.io.csrCtrl <> io.csrCtrl
924  load_s1.io.reExecuteQuery := io.reExecuteQuery
925  // provide paddr and vaddr for lq
926  io.lsq.loadPaddrIn.valid := load_s1.io.out.valid && !load_s1.io.out.bits.isHWPrefetch
927  io.lsq.loadPaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
928  io.lsq.loadPaddrIn.bits.paddr := load_s1.io.lsuPAddr
929
930  io.lsq.loadVaddrIn.valid := load_s1.io.in.valid && !load_s1.io.s1_kill && !load_s1.io.out.bits.isHWPrefetch
931  io.lsq.loadVaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
932  io.lsq.loadVaddrIn.bits.vaddr := load_s1.io.out.bits.vaddr
933
934  // when S0 has opportunity to try pointerchasing, make sure it truely goes to S1
935  // which is S0's out is ready and dcache is ready
936  val s0_doTryPointerChasing = s0_tryPointerChasing && load_s0.io.out.ready && load_s0.io.dcacheReq.ready
937  val s1_tryPointerChasing = RegNext(s0_doTryPointerChasing, false.B)
938  val s1_pointerChasingVAddr = RegEnable(s0_pointerChasingVAddr, s0_doTryPointerChasing)
939  val cancelPointerChasing = WireInit(false.B)
940  if (EnableLoadToLoadForward) {
941    // Sometimes, we need to cancel the load-load forwarding.
942    // These can be put at S0 if timing is bad at S1.
943    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
944    val addressMisMatch = s1_pointerChasingVAddr(6) || RegEnable(io.loadFastImm(11, 6).orR, s0_doTryPointerChasing)
945    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
946    val addressNotAligned = s1_pointerChasingVAddr(2, 0).orR
947    val fuOpTypeIsNotLd = io.ldin.bits.uop.ctrl.fuOpType =/= LSUOpType.ld
948    // Case 2: this is not a valid load-load pair
949    val notFastMatch = RegEnable(!io.loadFastMatch, s0_tryPointerChasing)
950    // Case 3: this load-load uop is cancelled
951    val isCancelled = !io.ldin.valid
952    when (s1_tryPointerChasing) {
953      cancelPointerChasing := addressMisMatch || addressNotAligned || fuOpTypeIsNotLd || notFastMatch || isCancelled
954      load_s1.io.in.bits.uop := io.ldin.bits.uop
955      val spec_vaddr = s1_data.vaddr
956      val vaddr = Cat(spec_vaddr(VAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
957      load_s1.io.in.bits.vaddr := vaddr
958      load_s1.io.in.bits.rsIdx := io.rsIdx
959      load_s1.io.in.bits.isFirstIssue := io.isFirstIssue
960      // We need to replace vaddr(5, 3).
961      val spec_paddr = io.tlb.resp.bits.paddr(0)
962      load_s1.io.dtlbResp.bits.paddr.foreach(_ := Cat(spec_paddr(PAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W)))
963      // 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)
964      load_s1.io.in.bits.uop.debugInfo.tlbFirstReqTime := GTimer()
965      load_s1.io.in.bits.uop.debugInfo.tlbRespTime := GTimer()
966    }
967    when (cancelPointerChasing) {
968      load_s1.io.s1_kill := true.B
969    }.otherwise {
970      load_s0.io.s0_kill := s1_tryPointerChasing && !io.lsqOut.valid
971      when (s1_tryPointerChasing) {
972        io.ldin.ready := true.B
973      }
974    }
975
976    XSPerfAccumulate("load_to_load_forward", s1_tryPointerChasing && !cancelPointerChasing)
977    XSPerfAccumulate("load_to_load_forward_try", s1_tryPointerChasing)
978    XSPerfAccumulate("load_to_load_forward_fail", cancelPointerChasing)
979    XSPerfAccumulate("load_to_load_forward_fail_cancelled", cancelPointerChasing && isCancelled)
980    XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", cancelPointerChasing && !isCancelled && notFastMatch)
981    XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",
982      cancelPointerChasing && !isCancelled && !notFastMatch && fuOpTypeIsNotLd)
983    XSPerfAccumulate("load_to_load_forward_fail_addr_align",
984      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && addressNotAligned)
985    XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",
986      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && !addressNotAligned && addressMisMatch)
987  }
988  PipelineConnect(load_s1.io.out, load_s2.io.in, true.B,
989    load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect) || cancelPointerChasing)
990
991  val (forward_D, forwardData_D) = io.tlDchannel.forward(load_s1.io.out.valid && load_s1.io.out.bits.forward_tlDchannel, load_s1.io.out.bits.mshrid, load_s1.io.out.bits.paddr)
992
993  io.forward_mshr.valid := load_s1.io.out.valid && load_s1.io.out.bits.forward_tlDchannel
994  io.forward_mshr.mshrid := load_s1.io.out.bits.mshrid
995  io.forward_mshr.paddr := load_s1.io.out.bits.paddr
996  val (forward_result_valid, forward_mshr, forwardData_mshr) = io.forward_mshr.forward()
997
998  XSPerfAccumulate("successfully_forward_channel_D", forward_D && forward_result_valid)
999  XSPerfAccumulate("successfully_forward_mshr", forward_mshr && forward_result_valid)
1000  // load s2
1001  load_s2.io.forward_D := forward_D
1002  load_s2.io.forwardData_D := forwardData_D
1003  load_s2.io.forward_result_valid := forward_result_valid
1004  load_s2.io.forward_mshr := forward_mshr
1005  load_s2.io.forwardData_mshr := forwardData_mshr
1006  io.s2IsPointerChasing := RegEnable(s1_tryPointerChasing && !cancelPointerChasing, load_s1.io.out.fire)
1007  io.prefetch_train.bits.fromLsPipelineBundle(load_s2.io.in.bits)
1008  // override miss bit
1009  io.prefetch_train.bits.miss := io.dcache.resp.bits.miss
1010  io.prefetch_train.bits.meta_prefetch := io.dcache.resp.bits.meta_prefetch
1011  io.prefetch_train.bits.meta_access := io.dcache.resp.bits.meta_access
1012  io.prefetch_train.valid := load_s2.io.in.fire && !load_s2.io.out.bits.mmio && !load_s2.io.in.bits.tlbMiss
1013  io.dcache.s2_kill := load_s2.io.dcache_kill // to kill mmio resp which are redirected
1014  if (env.FPGAPlatform)
1015    io.dcache.s2_pc := DontCare
1016  else
1017    io.dcache.s2_pc := load_s2.io.out.bits.uop.cf.pc
1018  load_s2.io.dcacheResp <> io.dcache.resp
1019  load_s2.io.pmpResp <> io.pmp
1020  load_s2.io.static_pm := RegNext(io.tlb.resp.bits.static_pm)
1021  load_s2.io.lsq.forwardData <> io.lsq.forward.forwardData
1022  load_s2.io.lsq.forwardMask <> io.lsq.forward.forwardMask
1023  load_s2.io.lsq.forwardMaskFast <> io.lsq.forward.forwardMaskFast // should not be used in load_s2
1024  load_s2.io.lsq.dataInvalid <> io.lsq.forward.dataInvalid
1025  load_s2.io.lsq.matchInvalid <> io.lsq.forward.matchInvalid
1026  load_s2.io.sbuffer.forwardData <> io.sbuffer.forwardData
1027  load_s2.io.sbuffer.forwardMask <> io.sbuffer.forwardMask
1028  load_s2.io.sbuffer.forwardMaskFast <> io.sbuffer.forwardMaskFast // should not be used in load_s2
1029  load_s2.io.sbuffer.dataInvalid <> io.sbuffer.dataInvalid // always false
1030  load_s2.io.sbuffer.matchInvalid <> io.sbuffer.matchInvalid
1031  load_s2.io.dataForwarded <> io.lsq.s2_load_data_forwarded
1032  load_s2.io.dataInvalidSqIdx := io.lsq.forward.dataInvalidSqIdx // provide dataInvalidSqIdx to make wakeup faster
1033  load_s2.io.loadViolationQueryResp <> io.lsq.loadViolationQuery.resp
1034  load_s2.io.csrCtrl <> io.csrCtrl
1035  load_s2.io.sentFastUop := io.fastUop.valid
1036  load_s2.io.reExecuteQuery := io.reExecuteQuery
1037  // feedback bank conflict / ld-vio check struct hazard to rs
1038  io.feedbackFast.bits := RegNext(load_s1.io.rsFeedback.bits)
1039  io.feedbackFast.valid := RegNext(load_s1.io.rsFeedback.valid && !load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect))
1040
1041  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
1042  val sqIdxMaskReg = RegNext(UIntToMask(load_s0.io.s0_sqIdx.value, StoreQueueSize))
1043  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
1044  // If the timing here is not OK, load-load forwarding has to be disabled.
1045  // Or we calculate sqIdxMask at RS??
1046  io.lsq.forward.sqIdxMask := sqIdxMaskReg
1047  if (EnableLoadToLoadForward) {
1048    when (s1_tryPointerChasing) {
1049      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
1050    }
1051  }
1052
1053  // // use s2_hit_way to select data received in s1
1054  // load_s2.io.dcacheResp.bits.data := Mux1H(RegNext(io.dcache.s1_hit_way), RegNext(io.dcache.s1_data))
1055  // assert(load_s2.io.dcacheResp.bits.data === io.dcache.resp.bits.data)
1056
1057  // now io.fastUop.valid is sent to RS in load_s2
1058  val forward_D_or_mshr_valid = forward_result_valid && (forward_D || forward_mshr)
1059  val s2_dcache_hit = io.dcache.s2_hit || forward_D_or_mshr_valid // dcache hit dup in lsu side
1060
1061  io.fastUop.valid := RegNext(
1062      !io.dcache.s1_disable_fast_wakeup &&  // load fast wakeup should be disabled when dcache data read is not ready
1063      load_s1.io.in.valid && // valid load request
1064      !load_s1.io.in.bits.isHWPrefetch && // is not hardware prefetch req
1065      !load_s1.io.s1_kill && // killed by load-load forwarding
1066      !load_s1.io.dtlbResp.bits.fast_miss && // not mmio or tlb miss, pf / af not included here
1067      !io.lsq.forward.dataInvalidFast // forward failed
1068    ) &&
1069    !RegNext(load_s1.io.needLdVioCheckRedo) && // load-load violation check: load paddr cam struct hazard
1070    !RegNext(load_s1.io.needReExecute) &&
1071    !RegNext(load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) &&
1072    (load_s2.io.in.valid && !load_s2.io.needReExecute && s2_dcache_hit) // dcache hit in lsu side
1073
1074  io.fastUop.bits := RegNext(load_s1.io.out.bits.uop)
1075
1076  XSDebug(load_s0.io.out.valid,
1077    p"S0: pc ${Hexadecimal(load_s0.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s0.io.out.bits.uop.lqIdx.asUInt)}, " +
1078    p"vaddr ${Hexadecimal(load_s0.io.out.bits.vaddr)}, mask ${Hexadecimal(load_s0.io.out.bits.mask)}\n")
1079  XSDebug(load_s1.io.out.valid,
1080    p"S1: pc ${Hexadecimal(load_s1.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s1.io.out.bits.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
1081    p"paddr ${Hexadecimal(load_s1.io.out.bits.paddr)}, mmio ${load_s1.io.out.bits.mmio}\n")
1082
1083  // writeback to LSQ
1084  // Current dcache use MSHR
1085  // Load queue will be updated at s2 for both hit/miss int/fp load
1086  io.lsq.loadIn.valid := load_s2.io.out.valid && !load_s2.io.out.bits.isHWPrefetch
1087  // generate LqWriteBundle from LsPipelineBundle
1088  io.lsq.loadIn.bits.fromLsPipelineBundle(load_s2.io.out.bits)
1089
1090  io.lsq.replayFast := load_s1.io.replayFast
1091  io.lsq.replaySlow := load_s2.io.replaySlow
1092  io.lsq.replaySlow.valid := load_s2.io.replaySlow.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)
1093
1094  // generate duplicated load queue data wen
1095  val load_s2_valid_vec = RegInit(0.U(6.W))
1096  val load_s2_leftFire = load_s1.io.out.valid && load_s2.io.in.ready
1097  // val write_lq_safe = load_s2.io.write_lq_safe
1098  load_s2_valid_vec := 0x0.U(6.W)
1099  when (load_s2_leftFire && !load_s1.io.out.bits.isHWPrefetch) { load_s2_valid_vec := 0x3f.U(6.W)} // TODO: refactor me
1100  when (load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) { load_s2_valid_vec := 0x0.U(6.W) }
1101  assert(RegNext((load_s2.io.in.valid === load_s2_valid_vec(0)) || RegNext(load_s1.io.out.bits.isHWPrefetch)))
1102  io.lsq.loadIn.bits.lq_data_wen_dup := load_s2_valid_vec.asBools()
1103
1104  // s2_dcache_require_replay signal will be RegNexted, then used in s3
1105  io.lsq.s2_dcache_require_replay := load_s2.io.s2_dcache_require_replay
1106
1107  // write to rob and writeback bus
1108  val s2_wb_valid = load_s2.io.out.valid && !load_s2.io.out.bits.miss && !load_s2.io.out.bits.mmio
1109
1110  // Int load, if hit, will be writebacked at s2
1111  val hitLoadOut = Wire(Valid(new ExuOutput))
1112  hitLoadOut.valid := s2_wb_valid
1113  hitLoadOut.bits.uop := load_s2.io.out.bits.uop
1114  hitLoadOut.bits.data := load_s2.io.out.bits.data
1115  hitLoadOut.bits.redirectValid := false.B
1116  hitLoadOut.bits.redirect := DontCare
1117  hitLoadOut.bits.debug.isMMIO := load_s2.io.out.bits.mmio
1118  hitLoadOut.bits.debug.isPerfCnt := false.B
1119  hitLoadOut.bits.debug.paddr := load_s2.io.out.bits.paddr
1120  hitLoadOut.bits.debug.vaddr := load_s2.io.out.bits.vaddr
1121  hitLoadOut.bits.fflags := DontCare
1122
1123  load_s2.io.out.ready := true.B
1124
1125  // load s3
1126  val s3_load_wb_meta_reg = RegNext(Mux(hitLoadOut.valid, hitLoadOut.bits, io.lsq.ldout.bits))
1127
1128  // data from load queue refill
1129  val s3_loadDataFromLQ = RegEnable(io.lsq.ldRawData, io.lsq.ldout.valid)
1130  val s3_rdataLQ = s3_loadDataFromLQ.mergedData()
1131  val s3_rdataSelLQ = LookupTree(s3_loadDataFromLQ.addrOffset, List(
1132    "b000".U -> s3_rdataLQ(63, 0),
1133    "b001".U -> s3_rdataLQ(63, 8),
1134    "b010".U -> s3_rdataLQ(63, 16),
1135    "b011".U -> s3_rdataLQ(63, 24),
1136    "b100".U -> s3_rdataLQ(63, 32),
1137    "b101".U -> s3_rdataLQ(63, 40),
1138    "b110".U -> s3_rdataLQ(63, 48),
1139    "b111".U -> s3_rdataLQ(63, 56)
1140  ))
1141  val s3_rdataPartialLoadLQ = rdataHelper(s3_loadDataFromLQ.uop, s3_rdataSelLQ)
1142
1143  // data from dcache hit
1144  val s3_loadDataFromDcache = load_s2.io.loadDataFromDcache
1145  val s3_rdataDcache = s3_loadDataFromDcache.mergedData()
1146  val s3_rdataSelDcache = LookupTree(s3_loadDataFromDcache.addrOffset, List(
1147    "b000".U -> s3_rdataDcache(63, 0),
1148    "b001".U -> s3_rdataDcache(63, 8),
1149    "b010".U -> s3_rdataDcache(63, 16),
1150    "b011".U -> s3_rdataDcache(63, 24),
1151    "b100".U -> s3_rdataDcache(63, 32),
1152    "b101".U -> s3_rdataDcache(63, 40),
1153    "b110".U -> s3_rdataDcache(63, 48),
1154    "b111".U -> s3_rdataDcache(63, 56)
1155  ))
1156  val s3_rdataPartialLoadDcache = rdataHelper(s3_loadDataFromDcache.uop, s3_rdataSelDcache)
1157
1158  io.ldout.bits := s3_load_wb_meta_reg
1159  io.ldout.bits.data := Mux(RegNext(hitLoadOut.valid), s3_rdataPartialLoadDcache, s3_rdataPartialLoadLQ)
1160  io.ldout.valid := RegNext(hitLoadOut.valid) && !RegNext(load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)) ||
1161    RegNext(io.lsq.ldout.valid) && !RegNext(io.lsq.ldout.bits.uop.robIdx.needFlush(io.redirect)) && !RegNext(hitLoadOut.valid)
1162
1163  io.ldout.bits.uop.cf.exceptionVec(loadAccessFault) := s3_load_wb_meta_reg.uop.cf.exceptionVec(loadAccessFault) ||
1164    RegNext(hitLoadOut.valid) && load_s2.io.s3_delayed_load_error
1165
1166  // fast load to load forward
1167  io.fastpathOut.valid := RegNext(load_s2.io.out.valid) // for debug only
1168  io.fastpathOut.data := s3_loadDataFromDcache.mergedData() // fastpath is for ld only
1169
1170  // feedback tlb miss / dcache miss queue full
1171  io.feedbackSlow.bits := RegNext(load_s2.io.rsFeedback.bits)
1172  io.feedbackSlow.valid := RegNext(load_s2.io.rsFeedback.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect))
1173  // If replay is reported at load_s1, inst will be canceled (will not enter load_s2),
1174  // in that case:
1175  // * replay should not be reported twice
1176  assert(!(RegNext(io.feedbackFast.valid) && io.feedbackSlow.valid))
1177  // * io.fastUop.valid should not be reported
1178  assert(!RegNext(io.feedbackFast.valid && !io.feedbackFast.bits.hit && io.fastUop.valid))
1179
1180  // load forward_fail/ldld_violation check
1181  // check for inst in load pipeline
1182  val s3_forward_fail = RegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid)
1183  val s3_ldld_violation = RegNext(
1184    io.lsq.loadViolationQuery.resp.valid &&
1185    io.lsq.loadViolationQuery.resp.bits.have_violation &&
1186    RegNext(io.csrCtrl.ldld_vio_check_enable)
1187  )
1188  val s3_need_replay_from_fetch = s3_forward_fail || s3_ldld_violation
1189  val s3_can_replay_from_fetch = RegEnable(load_s2.io.s2_can_replay_from_fetch, load_s2.io.out.valid)
1190  // 1) use load pipe check result generated in load_s3 iff load_hit
1191  when (RegNext(hitLoadOut.valid)) {
1192    io.ldout.bits.uop.ctrl.replayInst := s3_need_replay_from_fetch
1193  }
1194  // 2) otherwise, write check result to load queue
1195  io.lsq.s3_replay_from_fetch := s3_need_replay_from_fetch && s3_can_replay_from_fetch
1196
1197  // s3_delayed_load_error path is not used for now, as we writeback load result in load_s3
1198  // but we keep this path for future use
1199  io.s3_delayed_load_error := false.B
1200  io.lsq.s3_delayed_load_error := false.B //load_s2.io.s3_delayed_load_error
1201
1202  io.lsq.ldout.ready := !hitLoadOut.valid
1203
1204  when(io.feedbackSlow.valid && !io.feedbackSlow.bits.hit){
1205    // when need replay from rs, inst should not be writebacked to rob
1206    assert(RegNext(!hitLoadOut.valid))
1207    assert(RegNext(!io.lsq.loadIn.valid) || RegNext(load_s2.io.s2_dcache_require_replay))
1208  }
1209
1210  // hareware prefetch to l1
1211  io.prefetch_req <> load_s0.io.prefetch_in
1212
1213  // trigger
1214  val lastValidData = RegEnable(io.ldout.bits.data, io.ldout.fire)
1215  val hitLoadAddrTriggerHitVec = Wire(Vec(3, Bool()))
1216  val lqLoadAddrTriggerHitVec = io.lsq.trigger.lqLoadAddrTriggerHitVec
1217  (0 until 3).map{i => {
1218    val tdata2 = io.trigger(i).tdata2
1219    val matchType = io.trigger(i).matchType
1220    val tEnable = io.trigger(i).tEnable
1221
1222    hitLoadAddrTriggerHitVec(i) := TriggerCmp(load_s2.io.out.bits.vaddr, tdata2, matchType, tEnable)
1223    io.trigger(i).addrHit := Mux(hitLoadOut.valid, hitLoadAddrTriggerHitVec(i), lqLoadAddrTriggerHitVec(i))
1224    io.trigger(i).lastDataHit := TriggerCmp(lastValidData, tdata2, matchType, tEnable)
1225  }}
1226  io.lsq.trigger.hitLoadAddrTriggerHitVec := hitLoadAddrTriggerHitVec
1227
1228  // s1
1229  io.debug_ls.s1.isBankConflict := load_s1.io.in.fire && (!load_s1.io.dcacheKill && load_s1.io.dcacheBankConflict)
1230  io.debug_ls.s1.isLoadToLoadForward := load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing
1231  io.debug_ls.s1.isTlbFirstMiss := io.tlb.resp.valid && io.tlb.resp.bits.miss && io.tlb.resp.bits.debug.isFirstIssue
1232  io.debug_ls.s1.isReplayFast := io.lsq.replayFast.valid && io.lsq.replayFast.needreplay
1233  io.debug_ls.s1_robIdx := load_s1.io.in.bits.uop.robIdx.value
1234  // s2
1235  io.debug_ls.s2.isDcacheFirstMiss := load_s2.io.in.fire && load_s2.io.in.bits.isFirstIssue && load_s2.io.dcacheResp.bits.miss
1236  io.debug_ls.s2.isForwardFail := load_s2.io.in.fire && load_s2.io.s2_forward_fail
1237  io.debug_ls.s2.isReplaySlow := io.lsq.replaySlow.valid && io.lsq.replaySlow.needreplay
1238  io.debug_ls.s2.isLoadReplayTLBMiss := io.lsq.replaySlow.valid && !io.lsq.replaySlow.tlb_hited
1239  io.debug_ls.s2.isLoadReplayCacheMiss := io.lsq.replaySlow.valid && !io.lsq.replaySlow.cache_hited
1240  io.debug_ls.replayCnt := DontCare
1241  io.debug_ls.s2_robIdx := load_s2.io.in.bits.uop.robIdx.value
1242
1243  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1244  // hardware performance counter
1245  val perfEvents = Seq(
1246    ("load_s0_in_fire         ", load_s0.io.in.fire                                                                                                              ),
1247    ("load_to_load_forward    ", load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing                                                           ),
1248    ("stall_dcache            ", load_s0.io.out.valid && load_s0.io.out.ready && !load_s0.io.dcacheReq.ready                                                     ),
1249    ("load_s1_in_fire         ", load_s1.io.in.fire                                                                                                              ),
1250    ("load_s1_tlb_miss        ", load_s1.io.in.fire && load_s1.io.dtlbResp.bits.miss                                                                             ),
1251    ("load_s2_in_fire         ", load_s2.io.in.fire                                                                                                              ),
1252    ("load_s2_dcache_miss     ", load_s2.io.in.fire && load_s2.io.dcacheResp.bits.miss                                                                           ),
1253    ("load_s2_replay          ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit                                                                  ),
1254    ("load_s2_replay_tlb_miss ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && load_s2.io.in.bits.tlbMiss                                    ),
1255    ("load_s2_replay_cache    ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && !load_s2.io.in.bits.tlbMiss && load_s2.io.dcacheResp.bits.miss),
1256  )
1257  generatePerfEvent()
1258
1259  when(io.ldout.fire){
1260    XSDebug("ldout %x\n", io.ldout.bits.uop.cf.pc)
1261  }
1262}
1263