xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision 8a00ff566bcba2487c171ffd13c225a25e8ff441)
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.fu.FuConfig.LduCfg
28import xiangshan.backend.rob.DebugLsInfoBundle
29import xiangshan.cache._
30import xiangshan.cache.dcache.ReplayCarry
31import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
32import xiangshan.backend.Bundles.{DynInst, MemExuInput, MemExuOutput}
33
34class LoadToLsqFastIO(implicit p: Parameters) extends XSBundle {
35  val valid = Output(Bool())
36  val ld_ld_check_ok = Output(Bool())
37  val st_ld_check_ok = Output(Bool())
38  val cache_bank_no_conflict = Output(Bool())
39  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
40  val debug = Output(new PerfDebugInfo)
41
42  def needreplay: Bool = {
43    !ld_ld_check_ok || !st_ld_check_ok || !cache_bank_no_conflict
44  }
45}
46
47class LoadToLsqSlowIO(implicit p: Parameters) extends XSBundle with HasDCacheParameters {
48  val valid = Output(Bool())
49  val tlb_hited = Output(Bool())
50  val st_ld_check_ok = Output(Bool())
51  val cache_no_replay = Output(Bool())
52  val forward_data_valid = Output(Bool())
53  val cache_hited = Output(Bool())
54  val can_forward_full_data = Output(Bool())
55  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
56  val data_invalid_sq_idx = Output(UInt(log2Ceil(StoreQueueSize).W))
57  val replayCarry = Output(new ReplayCarry)
58  val miss_mshr_id = Output(UInt(log2Up(cfg.nMissEntries).W))
59  val data_in_last_beat = Output(Bool())
60  val debug = Output(new PerfDebugInfo)
61
62  def needreplay: Bool = {
63    !tlb_hited || !st_ld_check_ok || !cache_no_replay || !forward_data_valid || !cache_hited
64  }
65}
66
67class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
68  val loadIn = ValidIO(new LqWriteBundle)
69  val loadPaddrIn = ValidIO(new LqPaddrWriteBundle)
70  val loadVaddrIn = ValidIO(new LqVaddrWriteBundle)
71  val ldout = Flipped(DecoupledIO(new MemExuOutput))
72  val ldRawData = Input(new LoadDataFromLQBundle)
73  val s2_load_data_forwarded = Output(Bool())
74  val s3_delayed_load_error = Output(Bool())
75  val s2_dcache_require_replay = Output(Bool())
76  val s3_replay_from_fetch = Output(Bool()) // update uop.ctrl.replayInst in load queue in s3
77  val forward = new PipeLoadForwardQueryIO
78  val loadViolationQuery = new LoadViolationQueryIO
79  val trigger = Flipped(new LqTriggerIO)
80
81  // for load replay
82  val replayFast = new LoadToLsqFastIO
83  val replaySlow = new LoadToLsqSlowIO
84}
85
86class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
87  // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
88  val data = UInt(XLEN.W)
89  val valid = Bool()
90}
91
92class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
93  val tdata2 = Input(UInt(64.W))
94  val matchType = Input(UInt(2.W))
95  val tEnable = Input(Bool()) // timing is calculated before this
96  val addrHit = Output(Bool())
97  val lastDataHit = Output(Bool())
98}
99
100// Load Pipeline Stage 0
101// Generate addr, use addr to query DCache and DTLB
102class LoadUnit_S0(implicit p: Parameters) extends XSModule with HasDCacheParameters{
103  val io = IO(new Bundle() {
104    val in = Flipped(Decoupled(new MemExuInput))
105    val out = Decoupled(new LsPipelineBundle)
106    val prefetch_in = Flipped(ValidIO(new L1PrefetchReq))
107    val dtlbReq = DecoupledIO(new TlbReq)
108    val dcacheReq = DecoupledIO(new DCacheWordReq)
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 == backendParams.LduCnt)
119
120  val s0_vaddr = Wire(UInt(VAddrBits.W))
121  val s0_mask = Wire(UInt(8.W))
122  val s0_uop = Wire(new DynInst)
123  val s0_isFirstIssue = Wire(Bool())
124  val s0_rsIdx = Wire(UInt(log2Up(MemIQSizeMax).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.fuOpType === LSUOpType.prefetch_r)
209  val isPrefetchWrite = WireInit(s0_uop.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.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.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.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.imm(11, 0)
286    s0_vaddr := io.in.bits.src(0) + SignExt(imm12, VAddrBits)
287    s0_mask := genWmask(s0_vaddr, io.in.bits.uop.fuOpType(1,0))
288    s0_uop := io.in.bits.uop
289    s0_isFirstIssue := io.in.bits.isFirstIssue
290    s0_rsIdx := io.in.bits.iqIdx
291    s0_sqIdx := io.in.bits.uop.sqIdx
292    val issueUopIsPrefetch = WireInit(LSUOpType.isPrefetch(io.in.bits.uop.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.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.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.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.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.in.bits.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.in.bits.isFirstIssue)
366  XSPerfAccumulate("addr_spec_failed_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12) && io.in.bits.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.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.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.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.exceptionVec(loadPageFault) := io.dtlbResp.bits.excp(0).pf.ld
506  io.out.bits.uop.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.exceptionVec)
581  s2_exception_vec(loadAccessFault) := io.in.bits.uop.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.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.fpWen := io.in.bits.uop.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.flushPipe := s2_mmio && io.sentFastUop
721  io.out.bits.uop.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 MemExuInput))
845    val ldout = Decoupled(new MemExuOutput)
846    val redirect = Flipped(ValidIO(new Redirect))
847    val feedbackSlow = ValidIO(new RSFeedback)
848    val feedbackFast = ValidIO(new RSFeedback)
849    val dcache = new DCacheLoadIO
850    val sbuffer = new LoadForwardQueryIO
851    val lsq = new LoadToLsqIO
852    val tlDchannel = Input(new DcacheToLduForwardIO)
853    val forward_mshr = Flipped(new LduToMissqueueForwardIO)
854    val refill = Flipped(ValidIO(new Refill))
855    val fastUop = ValidIO(new DynInst) // early wakeup signal generated in load_s1, send to RS in load_s2
856    val trigger = Vec(3, new LoadUnitTriggerIO)
857
858    val tlb = new TlbRequestIO(2)
859    val pmp = Flipped(new PMPRespBundle()) // arrive same to tlb now
860
861    // provide prefetch info
862    val prefetch_train = ValidIO(new LdPrefetchTrainBundle())
863
864    // hardware prefetch to l1 cache req
865    val prefetch_req = Flipped(ValidIO(new L1PrefetchReq))
866
867    // load to load fast path
868    val fastpathOut = Output(new LoadToLoadIO)
869    val fastpathIn = Input(new LoadToLoadIO)
870    val loadFastMatch = Input(Bool())
871    val loadFastImm = Input(UInt(12.W))
872
873    // load ecc
874    val s3_delayed_load_error = Output(Bool()) // load ecc error
875    // Note that io.s3_delayed_load_error and io.lsq.s3_delayed_load_error is different
876
877    // load unit ctrl
878    val csrCtrl = Flipped(new CustomCSRCtrlIO)
879
880    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))    // load replay
881    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
882    val debug_ls = Output(new DebugLsInfoBundle)
883    val s2IsPointerChasing = Output(Bool()) // provide right pc for hw prefetch
884  })
885
886  val load_s0 = Module(new LoadUnit_S0)
887  val load_s1 = Module(new LoadUnit_S1)
888  val load_s2 = Module(new LoadUnit_S2)
889
890  load_s0.io.lsqOut <> io.lsqOut
891
892  // load s0
893  load_s0.io.in <> io.ldin
894  load_s0.io.dtlbReq <> io.tlb.req
895  load_s0.io.dcacheReq <> io.dcache.req
896  load_s0.io.s0_kill := false.B
897
898  // we try pointerchasing if lfsrc_l2lForward_select condition is satisfied
899  val s0_tryPointerChasing = load_s0.io.l2lForward_select
900  val s0_pointerChasingVAddr = io.fastpathIn.data(5, 0) +& io.loadFastImm(5, 0)
901  load_s0.io.fastpath.valid := io.fastpathIn.valid
902  load_s0.io.fastpath.data := Cat(io.fastpathIn.data(XLEN-1, 6), s0_pointerChasingVAddr(5,0))
903
904  val s1_data = PipelineConnect(load_s0.io.out, load_s1.io.in, true.B,
905    load_s0.io.out.bits.uop.robIdx.needFlush(io.redirect) && !s0_tryPointerChasing).get
906
907  // load s1
908  // update s1_kill when any source has valid request
909  load_s1.io.s1_kill := RegEnable(load_s0.io.s0_kill, false.B, io.ldin.valid || io.lsqOut.valid || io.fastpathIn.valid)
910  io.tlb.req_kill := load_s1.io.s1_kill
911  load_s1.io.dtlbResp <> io.tlb.resp
912  io.dcache.s1_paddr_dup_lsu <> load_s1.io.lsuPAddr
913  io.dcache.s1_paddr_dup_dcache <> load_s1.io.dcachePAddr
914  io.dcache.s1_kill := load_s1.io.dcacheKill
915  load_s1.io.sbuffer <> io.sbuffer
916  load_s1.io.lsq <> io.lsq.forward
917  load_s1.io.loadViolationQueryReq <> io.lsq.loadViolationQuery.req
918  load_s1.io.dcacheBankConflict <> io.dcache.s1_bank_conflict
919  load_s1.io.csrCtrl <> io.csrCtrl
920  load_s1.io.reExecuteQuery := io.reExecuteQuery
921  // provide paddr and vaddr for lq
922  io.lsq.loadPaddrIn.valid := load_s1.io.out.valid && !load_s1.io.out.bits.isHWPrefetch
923  io.lsq.loadPaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
924  io.lsq.loadPaddrIn.bits.paddr := load_s1.io.lsuPAddr
925
926  io.lsq.loadVaddrIn.valid := load_s1.io.in.valid && !load_s1.io.s1_kill && !load_s1.io.out.bits.isHWPrefetch
927  io.lsq.loadVaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
928  io.lsq.loadVaddrIn.bits.vaddr := load_s1.io.out.bits.vaddr
929
930  // when S0 has opportunity to try pointerchasing, make sure it truely goes to S1
931  // which is S0's out is ready and dcache is ready
932  val s0_doTryPointerChasing = s0_tryPointerChasing && load_s0.io.out.ready && load_s0.io.dcacheReq.ready
933  val s1_tryPointerChasing = RegNext(s0_doTryPointerChasing, false.B)
934  val s1_pointerChasingVAddr = RegEnable(s0_pointerChasingVAddr, s0_doTryPointerChasing)
935  val cancelPointerChasing = WireInit(false.B)
936  if (EnableLoadToLoadForward) {
937    // Sometimes, we need to cancel the load-load forwarding.
938    // These can be put at S0 if timing is bad at S1.
939    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
940    val addressMisMatch = s1_pointerChasingVAddr(6) || RegEnable(io.loadFastImm(11, 6).orR, s0_doTryPointerChasing)
941    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
942    val addressNotAligned = s1_pointerChasingVAddr(2, 0).orR
943    val fuOpTypeIsNotLd = io.ldin.bits.uop.fuOpType =/= LSUOpType.ld
944    // Case 2: this is not a valid load-load pair
945    val notFastMatch = RegEnable(!io.loadFastMatch, s0_tryPointerChasing)
946    // Case 3: this load-load uop is cancelled
947    val isCancelled = !io.ldin.valid
948    when (s1_tryPointerChasing) {
949      cancelPointerChasing := addressMisMatch || addressNotAligned || fuOpTypeIsNotLd || notFastMatch || isCancelled
950      load_s1.io.in.bits.uop := io.ldin.bits.uop
951      val spec_vaddr = s1_data.vaddr
952      val vaddr = Cat(spec_vaddr(VAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
953      load_s1.io.in.bits.vaddr := vaddr
954      load_s1.io.in.bits.rsIdx := io.ldin.bits.iqIdx
955      load_s1.io.in.bits.isFirstIssue := io.ldin.bits.isFirstIssue
956      // We need to replace vaddr(5, 3).
957      val spec_paddr = io.tlb.resp.bits.paddr(0)
958      load_s1.io.dtlbResp.bits.paddr.foreach(_ := Cat(spec_paddr(PAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W)))
959      // 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)
960      load_s1.io.in.bits.uop.debugInfo.tlbFirstReqTime := GTimer()
961      load_s1.io.in.bits.uop.debugInfo.tlbRespTime := GTimer()
962    }
963    when (cancelPointerChasing) {
964      load_s1.io.s1_kill := true.B
965    }.otherwise {
966      load_s0.io.s0_kill := s1_tryPointerChasing && !io.lsqOut.valid
967      when (s1_tryPointerChasing) {
968        io.ldin.ready := true.B
969      }
970    }
971
972    XSPerfAccumulate("load_to_load_forward", s1_tryPointerChasing && !cancelPointerChasing)
973    XSPerfAccumulate("load_to_load_forward_try", s1_tryPointerChasing)
974    XSPerfAccumulate("load_to_load_forward_fail", cancelPointerChasing)
975    XSPerfAccumulate("load_to_load_forward_fail_cancelled", cancelPointerChasing && isCancelled)
976    XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", cancelPointerChasing && !isCancelled && notFastMatch)
977    XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",
978      cancelPointerChasing && !isCancelled && !notFastMatch && fuOpTypeIsNotLd)
979    XSPerfAccumulate("load_to_load_forward_fail_addr_align",
980      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && addressNotAligned)
981    XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",
982      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && !addressNotAligned && addressMisMatch)
983  }
984  PipelineConnect(load_s1.io.out, load_s2.io.in, true.B,
985    load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect) || cancelPointerChasing)
986
987  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)
988
989  io.forward_mshr.valid := load_s1.io.out.valid && load_s1.io.out.bits.forward_tlDchannel
990  io.forward_mshr.mshrid := load_s1.io.out.bits.mshrid
991  io.forward_mshr.paddr := load_s1.io.out.bits.paddr
992  val (forward_result_valid, forward_mshr, forwardData_mshr) = io.forward_mshr.forward()
993
994  XSPerfAccumulate("successfully_forward_channel_D", forward_D && forward_result_valid)
995  XSPerfAccumulate("successfully_forward_mshr", forward_mshr && forward_result_valid)
996  // load s2
997  load_s2.io.forward_D := forward_D
998  load_s2.io.forwardData_D := forwardData_D
999  load_s2.io.forward_result_valid := forward_result_valid
1000  load_s2.io.forward_mshr := forward_mshr
1001  load_s2.io.forwardData_mshr := forwardData_mshr
1002  io.s2IsPointerChasing := RegEnable(s1_tryPointerChasing && !cancelPointerChasing, load_s1.io.out.fire)
1003  io.prefetch_train.bits.fromLsPipelineBundle(load_s2.io.in.bits)
1004  // override miss bit
1005  io.prefetch_train.bits.miss := io.dcache.resp.bits.miss
1006  io.prefetch_train.bits.meta_prefetch := io.dcache.resp.bits.meta_prefetch
1007  io.prefetch_train.bits.meta_access := io.dcache.resp.bits.meta_access
1008  io.prefetch_train.valid := load_s2.io.in.fire && !load_s2.io.out.bits.mmio && !load_s2.io.in.bits.tlbMiss
1009  io.dcache.s2_kill := load_s2.io.dcache_kill // to kill mmio resp which are redirected
1010  if (env.FPGAPlatform)
1011    io.dcache.s2_pc := DontCare
1012  else
1013    io.dcache.s2_pc := load_s2.io.out.bits.uop.pc
1014  load_s2.io.dcacheResp <> io.dcache.resp
1015  load_s2.io.pmpResp <> io.pmp
1016  load_s2.io.static_pm := RegNext(io.tlb.resp.bits.static_pm)
1017  load_s2.io.lsq.forwardData <> io.lsq.forward.forwardData
1018  load_s2.io.lsq.forwardMask <> io.lsq.forward.forwardMask
1019  load_s2.io.lsq.forwardMaskFast <> io.lsq.forward.forwardMaskFast // should not be used in load_s2
1020  load_s2.io.lsq.dataInvalid <> io.lsq.forward.dataInvalid
1021  load_s2.io.lsq.matchInvalid <> io.lsq.forward.matchInvalid
1022  load_s2.io.sbuffer.forwardData <> io.sbuffer.forwardData
1023  load_s2.io.sbuffer.forwardMask <> io.sbuffer.forwardMask
1024  load_s2.io.sbuffer.forwardMaskFast <> io.sbuffer.forwardMaskFast // should not be used in load_s2
1025  load_s2.io.sbuffer.dataInvalid <> io.sbuffer.dataInvalid // always false
1026  load_s2.io.sbuffer.matchInvalid <> io.sbuffer.matchInvalid
1027  load_s2.io.dataForwarded <> io.lsq.s2_load_data_forwarded
1028  load_s2.io.dataInvalidSqIdx := io.lsq.forward.dataInvalidSqIdx // provide dataInvalidSqIdx to make wakeup faster
1029  load_s2.io.loadViolationQueryResp <> io.lsq.loadViolationQuery.resp
1030  load_s2.io.csrCtrl <> io.csrCtrl
1031  load_s2.io.sentFastUop := io.fastUop.valid
1032  load_s2.io.reExecuteQuery := io.reExecuteQuery
1033  // feedback bank conflict / ld-vio check struct hazard to rs
1034  io.feedbackFast.bits := RegNext(load_s1.io.rsFeedback.bits)
1035  io.feedbackFast.valid := RegNext(load_s1.io.rsFeedback.valid && !load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect))
1036
1037  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
1038  val sqIdxMaskReg = RegNext(UIntToMask(load_s0.io.s0_sqIdx.value, StoreQueueSize))
1039  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
1040  // If the timing here is not OK, load-load forwarding has to be disabled.
1041  // Or we calculate sqIdxMask at RS??
1042  io.lsq.forward.sqIdxMask := sqIdxMaskReg
1043  if (EnableLoadToLoadForward) {
1044    when (s1_tryPointerChasing) {
1045      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
1046    }
1047  }
1048
1049  // // use s2_hit_way to select data received in s1
1050  // load_s2.io.dcacheResp.bits.data := Mux1H(RegNext(io.dcache.s1_hit_way), RegNext(io.dcache.s1_data))
1051  // assert(load_s2.io.dcacheResp.bits.data === io.dcache.resp.bits.data)
1052
1053  // now io.fastUop.valid is sent to RS in load_s2
1054  val forward_D_or_mshr_valid = forward_result_valid && (forward_D || forward_mshr)
1055  val s2_dcache_hit = io.dcache.s2_hit || forward_D_or_mshr_valid // dcache hit dup in lsu side
1056
1057  io.fastUop.valid := RegNext(
1058      !io.dcache.s1_disable_fast_wakeup &&  // load fast wakeup should be disabled when dcache data read is not ready
1059      load_s1.io.in.valid && // valid load request
1060      !load_s1.io.in.bits.isHWPrefetch && // is not hardware prefetch req
1061      !load_s1.io.s1_kill && // killed by load-load forwarding
1062      !load_s1.io.dtlbResp.bits.fast_miss && // not mmio or tlb miss, pf / af not included here
1063      !io.lsq.forward.dataInvalidFast // forward failed
1064    ) &&
1065    !RegNext(load_s1.io.needLdVioCheckRedo) && // load-load violation check: load paddr cam struct hazard
1066    !RegNext(load_s1.io.needReExecute) &&
1067    !RegNext(load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) &&
1068    (load_s2.io.in.valid && !load_s2.io.needReExecute && s2_dcache_hit) // dcache hit in lsu side
1069
1070  io.fastUop.bits := RegNext(load_s1.io.out.bits.uop)
1071
1072  XSDebug(load_s0.io.out.valid,
1073    p"S0: pc ${Hexadecimal(load_s0.io.out.bits.uop.pc)}, lId ${Hexadecimal(load_s0.io.out.bits.uop.lqIdx.asUInt)}, " +
1074    p"vaddr ${Hexadecimal(load_s0.io.out.bits.vaddr)}, mask ${Hexadecimal(load_s0.io.out.bits.mask)}\n")
1075  XSDebug(load_s1.io.out.valid,
1076    p"S1: pc ${Hexadecimal(load_s1.io.out.bits.uop.pc)}, lId ${Hexadecimal(load_s1.io.out.bits.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
1077    p"paddr ${Hexadecimal(load_s1.io.out.bits.paddr)}, mmio ${load_s1.io.out.bits.mmio}\n")
1078
1079  // writeback to LSQ
1080  // Current dcache use MSHR
1081  // Load queue will be updated at s2 for both hit/miss int/fp load
1082  io.lsq.loadIn.valid := load_s2.io.out.valid && !load_s2.io.out.bits.isHWPrefetch
1083  // generate LqWriteBundle from LsPipelineBundle
1084  io.lsq.loadIn.bits.fromLsPipelineBundle(load_s2.io.out.bits)
1085
1086  io.lsq.replayFast := load_s1.io.replayFast
1087  io.lsq.replaySlow := load_s2.io.replaySlow
1088  io.lsq.replaySlow.valid := load_s2.io.replaySlow.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)
1089
1090  // generate duplicated load queue data wen
1091  val load_s2_valid_vec = RegInit(0.U(6.W))
1092  val load_s2_leftFire = load_s1.io.out.valid && load_s2.io.in.ready
1093  // val write_lq_safe = load_s2.io.write_lq_safe
1094  load_s2_valid_vec := 0x0.U(6.W)
1095  when (load_s2_leftFire && !load_s1.io.out.bits.isHWPrefetch) { load_s2_valid_vec := 0x3f.U(6.W)} // TODO: refactor me
1096  when (load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) { load_s2_valid_vec := 0x0.U(6.W) }
1097  assert(RegNext((load_s2.io.in.valid === load_s2_valid_vec(0)) || RegNext(load_s1.io.out.bits.isHWPrefetch)))
1098  io.lsq.loadIn.bits.lq_data_wen_dup := load_s2_valid_vec.asBools()
1099
1100  // s2_dcache_require_replay signal will be RegNexted, then used in s3
1101  io.lsq.s2_dcache_require_replay := load_s2.io.s2_dcache_require_replay
1102
1103  // write to rob and writeback bus
1104  val s2_wb_valid = load_s2.io.out.valid && !load_s2.io.out.bits.miss && !load_s2.io.out.bits.mmio
1105
1106  // Int load, if hit, will be writebacked at s2
1107  val hitLoadOut = Wire(Valid(new MemExuOutput))
1108  hitLoadOut.valid := s2_wb_valid
1109  hitLoadOut.bits.uop := load_s2.io.out.bits.uop
1110  hitLoadOut.bits.data := load_s2.io.out.bits.data
1111  hitLoadOut.bits.debug.isMMIO := load_s2.io.out.bits.mmio
1112  hitLoadOut.bits.debug.isPerfCnt := false.B
1113  hitLoadOut.bits.debug.paddr := load_s2.io.out.bits.paddr
1114  hitLoadOut.bits.debug.vaddr := load_s2.io.out.bits.vaddr
1115
1116  load_s2.io.out.ready := true.B
1117
1118  // load s3
1119  val s3_load_wb_meta_reg = RegNext(Mux(hitLoadOut.valid, hitLoadOut.bits, io.lsq.ldout.bits))
1120
1121  // data from load queue refill
1122  val s3_loadDataFromLQ = RegEnable(io.lsq.ldRawData, io.lsq.ldout.valid)
1123  val s3_rdataLQ = s3_loadDataFromLQ.mergedData()
1124  val s3_rdataSelLQ = LookupTree(s3_loadDataFromLQ.addrOffset, List(
1125    "b000".U -> s3_rdataLQ(63, 0),
1126    "b001".U -> s3_rdataLQ(63, 8),
1127    "b010".U -> s3_rdataLQ(63, 16),
1128    "b011".U -> s3_rdataLQ(63, 24),
1129    "b100".U -> s3_rdataLQ(63, 32),
1130    "b101".U -> s3_rdataLQ(63, 40),
1131    "b110".U -> s3_rdataLQ(63, 48),
1132    "b111".U -> s3_rdataLQ(63, 56)
1133  ))
1134  val s3_rdataPartialLoadLQ = rdataHelper(s3_loadDataFromLQ.uop, s3_rdataSelLQ)
1135
1136  // data from dcache hit
1137  val s3_loadDataFromDcache = load_s2.io.loadDataFromDcache
1138  val s3_rdataDcache = s3_loadDataFromDcache.mergedData()
1139  val s3_rdataSelDcache = LookupTree(s3_loadDataFromDcache.addrOffset, List(
1140    "b000".U -> s3_rdataDcache(63, 0),
1141    "b001".U -> s3_rdataDcache(63, 8),
1142    "b010".U -> s3_rdataDcache(63, 16),
1143    "b011".U -> s3_rdataDcache(63, 24),
1144    "b100".U -> s3_rdataDcache(63, 32),
1145    "b101".U -> s3_rdataDcache(63, 40),
1146    "b110".U -> s3_rdataDcache(63, 48),
1147    "b111".U -> s3_rdataDcache(63, 56)
1148  ))
1149  val s3_rdataPartialLoadDcache = rdataHelper(s3_loadDataFromDcache.uop, s3_rdataSelDcache)
1150
1151  io.ldout.bits := s3_load_wb_meta_reg
1152  io.ldout.bits.data := Mux(RegNext(hitLoadOut.valid), s3_rdataPartialLoadDcache, s3_rdataPartialLoadLQ)
1153  io.ldout.valid := RegNext(hitLoadOut.valid) && !RegNext(load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)) ||
1154    RegNext(io.lsq.ldout.valid) && !RegNext(io.lsq.ldout.bits.uop.robIdx.needFlush(io.redirect)) && !RegNext(hitLoadOut.valid)
1155
1156  io.ldout.bits.uop.exceptionVec(loadAccessFault) := s3_load_wb_meta_reg.uop.exceptionVec(loadAccessFault) ||
1157    RegNext(hitLoadOut.valid) && load_s2.io.s3_delayed_load_error
1158
1159  // fast load to load forward
1160  io.fastpathOut.valid := RegNext(load_s2.io.out.valid) // for debug only
1161  io.fastpathOut.data := s3_loadDataFromDcache.mergedData() // fastpath is for ld only
1162
1163  // feedback tlb miss / dcache miss queue full
1164  io.feedbackSlow.bits := RegNext(load_s2.io.rsFeedback.bits)
1165  io.feedbackSlow.valid := RegNext(load_s2.io.rsFeedback.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect))
1166  // If replay is reported at load_s1, inst will be canceled (will not enter load_s2),
1167  // in that case:
1168  // * replay should not be reported twice
1169  assert(!(RegNext(io.feedbackFast.valid) && io.feedbackSlow.valid))
1170  // * io.fastUop.valid should not be reported
1171  assert(!RegNext(io.feedbackFast.valid && !io.feedbackFast.bits.hit && io.fastUop.valid))
1172
1173  // load forward_fail/ldld_violation check
1174  // check for inst in load pipeline
1175  val s3_forward_fail = RegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid)
1176  val s3_ldld_violation = RegNext(
1177    io.lsq.loadViolationQuery.resp.valid &&
1178    io.lsq.loadViolationQuery.resp.bits.have_violation &&
1179    RegNext(io.csrCtrl.ldld_vio_check_enable)
1180  )
1181  val s3_need_replay_from_fetch = s3_forward_fail || s3_ldld_violation
1182  val s3_can_replay_from_fetch = RegEnable(load_s2.io.s2_can_replay_from_fetch, load_s2.io.out.valid)
1183  // 1) use load pipe check result generated in load_s3 iff load_hit
1184  when (RegNext(hitLoadOut.valid)) {
1185    io.ldout.bits.uop.replayInst := s3_need_replay_from_fetch
1186  }
1187  // 2) otherwise, write check result to load queue
1188  io.lsq.s3_replay_from_fetch := s3_need_replay_from_fetch && s3_can_replay_from_fetch
1189
1190  // s3_delayed_load_error path is not used for now, as we writeback load result in load_s3
1191  // but we keep this path for future use
1192  io.s3_delayed_load_error := false.B
1193  io.lsq.s3_delayed_load_error := false.B //load_s2.io.s3_delayed_load_error
1194
1195  io.lsq.ldout.ready := !hitLoadOut.valid
1196
1197  when(io.feedbackSlow.valid && !io.feedbackSlow.bits.hit){
1198    // when need replay from rs, inst should not be writebacked to rob
1199    assert(RegNext(!hitLoadOut.valid))
1200    assert(RegNext(!io.lsq.loadIn.valid) || RegNext(load_s2.io.s2_dcache_require_replay))
1201  }
1202
1203  // hareware prefetch to l1
1204  io.prefetch_req <> load_s0.io.prefetch_in
1205
1206  // trigger
1207  val lastValidData = RegEnable(io.ldout.bits.data, io.ldout.fire)
1208  val hitLoadAddrTriggerHitVec = Wire(Vec(3, Bool()))
1209  val lqLoadAddrTriggerHitVec = io.lsq.trigger.lqLoadAddrTriggerHitVec
1210  (0 until 3).map{i => {
1211    val tdata2 = io.trigger(i).tdata2
1212    val matchType = io.trigger(i).matchType
1213    val tEnable = io.trigger(i).tEnable
1214
1215    hitLoadAddrTriggerHitVec(i) := TriggerCmp(load_s2.io.out.bits.vaddr, tdata2, matchType, tEnable)
1216    io.trigger(i).addrHit := Mux(hitLoadOut.valid, hitLoadAddrTriggerHitVec(i), lqLoadAddrTriggerHitVec(i))
1217    io.trigger(i).lastDataHit := TriggerCmp(lastValidData, tdata2, matchType, tEnable)
1218  }}
1219  io.lsq.trigger.hitLoadAddrTriggerHitVec := hitLoadAddrTriggerHitVec
1220
1221  // s1
1222  io.debug_ls.s1.isBankConflict := load_s1.io.in.fire && (!load_s1.io.dcacheKill && load_s1.io.dcacheBankConflict)
1223  io.debug_ls.s1.isLoadToLoadForward := load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing
1224  io.debug_ls.s1.isTlbFirstMiss := io.tlb.resp.valid && io.tlb.resp.bits.miss && io.tlb.resp.bits.debug.isFirstIssue
1225  io.debug_ls.s1.isReplayFast := io.lsq.replayFast.valid && io.lsq.replayFast.needreplay
1226  io.debug_ls.s1_robIdx := load_s1.io.in.bits.uop.robIdx.value
1227  // s2
1228  io.debug_ls.s2.isDcacheFirstMiss := load_s2.io.in.fire && load_s2.io.in.bits.isFirstIssue && load_s2.io.dcacheResp.bits.miss
1229  io.debug_ls.s2.isForwardFail := load_s2.io.in.fire && load_s2.io.s2_forward_fail
1230  io.debug_ls.s2.isReplaySlow := io.lsq.replaySlow.valid && io.lsq.replaySlow.needreplay
1231  io.debug_ls.s2.isLoadReplayTLBMiss := io.lsq.replaySlow.valid && !io.lsq.replaySlow.tlb_hited
1232  io.debug_ls.s2.isLoadReplayCacheMiss := io.lsq.replaySlow.valid && !io.lsq.replaySlow.cache_hited
1233  io.debug_ls.replayCnt := DontCare
1234  io.debug_ls.s2_robIdx := load_s2.io.in.bits.uop.robIdx.value
1235
1236  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1237  // hardware performance counter
1238  val perfEvents = Seq(
1239    ("load_s0_in_fire         ", load_s0.io.in.fire                                                                                                              ),
1240    ("load_to_load_forward    ", load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing                                                           ),
1241    ("stall_dcache            ", load_s0.io.out.valid && load_s0.io.out.ready && !load_s0.io.dcacheReq.ready                                                     ),
1242    ("load_s1_in_fire         ", load_s1.io.in.fire                                                                                                              ),
1243    ("load_s1_tlb_miss        ", load_s1.io.in.fire && load_s1.io.dtlbResp.bits.miss                                                                             ),
1244    ("load_s2_in_fire         ", load_s2.io.in.fire                                                                                                              ),
1245    ("load_s2_dcache_miss     ", load_s2.io.in.fire && load_s2.io.dcacheResp.bits.miss                                                                           ),
1246    ("load_s2_replay          ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit                                                                  ),
1247    ("load_s2_replay_tlb_miss ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && load_s2.io.in.bits.tlbMiss                                    ),
1248    ("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),
1249  )
1250  generatePerfEvent()
1251
1252  when(io.ldout.fire){
1253    XSDebug("ldout %x\n", io.ldout.bits.uop.pc)
1254  }
1255}
1256