xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision 149e918c520847554be4cf7f6594881d6d3a32c8)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.mem
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan.ExceptionNO._
25import xiangshan._
26import xiangshan.backend.Bundles.{DynInst, MemExuInput, MemExuOutput}
27import xiangshan.backend.fu.PMPRespBundle
28import xiangshan.backend.fu.FuConfig._
29import xiangshan.backend.fu.FuType
30import xiangshan.backend.ctrlblock.{DebugLsInfoBundle, LsTopdownInfo}
31import xiangshan.backend.rob.RobPtr
32import xiangshan.backend.ctrlblock.DebugLsInfoBundle
33import xiangshan.backend.fu.NewCSR._
34import xiangshan.backend.fu.util.SdtrigExt
35import xiangshan.cache._
36import xiangshan.cache.wpu.ReplayCarry
37import xiangshan.cache.mmu._
38import xiangshan.mem.mdp._
39
40class LoadToLsqReplayIO(implicit p: Parameters) extends XSBundle
41  with HasDCacheParameters
42  with HasTlbConst
43{
44  // mshr refill index
45  val mshr_id         = UInt(log2Up(cfg.nMissEntries).W)
46  // get full data from store queue and sbuffer
47  val full_fwd        = Bool()
48  // wait for data from store inst's store queue index
49  val data_inv_sq_idx = new SqPtr
50  // wait for address from store queue index
51  val addr_inv_sq_idx = new SqPtr
52  // replay carry
53  val rep_carry       = new ReplayCarry(nWays)
54  // data in last beat
55  val last_beat       = Bool()
56  // replay cause
57  val cause           = Vec(LoadReplayCauses.allCauses, Bool())
58  // performance debug information
59  val debug           = new PerfDebugInfo
60  // tlb hint
61  val tlb_id          = UInt(log2Up(loadfiltersize).W)
62  val tlb_full        = Bool()
63
64  // alias
65  def mem_amb       = cause(LoadReplayCauses.C_MA)
66  def tlb_miss      = cause(LoadReplayCauses.C_TM)
67  def fwd_fail      = cause(LoadReplayCauses.C_FF)
68  def dcache_rep    = cause(LoadReplayCauses.C_DR)
69  def dcache_miss   = cause(LoadReplayCauses.C_DM)
70  def wpu_fail      = cause(LoadReplayCauses.C_WF)
71  def bank_conflict = cause(LoadReplayCauses.C_BC)
72  def rar_nack      = cause(LoadReplayCauses.C_RAR)
73  def raw_nack      = cause(LoadReplayCauses.C_RAW)
74  def nuke          = cause(LoadReplayCauses.C_NK)
75  def need_rep      = cause.asUInt.orR
76}
77
78
79class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
80  val ldin            = DecoupledIO(new LqWriteBundle)
81  val uncache         = Flipped(DecoupledIO(new MemExuOutput))
82  val ld_raw_data     = Input(new LoadDataFromLQBundle)
83  val forward         = new PipeLoadForwardQueryIO
84  val stld_nuke_query = new LoadNukeQueryIO
85  val ldld_nuke_query = new LoadNukeQueryIO
86}
87
88class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
89  val valid      = Bool()
90  val data       = UInt(XLEN.W) // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
91  val dly_ld_err = Bool()
92}
93
94class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
95  val tdata2      = Input(UInt(64.W))
96  val matchType   = Input(UInt(2.W))
97  val tEnable     = Input(Bool()) // timing is calculated before this
98  val addrHit     = Output(Bool())
99}
100
101class LoadUnit(implicit p: Parameters) extends XSModule
102  with HasLoadHelper
103  with HasPerfEvents
104  with HasDCacheParameters
105  with HasCircularQueuePtrHelper
106  with HasVLSUParameters
107  with SdtrigExt
108{
109  val io = IO(new Bundle() {
110    // control
111    val redirect      = Flipped(ValidIO(new Redirect))
112    val csrCtrl       = Flipped(new CustomCSRCtrlIO)
113
114    // int issue path
115    val ldin          = Flipped(Decoupled(new MemExuInput))
116    val ldout         = Decoupled(new MemExuOutput)
117
118    // vec issue path
119    val vecldin = Flipped(Decoupled(new VecPipeBundle))
120    val vecldout = Decoupled(new VecPipelineFeedbackIO(isVStore = false))
121
122    // misalignBuffer issue path
123    val misalign_ldin = Flipped(Decoupled(new LsPipelineBundle))
124    val misalign_ldout = Valid(new LqWriteBundle)
125
126    // data path
127    val tlb           = new TlbRequestIO(2)
128    val pmp           = Flipped(new PMPRespBundle()) // arrive same to tlb now
129    val dcache        = new DCacheLoadIO
130    val sbuffer       = new LoadForwardQueryIO
131    val lsq           = new LoadToLsqIO
132    val tl_d_channel  = Input(new DcacheToLduForwardIO)
133    val forward_mshr  = Flipped(new LduToMissqueueForwardIO)
134   // val refill        = Flipped(ValidIO(new Refill))
135    val l2_hint       = Input(Valid(new L2ToL1Hint))
136    val tlb_hint      = Flipped(new TlbHintReq)
137    // fast wakeup
138    // TODO: implement vector fast wakeup
139    val fast_uop = ValidIO(new DynInst) // early wakeup signal generated in load_s1, send to RS in load_s2
140
141    // trigger
142    val fromCsrTrigger = Input(new CsrTriggerBundle)
143
144    // prefetch
145    val prefetch_train            = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to sms
146    val prefetch_train_l1         = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to stream & stride
147    // speculative for gated control
148    val s1_prefetch_spec = Output(Bool())
149    val s2_prefetch_spec = Output(Bool())
150
151    val prefetch_req              = Flipped(ValidIO(new L1PrefetchReq)) // hardware prefetch to l1 cache req
152    val canAcceptLowConfPrefetch  = Output(Bool())
153    val canAcceptHighConfPrefetch = Output(Bool())
154
155    // ifetchPrefetch
156    val ifetchPrefetch = ValidIO(new SoftIfetchPrefetchBundle)
157
158    // load to load fast path
159    val l2l_fwd_in    = Input(new LoadToLoadIO)
160    val l2l_fwd_out   = Output(new LoadToLoadIO)
161
162    val ld_fast_match    = Input(Bool())
163    val ld_fast_fuOpType = Input(UInt())
164    val ld_fast_imm      = Input(UInt(12.W))
165
166    // rs feedback
167    val wakeup = ValidIO(new DynInst)
168    val feedback_fast = ValidIO(new RSFeedback) // stage 2
169    val feedback_slow = ValidIO(new RSFeedback) // stage 3
170    val ldCancel = Output(new LoadCancelIO()) // use to cancel the uops waked by this load, and cancel load
171
172    // load ecc error
173    val s3_dly_ld_err = Output(Bool()) // Note that io.s3_dly_ld_err and io.lsq.s3_dly_ld_err is different
174
175    // schedule error query
176    val stld_nuke_query = Flipped(Vec(StorePipelineWidth, Valid(new StoreNukeQueryIO)))
177
178    // queue-based replay
179    val replay       = Flipped(Decoupled(new LsPipelineBundle))
180    val lq_rep_full  = Input(Bool())
181
182    // misc
183    val s2_ptr_chasing = Output(Bool()) // provide right pc for hw prefetch
184
185    // Load fast replay path
186    val fast_rep_in  = Flipped(Decoupled(new LqWriteBundle))
187    val fast_rep_out = Decoupled(new LqWriteBundle)
188
189    // to misalign buffer
190    val misalign_buf = Valid(new LqWriteBundle)
191
192    // Load RAR rollback
193    val rollback = Valid(new Redirect)
194
195    // perf
196    val debug_ls         = Output(new DebugLsInfoBundle)
197    val lsTopdownInfo    = Output(new LsTopdownInfo)
198    val correctMissTrain = Input(Bool())
199  })
200
201  val s1_ready, s2_ready, s3_ready = WireInit(false.B)
202
203  // Pipeline
204  // --------------------------------------------------------------------------------
205  // stage 0
206  // --------------------------------------------------------------------------------
207  // generate addr, use addr to query DCache and DTLB
208  val s0_valid         = Wire(Bool())
209  val s0_mmio_select   = Wire(Bool())
210  val s0_kill          = Wire(Bool())
211  val s0_can_go        = s1_ready
212  val s0_fire          = s0_valid && s0_can_go
213  val s0_mmio_fire     = s0_mmio_select && s0_can_go
214  val s0_out           = Wire(new LqWriteBundle)
215  val s0_tlb_valid     = Wire(Bool())
216  val s0_tlb_hlv       = Wire(Bool())
217  val s0_tlb_hlvx      = Wire(Bool())
218  val s0_tlb_vaddr     = Wire(UInt(VAddrBits.W))
219  val s0_tlb_fullva    = Wire(UInt(XLEN.W))
220  val s0_dcache_vaddr  = Wire(UInt(VAddrBits.W))
221
222  // flow source bundle
223  class FlowSource extends Bundle {
224    val vaddr         = UInt(VAddrBits.W)
225    val mask          = UInt((VLEN/8).W)
226    val uop           = new DynInst
227    val try_l2l       = Bool()
228    val has_rob_entry = Bool()
229    val rep_carry     = new ReplayCarry(nWays)
230    val mshrid        = UInt(log2Up(cfg.nMissEntries).W)
231    val isFirstIssue  = Bool()
232    val fast_rep      = Bool()
233    val ld_rep        = Bool()
234    val l2l_fwd       = Bool()
235    val prf           = Bool()
236    val prf_rd        = Bool()
237    val prf_wr        = Bool()
238    val prf_i         = Bool()
239    val sched_idx     = UInt(log2Up(LoadQueueReplaySize+1).W)
240    // Record the issue port idx of load issue queue. This signal is used by load cancel.
241    val deqPortIdx    = UInt(log2Ceil(LoadPipelineWidth).W)
242    val frm_mabuf     = Bool()
243    // vec only
244    val isvec         = Bool()
245    val is128bit      = Bool()
246    val uop_unit_stride_fof = Bool()
247    val reg_offset    = UInt(vOffsetBits.W)
248    val vecActive     = Bool() // 1: vector active element or scala mem operation, 0: vector not active element
249    val is_first_ele  = Bool()
250    // val flowPtr       = new VlflowPtr
251    val usSecondInv   = Bool()
252    val mbIndex       = UInt(vlmBindexBits.W)
253    val elemIdx       = UInt(elemIdxBits.W)
254    val elemIdxInsideVd = UInt(elemIdxBits.W)
255    val alignedType   = UInt(alignTypeBits.W)
256    val vecBaseVaddr  = UInt(VAddrBits.W)
257  }
258  val s0_sel_src = Wire(new FlowSource)
259
260  // load flow select/gen
261  // src0: misalignBuffer load (io.misalign_ldin)
262  // src1: super load replayed by LSQ (cache miss replay) (io.replay)
263  // src2: fast load replay (io.fast_rep_in)
264  // src3: mmio (io.lsq.uncache)
265  // src4: load replayed by LSQ (io.replay)
266  // src5: hardware prefetch from prefetchor (high confidence) (io.prefetch)
267  // NOTE: Now vec/int loads are sent from same RS
268  //       A vec load will be splited into multiple uops,
269  //       so as long as one uop is issued,
270  //       the other uops should have higher priority
271  // src6: vec read from RS (io.vecldin)
272  // src7: int read / software prefetch first issue from RS (io.in)
273  // src8: load try pointchaising when no issued or replayed load (io.fastpath)
274  // src9: hardware prefetch from prefetchor (high confidence) (io.prefetch)
275  // priority: high to low
276  val s0_rep_stall           = io.ldin.valid && isAfter(io.replay.bits.uop.robIdx, io.ldin.bits.uop.robIdx)
277  private val SRC_NUM = 10
278  private val Seq(
279    mab_idx, super_rep_idx, fast_rep_idx, mmio_idx, lsq_rep_idx,
280    high_pf_idx, vec_iss_idx, int_iss_idx, l2l_fwd_idx, low_pf_idx
281  ) = (0 until SRC_NUM).toSeq
282  // load flow source valid
283  val s0_src_valid_vec = WireInit(VecInit(Seq(
284    io.misalign_ldin.valid,
285    io.replay.valid && io.replay.bits.forward_tlDchannel,
286    io.fast_rep_in.valid,
287    io.lsq.uncache.valid,
288    io.replay.valid && !io.replay.bits.forward_tlDchannel && !s0_rep_stall,
289    io.prefetch_req.valid && io.prefetch_req.bits.confidence > 0.U,
290    io.vecldin.valid,
291    io.ldin.valid, // int flow first issue or software prefetch
292    io.l2l_fwd_in.valid,
293    io.prefetch_req.valid && io.prefetch_req.bits.confidence === 0.U,
294  )))
295  // load flow source ready
296  val s0_src_ready_vec = Wire(Vec(SRC_NUM, Bool()))
297  s0_src_ready_vec(0) := true.B
298  for(i <- 1 until SRC_NUM){
299    s0_src_ready_vec(i) := !s0_src_valid_vec.take(i).reduce(_ || _)
300  }
301  // load flow source select (OH)
302  val s0_src_select_vec = WireInit(VecInit((0 until SRC_NUM).map{i => s0_src_valid_vec(i) && s0_src_ready_vec(i)}))
303  val s0_hw_prf_select = s0_src_select_vec(high_pf_idx) || s0_src_select_vec(low_pf_idx)
304
305  if (backendParams.debugEn){
306    dontTouch(s0_src_valid_vec)
307    dontTouch(s0_src_ready_vec)
308    dontTouch(s0_src_select_vec)
309  }
310
311  val s0_tlb_no_query = s0_hw_prf_select || s0_src_select_vec(fast_rep_idx) || s0_src_select_vec(mmio_idx) || s0_sel_src.prf_i
312  s0_valid := (
313    s0_src_valid_vec(mab_idx) ||
314    s0_src_valid_vec(super_rep_idx) ||
315    s0_src_valid_vec(fast_rep_idx) ||
316    s0_src_valid_vec(lsq_rep_idx) ||
317    s0_src_valid_vec(high_pf_idx) ||
318    s0_src_valid_vec(vec_iss_idx) ||
319    s0_src_valid_vec(int_iss_idx) ||
320    s0_src_valid_vec(l2l_fwd_idx) ||
321    s0_src_valid_vec(low_pf_idx)
322  ) && !s0_src_select_vec(mmio_idx) && io.dcache.req.ready && !s0_kill
323
324  s0_mmio_select := s0_src_select_vec(mmio_idx) && !s0_kill
325
326   // if is hardware prefetch or fast replay, don't send valid to tlb
327  s0_tlb_valid := (
328    s0_src_valid_vec(mab_idx) ||
329    s0_src_valid_vec(super_rep_idx) ||
330    s0_src_valid_vec(lsq_rep_idx) ||
331    s0_src_valid_vec(vec_iss_idx) ||
332    s0_src_valid_vec(int_iss_idx) ||
333    s0_src_valid_vec(l2l_fwd_idx)
334  ) && io.dcache.req.ready
335
336  // which is S0's out is ready and dcache is ready
337  val s0_try_ptr_chasing      = s0_src_select_vec(l2l_fwd_idx)
338  val s0_do_try_ptr_chasing   = s0_try_ptr_chasing && s0_can_go && io.dcache.req.ready
339  val s0_ptr_chasing_vaddr    = io.l2l_fwd_in.data(5, 0) +& io.ld_fast_imm(5, 0)
340  val s0_ptr_chasing_canceled = WireInit(false.B)
341  s0_kill := s0_ptr_chasing_canceled
342
343  // prefetch related ctrl signal
344  io.canAcceptLowConfPrefetch  := s0_src_ready_vec(low_pf_idx) && io.dcache.req.ready
345  io.canAcceptHighConfPrefetch := s0_src_ready_vec(high_pf_idx) && io.dcache.req.ready
346
347  // query DTLB
348  io.tlb.req.valid                   := s0_tlb_valid
349  io.tlb.req.bits.cmd                := Mux(s0_sel_src.prf,
350                                         Mux(s0_sel_src.prf_wr, TlbCmd.write, TlbCmd.read),
351                                         TlbCmd.read
352                                       )
353  io.tlb.req.bits.isPrefetch         := s0_sel_src.prf
354  io.tlb.req.bits.vaddr              := s0_tlb_vaddr
355  io.tlb.req.bits.fullva             := s0_tlb_fullva
356  io.tlb.req.bits.checkfullva        := s0_src_select_vec(vec_iss_idx) || s0_src_select_vec(int_iss_idx)
357  io.tlb.req.bits.hyperinst          := s0_tlb_hlv
358  io.tlb.req.bits.hlvx               := s0_tlb_hlvx
359  io.tlb.req.bits.size               := Mux(s0_sel_src.isvec, s0_sel_src.alignedType(2,0), LSUOpType.size(s0_sel_src.uop.fuOpType))
360  io.tlb.req.bits.kill               := s0_kill || s0_tlb_no_query // if does not need to be translated, kill it
361  io.tlb.req.bits.memidx.is_ld       := true.B
362  io.tlb.req.bits.memidx.is_st       := false.B
363  io.tlb.req.bits.memidx.idx         := s0_sel_src.uop.lqIdx.value
364  io.tlb.req.bits.debug.robIdx       := s0_sel_src.uop.robIdx
365  io.tlb.req.bits.no_translate       := s0_tlb_no_query  // hardware prefetch and fast replay does not need to be translated, need this signal for pmp check
366  io.tlb.req.bits.debug.pc           := s0_sel_src.uop.pc
367  io.tlb.req.bits.debug.isFirstIssue := s0_sel_src.isFirstIssue
368
369  // query DCache
370  io.dcache.req.valid             := s0_valid && !s0_sel_src.prf_i
371  io.dcache.req.bits.cmd          := Mux(s0_sel_src.prf_rd,
372                                      MemoryOpConstants.M_PFR,
373                                      Mux(s0_sel_src.prf_wr, MemoryOpConstants.M_PFW, MemoryOpConstants.M_XRD)
374                                    )
375  io.dcache.req.bits.vaddr        := s0_dcache_vaddr
376  io.dcache.req.bits.mask         := s0_sel_src.mask
377  io.dcache.req.bits.data         := DontCare
378  io.dcache.req.bits.isFirstIssue := s0_sel_src.isFirstIssue
379  io.dcache.req.bits.instrtype    := Mux(s0_sel_src.prf, DCACHE_PREFETCH_SOURCE.U, LOAD_SOURCE.U)
380  io.dcache.req.bits.debug_robIdx := s0_sel_src.uop.robIdx.value
381  io.dcache.req.bits.replayCarry  := s0_sel_src.rep_carry
382  io.dcache.req.bits.id           := DontCare // TODO: update cache meta
383  io.dcache.req.bits.lqIdx        := s0_sel_src.uop.lqIdx
384  io.dcache.pf_source             := Mux(s0_hw_prf_select, io.prefetch_req.bits.pf_source.value, L1_HW_PREFETCH_NULL)
385  io.dcache.is128Req              := s0_sel_src.is128bit
386
387  // load flow priority mux
388  def fromNullSource(): FlowSource = {
389    val out = WireInit(0.U.asTypeOf(new FlowSource))
390    out
391  }
392
393  def fromMisAlignBufferSource(src: LsPipelineBundle): FlowSource = {
394    val out = WireInit(0.U.asTypeOf(new FlowSource))
395    out.vaddr         := src.vaddr
396    out.mask          := src.mask
397    out.uop           := src.uop
398    out.try_l2l       := false.B
399    out.has_rob_entry := false.B
400    out.rep_carry     := src.replayCarry
401    out.mshrid        := src.mshrid
402    out.frm_mabuf     := true.B
403    out.isFirstIssue  := false.B
404    out.fast_rep      := false.B
405    out.ld_rep        := false.B
406    out.l2l_fwd       := false.B
407    out.prf           := false.B
408    out.prf_rd        := false.B
409    out.prf_wr        := false.B
410    out.sched_idx     := src.schedIndex
411    out.isvec         := false.B
412    out.is128bit      := src.is128bit
413    out.vecActive     := true.B
414    out
415  }
416
417  def fromFastReplaySource(src: LqWriteBundle): FlowSource = {
418    val out = WireInit(0.U.asTypeOf(new FlowSource))
419    out.mask          := src.mask
420    out.uop           := src.uop
421    out.try_l2l       := false.B
422    out.has_rob_entry := src.hasROBEntry
423    out.rep_carry     := src.rep_info.rep_carry
424    out.mshrid        := src.rep_info.mshr_id
425    out.frm_mabuf     := src.isFrmMisAlignBuf
426    out.isFirstIssue  := false.B
427    out.fast_rep      := true.B
428    out.ld_rep        := src.isLoadReplay
429    out.l2l_fwd       := false.B
430    out.prf           := LSUOpType.isPrefetch(src.uop.fuOpType) && !src.isvec
431    out.prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
432    out.prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
433    out.prf_i         := false.B
434    out.sched_idx     := src.schedIndex
435    out.isvec         := src.isvec
436    out.is128bit      := src.is128bit
437    out.uop_unit_stride_fof := src.uop_unit_stride_fof
438    out.reg_offset    := src.reg_offset
439    out.vecActive     := src.vecActive
440    out.is_first_ele  := src.is_first_ele
441    out.usSecondInv   := src.usSecondInv
442    out.mbIndex       := src.mbIndex
443    out.elemIdx       := src.elemIdx
444    out.elemIdxInsideVd := src.elemIdxInsideVd
445    out.alignedType   := src.alignedType
446    out
447  }
448
449  // TODO: implement vector mmio
450  def fromMmioSource(src: MemExuOutput) = {
451    val out = WireInit(0.U.asTypeOf(new FlowSource))
452    out.mask          := 0.U
453    out.uop           := src.uop
454    out.try_l2l       := false.B
455    out.has_rob_entry := false.B
456    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
457    out.mshrid        := 0.U
458    out.frm_mabuf     := false.B
459    out.isFirstIssue  := false.B
460    out.fast_rep      := false.B
461    out.ld_rep        := false.B
462    out.l2l_fwd       := false.B
463    out.prf           := false.B
464    out.prf_rd        := false.B
465    out.prf_wr        := false.B
466    out.prf_i         := false.B
467    out.sched_idx     := 0.U
468    out.vecActive     := true.B
469    out
470  }
471
472  def fromNormalReplaySource(src: LsPipelineBundle): FlowSource = {
473    val out = WireInit(0.U.asTypeOf(new FlowSource))
474    out.mask          := Mux(src.isvec, src.mask, genVWmask(src.vaddr, src.uop.fuOpType(1, 0)))
475    out.uop           := src.uop
476    out.try_l2l       := false.B
477    out.has_rob_entry := true.B
478    out.rep_carry     := src.replayCarry
479    out.mshrid        := src.mshrid
480    out.frm_mabuf     := false.B
481    out.isFirstIssue  := false.B
482    out.fast_rep      := false.B
483    out.ld_rep        := true.B
484    out.l2l_fwd       := false.B
485    out.prf           := LSUOpType.isPrefetch(src.uop.fuOpType) && !src.isvec
486    out.prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
487    out.prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
488    out.prf_i         := false.B
489    out.sched_idx     := src.schedIndex
490    out.isvec         := src.isvec
491    out.is128bit      := src.is128bit
492    out.uop_unit_stride_fof := src.uop_unit_stride_fof
493    out.reg_offset    := src.reg_offset
494    out.vecActive     := src.vecActive
495    out.is_first_ele  := src.is_first_ele
496    out.usSecondInv   := src.usSecondInv
497    out.mbIndex       := src.mbIndex
498    out.elemIdx       := src.elemIdx
499    out.elemIdxInsideVd := src.elemIdxInsideVd
500    out.alignedType   := src.alignedType
501    out
502  }
503
504  // TODO: implement vector prefetch
505  def fromPrefetchSource(src: L1PrefetchReq): FlowSource = {
506    val out = WireInit(0.U.asTypeOf(new FlowSource))
507    out.mask          := 0.U
508    out.uop           := DontCare
509    out.try_l2l       := false.B
510    out.has_rob_entry := false.B
511    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
512    out.mshrid        := 0.U
513    out.frm_mabuf     := false.B
514    out.isFirstIssue  := false.B
515    out.fast_rep      := false.B
516    out.ld_rep        := false.B
517    out.l2l_fwd       := false.B
518    out.prf           := true.B
519    out.prf_rd        := !src.is_store
520    out.prf_wr        := src.is_store
521    out.prf_i         := false.B
522    out.sched_idx     := 0.U
523    out
524  }
525
526  def fromVecIssueSource(src: VecPipeBundle): FlowSource = {
527    val out = WireInit(0.U.asTypeOf(new FlowSource))
528    out.mask          := src.mask
529    out.uop           := src.uop
530    out.try_l2l       := false.B
531    out.has_rob_entry := true.B
532    // TODO: VLSU, implement replay carry
533    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
534    out.mshrid        := 0.U
535    out.frm_mabuf     := false.B
536    // TODO: VLSU, implement first issue
537//    out.isFirstIssue  := src.isFirstIssue
538    out.fast_rep      := false.B
539    out.ld_rep        := false.B
540    out.l2l_fwd       := false.B
541    out.prf           := false.B
542    out.prf_rd        := false.B
543    out.prf_wr        := false.B
544    out.prf_i         := false.B
545    out.sched_idx     := 0.U
546    // Vector load interface
547    out.isvec               := true.B
548    // vector loads only access a single element at a time, so 128-bit path is not used for now
549    out.is128bit            := is128Bit(src.alignedType)
550    out.uop_unit_stride_fof := src.uop_unit_stride_fof
551    // out.rob_idx_valid       := src.rob_idx_valid
552    // out.inner_idx           := src.inner_idx
553    // out.rob_idx             := src.rob_idx
554    out.reg_offset          := src.reg_offset
555    // out.offset              := src.offset
556    out.vecActive           := src.vecActive
557    out.is_first_ele        := src.is_first_ele
558    // out.flowPtr             := src.flowPtr
559    out.usSecondInv         := src.usSecondInv
560    out.mbIndex             := src.mBIndex
561    out.elemIdx             := src.elemIdx
562    out.elemIdxInsideVd     := src.elemIdxInsideVd
563    out.vecBaseVaddr        := src.basevaddr
564    out.alignedType         := src.alignedType
565    out
566  }
567
568  def fromIntIssueSource(src: MemExuInput): FlowSource = {
569    val out = WireInit(0.U.asTypeOf(new FlowSource))
570    val addr           = io.ldin.bits.src(0) + SignExt(io.ldin.bits.uop.imm(11, 0), VAddrBits)
571    out.mask          := genVWmask(addr, src.uop.fuOpType(1,0))
572    out.uop           := src.uop
573    out.try_l2l       := false.B
574    out.has_rob_entry := true.B
575    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
576    out.mshrid        := 0.U
577    out.frm_mabuf     := false.B
578    out.isFirstIssue  := true.B
579    out.fast_rep      := false.B
580    out.ld_rep        := false.B
581    out.l2l_fwd       := false.B
582    out.prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
583    out.prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
584    out.prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
585    out.prf_i         := src.uop.fuOpType === LSUOpType.prefetch_i
586    out.sched_idx     := 0.U
587    out.vecActive     := true.B // true for scala load
588    out
589  }
590
591  // TODO: implement vector l2l
592  def fromLoadToLoadSource(src: LoadToLoadIO): FlowSource = {
593    val out = WireInit(0.U.asTypeOf(new FlowSource))
594    out.mask               := genVWmask(0.U, LSUOpType.ld)
595    // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
596    // Assume the pointer chasing is always ld.
597    out.uop.fuOpType       := LSUOpType.ld
598    out.try_l2l            := true.B
599    // we dont care out.isFirstIssue and out.rsIdx and s0_sqIdx in S0 when trying pointchasing
600    // because these signals will be updated in S1
601    out.has_rob_entry      := false.B
602    out.mshrid             := 0.U
603    out.frm_mabuf          := false.B
604    out.rep_carry          := 0.U.asTypeOf(out.rep_carry)
605    out.isFirstIssue       := true.B
606    out.fast_rep           := false.B
607    out.ld_rep             := false.B
608    out.l2l_fwd            := true.B
609    out.prf                := false.B
610    out.prf_rd             := false.B
611    out.prf_wr             := false.B
612    out.prf_i              := false.B
613    out.sched_idx          := 0.U
614    out
615  }
616
617  // set default
618  val s0_src_selector = WireInit(s0_src_valid_vec)
619  if (!EnableLoadToLoadForward) { s0_src_selector(l2l_fwd_idx) := false.B }
620  val s0_src_format = Seq(
621    fromMisAlignBufferSource(io.misalign_ldin.bits),
622    fromNormalReplaySource(io.replay.bits),
623    fromFastReplaySource(io.fast_rep_in.bits),
624    fromMmioSource(io.lsq.uncache.bits),
625    fromNormalReplaySource(io.replay.bits),
626    fromPrefetchSource(io.prefetch_req.bits),
627    fromVecIssueSource(io.vecldin.bits),
628    fromIntIssueSource(io.ldin.bits),
629    (if (EnableLoadToLoadForward) fromLoadToLoadSource(io.l2l_fwd_in) else fromNullSource()),
630    fromPrefetchSource(io.prefetch_req.bits)
631  )
632  s0_sel_src := ParallelPriorityMux(s0_src_selector, s0_src_format)
633
634  // fast replay and hardware prefetch don't need to query tlb
635  val int_issue_vaddr = io.ldin.bits.src(0) + SignExt(io.ldin.bits.uop.imm(11, 0), VAddrBits)
636  val int_vec_vaddr = Mux(s0_src_valid_vec(vec_iss_idx), io.vecldin.bits.vaddr(VAddrBits - 1, 0), int_issue_vaddr)
637  s0_tlb_vaddr := Mux(
638    s0_src_valid_vec(mab_idx),
639    io.misalign_ldin.bits.vaddr,
640    Mux(
641      s0_src_valid_vec(super_rep_idx) || s0_src_valid_vec(lsq_rep_idx),
642      io.replay.bits.vaddr,
643      int_vec_vaddr
644    )
645  )
646
647  // only first issue of int / vec load intructions need to check full vaddr
648  s0_tlb_fullva := Mux(s0_src_valid_vec(mab_idx),
649    io.misalign_ldin.bits.fullva,
650    Mux(s0_src_select_vec(vec_iss_idx),
651      io.vecldin.bits.vaddr,
652      Mux(
653        s0_src_select_vec(int_iss_idx),
654        io.ldin.bits.src(0) + SignExt(io.ldin.bits.uop.imm(11, 0), XLEN),
655        s0_dcache_vaddr
656      )
657    )
658  )
659
660  s0_dcache_vaddr := Mux(
661    s0_src_select_vec(fast_rep_idx),
662    io.fast_rep_in.bits.vaddr,
663    Mux(
664      s0_hw_prf_select,
665      io.prefetch_req.bits.getVaddr(),
666      s0_tlb_vaddr
667    )
668  )
669
670  s0_tlb_hlv := Mux(
671    s0_src_valid_vec(mab_idx),
672    LSUOpType.isHlv(io.misalign_ldin.bits.uop.fuOpType),
673    Mux(
674      s0_src_valid_vec(super_rep_idx) || s0_src_valid_vec(lsq_rep_idx),
675      LSUOpType.isHlv(io.replay.bits.uop.fuOpType),
676      Mux(
677        s0_src_valid_vec(int_iss_idx),
678        LSUOpType.isHlv(io.ldin.bits.uop.fuOpType),
679        false.B
680      )
681    )
682  )
683  s0_tlb_hlvx := Mux(
684    s0_src_valid_vec(mab_idx),
685    LSUOpType.isHlvx(io.misalign_ldin.bits.uop.fuOpType),
686    Mux(
687      s0_src_valid_vec(super_rep_idx) || s0_src_valid_vec(lsq_rep_idx),
688      LSUOpType.isHlvx(io.replay.bits.uop.fuOpType),
689      Mux(
690        s0_src_valid_vec(int_iss_idx),
691        LSUOpType.isHlvx(io.ldin.bits.uop.fuOpType),
692        false.B
693      )
694    )
695  )
696
697  // address align check
698  val s0_addr_aligned = LookupTree(Mux(s0_sel_src.isvec, s0_sel_src.alignedType(1,0), s0_sel_src.uop.fuOpType(1, 0)), List(
699    "b00".U   -> true.B,                   //b
700    "b01".U   -> (s0_dcache_vaddr(0)    === 0.U), //h
701    "b10".U   -> (s0_dcache_vaddr(1, 0) === 0.U), //w
702    "b11".U   -> (s0_dcache_vaddr(2, 0) === 0.U)  //d
703  ))
704  XSError(s0_sel_src.isvec && s0_dcache_vaddr(3, 0) =/= 0.U && s0_sel_src.alignedType(2), "unit-stride 128 bit element is not aligned!")
705
706  // accept load flow if dcache ready (tlb is always ready)
707  // TODO: prefetch need writeback to loadQueueFlag
708  s0_out               := DontCare
709  s0_out.vaddr         := s0_dcache_vaddr
710  s0_out.fullva        := s0_tlb_fullva
711  s0_out.mask          := s0_sel_src.mask
712  s0_out.uop           := s0_sel_src.uop
713  s0_out.isFirstIssue  := s0_sel_src.isFirstIssue
714  s0_out.hasROBEntry   := s0_sel_src.has_rob_entry
715  s0_out.isPrefetch    := s0_sel_src.prf
716  s0_out.isHWPrefetch  := s0_hw_prf_select
717  s0_out.isFastReplay  := s0_sel_src.fast_rep
718  s0_out.isLoadReplay  := s0_sel_src.ld_rep
719  s0_out.isFastPath    := s0_sel_src.l2l_fwd
720  s0_out.mshrid        := s0_sel_src.mshrid
721  s0_out.isvec           := s0_sel_src.isvec
722  s0_out.is128bit        := s0_sel_src.is128bit
723  s0_out.isFrmMisAlignBuf    := s0_sel_src.frm_mabuf
724  s0_out.uop_unit_stride_fof := s0_sel_src.uop_unit_stride_fof
725  s0_out.paddr         := Mux(s0_src_valid_vec(fast_rep_idx), io.fast_rep_in.bits.paddr,
726    Mux(s0_src_select_vec(int_iss_idx) && s0_sel_src.prf_i, 0.U, io.prefetch_req.bits.paddr)) // only for prefetch and fast_rep
727  s0_out.tlbNoQuery    := s0_tlb_no_query
728  // s0_out.rob_idx_valid   := s0_rob_idx_valid
729  // s0_out.inner_idx       := s0_inner_idx
730  // s0_out.rob_idx         := s0_rob_idx
731  s0_out.reg_offset      := s0_sel_src.reg_offset
732  // s0_out.offset          := s0_offset
733  s0_out.vecActive             := s0_sel_src.vecActive
734  s0_out.usSecondInv    := s0_sel_src.usSecondInv
735  s0_out.is_first_ele   := s0_sel_src.is_first_ele
736  s0_out.elemIdx        := s0_sel_src.elemIdx
737  s0_out.elemIdxInsideVd := s0_sel_src.elemIdxInsideVd
738  s0_out.alignedType    := s0_sel_src.alignedType
739  s0_out.mbIndex        := s0_sel_src.mbIndex
740  s0_out.vecBaseVaddr   := s0_sel_src.vecBaseVaddr
741  // s0_out.flowPtr         := s0_sel_src.flowPtr
742  s0_out.uop.exceptionVec(loadAddrMisaligned) := (!s0_addr_aligned || s0_sel_src.uop.exceptionVec(loadAddrMisaligned)) && s0_sel_src.vecActive
743  s0_out.forward_tlDchannel := s0_src_select_vec(super_rep_idx)
744  when(io.tlb.req.valid && s0_sel_src.isFirstIssue) {
745    s0_out.uop.debugInfo.tlbFirstReqTime := GTimer()
746  }.otherwise{
747    s0_out.uop.debugInfo.tlbFirstReqTime := s0_sel_src.uop.debugInfo.tlbFirstReqTime
748  }
749  s0_out.schedIndex     := s0_sel_src.sched_idx
750
751  // load fast replay
752  io.fast_rep_in.ready := (s0_can_go && io.dcache.req.ready && s0_src_ready_vec(fast_rep_idx))
753
754  // mmio
755  io.lsq.uncache.ready := s0_mmio_fire
756
757  // load flow source ready
758  // cache missed load has highest priority
759  // always accept cache missed load flow from load replay queue
760  io.replay.ready := (s0_can_go && io.dcache.req.ready && (s0_src_ready_vec(lsq_rep_idx) && !s0_rep_stall || s0_src_select_vec(super_rep_idx)))
761
762  // accept load flow from rs when:
763  // 1) there is no lsq-replayed load
764  // 2) there is no fast replayed load
765  // 3) there is no high confidence prefetch request
766  io.vecldin.ready := s0_can_go && io.dcache.req.ready && s0_src_ready_vec(vec_iss_idx)
767  io.ldin.ready := s0_can_go && io.dcache.req.ready && s0_src_ready_vec(int_iss_idx)
768  io.misalign_ldin.ready := s0_can_go && io.dcache.req.ready && s0_src_ready_vec(mab_idx)
769
770  // for hw prefetch load flow feedback, to be added later
771  // io.prefetch_in.ready := s0_hw_prf_select
772
773  // dcache replacement extra info
774  // TODO: should prefetch load update replacement?
775  io.dcache.replacementUpdated := Mux(s0_src_select_vec(lsq_rep_idx) || s0_src_select_vec(super_rep_idx), io.replay.bits.replacementUpdated, false.B)
776
777  // load wakeup
778  // TODO: vector load wakeup?
779  val s0_wakeup_selector = Seq(
780    s0_src_valid_vec(super_rep_idx),
781    s0_src_valid_vec(fast_rep_idx),
782    s0_mmio_fire,
783    s0_src_valid_vec(lsq_rep_idx),
784    s0_src_valid_vec(int_iss_idx)
785  )
786  val s0_wakeup_format = Seq(
787    io.replay.bits.uop,
788    io.fast_rep_in.bits.uop,
789    io.lsq.uncache.bits.uop,
790    io.replay.bits.uop,
791    io.ldin.bits.uop,
792  )
793  val s0_wakeup_uop = ParallelPriorityMux(s0_wakeup_selector, s0_wakeup_format)
794  io.wakeup.valid := s0_fire && !s0_sel_src.isvec && !s0_sel_src.frm_mabuf &&
795                    (s0_src_valid_vec(super_rep_idx) || s0_src_valid_vec(fast_rep_idx) || s0_src_valid_vec(lsq_rep_idx) || ((s0_src_valid_vec(int_iss_idx) && !s0_sel_src.prf) && !s0_src_valid_vec(vec_iss_idx) && !s0_src_valid_vec(high_pf_idx))) || s0_mmio_fire
796  io.wakeup.bits := s0_wakeup_uop
797
798  // prefetch.i(Zicbop)
799  io.ifetchPrefetch.valid := RegNext(s0_src_select_vec(int_iss_idx) && s0_sel_src.prf_i)
800  io.ifetchPrefetch.bits.vaddr := RegEnable(s0_out.vaddr, 0.U, s0_src_select_vec(int_iss_idx) && s0_sel_src.prf_i)
801
802  XSDebug(io.dcache.req.fire,
803    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_sel_src.uop.pc)}, vaddr ${Hexadecimal(s0_dcache_vaddr)}\n"
804  )
805  XSDebug(s0_valid,
806    p"S0: pc ${Hexadecimal(s0_out.uop.pc)}, lId ${Hexadecimal(s0_out.uop.lqIdx.asUInt)}, " +
807    p"vaddr ${Hexadecimal(s0_out.vaddr)}, mask ${Hexadecimal(s0_out.mask)}\n")
808
809  // Pipeline
810  // --------------------------------------------------------------------------------
811  // stage 1
812  // --------------------------------------------------------------------------------
813  // TLB resp (send paddr to dcache)
814  val s1_valid      = RegInit(false.B)
815  val s1_in         = Wire(new LqWriteBundle)
816  val s1_out        = Wire(new LqWriteBundle)
817  val s1_kill       = Wire(Bool())
818  val s1_can_go     = s2_ready
819  val s1_fire       = s1_valid && !s1_kill && s1_can_go
820  val s1_vecActive        = RegEnable(s0_out.vecActive, true.B, s0_fire)
821
822  s1_ready := !s1_valid || s1_kill || s2_ready
823  when (s0_fire) { s1_valid := true.B }
824  .elsewhen (s1_fire) { s1_valid := false.B }
825  .elsewhen (s1_kill) { s1_valid := false.B }
826  s1_in   := RegEnable(s0_out, s0_fire)
827
828  val s1_fast_rep_dly_kill = RegEnable(io.fast_rep_in.bits.lateKill, io.fast_rep_in.valid) && s1_in.isFastReplay
829  val s1_fast_rep_dly_err =  RegEnable(io.fast_rep_in.bits.delayedLoadError, io.fast_rep_in.valid) && s1_in.isFastReplay
830  val s1_l2l_fwd_dly_err  = RegEnable(io.l2l_fwd_in.dly_ld_err, io.l2l_fwd_in.valid) && s1_in.isFastPath
831  val s1_dly_err          = s1_fast_rep_dly_err || s1_l2l_fwd_dly_err
832  val s1_vaddr_hi         = Wire(UInt())
833  val s1_vaddr_lo         = Wire(UInt())
834  val s1_vaddr            = Wire(UInt())
835  val s1_paddr_dup_lsu    = Wire(UInt())
836  val s1_gpaddr_dup_lsu   = Wire(UInt())
837  val s1_paddr_dup_dcache = Wire(UInt())
838  val s1_exception        = ExceptionNO.selectByFu(s1_out.uop.exceptionVec, LduCfg).asUInt.orR   // af & pf exception were modified below.
839  val s1_tlb_miss         = io.tlb.resp.bits.miss && io.tlb.resp.valid && s1_valid
840  val s1_tlb_fast_miss    = io.tlb.resp.bits.fastMiss && io.tlb.resp.valid && s1_valid
841  val s1_pbmt             = Mux(io.tlb.resp.valid, io.tlb.resp.bits.pbmt(0), 0.U(2.W))
842  val s1_prf              = s1_in.isPrefetch
843  val s1_hw_prf           = s1_in.isHWPrefetch
844  val s1_sw_prf           = s1_prf && !s1_hw_prf
845  val s1_tlb_memidx       = io.tlb.resp.bits.memidx
846
847  s1_vaddr_hi         := s1_in.vaddr(VAddrBits - 1, 6)
848  s1_vaddr_lo         := s1_in.vaddr(5, 0)
849  s1_vaddr            := Cat(s1_vaddr_hi, s1_vaddr_lo)
850  s1_paddr_dup_lsu    := Mux(s1_in.tlbNoQuery, s1_in.paddr, io.tlb.resp.bits.paddr(0))
851  s1_paddr_dup_dcache := Mux(s1_in.tlbNoQuery, s1_in.paddr, io.tlb.resp.bits.paddr(1))
852  s1_gpaddr_dup_lsu   := Mux(s1_in.isFastReplay, s1_in.paddr, io.tlb.resp.bits.gpaddr(0))
853
854  when (s1_tlb_memidx.is_ld && io.tlb.resp.valid && !s1_tlb_miss && s1_tlb_memidx.idx === s1_in.uop.lqIdx.value) {
855    // printf("load idx = %d\n", s1_tlb_memidx.idx)
856    s1_out.uop.debugInfo.tlbRespTime := GTimer()
857  }
858
859  io.tlb.req_kill   := s1_kill || s1_dly_err
860  io.tlb.req.bits.pmp_addr := s1_in.paddr
861  io.tlb.resp.ready := true.B
862
863  io.dcache.s1_paddr_dup_lsu    <> s1_paddr_dup_lsu
864  io.dcache.s1_paddr_dup_dcache <> s1_paddr_dup_dcache
865  io.dcache.s1_kill             := s1_kill || s1_dly_err || s1_tlb_miss || s1_exception
866  io.dcache.s1_kill_data_read   := s1_kill || s1_dly_err || s1_tlb_fast_miss
867
868  // store to load forwarding
869  io.sbuffer.valid := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_dly_err || s1_prf)
870  io.sbuffer.vaddr := s1_vaddr
871  io.sbuffer.paddr := s1_paddr_dup_lsu
872  io.sbuffer.uop   := s1_in.uop
873  io.sbuffer.sqIdx := s1_in.uop.sqIdx
874  io.sbuffer.mask  := s1_in.mask
875  io.sbuffer.pc    := s1_in.uop.pc // FIXME: remove it
876
877  io.lsq.forward.valid     := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_dly_err || s1_prf)
878  io.lsq.forward.vaddr     := s1_vaddr
879  io.lsq.forward.paddr     := s1_paddr_dup_lsu
880  io.lsq.forward.uop       := s1_in.uop
881  io.lsq.forward.sqIdx     := s1_in.uop.sqIdx
882  io.lsq.forward.sqIdxMask := 0.U
883  io.lsq.forward.mask      := s1_in.mask
884  io.lsq.forward.pc        := s1_in.uop.pc // FIXME: remove it
885
886  // st-ld violation query
887    // if store unit is 128-bits memory access, need match 128-bit
888  private val s1_isMatch128 = io.stld_nuke_query.map(x => (x.bits.matchLine || (s1_in.isvec && s1_in.is128bit)))
889  val s1_nuke_paddr_match = VecInit((0 until StorePipelineWidth).zip(s1_isMatch128).map{case (w, s) => {Mux(s,
890    s1_paddr_dup_lsu(PAddrBits-1, 4) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 4),
891    s1_paddr_dup_lsu(PAddrBits-1, 3) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3))}})
892  val s1_nuke = VecInit((0 until StorePipelineWidth).map(w => {
893                       io.stld_nuke_query(w).valid && // query valid
894                       isAfter(s1_in.uop.robIdx, io.stld_nuke_query(w).bits.robIdx) && // older store
895                       s1_nuke_paddr_match(w) && // paddr match
896                       (s1_in.mask & io.stld_nuke_query(w).bits.mask).orR // data mask contain
897                      })).asUInt.orR && !s1_tlb_miss
898
899  s1_out                   := s1_in
900  s1_out.vaddr             := s1_vaddr
901  s1_out.vaNeedExt         := io.tlb.resp.bits.excp(0).vaNeedExt
902  s1_out.isHyper           := io.tlb.resp.bits.excp(0).isHyper
903  s1_out.paddr             := s1_paddr_dup_lsu
904  s1_out.gpaddr            := s1_gpaddr_dup_lsu
905  s1_out.isForVSnonLeafPTE := io.tlb.resp.bits.isForVSnonLeafPTE
906  s1_out.tlbMiss           := s1_tlb_miss
907  s1_out.ptwBack           := io.tlb.resp.bits.ptwBack
908  s1_out.rep_info.debug    := s1_in.uop.debugInfo
909  s1_out.rep_info.nuke     := s1_nuke && !s1_sw_prf
910  s1_out.delayedLoadError  := s1_dly_err
911
912  when (!s1_dly_err) {
913    // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
914    // af & pf exception were modified
915    // if is tlbNoQuery request, don't trigger exception from tlb resp
916    s1_out.uop.exceptionVec(loadPageFault)   := io.tlb.resp.bits.excp(0).pf.ld && s1_vecActive && !s1_tlb_miss && !s1_in.tlbNoQuery
917    s1_out.uop.exceptionVec(loadGuestPageFault)   := io.tlb.resp.bits.excp(0).gpf.ld && !s1_tlb_miss && !s1_in.tlbNoQuery
918    s1_out.uop.exceptionVec(loadAccessFault) := io.tlb.resp.bits.excp(0).af.ld && s1_vecActive && !s1_tlb_miss && !s1_in.tlbNoQuery
919    when (!s1_out.isvec && RegNext(io.tlb.req.bits.checkfullva) &&
920      (s1_out.uop.exceptionVec(loadPageFault) ||
921        s1_out.uop.exceptionVec(loadGuestPageFault) ||
922        s1_out.uop.exceptionVec(loadAccessFault))) {
923      s1_out.uop.exceptionVec(loadAddrMisaligned) := false.B
924    }
925  } .otherwise {
926    s1_out.uop.exceptionVec(loadPageFault)      := false.B
927    s1_out.uop.exceptionVec(loadGuestPageFault) := false.B
928    s1_out.uop.exceptionVec(loadAddrMisaligned) := false.B
929    s1_out.uop.exceptionVec(loadAccessFault)    := s1_dly_err && s1_vecActive
930  }
931
932  // pointer chasing
933  val s1_try_ptr_chasing       = GatedValidRegNext(s0_do_try_ptr_chasing, false.B)
934  val s1_ptr_chasing_vaddr     = RegEnable(s0_ptr_chasing_vaddr, s0_do_try_ptr_chasing)
935  val s1_fu_op_type_not_ld     = WireInit(false.B)
936  val s1_not_fast_match        = WireInit(false.B)
937  val s1_addr_mismatch         = WireInit(false.B)
938  val s1_addr_misaligned       = WireInit(false.B)
939  val s1_fast_mismatch         = WireInit(false.B)
940  val s1_ptr_chasing_canceled  = WireInit(false.B)
941  val s1_cancel_ptr_chasing    = WireInit(false.B)
942
943  val s1_redirect_reg = Wire(Valid(new Redirect))
944  s1_redirect_reg.bits := RegEnable(io.redirect.bits, io.redirect.valid)
945  s1_redirect_reg.valid := GatedValidRegNext(io.redirect.valid)
946
947  s1_kill := s1_fast_rep_dly_kill ||
948             s1_cancel_ptr_chasing ||
949             s1_in.uop.robIdx.needFlush(io.redirect) ||
950            (s1_in.uop.robIdx.needFlush(s1_redirect_reg) && !GatedValidRegNext(s0_try_ptr_chasing)) ||
951             RegEnable(s0_kill, false.B, io.ldin.valid || io.vecldin.valid || io.replay.valid || io.l2l_fwd_in.valid || io.fast_rep_in.valid || io.misalign_ldin.valid)
952
953  if (EnableLoadToLoadForward) {
954    // Sometimes, we need to cancel the load-load forwarding.
955    // These can be put at S0 if timing is bad at S1.
956    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
957    s1_addr_mismatch     := s1_ptr_chasing_vaddr(6) ||
958                             RegEnable(io.ld_fast_imm(11, 6).orR, s0_do_try_ptr_chasing)
959    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
960    s1_addr_misaligned := s1_ptr_chasing_vaddr(2, 0).orR
961    s1_fu_op_type_not_ld := io.ldin.bits.uop.fuOpType =/= LSUOpType.ld
962    // Case 2: this load-load uop is cancelled
963    s1_ptr_chasing_canceled := !io.ldin.valid
964    // Case 3: fast mismatch
965    s1_fast_mismatch := RegEnable(!io.ld_fast_match, s0_do_try_ptr_chasing)
966
967    when (s1_try_ptr_chasing) {
968      s1_cancel_ptr_chasing := s1_addr_mismatch ||
969                               s1_addr_misaligned ||
970                               s1_fu_op_type_not_ld ||
971                               s1_ptr_chasing_canceled ||
972                               s1_fast_mismatch
973
974      s1_in.uop           := io.ldin.bits.uop
975      s1_in.isFirstIssue  := io.ldin.bits.isFirstIssue
976      s1_vaddr_lo         := s1_ptr_chasing_vaddr(5, 0)
977      s1_paddr_dup_lsu    := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
978      s1_paddr_dup_dcache := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
979
980      // 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)
981      s1_in.uop.debugInfo.tlbFirstReqTime := GTimer()
982      s1_in.uop.debugInfo.tlbRespTime     := GTimer()
983    }
984    when (!s1_cancel_ptr_chasing) {
985      s0_ptr_chasing_canceled := s1_try_ptr_chasing && !io.replay.fire && !io.fast_rep_in.fire && !(s0_src_valid_vec(high_pf_idx) && io.canAcceptHighConfPrefetch) && !io.misalign_ldin.fire
986      when (s1_try_ptr_chasing) {
987        io.ldin.ready := true.B
988      }
989    }
990  }
991
992  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
993  val s1_sqIdx_mask = RegEnable(UIntToMask(s0_out.uop.sqIdx.value, StoreQueueSize), s0_fire)
994  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
995  // If the timing here is not OK, load-load forwarding has to be disabled.
996  // Or we calculate sqIdxMask at RS??
997  io.lsq.forward.sqIdxMask := s1_sqIdx_mask
998  if (EnableLoadToLoadForward) {
999    when (s1_try_ptr_chasing) {
1000      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
1001    }
1002  }
1003
1004  io.forward_mshr.valid  := s1_valid && s1_out.forward_tlDchannel
1005  io.forward_mshr.mshrid := s1_out.mshrid
1006  io.forward_mshr.paddr  := s1_out.paddr
1007
1008  val loadTrigger = Module(new MemTrigger(MemType.LOAD))
1009  loadTrigger.io.fromCsrTrigger.tdataVec             := io.fromCsrTrigger.tdataVec
1010  loadTrigger.io.fromCsrTrigger.tEnableVec           := io.fromCsrTrigger.tEnableVec
1011  loadTrigger.io.fromCsrTrigger.triggerCanRaiseBpExp := io.fromCsrTrigger.triggerCanRaiseBpExp
1012  loadTrigger.io.fromCsrTrigger.debugMode            := io.fromCsrTrigger.debugMode
1013  loadTrigger.io.fromLoadStore.vaddr                 := s1_vaddr
1014  loadTrigger.io.fromLoadStore.isVectorUnitStride    := s1_in.isvec && s1_in.is128bit
1015  loadTrigger.io.fromLoadStore.mask                  := s1_in.mask
1016
1017  val s1_trigger_action = loadTrigger.io.toLoadStore.triggerAction
1018  val s1_trigger_debug_mode = TriggerAction.isDmode(s1_trigger_action)
1019  val s1_trigger_breakpoint = TriggerAction.isExp(s1_trigger_action)
1020  s1_out.uop.trigger                  := s1_trigger_action
1021  s1_out.uop.exceptionVec(breakPoint) := s1_trigger_breakpoint
1022  s1_out.vecVaddrOffset := Mux(
1023    s1_trigger_debug_mode || s1_trigger_breakpoint,
1024    loadTrigger.io.toLoadStore.triggerVaddr - s1_in.vecBaseVaddr,
1025    s1_in.vaddr + genVFirstUnmask(s1_in.mask).asUInt - s1_in.vecBaseVaddr
1026  )
1027  s1_out.vecTriggerMask := Mux(s1_trigger_debug_mode || s1_trigger_breakpoint, loadTrigger.io.toLoadStore.triggerMask, 0.U)
1028
1029  XSDebug(s1_valid,
1030    p"S1: pc ${Hexadecimal(s1_out.uop.pc)}, lId ${Hexadecimal(s1_out.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
1031    p"paddr ${Hexadecimal(s1_out.paddr)}, mmio ${s1_out.mmio}\n")
1032
1033  // Pipeline
1034  // --------------------------------------------------------------------------------
1035  // stage 2
1036  // --------------------------------------------------------------------------------
1037  // s2: DCache resp
1038  val s2_valid  = RegInit(false.B)
1039  val s2_in     = Wire(new LqWriteBundle)
1040  val s2_out    = Wire(new LqWriteBundle)
1041  val s2_kill   = Wire(Bool())
1042  val s2_can_go = s3_ready
1043  val s2_fire   = s2_valid && !s2_kill && s2_can_go
1044  val s2_vecActive = RegEnable(s1_out.vecActive, true.B, s1_fire)
1045  val s2_isvec  = RegEnable(s1_out.isvec, false.B, s1_fire)
1046  val s2_data_select  = genRdataOH(s2_out.uop)
1047  val s2_data_select_by_offset = genDataSelectByOffset(s2_out.paddr(2, 0))
1048  val s2_frm_mabuf = s2_in.isFrmMisAlignBuf
1049  val s2_pbmt = RegEnable(s1_pbmt, s1_fire)
1050  val s2_trigger_debug_mode = RegEnable(s1_trigger_debug_mode, false.B, s1_fire)
1051
1052  s2_kill := s2_in.uop.robIdx.needFlush(io.redirect)
1053  s2_ready := !s2_valid || s2_kill || s3_ready
1054  when (s1_fire) { s2_valid := true.B }
1055  .elsewhen (s2_fire) { s2_valid := false.B }
1056  .elsewhen (s2_kill) { s2_valid := false.B }
1057  s2_in := RegEnable(s1_out, s1_fire)
1058
1059  val s2_pmp = WireInit(io.pmp)
1060
1061  val s2_prf    = s2_in.isPrefetch
1062  val s2_hw_prf = s2_in.isHWPrefetch
1063
1064  // exception that may cause load addr to be invalid / illegal
1065  // if such exception happen, that inst and its exception info
1066  // will be force writebacked to rob
1067  val s2_exception_vec = WireInit(s2_in.uop.exceptionVec)
1068  when (!s2_in.delayedLoadError) {
1069    s2_exception_vec(loadAccessFault) := (s2_in.uop.exceptionVec(loadAccessFault) ||
1070                                         s2_pmp.ld ||
1071                                         s2_isvec && s2_pmp.mmio && !s2_prf && !s2_in.tlbMiss ||
1072                                         (io.dcache.resp.bits.tag_error && GatedValidRegNext(io.csrCtrl.cache_error_enable))
1073                                         ) && s2_vecActive
1074  }
1075
1076  // soft prefetch will not trigger any exception (but ecc error interrupt may
1077  // be triggered)
1078  val s2_tlb_unrelated_exceps = s2_in.uop.exceptionVec(loadAddrMisaligned) ||
1079                                s2_in.uop.exceptionVec(breakPoint)
1080  when (!s2_in.delayedLoadError && (s2_prf || s2_in.tlbMiss && !s2_tlb_unrelated_exceps)) {
1081    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
1082  }
1083  val s2_exception = s2_vecActive &&
1084                    (s2_trigger_debug_mode || ExceptionNO.selectByFu(s2_exception_vec, LduCfg).asUInt.orR)
1085  val s2_mis_align = s2_valid && GatedValidRegNext(io.csrCtrl.hd_misalign_ld_enable) && !s2_in.isvec &&
1086                     s2_exception_vec(loadAddrMisaligned) && !s2_exception_vec(breakPoint) && !s2_trigger_debug_mode
1087  val (s2_fwd_frm_d_chan, s2_fwd_data_frm_d_chan) = io.tl_d_channel.forward(s1_valid && s1_out.forward_tlDchannel, s1_out.mshrid, s1_out.paddr)
1088  val (s2_fwd_data_valid, s2_fwd_frm_mshr, s2_fwd_data_frm_mshr) = io.forward_mshr.forward()
1089  val s2_fwd_frm_d_chan_or_mshr = s2_fwd_data_valid && (s2_fwd_frm_d_chan || s2_fwd_frm_mshr)
1090
1091  // writeback access fault caused by ecc error / bus error
1092  // * ecc data error is slow to generate, so we will not use it until load stage 3
1093  // * in load stage 3, an extra signal io.load_error will be used to
1094  val s2_actually_mmio = s2_pmp.mmio || Pbmt.isUncache(s2_pbmt)
1095  val s2_mmio          = !s2_prf &&
1096                          s2_actually_mmio &&
1097                         !s2_exception &&
1098                         !s2_in.tlbMiss
1099
1100  val s2_full_fwd      = Wire(Bool())
1101  val s2_mem_amb       = s2_in.uop.storeSetHit &&
1102                         io.lsq.forward.addrInvalid && RegNext(io.lsq.forward.valid)
1103
1104  val s2_tlb_miss      = s2_in.tlbMiss
1105  val s2_fwd_fail      = io.lsq.forward.dataInvalid && RegNext(io.lsq.forward.valid)
1106  val s2_dcache_miss   = io.dcache.resp.bits.miss &&
1107                         !s2_fwd_frm_d_chan_or_mshr &&
1108                         !s2_full_fwd
1109
1110  val s2_mq_nack       = io.dcache.s2_mq_nack &&
1111                         !s2_fwd_frm_d_chan_or_mshr &&
1112                         !s2_full_fwd
1113
1114  val s2_bank_conflict = io.dcache.s2_bank_conflict &&
1115                         !s2_fwd_frm_d_chan_or_mshr &&
1116                         !s2_full_fwd
1117
1118  val s2_wpu_pred_fail = io.dcache.s2_wpu_pred_fail &&
1119                        !s2_fwd_frm_d_chan_or_mshr &&
1120                        !s2_full_fwd
1121
1122  val s2_rar_nack      = io.lsq.ldld_nuke_query.req.valid &&
1123                         !io.lsq.ldld_nuke_query.req.ready
1124
1125  val s2_raw_nack      = io.lsq.stld_nuke_query.req.valid &&
1126                         !io.lsq.stld_nuke_query.req.ready
1127  // st-ld violation query
1128  //  NeedFastRecovery Valid when
1129  //  1. Fast recovery query request Valid.
1130  //  2. Load instruction is younger than requestors(store instructions).
1131  //  3. Physical address match.
1132  //  4. Data contains.
1133  private val s2_isMatch128 = io.stld_nuke_query.map(x => (x.bits.matchLine || (s2_in.isvec && s2_in.is128bit)))
1134  val s2_nuke_paddr_match = VecInit((0 until StorePipelineWidth).zip(s2_isMatch128).map{case (w, s) => {Mux(s,
1135    s2_in.paddr(PAddrBits-1, 4) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 4),
1136    s2_in.paddr(PAddrBits-1, 3) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3))}})
1137  val s2_nuke          = VecInit((0 until StorePipelineWidth).map(w => {
1138                          io.stld_nuke_query(w).valid && // query valid
1139                          isAfter(s2_in.uop.robIdx, io.stld_nuke_query(w).bits.robIdx) && // older store
1140                          s2_nuke_paddr_match(w) && // paddr match
1141                          (s2_in.mask & io.stld_nuke_query(w).bits.mask).orR // data mask contain
1142                        })).asUInt.orR && !s2_tlb_miss || s2_in.rep_info.nuke
1143
1144  val s2_cache_handled   = io.dcache.resp.bits.handled
1145  val s2_cache_tag_error = GatedValidRegNext(io.csrCtrl.cache_error_enable) &&
1146                           io.dcache.resp.bits.tag_error
1147
1148  val s2_troublem        = !s2_exception &&
1149                           !s2_mmio &&
1150                           !s2_prf &&
1151                           !s2_in.delayedLoadError
1152
1153  io.dcache.resp.ready  := true.B
1154  val s2_dcache_should_resp = !(s2_in.tlbMiss || s2_exception || s2_in.delayedLoadError || s2_mmio || s2_prf)
1155  assert(!(s2_valid && (s2_dcache_should_resp && !io.dcache.resp.valid)), "DCache response got lost")
1156
1157  // fast replay require
1158  val s2_dcache_fast_rep = (s2_mq_nack || !s2_dcache_miss && (s2_bank_conflict || s2_wpu_pred_fail))
1159  val s2_nuke_fast_rep   = !s2_mq_nack &&
1160                           !s2_dcache_miss &&
1161                           !s2_bank_conflict &&
1162                           !s2_wpu_pred_fail &&
1163                           !s2_rar_nack &&
1164                           !s2_raw_nack &&
1165                           s2_nuke
1166
1167  val s2_fast_rep = !s2_mem_amb &&
1168                    !s2_tlb_miss &&
1169                    !s2_fwd_fail &&
1170                    (s2_dcache_fast_rep || s2_nuke_fast_rep) &&
1171                    s2_troublem
1172
1173  // need allocate new entry
1174  val s2_can_query = !s2_mem_amb &&
1175                     !s2_tlb_miss &&
1176                     !s2_fwd_fail &&
1177                     !s2_frm_mabuf &&
1178                     s2_troublem
1179
1180  val s2_data_fwded = s2_dcache_miss && (s2_full_fwd || s2_cache_tag_error)
1181
1182  val s2_vp_match_fail = (io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid) && s2_troublem
1183  val s2_safe_wakeup = !s2_out.rep_info.need_rep && !s2_mmio && !s2_mis_align && !s2_exception // don't need to replay and is not a mmio and misalign
1184  val s2_safe_writeback = s2_exception || s2_safe_wakeup || s2_vp_match_fail
1185
1186  // ld-ld violation require
1187  io.lsq.ldld_nuke_query.req.valid           := s2_valid && s2_can_query
1188  io.lsq.ldld_nuke_query.req.bits.uop        := s2_in.uop
1189  io.lsq.ldld_nuke_query.req.bits.mask       := s2_in.mask
1190  io.lsq.ldld_nuke_query.req.bits.paddr      := s2_in.paddr
1191  io.lsq.ldld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
1192
1193  // st-ld violation require
1194  io.lsq.stld_nuke_query.req.valid           := s2_valid && s2_can_query
1195  io.lsq.stld_nuke_query.req.bits.uop        := s2_in.uop
1196  io.lsq.stld_nuke_query.req.bits.mask       := s2_in.mask
1197  io.lsq.stld_nuke_query.req.bits.paddr      := s2_in.paddr
1198  io.lsq.stld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
1199
1200  // merge forward result
1201  // lsq has higher priority than sbuffer
1202  val s2_fwd_mask = Wire(Vec((VLEN/8), Bool()))
1203  val s2_fwd_data = Wire(Vec((VLEN/8), UInt(8.W)))
1204  s2_full_fwd := ((~s2_fwd_mask.asUInt).asUInt & s2_in.mask) === 0.U && !io.lsq.forward.dataInvalid
1205  // generate XLEN/8 Muxs
1206  for (i <- 0 until VLEN / 8) {
1207    s2_fwd_mask(i) := io.lsq.forward.forwardMask(i) || io.sbuffer.forwardMask(i)
1208    s2_fwd_data(i) := Mux(io.lsq.forward.forwardMask(i), io.lsq.forward.forwardData(i), io.sbuffer.forwardData(i))
1209  }
1210
1211  XSDebug(s2_fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
1212    s2_in.uop.pc,
1213    io.lsq.forward.forwardData.asUInt, io.lsq.forward.forwardMask.asUInt,
1214    s2_in.forwardData.asUInt, s2_in.forwardMask.asUInt
1215  )
1216
1217  //
1218  s2_out                     := s2_in
1219  s2_out.data                := 0.U // data will be generated in load s3
1220  s2_out.uop.fpWen           := s2_in.uop.fpWen
1221  s2_out.mmio                := s2_mmio
1222  s2_out.uop.flushPipe       := false.B
1223  s2_out.uop.exceptionVec    := s2_exception_vec
1224  s2_out.forwardMask         := s2_fwd_mask
1225  s2_out.forwardData         := s2_fwd_data
1226  s2_out.handledByMSHR       := s2_cache_handled
1227  s2_out.miss                := s2_dcache_miss && s2_troublem
1228  s2_out.feedbacked          := io.feedback_fast.valid
1229  s2_out.uop.vpu.vstart      := Mux(s2_in.isLoadReplay || s2_in.isFastReplay, s2_in.uop.vpu.vstart, s2_in.vecVaddrOffset >> s2_in.uop.vpu.veew)
1230
1231  // Generate replay signal caused by:
1232  // * st-ld violation check
1233  // * tlb miss
1234  // * dcache replay
1235  // * forward data invalid
1236  // * dcache miss
1237  s2_out.rep_info.mem_amb         := s2_mem_amb && s2_troublem
1238  s2_out.rep_info.tlb_miss        := s2_tlb_miss && s2_troublem
1239  s2_out.rep_info.fwd_fail        := s2_fwd_fail && s2_troublem
1240  s2_out.rep_info.dcache_rep      := s2_mq_nack && s2_troublem
1241  s2_out.rep_info.dcache_miss     := s2_dcache_miss && s2_troublem
1242  s2_out.rep_info.bank_conflict   := s2_bank_conflict && s2_troublem
1243  s2_out.rep_info.wpu_fail        := s2_wpu_pred_fail && s2_troublem
1244  s2_out.rep_info.rar_nack        := s2_rar_nack && s2_troublem
1245  s2_out.rep_info.raw_nack        := s2_raw_nack && s2_troublem
1246  s2_out.rep_info.nuke            := s2_nuke && s2_troublem
1247  s2_out.rep_info.full_fwd        := s2_data_fwded
1248  s2_out.rep_info.data_inv_sq_idx := io.lsq.forward.dataInvalidSqIdx
1249  s2_out.rep_info.addr_inv_sq_idx := io.lsq.forward.addrInvalidSqIdx
1250  s2_out.rep_info.rep_carry       := io.dcache.resp.bits.replayCarry
1251  s2_out.rep_info.mshr_id         := io.dcache.resp.bits.mshr_id
1252  s2_out.rep_info.last_beat       := s2_in.paddr(log2Up(refillBytes))
1253  s2_out.rep_info.debug           := s2_in.uop.debugInfo
1254  s2_out.rep_info.tlb_id          := io.tlb_hint.id
1255  s2_out.rep_info.tlb_full        := io.tlb_hint.full
1256
1257  // if forward fail, replay this inst from fetch
1258  val debug_fwd_fail_rep = s2_fwd_fail && !s2_troublem && !s2_in.tlbMiss
1259  // if ld-ld violation is detected, replay from this inst from fetch
1260  val debug_ldld_nuke_rep = false.B // s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_in.tlbMiss
1261
1262  // to be removed
1263  io.feedback_fast.valid                 := false.B
1264  io.feedback_fast.bits.hit              := false.B
1265  io.feedback_fast.bits.flushState       := s2_in.ptwBack
1266  io.feedback_fast.bits.robIdx           := s2_in.uop.robIdx
1267  io.feedback_fast.bits.sqIdx            := s2_in.uop.sqIdx
1268  io.feedback_fast.bits.lqIdx            := s2_in.uop.lqIdx
1269  io.feedback_fast.bits.sourceType       := RSFeedbackType.lrqFull
1270  io.feedback_fast.bits.dataInvalidSqIdx := DontCare
1271
1272  io.ldCancel.ld1Cancel := false.B
1273
1274  // fast wakeup
1275  val s1_fast_uop_valid = WireInit(false.B)
1276  s1_fast_uop_valid :=
1277    !io.dcache.s1_disable_fast_wakeup &&
1278    s1_valid &&
1279    !s1_kill &&
1280    !io.tlb.resp.bits.miss &&
1281    !io.lsq.forward.dataInvalidFast
1282  io.fast_uop.valid := GatedValidRegNext(s1_fast_uop_valid) && (s2_valid && !s2_out.rep_info.need_rep && !s2_mmio && !(s2_prf && !s2_hw_prf)) && !s2_isvec && !s2_frm_mabuf
1283  io.fast_uop.bits := RegEnable(s1_out.uop, s1_fast_uop_valid)
1284
1285  //
1286  io.s2_ptr_chasing                    := RegEnable(s1_try_ptr_chasing && !s1_cancel_ptr_chasing, false.B, s1_fire)
1287
1288  // RegNext prefetch train for better timing
1289  // ** Now, prefetch train is valid at load s3 **
1290  val s2_prefetch_train_valid = WireInit(false.B)
1291  s2_prefetch_train_valid              := s2_valid && !s2_actually_mmio && (!s2_in.tlbMiss || s2_hw_prf)
1292  io.prefetch_train.valid              := GatedValidRegNext(s2_prefetch_train_valid)
1293  io.prefetch_train.bits.fromLsPipelineBundle(s2_in, latch = true, enable = s2_prefetch_train_valid)
1294  io.prefetch_train.bits.miss          := RegEnable(io.dcache.resp.bits.miss, s2_prefetch_train_valid) // TODO: use trace with bank conflict?
1295  io.prefetch_train.bits.meta_prefetch := RegEnable(io.dcache.resp.bits.meta_prefetch, s2_prefetch_train_valid)
1296  io.prefetch_train.bits.meta_access   := RegEnable(io.dcache.resp.bits.meta_access, s2_prefetch_train_valid)
1297  io.s1_prefetch_spec := s1_fire
1298  io.s2_prefetch_spec := s2_prefetch_train_valid
1299
1300  val s2_prefetch_train_l1_valid = WireInit(false.B)
1301  s2_prefetch_train_l1_valid              := s2_valid && !s2_actually_mmio
1302  io.prefetch_train_l1.valid              := GatedValidRegNext(s2_prefetch_train_l1_valid)
1303  io.prefetch_train_l1.bits.fromLsPipelineBundle(s2_in, latch = true, enable = s2_prefetch_train_l1_valid)
1304  io.prefetch_train_l1.bits.miss          := RegEnable(io.dcache.resp.bits.miss, s2_prefetch_train_l1_valid)
1305  io.prefetch_train_l1.bits.meta_prefetch := RegEnable(io.dcache.resp.bits.meta_prefetch, s2_prefetch_train_l1_valid)
1306  io.prefetch_train_l1.bits.meta_access   := RegEnable(io.dcache.resp.bits.meta_access, s2_prefetch_train_l1_valid)
1307  if (env.FPGAPlatform){
1308    io.dcache.s0_pc := DontCare
1309    io.dcache.s1_pc := DontCare
1310    io.dcache.s2_pc := DontCare
1311  }else{
1312    io.dcache.s0_pc := s0_out.uop.pc
1313    io.dcache.s1_pc := s1_out.uop.pc
1314    io.dcache.s2_pc := s2_out.uop.pc
1315  }
1316  io.dcache.s2_kill := s2_pmp.ld || s2_actually_mmio || s2_kill
1317
1318  val s1_ld_left_fire = s1_valid && !s1_kill && s2_ready
1319  val s2_ld_valid_dup = RegInit(0.U(6.W))
1320  s2_ld_valid_dup := 0x0.U(6.W)
1321  when (s1_ld_left_fire && !s1_out.isHWPrefetch) { s2_ld_valid_dup := 0x3f.U(6.W) }
1322  when (s1_kill || s1_out.isHWPrefetch) { s2_ld_valid_dup := 0x0.U(6.W) }
1323  assert(RegNext((s2_valid === s2_ld_valid_dup(0)) || RegNext(s1_out.isHWPrefetch)))
1324
1325  // Pipeline
1326  // --------------------------------------------------------------------------------
1327  // stage 3
1328  // --------------------------------------------------------------------------------
1329  // writeback and update load queue
1330  val s3_valid        = GatedValidRegNext(s2_valid && !s2_out.isHWPrefetch && !s2_out.uop.robIdx.needFlush(io.redirect))
1331  val s3_in           = RegEnable(s2_out, s2_fire)
1332  val s3_out          = Wire(Valid(new MemExuOutput))
1333  val s3_dcache_rep   = RegEnable(s2_dcache_fast_rep && s2_troublem, false.B, s2_fire)
1334  val s3_ld_valid_dup = RegEnable(s2_ld_valid_dup, s2_fire)
1335  val s3_fast_rep     = Wire(Bool())
1336  val s3_troublem     = GatedValidRegNext(s2_troublem)
1337  val s3_kill         = s3_in.uop.robIdx.needFlush(io.redirect)
1338  val s3_vecout       = Wire(new OnlyVecExuOutput)
1339  val s3_vecActive    = RegEnable(s2_out.vecActive, true.B, s2_fire)
1340  val s3_isvec        = RegEnable(s2_out.isvec, false.B, s2_fire)
1341  val s3_vec_alignedType = RegEnable(s2_out.alignedType, s2_fire)
1342  val s3_vec_mBIndex     = RegEnable(s2_out.mbIndex, s2_fire)
1343  val s3_frm_mabuf       = s3_in.isFrmMisAlignBuf
1344  val s3_mmio         = Wire(Valid(new MemExuOutput))
1345  val s3_data_select  = RegEnable(s2_data_select, 0.U(s2_data_select.getWidth.W), s2_fire)
1346  val s3_data_select_by_offset = RegEnable(s2_data_select_by_offset, 0.U.asTypeOf(s2_data_select_by_offset), s2_fire)
1347  val s3_dly_ld_err   =
1348      if (EnableAccurateLoadError) {
1349        io.dcache.resp.bits.error_delayed && GatedValidRegNext(io.csrCtrl.cache_error_enable) && s3_troublem
1350      } else {
1351        WireInit(false.B)
1352      }
1353  val s3_safe_wakeup  = RegEnable(s2_safe_wakeup, s2_fire)
1354  val s3_safe_writeback = RegEnable(s2_safe_writeback, s2_fire) || s3_dly_ld_err
1355  val s3_exception = RegEnable(s2_exception, s2_fire)
1356  val s3_mis_align = RegEnable(s2_mis_align, s2_fire)
1357  val s3_trigger_debug_mode = RegEnable(s2_trigger_debug_mode, false.B, s2_fire)
1358  // TODO: Fix vector load merge buffer nack
1359  val s3_vec_mb_nack  = Wire(Bool())
1360  s3_vec_mb_nack     := false.B
1361  XSError(s3_valid && s3_vec_mb_nack, "Merge buffer should always accept vector loads!")
1362
1363  s3_ready := !s3_valid || s3_kill || io.ldout.ready
1364  s3_mmio.valid := RegNextN(io.lsq.uncache.fire, 3, Some(false.B))
1365  s3_mmio.bits  := RegNextN(io.lsq.uncache.bits, 3)
1366
1367  // forwrad last beat
1368  val s3_fast_rep_canceled = io.replay.valid && io.replay.bits.forward_tlDchannel || io.misalign_ldin.valid || !io.dcache.req.ready
1369
1370  // s3 load fast replay
1371  io.fast_rep_out.valid := s3_valid && s3_fast_rep && !s3_in.uop.robIdx.needFlush(io.redirect)
1372  io.fast_rep_out.bits := s3_in
1373
1374  io.lsq.ldin.valid := s3_valid && (!s3_fast_rep || s3_fast_rep_canceled) && !s3_in.feedbacked && !s3_frm_mabuf
1375  // TODO: check this --by hx
1376  // io.lsq.ldin.valid := s3_valid && (!s3_fast_rep || !io.fast_rep_out.ready) && !s3_in.feedbacked && !s3_in.lateKill
1377  io.lsq.ldin.bits := s3_in
1378  io.lsq.ldin.bits.miss := s3_in.miss
1379
1380  // connect to misalignBuffer
1381  io.misalign_buf.valid := io.lsq.ldin.valid && GatedValidRegNext(io.csrCtrl.hd_misalign_ld_enable) && !io.lsq.ldin.bits.isvec
1382  io.misalign_buf.bits  := s3_in
1383
1384  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1385  io.lsq.ldin.bits.data_wen_dup := s3_ld_valid_dup.asBools
1386  io.lsq.ldin.bits.replacementUpdated := io.dcache.resp.bits.replacementUpdated
1387  io.lsq.ldin.bits.missDbUpdated := GatedValidRegNext(s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated)
1388
1389  io.s3_dly_ld_err := false.B // s3_dly_ld_err && s3_valid
1390  io.lsq.ldin.bits.dcacheRequireReplay  := s3_dcache_rep
1391  io.fast_rep_out.bits.delayedLoadError := s3_dly_ld_err
1392
1393  val s3_vp_match_fail = GatedValidRegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid) && s3_troublem
1394  val s3_rep_frm_fetch = s3_vp_match_fail
1395  val s3_ldld_rep_inst =
1396      io.lsq.ldld_nuke_query.resp.valid &&
1397      io.lsq.ldld_nuke_query.resp.bits.rep_frm_fetch &&
1398      GatedValidRegNext(io.csrCtrl.ldld_vio_check_enable)
1399  val s3_flushPipe = s3_ldld_rep_inst
1400
1401  val s3_rep_info = WireInit(s3_in.rep_info)
1402  val s3_sel_rep_cause = PriorityEncoderOH(s3_rep_info.cause.asUInt)
1403
1404  when (s3_exception || s3_dly_ld_err || s3_rep_frm_fetch) {
1405    io.lsq.ldin.bits.rep_info.cause := 0.U.asTypeOf(s3_rep_info.cause.cloneType)
1406  } .otherwise {
1407    io.lsq.ldin.bits.rep_info.cause := VecInit(s3_sel_rep_cause.asBools)
1408  }
1409
1410  // Int load, if hit, will be writebacked at s3
1411  s3_out.valid                := s3_valid && s3_safe_writeback
1412  s3_out.bits.uop             := s3_in.uop
1413  s3_out.bits.uop.fpWen       := s3_in.uop.fpWen
1414  s3_out.bits.uop.exceptionVec(loadAccessFault) := (s3_dly_ld_err || s3_in.uop.exceptionVec(loadAccessFault)) && s3_vecActive
1415  s3_out.bits.uop.flushPipe   := false.B
1416  s3_out.bits.uop.replayInst  := s3_rep_frm_fetch || s3_flushPipe
1417  s3_out.bits.data            := s3_in.data
1418  s3_out.bits.isFromLoadUnit  := true.B
1419  s3_out.bits.debug.isMMIO    := s3_in.mmio
1420  s3_out.bits.debug.isPerfCnt := false.B
1421  s3_out.bits.debug.paddr     := s3_in.paddr
1422  s3_out.bits.debug.vaddr     := s3_in.vaddr
1423
1424  // Vector load, writeback to merge buffer
1425  // TODO: Add assertion in merge buffer, merge buffer must accept vec load writeback
1426  s3_vecout.isvec             := s3_isvec
1427  s3_vecout.vecdata           := 0.U // Data will be assigned later
1428  s3_vecout.mask              := s3_in.mask
1429  // s3_vecout.rob_idx_valid     := s3_in.rob_idx_valid
1430  // s3_vecout.inner_idx         := s3_in.inner_idx
1431  // s3_vecout.rob_idx           := s3_in.rob_idx
1432  // s3_vecout.offset            := s3_in.offset
1433  s3_vecout.reg_offset        := s3_in.reg_offset
1434  s3_vecout.vecActive         := s3_vecActive
1435  s3_vecout.is_first_ele      := s3_in.is_first_ele
1436  // s3_vecout.uopQueuePtr       := DontCare // uopQueuePtr is already saved in flow queue
1437  // s3_vecout.flowPtr           := s3_in.flowPtr
1438  s3_vecout.elemIdx           := s3_in.elemIdx // elemIdx is already saved in flow queue // TODO:
1439  s3_vecout.elemIdxInsideVd   := s3_in.elemIdxInsideVd
1440  s3_vecout.trigger           := s3_in.uop.trigger
1441  s3_vecout.vstart            := s3_in.uop.vpu.vstart
1442  s3_vecout.vecTriggerMask    := s3_in.vecTriggerMask
1443  val s3_usSecondInv          = s3_in.usSecondInv
1444
1445  io.rollback.valid := s3_valid && (s3_rep_frm_fetch || s3_flushPipe) && !s3_exception
1446  io.rollback.bits             := DontCare
1447  io.rollback.bits.isRVC       := s3_out.bits.uop.preDecodeInfo.isRVC
1448  io.rollback.bits.robIdx      := s3_out.bits.uop.robIdx
1449  io.rollback.bits.ftqIdx      := s3_out.bits.uop.ftqPtr
1450  io.rollback.bits.ftqOffset   := s3_out.bits.uop.ftqOffset
1451  io.rollback.bits.level       := Mux(s3_rep_frm_fetch, RedirectLevel.flush, RedirectLevel.flushAfter)
1452  io.rollback.bits.cfiUpdate.target := s3_out.bits.uop.pc
1453  io.rollback.bits.debug_runahead_checkpoint_id := s3_out.bits.uop.debugInfo.runahead_checkpoint_id
1454  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1455
1456  io.lsq.ldin.bits.uop := s3_out.bits.uop
1457
1458  val s3_revoke = s3_exception || io.lsq.ldin.bits.rep_info.need_rep
1459  io.lsq.ldld_nuke_query.revoke := s3_revoke
1460  io.lsq.stld_nuke_query.revoke := s3_revoke
1461
1462  // feedback slow
1463  s3_fast_rep := RegNext(s2_fast_rep)
1464
1465  val s3_fb_no_waiting = !s3_in.isLoadReplay &&
1466                        (!(s3_fast_rep && !s3_fast_rep_canceled)) &&
1467                        !s3_in.feedbacked
1468
1469  // feedback: scalar load will send feedback to RS
1470  //           vector load will send signal to VL Merge Buffer, then send feedback at granularity of uops
1471  io.feedback_slow.valid                 := s3_valid && s3_fb_no_waiting && !s3_isvec && !s3_frm_mabuf
1472  io.feedback_slow.bits.hit              := !s3_rep_info.need_rep || io.lsq.ldin.ready
1473  io.feedback_slow.bits.flushState       := s3_in.ptwBack
1474  io.feedback_slow.bits.robIdx           := s3_in.uop.robIdx
1475  io.feedback_slow.bits.sqIdx            := s3_in.uop.sqIdx
1476  io.feedback_slow.bits.lqIdx            := s3_in.uop.lqIdx
1477  io.feedback_slow.bits.sourceType       := RSFeedbackType.lrqFull
1478  io.feedback_slow.bits.dataInvalidSqIdx := DontCare
1479
1480  // TODO: vector wakeup?
1481  io.ldCancel.ld2Cancel := s3_valid && !s3_safe_wakeup && !s3_isvec && !s3_frm_mabuf
1482
1483  val s3_ld_wb_meta = Mux(s3_valid, s3_out.bits, s3_mmio.bits)
1484
1485  // data from load queue refill
1486  val s3_ld_raw_data_frm_uncache = RegNextN(io.lsq.ld_raw_data, 3)
1487  val s3_merged_data_frm_uncache = s3_ld_raw_data_frm_uncache.mergedData()
1488  val s3_picked_data_frm_uncache = LookupTree(s3_ld_raw_data_frm_uncache.addrOffset, List(
1489    "b000".U -> s3_merged_data_frm_uncache(63,  0),
1490    "b001".U -> s3_merged_data_frm_uncache(63,  8),
1491    "b010".U -> s3_merged_data_frm_uncache(63, 16),
1492    "b011".U -> s3_merged_data_frm_uncache(63, 24),
1493    "b100".U -> s3_merged_data_frm_uncache(63, 32),
1494    "b101".U -> s3_merged_data_frm_uncache(63, 40),
1495    "b110".U -> s3_merged_data_frm_uncache(63, 48),
1496    "b111".U -> s3_merged_data_frm_uncache(63, 56)
1497  ))
1498  val s3_ld_data_frm_uncache = rdataHelper(s3_ld_raw_data_frm_uncache.uop, s3_picked_data_frm_uncache)
1499
1500  // data from dcache hit
1501  val s3_ld_raw_data_frm_cache = Wire(new LoadDataFromDcacheBundle)
1502  s3_ld_raw_data_frm_cache.respDcacheData       := io.dcache.resp.bits.data
1503  s3_ld_raw_data_frm_cache.forward_D            := s2_fwd_frm_d_chan
1504  s3_ld_raw_data_frm_cache.forwardData_D        := s2_fwd_data_frm_d_chan
1505  s3_ld_raw_data_frm_cache.forward_mshr         := s2_fwd_frm_mshr
1506  s3_ld_raw_data_frm_cache.forwardData_mshr     := s2_fwd_data_frm_mshr
1507  s3_ld_raw_data_frm_cache.forward_result_valid := s2_fwd_data_valid
1508
1509  s3_ld_raw_data_frm_cache.forwardMask          := RegEnable(s2_fwd_mask, s2_valid)
1510  s3_ld_raw_data_frm_cache.forwardData          := RegEnable(s2_fwd_data, s2_valid)
1511  s3_ld_raw_data_frm_cache.uop                  := RegEnable(s2_out.uop, s2_valid)
1512  s3_ld_raw_data_frm_cache.addrOffset           := RegEnable(s2_out.paddr(3, 0), s2_valid)
1513
1514  val s3_merged_data_frm_tlD   = RegEnable(s3_ld_raw_data_frm_cache.mergeTLData(), s2_valid)
1515  val s3_merged_data_frm_cache = s3_ld_raw_data_frm_cache.mergeLsqFwdData(s3_merged_data_frm_tlD)
1516
1517  // duplicate reg for ldout and vecldout
1518  private val LdDataDup = 3
1519  require(LdDataDup >= 2)
1520  // truncate forward data and cache data to XLEN width to writeback
1521  val s3_fwd_mask_clip = VecInit(List.fill(LdDataDup)(
1522    RegEnable(Mux(
1523      s2_out.paddr(3),
1524      (s2_fwd_mask.asUInt)(VLEN / 8 - 1, 8),
1525      (s2_fwd_mask.asUInt)(7, 0)
1526    ).asTypeOf(Vec(XLEN / 8, Bool())), s2_valid)
1527  ))
1528  val s3_fwd_data_clip = VecInit(List.fill(LdDataDup)(
1529    RegEnable(Mux(
1530      s2_out.paddr(3),
1531      (s2_fwd_data.asUInt)(VLEN - 1, 64),
1532      (s2_fwd_data.asUInt)(63, 0)
1533    ).asTypeOf(Vec(XLEN / 8, UInt(8.W))), s2_valid)
1534  ))
1535  val s3_merged_data_frm_tld_clip = VecInit(List.fill(LdDataDup)(
1536    RegEnable(Mux(
1537      s2_out.paddr(3),
1538      s3_ld_raw_data_frm_cache.mergeTLData()(VLEN - 1, 64),
1539      s3_ld_raw_data_frm_cache.mergeTLData()(63, 0)
1540    ).asTypeOf(Vec(XLEN / 8, UInt(8.W))), s2_valid)
1541  ))
1542  val s3_merged_data_frm_cache_clip = VecInit((0 until LdDataDup).map(i => {
1543    VecInit((0 until XLEN / 8).map(j =>
1544      Mux(s3_fwd_mask_clip(i)(j), s3_fwd_data_clip(i)(j), s3_merged_data_frm_tld_clip(i)(j))
1545    )).asUInt
1546  }))
1547
1548  val s3_data_frm_cache = VecInit((0 until LdDataDup).map(i => {
1549    VecInit(Seq(
1550      s3_merged_data_frm_cache_clip(i)(63,    0),
1551      s3_merged_data_frm_cache_clip(i)(63,    8),
1552      s3_merged_data_frm_cache_clip(i)(63,   16),
1553      s3_merged_data_frm_cache_clip(i)(63,   24),
1554      s3_merged_data_frm_cache_clip(i)(63,   32),
1555      s3_merged_data_frm_cache_clip(i)(63,   40),
1556      s3_merged_data_frm_cache_clip(i)(63,   48),
1557      s3_merged_data_frm_cache_clip(i)(63,   56),
1558    ))
1559  }))
1560  val s3_picked_data_frm_cache = VecInit((0 until LdDataDup).map(i => {
1561    Mux1H(s3_data_select_by_offset, s3_data_frm_cache(i))
1562  }))
1563  val s3_ld_data_frm_cache = newRdataHelper(s3_data_select, s3_picked_data_frm_cache(0))
1564
1565  // FIXME: add 1 cycle delay ?
1566  // io.lsq.uncache.ready := !s3_valid
1567  val s3_outexception = ExceptionNO.selectByFu(s3_out.bits.uop.exceptionVec, LduCfg).asUInt.orR && s3_vecActive
1568  io.ldout.bits        := s3_ld_wb_meta
1569  io.ldout.bits.data   := Mux(s3_valid, s3_ld_data_frm_cache, s3_ld_data_frm_uncache)
1570  io.ldout.valid       := (s3_mmio.valid ||
1571                          (s3_out.valid && !s3_vecout.isvec && !s3_mis_align && !s3_frm_mabuf))
1572  io.ldout.bits.uop.exceptionVec := ExceptionNO.selectByFu(s3_ld_wb_meta.uop.exceptionVec, LduCfg)
1573  io.ldout.bits.isFromLoadUnit := true.B
1574  io.ldout.bits.uop.fuType := Mux(
1575                                  s3_valid && s3_isvec,
1576                                  FuType.vldu.U,
1577                                  FuType.ldu.U
1578  )
1579
1580  // TODO: check this --hx
1581  // io.ldout.valid       := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) && !s3_vecout.isvec ||
1582  //   io.lsq.uncache.valid && !io.lsq.uncache.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid && !io.lsq.uncache.bits.isVls
1583  //  io.ldout.bits.data   := Mux(s3_out.valid, s3_ld_data_frm_cache, s3_ld_data_frm_uncache)
1584  //  io.ldout.valid       := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) ||
1585  //                         s3_mmio.valid && !s3_mmio.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid
1586
1587  // s3 load fast replay
1588  io.fast_rep_out.valid := s3_valid && s3_fast_rep
1589  io.fast_rep_out.bits := s3_in
1590  io.fast_rep_out.bits.lateKill := s3_rep_frm_fetch
1591
1592  val vecFeedback = s3_valid && s3_fb_no_waiting && s3_rep_info.need_rep && !io.lsq.ldin.ready && s3_isvec
1593
1594  // vector output
1595  io.vecldout.bits.alignedType := s3_vec_alignedType
1596  // vec feedback
1597  io.vecldout.bits.vecFeedback := vecFeedback
1598  // TODO: VLSU, uncache data logic
1599  val vecdata = rdataVecHelper(s3_vec_alignedType(1,0), s3_picked_data_frm_cache(1))
1600  io.vecldout.bits.vecdata.get := Mux(s3_in.is128bit, s3_merged_data_frm_cache, vecdata)
1601  io.vecldout.bits.isvec := s3_vecout.isvec
1602  io.vecldout.bits.elemIdx := s3_vecout.elemIdx
1603  io.vecldout.bits.elemIdxInsideVd.get := s3_vecout.elemIdxInsideVd
1604  io.vecldout.bits.mask := s3_vecout.mask
1605  io.vecldout.bits.reg_offset.get := s3_vecout.reg_offset
1606  io.vecldout.bits.usSecondInv := s3_usSecondInv
1607  io.vecldout.bits.mBIndex := s3_vec_mBIndex
1608  io.vecldout.bits.hit := !s3_rep_info.need_rep || io.lsq.ldin.ready
1609  io.vecldout.bits.sourceType := RSFeedbackType.lrqFull
1610  io.vecldout.bits.trigger := s3_vecout.trigger
1611  io.vecldout.bits.flushState := DontCare
1612  io.vecldout.bits.exceptionVec := ExceptionNO.selectByFu(s3_out.bits.uop.exceptionVec, VlduCfg)
1613  io.vecldout.bits.vaddr := s3_in.fullva
1614  io.vecldout.bits.vaNeedExt := s3_in.vaNeedExt
1615  io.vecldout.bits.gpaddr := s3_in.gpaddr
1616  io.vecldout.bits.isForVSnonLeafPTE := s3_in.isForVSnonLeafPTE
1617  io.vecldout.bits.mmio := DontCare
1618  io.vecldout.bits.vstart := s3_vecout.vstart
1619  io.vecldout.bits.vecTriggerMask := s3_vecout.vecTriggerMask
1620
1621  io.vecldout.valid := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) && s3_vecout.isvec //||
1622  // TODO: check this, why !io.lsq.uncache.bits.isVls before?
1623  // Now vector instruction don't support mmio.
1624    // io.lsq.uncache.valid && !io.lsq.uncache.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid && io.lsq.uncache.bits.isVls
1625    //io.lsq.uncache.valid && !io.lsq.uncache.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid && !io.lsq.uncache.bits.isVls
1626
1627  io.misalign_ldout.valid     := s3_valid && (!s3_fast_rep || s3_fast_rep_canceled) && s3_frm_mabuf
1628  io.misalign_ldout.bits      := io.lsq.ldin.bits
1629  io.misalign_ldout.bits.data := Mux(s3_in.is128bit, s3_merged_data_frm_cache, s3_picked_data_frm_cache(2))
1630
1631  // fast load to load forward
1632  if (EnableLoadToLoadForward) {
1633    io.l2l_fwd_out.valid      := s3_valid && !s3_in.mmio && !s3_rep_info.need_rep
1634    io.l2l_fwd_out.data       := Mux(s3_in.vaddr(3), s3_merged_data_frm_cache(127, 64), s3_merged_data_frm_cache(63, 0))
1635    io.l2l_fwd_out.dly_ld_err := s3_dly_ld_err || // ecc delayed error
1636                                 s3_ldld_rep_inst ||
1637                                 s3_rep_frm_fetch
1638  } else {
1639    io.l2l_fwd_out.valid := false.B
1640    io.l2l_fwd_out.data := DontCare
1641    io.l2l_fwd_out.dly_ld_err := DontCare
1642  }
1643
1644  // s1
1645  io.debug_ls.s1_robIdx := s1_in.uop.robIdx.value
1646  io.debug_ls.s1_isLoadToLoadForward := s1_fire && s1_try_ptr_chasing && !s1_ptr_chasing_canceled
1647  io.debug_ls.s1_isTlbFirstMiss := s1_fire && s1_tlb_miss && s1_in.isFirstIssue
1648  // s2
1649  io.debug_ls.s2_robIdx := s2_in.uop.robIdx.value
1650  io.debug_ls.s2_isBankConflict := s2_fire && (!s2_kill && s2_bank_conflict)
1651  io.debug_ls.s2_isDcacheFirstMiss := s2_fire && io.dcache.resp.bits.miss && s2_in.isFirstIssue
1652  io.debug_ls.s2_isForwardFail := s2_fire && s2_fwd_fail
1653  // s3
1654  io.debug_ls.s3_robIdx := s3_in.uop.robIdx.value
1655  io.debug_ls.s3_isReplayFast := s3_valid && s3_fast_rep && !s3_fast_rep_canceled
1656  io.debug_ls.s3_isReplayRS :=  RegNext(io.feedback_fast.valid && !io.feedback_fast.bits.hit) || (io.feedback_slow.valid && !io.feedback_slow.bits.hit)
1657  io.debug_ls.s3_isReplaySlow := io.lsq.ldin.valid && io.lsq.ldin.bits.rep_info.need_rep
1658  io.debug_ls.s3_isReplay := s3_valid && s3_rep_info.need_rep // include fast+slow+rs replay
1659  io.debug_ls.replayCause := s3_rep_info.cause
1660  io.debug_ls.replayCnt := 1.U
1661
1662  // Topdown
1663  io.lsTopdownInfo.s1.robIdx          := s1_in.uop.robIdx.value
1664  io.lsTopdownInfo.s1.vaddr_valid     := s1_valid && s1_in.hasROBEntry
1665  io.lsTopdownInfo.s1.vaddr_bits      := s1_vaddr
1666  io.lsTopdownInfo.s2.robIdx          := s2_in.uop.robIdx.value
1667  io.lsTopdownInfo.s2.paddr_valid     := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss
1668  io.lsTopdownInfo.s2.paddr_bits      := s2_in.paddr
1669  io.lsTopdownInfo.s2.first_real_miss := io.dcache.resp.bits.real_miss
1670  io.lsTopdownInfo.s2.cache_miss_en   := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated
1671
1672  // perf cnt
1673  XSPerfAccumulate("s0_in_valid",                  io.ldin.valid)
1674  XSPerfAccumulate("s0_in_block",                  io.ldin.valid && !io.ldin.fire)
1675  XSPerfAccumulate("s0_vecin_valid",               io.vecldin.valid)
1676  XSPerfAccumulate("s0_vecin_block",               io.vecldin.valid && !io.vecldin.fire)
1677  XSPerfAccumulate("s0_in_fire_first_issue",       s0_valid && s0_sel_src.isFirstIssue)
1678  XSPerfAccumulate("s0_lsq_replay_issue",          io.replay.fire)
1679  XSPerfAccumulate("s0_lsq_replay_vecissue",       io.replay.fire && io.replay.bits.isvec)
1680  XSPerfAccumulate("s0_ldu_fire_first_issue",      io.ldin.fire && s0_sel_src.isFirstIssue)
1681  XSPerfAccumulate("s0_fast_replay_issue",         io.fast_rep_in.fire)
1682  XSPerfAccumulate("s0_fast_replay_vecissue",      io.fast_rep_in.fire && io.fast_rep_in.bits.isvec)
1683  XSPerfAccumulate("s0_stall_out",                 s0_valid && !s0_can_go)
1684  XSPerfAccumulate("s0_stall_dcache",              s0_valid && !io.dcache.req.ready)
1685  XSPerfAccumulate("s0_addr_spec_success",         s0_fire && s0_dcache_vaddr(VAddrBits-1, 12) === io.ldin.bits.src(0)(VAddrBits-1, 12))
1686  XSPerfAccumulate("s0_addr_spec_failed",          s0_fire && s0_dcache_vaddr(VAddrBits-1, 12) =/= io.ldin.bits.src(0)(VAddrBits-1, 12))
1687  XSPerfAccumulate("s0_addr_spec_success_once",    s0_fire && s0_dcache_vaddr(VAddrBits-1, 12) === io.ldin.bits.src(0)(VAddrBits-1, 12) && s0_sel_src.isFirstIssue)
1688  XSPerfAccumulate("s0_addr_spec_failed_once",     s0_fire && s0_dcache_vaddr(VAddrBits-1, 12) =/= io.ldin.bits.src(0)(VAddrBits-1, 12) && s0_sel_src.isFirstIssue)
1689  XSPerfAccumulate("s0_vec_addr_vlen_aligned",     s0_fire && s0_sel_src.isvec && s0_dcache_vaddr(3, 0) === 0.U)
1690  XSPerfAccumulate("s0_vec_addr_vlen_unaligned",   s0_fire && s0_sel_src.isvec && s0_dcache_vaddr(3, 0) =/= 0.U)
1691  XSPerfAccumulate("s0_forward_tl_d_channel",      s0_out.forward_tlDchannel)
1692  XSPerfAccumulate("s0_hardware_prefetch_fire",    s0_fire && s0_hw_prf_select)
1693  XSPerfAccumulate("s0_software_prefetch_fire",    s0_fire && s0_sel_src.prf && s0_src_select_vec(int_iss_idx))
1694  XSPerfAccumulate("s0_hardware_prefetch_blocked", io.prefetch_req.valid && !s0_hw_prf_select)
1695  XSPerfAccumulate("s0_hardware_prefetch_total",   io.prefetch_req.valid)
1696
1697  XSPerfAccumulate("s1_in_valid",                  s1_valid)
1698  XSPerfAccumulate("s1_in_fire",                   s1_fire)
1699  XSPerfAccumulate("s1_in_fire_first_issue",       s1_fire && s1_in.isFirstIssue)
1700  XSPerfAccumulate("s1_tlb_miss",                  s1_fire && s1_tlb_miss)
1701  XSPerfAccumulate("s1_tlb_miss_first_issue",      s1_fire && s1_tlb_miss && s1_in.isFirstIssue)
1702  XSPerfAccumulate("s1_stall_out",                 s1_valid && !s1_can_go)
1703  XSPerfAccumulate("s1_dly_err",                   s1_valid && s1_fast_rep_dly_err)
1704
1705  XSPerfAccumulate("s2_in_valid",                  s2_valid)
1706  XSPerfAccumulate("s2_in_fire",                   s2_fire)
1707  XSPerfAccumulate("s2_in_fire_first_issue",       s2_fire && s2_in.isFirstIssue)
1708  XSPerfAccumulate("s2_dcache_miss",               s2_fire && io.dcache.resp.bits.miss)
1709  XSPerfAccumulate("s2_dcache_miss_first_issue",   s2_fire && io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1710  XSPerfAccumulate("s2_dcache_real_miss_first_issue",   s2_fire && io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1711  XSPerfAccumulate("s2_full_forward",              s2_fire && s2_full_fwd)
1712  XSPerfAccumulate("s2_dcache_miss_full_forward",  s2_fire && s2_dcache_miss)
1713  XSPerfAccumulate("s2_fwd_frm_d_can",             s2_valid && s2_fwd_frm_d_chan)
1714  XSPerfAccumulate("s2_fwd_frm_d_chan_or_mshr",    s2_valid && s2_fwd_frm_d_chan_or_mshr)
1715  XSPerfAccumulate("s2_stall_out",                 s2_fire && !s2_can_go)
1716  XSPerfAccumulate("s2_prefetch",                  s2_fire && s2_prf)
1717  XSPerfAccumulate("s2_prefetch_ignored",          s2_fire && s2_prf && io.dcache.s2_mq_nack) // ignore prefetch for mshr full / miss req port conflict
1718  XSPerfAccumulate("s2_prefetch_miss",             s2_fire && s2_prf && io.dcache.resp.bits.miss) // prefetch req miss in l1
1719  XSPerfAccumulate("s2_prefetch_hit",              s2_fire && s2_prf && !io.dcache.resp.bits.miss) // prefetch req hit in l1
1720  XSPerfAccumulate("s2_prefetch_accept",           s2_fire && s2_prf && io.dcache.resp.bits.miss && !io.dcache.s2_mq_nack) // prefetch a missed line in l1, and l1 accepted it
1721  XSPerfAccumulate("s2_forward_req",               s2_fire && s2_in.forward_tlDchannel)
1722  XSPerfAccumulate("s2_successfully_forward_channel_D", s2_fire && s2_fwd_frm_d_chan && s2_fwd_data_valid)
1723  XSPerfAccumulate("s2_successfully_forward_mshr",      s2_fire && s2_fwd_frm_mshr && s2_fwd_data_valid)
1724
1725  XSPerfAccumulate("load_to_load_forward",                      s1_try_ptr_chasing && !s1_ptr_chasing_canceled)
1726  XSPerfAccumulate("load_to_load_forward_try",                  s1_try_ptr_chasing)
1727  XSPerfAccumulate("load_to_load_forward_fail",                 s1_cancel_ptr_chasing)
1728  XSPerfAccumulate("load_to_load_forward_fail_cancelled",       s1_cancel_ptr_chasing && s1_ptr_chasing_canceled)
1729  XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && s1_not_fast_match)
1730  XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",       s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && s1_fu_op_type_not_ld)
1731  XSPerfAccumulate("load_to_load_forward_fail_addr_align",      s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && !s1_fu_op_type_not_ld && s1_addr_misaligned)
1732  XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",    s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && !s1_fu_op_type_not_ld && !s1_addr_misaligned && s1_addr_mismatch)
1733
1734  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1735  // hardware performance counter
1736  val perfEvents = Seq(
1737    ("load_s0_in_fire         ", s0_fire                                                        ),
1738    ("load_to_load_forward    ", s1_fire && s1_try_ptr_chasing && !s1_ptr_chasing_canceled      ),
1739    ("stall_dcache            ", s0_valid && s0_can_go && !io.dcache.req.ready                  ),
1740    ("load_s1_in_fire         ", s0_fire                                                        ),
1741    ("load_s1_tlb_miss        ", s1_fire && io.tlb.resp.bits.miss                               ),
1742    ("load_s2_in_fire         ", s1_fire                                                        ),
1743    ("load_s2_dcache_miss     ", s2_fire && io.dcache.resp.bits.miss                            ),
1744  )
1745  generatePerfEvent()
1746
1747  when(io.ldout.fire){
1748    XSDebug("ldout %x\n", io.ldout.bits.uop.pc)
1749  }
1750  // end
1751}
1752