xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision a760aeb0b1b64540d1f49146f82ddd6e87aa1e5e)
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 xiangshan.ExceptionNO._
24import xiangshan._
25import xiangshan.backend.fu.PMPRespBundle
26import xiangshan.cache._
27import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
28
29class LoadToLsqFastIO(implicit p: Parameters) extends XSBundle {
30  val valid = Output(Bool())
31  val ld_ld_check_ok = Output(Bool())
32  val cache_bank_no_conflict = Output(Bool())
33  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
34}
35
36class LoadToLsqSlowIO(implicit p: Parameters) extends XSBundle {
37  val valid = Output(Bool())
38  val tlb_hited = Output(Bool())
39  val cache_no_replay = Output(Bool())
40  val forward_data_valid = Output(Bool())
41  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
42  val data_invalid_sq_idx = Output(UInt(log2Ceil(StoreQueueSize).W))
43}
44
45class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
46  val loadIn = ValidIO(new LqWriteBundle)
47  val loadPaddrIn = ValidIO(new LqPaddrWriteBundle)
48  val loadVaddrIn = ValidIO(new LqVaddrWriteBundle)
49  val ldout = Flipped(DecoupledIO(new ExuOutput))
50  val ldRawData = Input(new LoadDataFromLQBundle)
51  val s2_load_data_forwarded = Output(Bool())
52  val s3_delayed_load_error = Output(Bool())
53  val s2_dcache_require_replay = Output(Bool())
54  val s3_replay_from_fetch = Output(Bool()) // update uop.ctrl.replayInst in load queue in s3
55  val forward = new PipeLoadForwardQueryIO
56  val loadViolationQuery = new LoadViolationQueryIO
57  val trigger = Flipped(new LqTriggerIO)
58
59  // for load replay
60  val replayFast = new LoadToLsqFastIO
61  val replaySlow = new LoadToLsqSlowIO
62}
63
64class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
65  // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
66  val data = UInt(XLEN.W)
67  val valid = Bool()
68}
69
70class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
71  val tdata2 = Input(UInt(64.W))
72  val matchType = Input(UInt(2.W))
73  val tEnable = Input(Bool()) // timing is calculated before this
74  val addrHit = Output(Bool())
75  val lastDataHit = Output(Bool())
76}
77
78// Load Pipeline Stage 0
79// Generate addr, use addr to query DCache and DTLB
80class LoadUnit_S0(implicit p: Parameters) extends XSModule with HasDCacheParameters{
81  val io = IO(new Bundle() {
82    val in = Flipped(Decoupled(new ExuInput))
83    val out = Decoupled(new LsPipelineBundle)
84    val dtlbReq = DecoupledIO(new TlbReq)
85    val dcacheReq = DecoupledIO(new DCacheWordReq)
86    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
87    val isFirstIssue = Input(Bool())
88    val fastpath = Input(new LoadToLoadIO)
89    val s0_kill = Input(Bool())
90    // wire from lq to load pipeline
91    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
92
93    val s0_sqIdx = Output(new SqPtr)
94  })
95  require(LoadPipelineWidth == exuParameters.LduCnt)
96
97  // there are three sources of load pipeline's input
98  // * 1. load issued by RS  (io.in)
99  // * 2. load replayed by LSQ  (io.lsqOut)
100  // * 3. load try pointchaising when no issued or replayed load  (io.fastpath)
101
102  // the priority is
103  // 1 > 2 > 3
104  // now in S0, choise a load according to priority
105
106  val s0_vaddr = Wire(UInt(VAddrBits.W))
107  val s0_mask = Wire(UInt(8.W))
108  val s0_uop = Wire(new MicroOp)
109  val s0_isFirstIssue = Wire(Bool())
110  val s0_rsIdx = Wire(UInt(log2Up(IssQueSize).W))
111  val s0_sqIdx = Wire(new SqPtr)
112
113  io.s0_sqIdx := s0_sqIdx
114
115  val tryFastpath = WireInit(false.B)
116
117  val s0_valid = Wire(Bool())
118
119  s0_valid := io.in.valid || io.lsqOut.valid || tryFastpath
120
121  // assign default value
122  s0_uop := DontCare
123
124  when(io.in.valid) {
125    val imm12 = io.in.bits.uop.ctrl.imm(11, 0)
126    s0_vaddr := io.in.bits.src(0) + SignExt(imm12, VAddrBits)
127    s0_mask := genWmask(s0_vaddr, io.in.bits.uop.ctrl.fuOpType(1,0))
128    s0_uop := io.in.bits.uop
129    s0_isFirstIssue := io.isFirstIssue
130    s0_rsIdx := io.rsIdx
131    s0_sqIdx := io.in.bits.uop.sqIdx
132
133  }.elsewhen(io.lsqOut.valid) {
134    s0_vaddr := io.lsqOut.bits.vaddr
135    s0_mask := io.lsqOut.bits.mask
136    s0_uop := io.lsqOut.bits.uop
137    s0_isFirstIssue := io.lsqOut.bits.isFirstIssue
138    s0_rsIdx := io.lsqOut.bits.rsIdx
139    s0_sqIdx := io.lsqOut.bits.uop.sqIdx
140
141  }.otherwise {
142    if (EnableLoadToLoadForward) {
143      tryFastpath := io.fastpath.valid
144      // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
145      s0_vaddr := io.fastpath.data
146      // Assume the pointer chasing is always ld.
147      s0_uop.ctrl.fuOpType := LSUOpType.ld
148      s0_mask := genWmask(0.U, LSUOpType.ld)
149      // we dont care s0_isFirstIssue and s0_rsIdx and s0_sqIdx in S0 when trying pointchasing
150      // because these signals will be updated in S1
151      s0_isFirstIssue := DontCare
152      s0_rsIdx := DontCare
153      s0_sqIdx := DontCare
154    }
155  }
156
157  val addrAligned = LookupTree(s0_uop.ctrl.fuOpType(1, 0), List(
158    "b00".U   -> true.B,                   //b
159    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
160    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
161    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
162  ))
163
164  // io.in has highest priority
165  io.in.ready := !io.in.valid || (io.out.ready && io.dcacheReq.ready)
166  // io.lsqOut can fire only when there in no RS-issued load
167  io.lsqOut.ready := (io.out.ready && io.dcacheReq.ready && !io.in.valid)
168
169  val isSoftPrefetch = LSUOpType.isPrefetch(s0_uop.ctrl.fuOpType)
170  val isSoftPrefetchRead = s0_uop.ctrl.fuOpType === LSUOpType.prefetch_r
171  val isSoftPrefetchWrite = s0_uop.ctrl.fuOpType === LSUOpType.prefetch_w
172
173  // query DTLB
174  io.dtlbReq.valid := s0_valid
175  io.dtlbReq.bits.vaddr := s0_vaddr
176  io.dtlbReq.bits.cmd := TlbCmd.read
177  io.dtlbReq.bits.size := LSUOpType.size(s0_uop.ctrl.fuOpType)
178  io.dtlbReq.bits.kill := DontCare
179  io.dtlbReq.bits.debug.robIdx := s0_uop.robIdx
180  io.dtlbReq.bits.debug.pc := s0_uop.cf.pc
181  io.dtlbReq.bits.debug.isFirstIssue := s0_isFirstIssue
182
183  // query DCache
184  io.dcacheReq.valid := s0_valid
185  when (isSoftPrefetchRead) {
186    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFR
187  }.elsewhen (isSoftPrefetchWrite) {
188    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFW
189  }.otherwise {
190    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_XRD
191  }
192  io.dcacheReq.bits.addr := s0_vaddr
193  io.dcacheReq.bits.mask := s0_mask
194  io.dcacheReq.bits.data := DontCare
195  when(isSoftPrefetch) {
196    io.dcacheReq.bits.instrtype := SOFT_PREFETCH.U
197  }.otherwise {
198    io.dcacheReq.bits.instrtype := LOAD_SOURCE.U
199  }
200
201  // TODO: update cache meta
202  io.dcacheReq.bits.id   := DontCare
203
204  io.out.valid := s0_valid && io.dcacheReq.ready && !io.s0_kill
205
206  io.out.bits := DontCare
207  io.out.bits.vaddr := s0_vaddr
208  io.out.bits.mask := s0_mask
209  io.out.bits.uop := s0_uop
210  io.out.bits.uop.cf.exceptionVec(loadAddrMisaligned) := !addrAligned
211  io.out.bits.rsIdx := s0_rsIdx
212  io.out.bits.isFirstIssue := s0_isFirstIssue
213  io.out.bits.isSoftPrefetch := isSoftPrefetch
214  io.out.bits.isLoadReplay := !io.in.valid && io.lsqOut.valid
215
216  XSDebug(io.dcacheReq.fire,
217    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.cf.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
218  )
219  XSPerfAccumulate("in_valid", io.in.valid)
220  XSPerfAccumulate("in_fire", io.in.fire)
221  XSPerfAccumulate("in_fire_first_issue", io.in.valid && io.isFirstIssue)
222  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready && io.dcacheReq.ready)
223  XSPerfAccumulate("stall_dcache", io.out.valid && io.out.ready && !io.dcacheReq.ready)
224  XSPerfAccumulate("addr_spec_success", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12))
225  XSPerfAccumulate("addr_spec_failed", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12))
226  XSPerfAccumulate("addr_spec_success_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
227  XSPerfAccumulate("addr_spec_failed_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
228}
229
230
231// Load Pipeline Stage 1
232// TLB resp (send paddr to dcache)
233class LoadUnit_S1(implicit p: Parameters) extends XSModule {
234  val io = IO(new Bundle() {
235    val in = Flipped(Decoupled(new LsPipelineBundle))
236    val s1_kill = Input(Bool())
237    val out = Decoupled(new LsPipelineBundle)
238    val dtlbResp = Flipped(DecoupledIO(new TlbResp(2)))
239    val lsuPAddr = Output(UInt(PAddrBits.W))
240    val dcachePAddr = Output(UInt(PAddrBits.W))
241    val dcacheKill = Output(Bool())
242    val dcacheBankConflict = Input(Bool())
243    val fullForwardFast = Output(Bool())
244    val sbuffer = new LoadForwardQueryIO
245    val lsq = new PipeLoadForwardQueryIO
246    val loadViolationQueryReq = Decoupled(new LoadViolationQueryReq)
247    val rsFeedback = ValidIO(new RSFeedback)
248    val replayFast = new LoadToLsqFastIO
249    val csrCtrl = Flipped(new CustomCSRCtrlIO)
250    val needLdVioCheckRedo = Output(Bool())
251  })
252
253  val s1_uop = io.in.bits.uop
254  val s1_paddr_dup_lsu = io.dtlbResp.bits.paddr(0)
255  val s1_paddr_dup_dcache = io.dtlbResp.bits.paddr(1)
256  // af & pf exception were modified below.
257  val s1_exception = ExceptionNO.selectByFu(io.out.bits.uop.cf.exceptionVec, lduCfg).asUInt.orR
258  val s1_tlb_miss = io.dtlbResp.bits.miss
259  val s1_mask = io.in.bits.mask
260  val s1_bank_conflict = io.dcacheBankConflict
261
262  io.out.bits := io.in.bits // forwardXX field will be updated in s1
263
264  io.dtlbResp.ready := true.B
265
266  io.lsuPAddr := s1_paddr_dup_lsu
267  io.dcachePAddr := s1_paddr_dup_dcache
268  //io.dcacheKill := s1_tlb_miss || s1_exception || s1_mmio
269  io.dcacheKill := s1_tlb_miss || s1_exception || io.s1_kill
270  // load forward query datapath
271  io.sbuffer.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
272  io.sbuffer.vaddr := io.in.bits.vaddr
273  io.sbuffer.paddr := s1_paddr_dup_lsu
274  io.sbuffer.uop := s1_uop
275  io.sbuffer.sqIdx := s1_uop.sqIdx
276  io.sbuffer.mask := s1_mask
277  io.sbuffer.pc := s1_uop.cf.pc // FIXME: remove it
278
279  io.lsq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
280  io.lsq.vaddr := io.in.bits.vaddr
281  io.lsq.paddr := s1_paddr_dup_lsu
282  io.lsq.uop := s1_uop
283  io.lsq.sqIdx := s1_uop.sqIdx
284  io.lsq.sqIdxMask := DontCare // will be overwritten by sqIdxMask pre-generated in s0
285  io.lsq.mask := s1_mask
286  io.lsq.pc := s1_uop.cf.pc // FIXME: remove it
287
288  // ld-ld violation query
289  io.loadViolationQueryReq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
290  io.loadViolationQueryReq.bits.paddr := s1_paddr_dup_lsu
291  io.loadViolationQueryReq.bits.uop := s1_uop
292
293  // Generate forwardMaskFast to wake up insts earlier
294  val forwardMaskFast = io.lsq.forwardMaskFast.asUInt | io.sbuffer.forwardMaskFast.asUInt
295  io.fullForwardFast := ((~forwardMaskFast).asUInt & s1_mask) === 0.U
296
297  // Generate feedback signal caused by:
298  // * dcache bank conflict
299  // * need redo ld-ld violation check
300  val needLdVioCheckRedo = io.loadViolationQueryReq.valid &&
301    !io.loadViolationQueryReq.ready &&
302    RegNext(io.csrCtrl.ldld_vio_check_enable)
303  io.needLdVioCheckRedo := needLdVioCheckRedo
304  // io.rsFeedback.valid := io.in.valid && (s1_bank_conflict || needLdVioCheckRedo) && !io.s1_kill
305  io.rsFeedback.valid := Mux(io.in.bits.isLoadReplay, false.B, io.in.valid && !io.s1_kill)
306  io.rsFeedback.bits.hit := true.B // we have found s1_bank_conflict / re do ld-ld violation check
307  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
308  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
309  io.rsFeedback.bits.sourceType := Mux(s1_bank_conflict, RSFeedbackType.bankConflict, RSFeedbackType.ldVioCheckRedo)
310  io.rsFeedback.bits.dataInvalidSqIdx := DontCare
311
312  io.replayFast.valid := io.in.valid && !io.s1_kill
313  io.replayFast.ld_ld_check_ok := !needLdVioCheckRedo
314  io.replayFast.cache_bank_no_conflict := !s1_bank_conflict
315  io.replayFast.ld_idx := io.in.bits.uop.lqIdx.value
316
317  // if replay is detected in load_s1,
318  // load inst will be canceled immediately
319  io.out.valid := io.in.valid && (!needLdVioCheckRedo && !s1_bank_conflict) && !io.s1_kill
320  io.out.bits.paddr := s1_paddr_dup_lsu
321  io.out.bits.tlbMiss := s1_tlb_miss
322
323  // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
324  // af & pf exception were modified
325  io.out.bits.uop.cf.exceptionVec(loadPageFault) := io.dtlbResp.bits.excp(0).pf.ld
326  io.out.bits.uop.cf.exceptionVec(loadAccessFault) := io.dtlbResp.bits.excp(0).af.ld
327
328  io.out.bits.ptwBack := io.dtlbResp.bits.ptwBack
329  io.out.bits.rsIdx := io.in.bits.rsIdx
330
331  io.out.bits.isSoftPrefetch := io.in.bits.isSoftPrefetch
332
333  io.in.ready := !io.in.valid || io.out.ready
334
335  XSPerfAccumulate("in_valid", io.in.valid)
336  XSPerfAccumulate("in_fire", io.in.fire)
337  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
338  XSPerfAccumulate("tlb_miss", io.in.fire && s1_tlb_miss)
339  XSPerfAccumulate("tlb_miss_first_issue", io.in.fire && s1_tlb_miss && io.in.bits.isFirstIssue)
340  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
341}
342
343// Load Pipeline Stage 2
344// DCache resp
345class LoadUnit_S2(implicit p: Parameters) extends XSModule with HasLoadHelper {
346  val io = IO(new Bundle() {
347    val in = Flipped(Decoupled(new LsPipelineBundle))
348    val out = Decoupled(new LsPipelineBundle)
349    val rsFeedback = ValidIO(new RSFeedback)
350    val replaySlow = new LoadToLsqSlowIO
351    val dcacheResp = Flipped(DecoupledIO(new BankedDCacheWordResp))
352    val pmpResp = Flipped(new PMPRespBundle())
353    val lsq = new LoadForwardQueryIO
354    val dataInvalidSqIdx = Input(UInt())
355    val sbuffer = new LoadForwardQueryIO
356    val dataForwarded = Output(Bool())
357    val s2_dcache_require_replay = Output(Bool())
358    val fullForward = Output(Bool())
359    val dcache_kill = Output(Bool())
360    val s3_delayed_load_error = Output(Bool())
361    val loadViolationQueryResp = Flipped(Valid(new LoadViolationQueryResp))
362    val csrCtrl = Flipped(new CustomCSRCtrlIO)
363    val sentFastUop = Input(Bool())
364    val static_pm = Input(Valid(Bool())) // valid for static, bits for mmio
365    val s2_can_replay_from_fetch = Output(Bool()) // dirty code
366    val loadDataFromDcache = Output(new LoadDataFromDcacheBundle)
367
368    // val write_lq_safe = Output(Bool()) // used by duplicate wen signals
369  })
370
371  val pmp = WireInit(io.pmpResp)
372  when (io.static_pm.valid) {
373    pmp.ld := false.B
374    pmp.st := false.B
375    pmp.instr := false.B
376    pmp.mmio := io.static_pm.bits
377  }
378
379  val s2_is_prefetch = io.in.bits.isSoftPrefetch
380
381  // exception that may cause load addr to be invalid / illegal
382  //
383  // if such exception happen, that inst and its exception info
384  // will be force writebacked to rob
385  val s2_exception_vec = WireInit(io.in.bits.uop.cf.exceptionVec)
386  s2_exception_vec(loadAccessFault) := io.in.bits.uop.cf.exceptionVec(loadAccessFault) || pmp.ld
387  // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
388  when (s2_is_prefetch) {
389    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
390  }
391  val s2_exception = ExceptionNO.selectByFu(s2_exception_vec, lduCfg).asUInt.orR && !io.in.bits.tlbMiss // ????????
392
393  // writeback access fault caused by ecc error / bus error
394  //
395  // * ecc data error is slow to generate, so we will not use it until load stage 3
396  // * in load stage 3, an extra signal io.load_error will be used to
397
398  // now cache ecc error will raise an access fault
399  // at the same time, error info (including error paddr) will be write to
400  // an customized CSR "CACHE_ERROR"
401  if (EnableAccurateLoadError) {
402    io.s3_delayed_load_error := io.dcacheResp.bits.error_delayed &&
403      io.csrCtrl.cache_error_enable &&
404      RegNext(io.out.valid)
405  } else {
406    io.s3_delayed_load_error := false.B
407  }
408
409  val actually_mmio = pmp.mmio
410  val s2_uop = io.in.bits.uop
411  val s2_mask = io.in.bits.mask
412  val s2_paddr = io.in.bits.paddr
413  val s2_tlb_miss = io.in.bits.tlbMiss
414  val s2_mmio = !s2_is_prefetch && actually_mmio && !s2_exception
415  val s2_cache_miss = io.dcacheResp.bits.miss
416  val s2_cache_replay = io.dcacheResp.bits.replay
417  val s2_cache_tag_error = io.dcacheResp.bits.tag_error
418  val s2_forward_fail = io.lsq.matchInvalid || io.sbuffer.matchInvalid
419  val s2_ldld_violation = io.loadViolationQueryResp.valid &&
420    io.loadViolationQueryResp.bits.have_violation &&
421    RegNext(io.csrCtrl.ldld_vio_check_enable)
422  val s2_data_invalid = io.lsq.dataInvalid && !s2_ldld_violation && !s2_exception
423
424  io.dcache_kill := pmp.ld || pmp.mmio // move pmp resp kill to outside
425  io.dcacheResp.ready := true.B
426  val dcacheShouldResp = !(s2_tlb_miss || s2_exception || s2_mmio || s2_is_prefetch)
427  assert(!(io.in.valid && (dcacheShouldResp && !io.dcacheResp.valid)), "DCache response got lost")
428
429  // merge forward result
430  // lsq has higher priority than sbuffer
431  val forwardMask = Wire(Vec(8, Bool()))
432  val forwardData = Wire(Vec(8, UInt(8.W)))
433
434  val fullForward = ((~forwardMask.asUInt).asUInt & s2_mask) === 0.U && !io.lsq.dataInvalid
435  io.lsq := DontCare
436  io.sbuffer := DontCare
437  io.fullForward := fullForward
438
439  // generate XLEN/8 Muxs
440  for (i <- 0 until XLEN / 8) {
441    forwardMask(i) := io.lsq.forwardMask(i) || io.sbuffer.forwardMask(i)
442    forwardData(i) := Mux(io.lsq.forwardMask(i), io.lsq.forwardData(i), io.sbuffer.forwardData(i))
443  }
444
445  XSDebug(io.out.fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
446    s2_uop.cf.pc,
447    io.lsq.forwardData.asUInt, io.lsq.forwardMask.asUInt,
448    io.in.bits.forwardData.asUInt, io.in.bits.forwardMask.asUInt
449  )
450
451  // data merge
452  // val rdataVec = VecInit((0 until XLEN / 8).map(j =>
453  //   Mux(forwardMask(j), forwardData(j), io.dcacheResp.bits.data(8*(j+1)-1, 8*j))
454  // )) // s2_rdataVec will be write to load queue
455  // val rdata = rdataVec.asUInt
456  // val rdataSel = LookupTree(s2_paddr(2, 0), List(
457  //   "b000".U -> rdata(63, 0),
458  //   "b001".U -> rdata(63, 8),
459  //   "b010".U -> rdata(63, 16),
460  //   "b011".U -> rdata(63, 24),
461  //   "b100".U -> rdata(63, 32),
462  //   "b101".U -> rdata(63, 40),
463  //   "b110".U -> rdata(63, 48),
464  //   "b111".U -> rdata(63, 56)
465  // ))
466  // val rdataPartialLoad = rdataHelper(s2_uop, rdataSel) // s2_rdataPartialLoad is not used
467
468  io.out.valid := io.in.valid && !s2_tlb_miss && !s2_data_invalid
469  // write_lq_safe is needed by dup logic
470  // io.write_lq_safe := !s2_tlb_miss && !s2_data_invalid
471  // Inst will be canceled in store queue / lsq,
472  // so we do not need to care about flush in load / store unit's out.valid
473  io.out.bits := io.in.bits
474  // io.out.bits.data := rdataPartialLoad
475  io.out.bits.data := 0.U // data will be generated in load_s3
476  // when exception occurs, set it to not miss and let it write back to rob (via int port)
477  if (EnableFastForward) {
478    io.out.bits.miss := s2_cache_miss &&
479      !s2_exception &&
480      !fullForward &&
481      !s2_is_prefetch
482  } else {
483    io.out.bits.miss := s2_cache_miss &&
484      !s2_exception &&
485      !s2_is_prefetch
486  }
487  io.out.bits.uop.ctrl.fpWen := io.in.bits.uop.ctrl.fpWen && !s2_exception
488
489  io.loadDataFromDcache.bankedDcacheData := io.dcacheResp.bits.bank_data
490  io.loadDataFromDcache.bank_oh := io.dcacheResp.bits.bank_oh
491  // io.loadDataFromDcache.dcacheData := io.dcacheResp.bits.data
492  io.loadDataFromDcache.forwardMask := forwardMask
493  io.loadDataFromDcache.forwardData := forwardData
494  io.loadDataFromDcache.uop := io.out.bits.uop
495  io.loadDataFromDcache.addrOffset := s2_paddr(2, 0)
496
497  io.s2_can_replay_from_fetch := !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
498  // if forward fail, replay this inst from fetch
499  val debug_forwardFailReplay = s2_forward_fail && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
500  // if ld-ld violation is detected, replay from this inst from fetch
501  val debug_ldldVioReplay = s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
502  // io.out.bits.uop.ctrl.replayInst := false.B
503
504  io.out.bits.mmio := s2_mmio
505  io.out.bits.uop.ctrl.flushPipe := s2_mmio && io.sentFastUop
506  io.out.bits.uop.cf.exceptionVec := s2_exception_vec // cache error not included
507
508  // For timing reasons, sometimes we can not let
509  // io.out.bits.miss := s2_cache_miss && !s2_exception && !fullForward
510  // We use io.dataForwarded instead. It means:
511  // 1. Forward logic have prepared all data needed,
512  //    and dcache query is no longer needed.
513  // 2. ... or data cache tag error is detected, this kind of inst
514  //    will not update miss queue. That is to say, if miss, that inst
515  //    may not be refilled
516  // Such inst will be writebacked from load queue.
517  io.dataForwarded := s2_cache_miss && !s2_exception &&
518    (fullForward || io.csrCtrl.cache_error_enable && s2_cache_tag_error)
519  // io.out.bits.forwardX will be send to lq
520  io.out.bits.forwardMask := forwardMask
521  // data from dcache is not included in io.out.bits.forwardData
522  io.out.bits.forwardData := forwardData
523
524  io.in.ready := io.out.ready || !io.in.valid
525
526  // feedback tlb result to RS
527  io.rsFeedback.valid := false.B
528  val s2_need_replay_from_rs = Wire(Bool())
529  if (EnableFastForward) {
530    s2_need_replay_from_rs :=
531      s2_tlb_miss || // replay if dtlb miss
532      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !fullForward || // replay if dcache miss queue full / busy
533      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
534  } else {
535    // Note that if all parts of data are available in sq / sbuffer, replay required by dcache will not be scheduled
536    s2_need_replay_from_rs :=
537      s2_tlb_miss || // replay if dtlb miss
538      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !io.dataForwarded || // replay if dcache miss queue full / busy
539      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
540  }
541  io.rsFeedback.bits.hit := !s2_need_replay_from_rs
542  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
543  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
544  // feedback source priority: tlbMiss > dataInvalid > mshrFull
545  // general case priority: tlbMiss > exception (include forward_fail / ldld_violation) > mmio > dataInvalid > mshrFull > normal miss / hit
546  io.rsFeedback.bits.sourceType := Mux(s2_tlb_miss, RSFeedbackType.tlbMiss,
547    Mux(s2_data_invalid,
548      RSFeedbackType.dataInvalid,
549      RSFeedbackType.mshrFull
550    )
551  )
552  io.rsFeedback.bits.dataInvalidSqIdx.value := io.dataInvalidSqIdx
553  io.rsFeedback.bits.dataInvalidSqIdx.flag := DontCare
554
555  io.replaySlow.valid := io.in.valid
556  io.replaySlow.tlb_hited := !s2_tlb_miss
557  if (EnableFastForward) {
558    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || fullForward
559  }else {
560    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || io.dataForwarded
561  }
562  io.replaySlow.forward_data_valid := !s2_data_invalid || s2_is_prefetch
563  io.replaySlow.ld_idx := io.in.bits.uop.lqIdx.value
564  io.replaySlow.data_invalid_sq_idx := io.dataInvalidSqIdx
565
566  // s2_cache_replay is quite slow to generate, send it separately to LQ
567  if (EnableFastForward) {
568    io.s2_dcache_require_replay := s2_cache_replay && !fullForward
569  } else {
570    io.s2_dcache_require_replay := s2_cache_replay &&
571      s2_need_replay_from_rs &&
572      !io.dataForwarded &&
573      !s2_is_prefetch &&
574      io.out.bits.miss
575  }
576
577  XSPerfAccumulate("in_valid", io.in.valid)
578  XSPerfAccumulate("in_fire", io.in.fire)
579  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
580  XSPerfAccumulate("dcache_miss", io.in.fire && s2_cache_miss)
581  XSPerfAccumulate("dcache_miss_first_issue", io.in.fire && s2_cache_miss && io.in.bits.isFirstIssue)
582  XSPerfAccumulate("full_forward", io.in.valid && fullForward)
583  XSPerfAccumulate("dcache_miss_full_forward", io.in.valid && s2_cache_miss && fullForward)
584  XSPerfAccumulate("replay",  io.rsFeedback.valid && !io.rsFeedback.bits.hit)
585  XSPerfAccumulate("replay_tlb_miss", io.rsFeedback.valid && !io.rsFeedback.bits.hit && s2_tlb_miss)
586  XSPerfAccumulate("replay_cache", io.rsFeedback.valid && !io.rsFeedback.bits.hit && !s2_tlb_miss && s2_cache_replay)
587  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
588  XSPerfAccumulate("replay_from_fetch_forward", io.out.valid && debug_forwardFailReplay)
589  XSPerfAccumulate("replay_from_fetch_load_vio", io.out.valid && debug_ldldVioReplay)
590
591  XSPerfAccumulate("replay_lq",  io.replaySlow.valid && (!io.replaySlow.tlb_hited || !io.replaySlow.cache_no_replay || !io.replaySlow.forward_data_valid))
592  XSPerfAccumulate("replay_tlb_miss_lq", io.replaySlow.valid && !io.replaySlow.tlb_hited)
593  XSPerfAccumulate("replay_cache_lq", io.replaySlow.valid && io.replaySlow.tlb_hited && !io.replaySlow.cache_no_replay)
594}
595
596class LoadUnit(implicit p: Parameters) extends XSModule
597  with HasLoadHelper
598  with HasPerfEvents
599  with HasDCacheParameters
600{
601  val io = IO(new Bundle() {
602    val ldin = Flipped(Decoupled(new ExuInput))
603    val ldout = Decoupled(new ExuOutput)
604    val redirect = Flipped(ValidIO(new Redirect))
605    val feedbackSlow = ValidIO(new RSFeedback)
606    val feedbackFast = ValidIO(new RSFeedback)
607    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
608    val isFirstIssue = Input(Bool())
609    val dcache = new DCacheLoadIO
610    val sbuffer = new LoadForwardQueryIO
611    val lsq = new LoadToLsqIO
612    val refill = Flipped(ValidIO(new Refill))
613    val fastUop = ValidIO(new MicroOp) // early wakeup signal generated in load_s1, send to RS in load_s2
614    val trigger = Vec(3, new LoadUnitTriggerIO)
615
616    val tlb = new TlbRequestIO(2)
617    val pmp = Flipped(new PMPRespBundle()) // arrive same to tlb now
618
619    val fastpathOut = Output(new LoadToLoadIO)
620    val fastpathIn = Input(new LoadToLoadIO)
621    val loadFastMatch = Input(Bool())
622    val loadFastImm = Input(UInt(12.W))
623
624    val s3_delayed_load_error = Output(Bool()) // load ecc error
625    // Note that io.s3_delayed_load_error and io.lsq.s3_delayed_load_error is different
626
627    val csrCtrl = Flipped(new CustomCSRCtrlIO)
628
629    // load replay
630    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
631  })
632
633  val load_s0 = Module(new LoadUnit_S0)
634  val load_s1 = Module(new LoadUnit_S1)
635  val load_s2 = Module(new LoadUnit_S2)
636
637  load_s0.io.lsqOut <> io.lsqOut
638
639  // load s0
640  load_s0.io.in <> io.ldin
641  load_s0.io.dtlbReq <> io.tlb.req
642  load_s0.io.dcacheReq <> io.dcache.req
643  load_s0.io.rsIdx := io.rsIdx
644  load_s0.io.isFirstIssue := io.isFirstIssue
645  load_s0.io.s0_kill := false.B
646  // we try pointerchasing when (1. no rs-issued load and 2. no LSQ replayed load)
647  val s0_tryPointerChasing = !io.ldin.valid && !io.lsqOut.valid && io.fastpathIn.valid
648  val s0_pointerChasingVAddr = io.fastpathIn.data(5, 0) +& io.loadFastImm(5, 0)
649  load_s0.io.fastpath.valid := io.fastpathIn.valid
650  load_s0.io.fastpath.data := Cat(io.fastpathIn.data(XLEN-1, 6), s0_pointerChasingVAddr(5,0))
651
652  val s1_data = PipelineConnect(load_s0.io.out, load_s1.io.in, true.B,
653    load_s0.io.out.bits.uop.robIdx.needFlush(io.redirect) && !s0_tryPointerChasing).get
654
655  // load s1
656  // update s1_kill when any source has valid request
657  load_s1.io.s1_kill := RegEnable(load_s0.io.s0_kill, false.B, io.ldin.valid || io.lsqOut.valid || io.fastpathIn.valid)
658  io.tlb.req_kill := load_s1.io.s1_kill
659  load_s1.io.dtlbResp <> io.tlb.resp
660  io.dcache.s1_paddr_dup_lsu <> load_s1.io.lsuPAddr
661  io.dcache.s1_paddr_dup_dcache <> load_s1.io.dcachePAddr
662  io.dcache.s1_kill := load_s1.io.dcacheKill
663  load_s1.io.sbuffer <> io.sbuffer
664  load_s1.io.lsq <> io.lsq.forward
665  load_s1.io.loadViolationQueryReq <> io.lsq.loadViolationQuery.req
666  load_s1.io.dcacheBankConflict <> io.dcache.s1_bank_conflict
667  load_s1.io.csrCtrl <> io.csrCtrl
668
669  // provide paddr and vaddr for lq
670  io.lsq.loadPaddrIn.valid := load_s1.io.out.valid
671  io.lsq.loadPaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
672  io.lsq.loadPaddrIn.bits.paddr := load_s1.io.lsuPAddr
673
674  io.lsq.loadVaddrIn.valid := load_s1.io.in.valid && !load_s1.io.s1_kill
675  io.lsq.loadVaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
676  io.lsq.loadVaddrIn.bits.vaddr := load_s1.io.out.bits.vaddr
677
678  // when S0 has opportunity to try pointerchasing, make sure it truely goes to S1
679  // which is S0's out is ready and dcache is ready
680  val s0_doTryPointerChasing = s0_tryPointerChasing && load_s0.io.out.ready && load_s0.io.dcacheReq.ready
681  val s1_tryPointerChasing = RegNext(s0_doTryPointerChasing, false.B)
682  val s1_pointerChasingVAddr = RegEnable(s0_pointerChasingVAddr, s0_doTryPointerChasing)
683  val cancelPointerChasing = WireInit(false.B)
684  if (EnableLoadToLoadForward) {
685    // Sometimes, we need to cancel the load-load forwarding.
686    // These can be put at S0 if timing is bad at S1.
687    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
688    val addressMisMatch = s1_pointerChasingVAddr(6) || RegEnable(io.loadFastImm(11, 6).orR, s0_doTryPointerChasing)
689    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
690    val addressNotAligned = s1_pointerChasingVAddr(2, 0).orR
691    val fuOpTypeIsNotLd = io.ldin.bits.uop.ctrl.fuOpType =/= LSUOpType.ld
692    // Case 2: this is not a valid load-load pair
693    val notFastMatch = RegEnable(!io.loadFastMatch, s0_tryPointerChasing)
694    // Case 3: this load-load uop is cancelled
695    val isCancelled = !io.ldin.valid
696    when (s1_tryPointerChasing) {
697      cancelPointerChasing := addressMisMatch || addressNotAligned || fuOpTypeIsNotLd || notFastMatch || isCancelled
698      load_s1.io.in.bits.uop := io.ldin.bits.uop
699      val spec_vaddr = s1_data.vaddr
700      val vaddr = Cat(spec_vaddr(VAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
701      load_s1.io.in.bits.vaddr := vaddr
702      load_s1.io.in.bits.rsIdx := io.rsIdx
703      load_s1.io.in.bits.isFirstIssue := io.isFirstIssue
704      // We need to replace vaddr(5, 3).
705      val spec_paddr = io.tlb.resp.bits.paddr(0)
706      load_s1.io.dtlbResp.bits.paddr.foreach(_ := Cat(spec_paddr(PAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W)))
707    }
708    when (cancelPointerChasing) {
709      load_s1.io.s1_kill := true.B
710    }.otherwise {
711      load_s0.io.s0_kill := s1_tryPointerChasing
712      when (s1_tryPointerChasing) {
713        io.ldin.ready := true.B
714      }
715    }
716
717    XSPerfAccumulate("load_to_load_forward", s1_tryPointerChasing && !cancelPointerChasing)
718    XSPerfAccumulate("load_to_load_forward_try", s1_tryPointerChasing)
719    XSPerfAccumulate("load_to_load_forward_fail", cancelPointerChasing)
720    XSPerfAccumulate("load_to_load_forward_fail_cancelled", cancelPointerChasing && isCancelled)
721    XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", cancelPointerChasing && !isCancelled && notFastMatch)
722    XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",
723      cancelPointerChasing && !isCancelled && !notFastMatch && fuOpTypeIsNotLd)
724    XSPerfAccumulate("load_to_load_forward_fail_addr_align",
725      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && addressNotAligned)
726    XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",
727      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && !addressNotAligned && addressMisMatch)
728  }
729  PipelineConnect(load_s1.io.out, load_s2.io.in, true.B,
730    load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect) || cancelPointerChasing)
731
732
733  // load s2
734  io.dcache.s2_kill := load_s2.io.dcache_kill // to kill mmio resp which are redirected
735  load_s2.io.dcacheResp <> io.dcache.resp
736  load_s2.io.pmpResp <> io.pmp
737  load_s2.io.static_pm := RegNext(io.tlb.resp.bits.static_pm)
738  load_s2.io.lsq.forwardData <> io.lsq.forward.forwardData
739  load_s2.io.lsq.forwardMask <> io.lsq.forward.forwardMask
740  load_s2.io.lsq.forwardMaskFast <> io.lsq.forward.forwardMaskFast // should not be used in load_s2
741  load_s2.io.lsq.dataInvalid <> io.lsq.forward.dataInvalid
742  load_s2.io.lsq.matchInvalid <> io.lsq.forward.matchInvalid
743  load_s2.io.sbuffer.forwardData <> io.sbuffer.forwardData
744  load_s2.io.sbuffer.forwardMask <> io.sbuffer.forwardMask
745  load_s2.io.sbuffer.forwardMaskFast <> io.sbuffer.forwardMaskFast // should not be used in load_s2
746  load_s2.io.sbuffer.dataInvalid <> io.sbuffer.dataInvalid // always false
747  load_s2.io.sbuffer.matchInvalid <> io.sbuffer.matchInvalid
748  load_s2.io.dataForwarded <> io.lsq.s2_load_data_forwarded
749  load_s2.io.dataInvalidSqIdx := io.lsq.forward.dataInvalidSqIdx // provide dataInvalidSqIdx to make wakeup faster
750  load_s2.io.loadViolationQueryResp <> io.lsq.loadViolationQuery.resp
751  load_s2.io.csrCtrl <> io.csrCtrl
752  load_s2.io.sentFastUop := io.fastUop.valid
753
754  // feedback bank conflict / ld-vio check struct hazard to rs
755  io.feedbackFast.bits := RegNext(load_s1.io.rsFeedback.bits)
756  io.feedbackFast.valid := RegNext(load_s1.io.rsFeedback.valid && !load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect))
757
758  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
759  val sqIdxMaskReg = RegNext(UIntToMask(load_s0.io.s0_sqIdx.value, StoreQueueSize))
760  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
761  // If the timing here is not OK, load-load forwarding has to be disabled.
762  // Or we calculate sqIdxMask at RS??
763  io.lsq.forward.sqIdxMask := sqIdxMaskReg
764  if (EnableLoadToLoadForward) {
765    when (s1_tryPointerChasing) {
766      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
767    }
768  }
769
770  // // use s2_hit_way to select data received in s1
771  // load_s2.io.dcacheResp.bits.data := Mux1H(RegNext(io.dcache.s1_hit_way), RegNext(io.dcache.s1_data))
772  // assert(load_s2.io.dcacheResp.bits.data === io.dcache.resp.bits.data)
773
774  // now io.fastUop.valid is sent to RS in load_s2
775  val s2_dcache_hit = io.dcache.s2_hit // dcache hit dup in lsu side
776
777  io.fastUop.valid := RegNext(
778      !io.dcache.s1_disable_fast_wakeup &&  // load fast wakeup should be disabled when dcache data read is not ready
779      load_s1.io.in.valid && // valid load request
780      !load_s1.io.s1_kill && // killed by load-load forwarding
781      !load_s1.io.dtlbResp.bits.fast_miss && // not mmio or tlb miss, pf / af not included here
782      !io.lsq.forward.dataInvalidFast // forward failed
783    ) &&
784    !RegNext(load_s1.io.needLdVioCheckRedo) && // load-load violation check: load paddr cam struct hazard
785    !RegNext(load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) &&
786    s2_dcache_hit // dcache hit in lsu side
787
788  io.fastUop.bits := RegNext(load_s1.io.out.bits.uop)
789
790  XSDebug(load_s0.io.out.valid,
791    p"S0: pc ${Hexadecimal(load_s0.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s0.io.out.bits.uop.lqIdx.asUInt)}, " +
792    p"vaddr ${Hexadecimal(load_s0.io.out.bits.vaddr)}, mask ${Hexadecimal(load_s0.io.out.bits.mask)}\n")
793  XSDebug(load_s1.io.out.valid,
794    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}, " +
795    p"paddr ${Hexadecimal(load_s1.io.out.bits.paddr)}, mmio ${load_s1.io.out.bits.mmio}\n")
796
797  // writeback to LSQ
798  // Current dcache use MSHR
799  // Load queue will be updated at s2 for both hit/miss int/fp load
800  io.lsq.loadIn.valid := load_s2.io.out.valid
801  // generate LqWriteBundle from LsPipelineBundle
802  io.lsq.loadIn.bits.fromLsPipelineBundle(load_s2.io.out.bits)
803
804  io.lsq.replayFast := load_s1.io.replayFast
805  io.lsq.replaySlow := load_s2.io.replaySlow
806  io.lsq.replaySlow.valid := load_s2.io.replaySlow.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)
807
808  // generate duplicated load queue data wen
809  val load_s2_valid_vec = RegInit(0.U(6.W))
810  val load_s2_leftFire = load_s1.io.out.valid && load_s2.io.in.ready
811  // val write_lq_safe = load_s2.io.write_lq_safe
812  load_s2_valid_vec := 0x0.U(6.W)
813  when (load_s2_leftFire) { load_s2_valid_vec := 0x3f.U(6.W)}
814  when (load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) { load_s2_valid_vec := 0x0.U(6.W) }
815  assert(RegNext(load_s2.io.in.valid === load_s2_valid_vec(0)))
816  io.lsq.loadIn.bits.lq_data_wen_dup := load_s2_valid_vec.asBools()
817
818  // s2_dcache_require_replay signal will be RegNexted, then used in s3
819  io.lsq.s2_dcache_require_replay := load_s2.io.s2_dcache_require_replay
820
821  // write to rob and writeback bus
822  val s2_wb_valid = load_s2.io.out.valid && !load_s2.io.out.bits.miss && !load_s2.io.out.bits.mmio
823
824  // Int load, if hit, will be writebacked at s2
825  val hitLoadOut = Wire(Valid(new ExuOutput))
826  hitLoadOut.valid := s2_wb_valid
827  hitLoadOut.bits.uop := load_s2.io.out.bits.uop
828  hitLoadOut.bits.data := load_s2.io.out.bits.data
829  hitLoadOut.bits.redirectValid := false.B
830  hitLoadOut.bits.redirect := DontCare
831  hitLoadOut.bits.debug.isMMIO := load_s2.io.out.bits.mmio
832  hitLoadOut.bits.debug.isPerfCnt := false.B
833  hitLoadOut.bits.debug.paddr := load_s2.io.out.bits.paddr
834  hitLoadOut.bits.debug.vaddr := load_s2.io.out.bits.vaddr
835  hitLoadOut.bits.fflags := DontCare
836
837  load_s2.io.out.ready := true.B
838
839  // load s3
840  val s3_load_wb_meta_reg = RegNext(Mux(hitLoadOut.valid, hitLoadOut.bits, io.lsq.ldout.bits))
841
842  // data from load queue refill
843  val s3_loadDataFromLQ = RegEnable(io.lsq.ldRawData, io.lsq.ldout.valid)
844  val s3_rdataLQ = s3_loadDataFromLQ.mergedData()
845  val s3_rdataSelLQ = LookupTree(s3_loadDataFromLQ.addrOffset, List(
846    "b000".U -> s3_rdataLQ(63, 0),
847    "b001".U -> s3_rdataLQ(63, 8),
848    "b010".U -> s3_rdataLQ(63, 16),
849    "b011".U -> s3_rdataLQ(63, 24),
850    "b100".U -> s3_rdataLQ(63, 32),
851    "b101".U -> s3_rdataLQ(63, 40),
852    "b110".U -> s3_rdataLQ(63, 48),
853    "b111".U -> s3_rdataLQ(63, 56)
854  ))
855  val s3_rdataPartialLoadLQ = rdataHelper(s3_loadDataFromLQ.uop, s3_rdataSelLQ)
856
857  // data from dcache hit
858  val s3_loadDataFromDcache = RegEnable(load_s2.io.loadDataFromDcache, load_s2.io.in.valid)
859  val s3_rdataDcache = s3_loadDataFromDcache.mergedData()
860  val s3_rdataSelDcache = LookupTree(s3_loadDataFromDcache.addrOffset, List(
861    "b000".U -> s3_rdataDcache(63, 0),
862    "b001".U -> s3_rdataDcache(63, 8),
863    "b010".U -> s3_rdataDcache(63, 16),
864    "b011".U -> s3_rdataDcache(63, 24),
865    "b100".U -> s3_rdataDcache(63, 32),
866    "b101".U -> s3_rdataDcache(63, 40),
867    "b110".U -> s3_rdataDcache(63, 48),
868    "b111".U -> s3_rdataDcache(63, 56)
869  ))
870  val s3_rdataPartialLoadDcache = rdataHelper(s3_loadDataFromDcache.uop, s3_rdataSelDcache)
871
872  io.ldout.bits := s3_load_wb_meta_reg
873  io.ldout.bits.data := Mux(RegNext(hitLoadOut.valid), s3_rdataPartialLoadDcache, s3_rdataPartialLoadLQ)
874  io.ldout.valid := RegNext(hitLoadOut.valid) && !RegNext(load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)) ||
875    RegNext(io.lsq.ldout.valid) && !RegNext(io.lsq.ldout.bits.uop.robIdx.needFlush(io.redirect)) && !RegNext(hitLoadOut.valid)
876
877  io.ldout.bits.uop.cf.exceptionVec(loadAccessFault) := s3_load_wb_meta_reg.uop.cf.exceptionVec(loadAccessFault) ||
878    RegNext(hitLoadOut.valid) && load_s2.io.s3_delayed_load_error
879
880  // fast load to load forward
881  io.fastpathOut.valid := RegNext(load_s2.io.out.valid) // for debug only
882  io.fastpathOut.data := s3_loadDataFromDcache.mergedData() // fastpath is for ld only
883
884  // feedback tlb miss / dcache miss queue full
885  io.feedbackSlow.bits := RegNext(load_s2.io.rsFeedback.bits)
886  io.feedbackSlow.valid := RegNext(load_s2.io.rsFeedback.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect))
887  // If replay is reported at load_s1, inst will be canceled (will not enter load_s2),
888  // in that case:
889  // * replay should not be reported twice
890  assert(!(RegNext(io.feedbackFast.valid) && io.feedbackSlow.valid))
891  // * io.fastUop.valid should not be reported
892  assert(!RegNext(io.feedbackFast.valid && !io.feedbackFast.bits.hit && io.fastUop.valid))
893
894  // load forward_fail/ldld_violation check
895  // check for inst in load pipeline
896  val s3_forward_fail = RegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid)
897  val s3_ldld_violation = RegNext(
898    io.lsq.loadViolationQuery.resp.valid &&
899    io.lsq.loadViolationQuery.resp.bits.have_violation &&
900    RegNext(io.csrCtrl.ldld_vio_check_enable)
901  )
902  val s3_need_replay_from_fetch = s3_forward_fail || s3_ldld_violation
903  val s3_can_replay_from_fetch = RegEnable(load_s2.io.s2_can_replay_from_fetch, load_s2.io.out.valid)
904  // 1) use load pipe check result generated in load_s3 iff load_hit
905  when (RegNext(hitLoadOut.valid)) {
906    io.ldout.bits.uop.ctrl.replayInst := s3_need_replay_from_fetch
907  }
908  // 2) otherwise, write check result to load queue
909  io.lsq.s3_replay_from_fetch := s3_need_replay_from_fetch && s3_can_replay_from_fetch
910
911  // s3_delayed_load_error path is not used for now, as we writeback load result in load_s3
912  // but we keep this path for future use
913  io.s3_delayed_load_error := false.B
914  io.lsq.s3_delayed_load_error := false.B //load_s2.io.s3_delayed_load_error
915
916  io.lsq.ldout.ready := !hitLoadOut.valid
917
918  when(io.feedbackSlow.valid && !io.feedbackSlow.bits.hit){
919    // when need replay from rs, inst should not be writebacked to rob
920    assert(RegNext(!hitLoadOut.valid))
921    assert(RegNext(!io.lsq.loadIn.valid) || RegNext(load_s2.io.s2_dcache_require_replay))
922  }
923
924  val lastValidData = RegEnable(io.ldout.bits.data, io.ldout.fire)
925  val hitLoadAddrTriggerHitVec = Wire(Vec(3, Bool()))
926  val lqLoadAddrTriggerHitVec = io.lsq.trigger.lqLoadAddrTriggerHitVec
927  (0 until 3).map{i => {
928    val tdata2 = io.trigger(i).tdata2
929    val matchType = io.trigger(i).matchType
930    val tEnable = io.trigger(i).tEnable
931
932    hitLoadAddrTriggerHitVec(i) := TriggerCmp(load_s2.io.out.bits.vaddr, tdata2, matchType, tEnable)
933    io.trigger(i).addrHit := Mux(hitLoadOut.valid, hitLoadAddrTriggerHitVec(i), lqLoadAddrTriggerHitVec(i))
934    io.trigger(i).lastDataHit := TriggerCmp(lastValidData, tdata2, matchType, tEnable)
935  }}
936  io.lsq.trigger.hitLoadAddrTriggerHitVec := hitLoadAddrTriggerHitVec
937
938  val perfEvents = Seq(
939    ("load_s0_in_fire         ", load_s0.io.in.fire                                                                                                              ),
940    ("load_to_load_forward    ", load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing                                                           ),
941    ("stall_dcache            ", load_s0.io.out.valid && load_s0.io.out.ready && !load_s0.io.dcacheReq.ready                                                     ),
942    ("load_s1_in_fire         ", load_s1.io.in.fire                                                                                                              ),
943    ("load_s1_tlb_miss        ", load_s1.io.in.fire && load_s1.io.dtlbResp.bits.miss                                                                             ),
944    ("load_s2_in_fire         ", load_s2.io.in.fire                                                                                                              ),
945    ("load_s2_dcache_miss     ", load_s2.io.in.fire && load_s2.io.dcacheResp.bits.miss                                                                           ),
946    ("load_s2_replay          ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit                                                                  ),
947    ("load_s2_replay_tlb_miss ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && load_s2.io.in.bits.tlbMiss                                    ),
948    ("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),
949  )
950  generatePerfEvent()
951
952  when(io.ldout.fire){
953    XSDebug("ldout %x\n", io.ldout.bits.uop.cf.pc)
954  }
955}
956