xref: /XiangShan/src/main/scala/xiangshan/mem/vector/VSegmentUnit.scala (revision ccd66eef3313eecad87fcdf70b933715a7086e6f)
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._
25import xiangshan.backend.rob.RobPtr
26import xiangshan.backend.Bundles._
27import xiangshan.mem._
28import xiangshan.backend.fu.{FuType, PMPRespBundle}
29import freechips.rocketchip.diplomacy.BufferParams
30import xiangshan.cache.mmu._
31import xiangshan.cache._
32import xiangshan.cache.wpu.ReplayCarry
33import xiangshan.backend.fu.util.SdtrigExt
34import xiangshan.ExceptionNO._
35import xiangshan.backend.fu.vector.Bundles.VConfig
36import xiangshan.backend.datapath.NewPipelineConnect
37import xiangshan.backend.fu.NewCSR._
38import xiangshan.backend.fu.vector.Utils.VecDataToMaskDataVec
39
40class VSegmentBundle(implicit p: Parameters) extends VLSUBundle
41{
42  val baseVaddr        = UInt(XLEN.W)
43  val uop              = new DynInst
44  val paddr            = UInt(PAddrBits.W)
45  val mask             = UInt(VLEN.W)
46  val alignedType      = UInt(alignTypeBits.W)
47  val vl               = UInt(elemIdxBits.W)
48  val uopFlowNum       = UInt(elemIdxBits.W)
49  val uopFlowNumMask   = UInt(elemIdxBits.W)
50  // for exception
51  val vstart           = UInt(elemIdxBits.W)
52  val exceptionVaddr   = UInt(XLEN.W)
53  val exceptionGpaddr  = UInt(XLEN.W)
54  val exceptionIsForVSnonLeafPTE = Bool()
55  val exception_va     = Bool()
56  val exception_gpa    = Bool()
57  val exception_pa     = Bool()
58  val exceptionVstart  = UInt(elemIdxBits.W)
59  val exceptionVl      = UInt(elemIdxBits.W)
60  val isFof            = Bool()
61}
62
63// latch each uop's VecWen, pdest, v0Wen, uopIdx
64class VSegmentUop(implicit p: Parameters) extends VLSUBundle{
65  val uop              = new DynInst
66}
67
68class VSegmentUnit (implicit p: Parameters) extends VLSUModule
69  with HasDCacheParameters
70  with MemoryOpConstants
71  with SdtrigExt
72  with HasLoadHelper
73{
74  val io               = IO(new VSegmentUnitIO)
75
76  val maxSize          = VSegmentBufferSize
77
78  class VSegUPtr(implicit p: Parameters) extends CircularQueuePtr[VSegUPtr](maxSize){
79  }
80
81  object VSegUPtr {
82    def apply(f: Bool, v: UInt)(implicit p: Parameters): VSegUPtr = {
83      val ptr           = Wire(new VSegUPtr)
84      ptr.flag         := f
85      ptr.value        := v
86      ptr
87    }
88  }
89
90
91  /**
92  ********************************************************************************************************
93  *  Use an example to illustrate the working logic of a segmentunit:                                    *
94  *    For:                                                                                              *
95  *      lmul=2 sew=32 emul=2 eew=32  vl=16                                                              *
96  *    Then:                                                                                             *
97  *      Access memory in the order:                                                                     *
98  *        (V2,S0),(V4,S0),(V6,S0),(V8,S0),                                                              *
99  *        (V2,S1),(V4,S1),(V6,S1),(V8,S1),                                                              *
100  *        (V2,S2),(V4,S2),(V6,S2),(V8,S2),                                                              *
101  *        (V2,S3),(V4,S3),(V6,S3),(V8,S3),                                                              *
102  *        (V3,S4),(V5,S4),(V7,S4),(V9,S4),                                                              *
103  *        (V3,S5),(V5,S5),(V7,S5),(V9,S5),                                                              *
104  *        (V3,S6),(V5,S6),(V7,S6),(V9,S6),                                                              *
105  *        (V3,S7),(V5,S7),(V7,S7),(V9,S7),                                                              *
106  *                                                                                                      *
107  *                                                                                                      *
108  *    [[data]] saves the data generated by the access and corresponds to the register.                  *
109  *    [[splitPtr]] controls the destination register written to.                                        *
110  *                                                                                                      *
111  *    splitptr offset can be seen in [[splitPtrNext]] is assignment logic,                              *
112  *    which is mainly calculated in terms of [[fieldIdx]] and [[segmentIdx]]                            *
113  *    First access different fields of the same segment, and then visit different segments.             *
114  *    For the case of 'emul' greater than 1, such as the following example,                             *
115  *    although 'v2' and 'v3' are different vd and the same field, they are still different segments,    *
116  *    so they should be accessed sequentially.Just like the 'Access memory in the order' above.         *
117  *                                                                                                      *
118  *                         [[segmentIdx]]                                                               *
119  *                               |                                                                      *
120  *                               |                                                                      *
121  *                               V                                                                      *
122  *                                                                                                      *
123  *                               S0               S1                S2                 S3               *
124  *                      ----------------------------------------------------------------------------    *
125  *  [[splitPtr]]--> v2  |     field0     |      field0     |      field0     |      field0         |    *
126  *                      ----------------------------------------------------------------------------    *
127  *                               S4               S5                S6                 S7               *
128  *                      ----------------------------------------------------------------------------    *
129  *                  v3  |     field0     |      field0     |      field0     |      field0         |    *
130  *                      ----------------------------------------------------------------------------    *
131  *                               S0               S1                S2                 S3               *
132  *                      ----------------------------------------------------------------------------    *
133  *                  v4  |     field1     |      field1     |      field1     |      field1         |    *
134  *                      ----------------------------------------------------------------------------    *
135  *                               S4               S5                S6                 S7               *
136  *                      ----------------------------------------------------------------------------    *
137  *                  v5  |     field1     |      field1     |      field1     |      field1         |    *
138  *                      ----------------------------------------------------------------------------    *
139  *                               S0               S1                S2                 S3               *
140  *                      ----------------------------------------------------------------------------    *
141  *                  v6  |     field2     |      field2     |      field2     |      field2         |    *
142  *                      ----------------------------------------------------------------------------    *
143  *                               S4               S5                S6                 S7               *
144  *                      ----------------------------------------------------------------------------    *
145  *                  v7  |     field2     |      field2     |      field2     |      field2         |    *
146  *                      ----------------------------------------------------------------------------    *
147  *                               S0               S1                S2                 S3               *
148  *                      ----------------------------------------------------------------------------    *
149  *                  v8  |     field3     |      field3     |      field3     |      field3         |    *
150  *                      ----------------------------------------------------------------------------    *
151  *                               S4               S5                S6                 S7               *
152  *                      ----------------------------------------------------------------------------    *
153  *                  v9  |     field3     |      field3     |      field3     |      field3         |    *
154  *                      ----------------------------------------------------------------------------    *                                                                                    *
155  *                                                                                                      *                                                                                    *
156  *                                                                                                      *                                                                                    *
157  ********************************************************************************************************
158  **/
159
160
161  // buffer uop
162  val instMicroOp       = Reg(new VSegmentBundle)
163  val instMicroOpValid  = RegInit(false.B)
164  val data              = Reg(Vec(maxSize, UInt(VLEN.W)))
165  val uopq              = Reg(Vec(maxSize, new VSegmentUop))
166  val stride            = Reg(Vec(maxSize, UInt(VLEN.W)))
167  val allocated         = RegInit(VecInit(Seq.fill(maxSize)(false.B)))
168  val enqPtr            = RegInit(0.U.asTypeOf(new VSegUPtr))
169  val deqPtr            = RegInit(0.U.asTypeOf(new VSegUPtr))
170  val stridePtr         = WireInit(0.U.asTypeOf(new VSegUPtr)) // for select stride/index
171
172  val segmentIdx        = RegInit(0.U(elemIdxBits.W))
173  val fieldIdx          = RegInit(0.U(fieldBits.W))
174  val segmentOffset     = RegInit(0.U(XLEN.W))
175  val splitPtr          = RegInit(0.U.asTypeOf(new VSegUPtr)) // for select load/store data
176  val splitPtrNext      = WireInit(0.U.asTypeOf(new VSegUPtr))
177
178  val exception_va      = WireInit(false.B)
179  val exception_gpa     = WireInit(false.B)
180  val exception_pa      = WireInit(false.B)
181
182  val maxSegIdx         = instMicroOp.vl - 1.U
183  val maxNfields        = instMicroOp.uop.vpu.nf
184  val latchVaddr        = RegInit(0.U(VAddrBits.W))
185
186  XSError((segmentIdx > maxSegIdx) && instMicroOpValid, s"segmentIdx > vl, something error!\n")
187  XSError((fieldIdx > maxNfields) &&  instMicroOpValid, s"fieldIdx > nfields, something error!\n")
188
189  // MicroOp
190  val baseVaddr                       = instMicroOp.baseVaddr
191  val alignedType                     = instMicroOp.alignedType
192  val fuType                          = instMicroOp.uop.fuType
193  val mask                            = instMicroOp.mask
194  val exceptionVec                    = instMicroOp.uop.exceptionVec
195  val issueEew                        = instMicroOp.uop.vpu.veew
196  val issueLmul                       = instMicroOp.uop.vpu.vtype.vlmul
197  val issueSew                        = instMicroOp.uop.vpu.vtype.vsew
198  val issueEmul                       = EewLog2(issueEew) - issueSew + issueLmul
199  val elemIdxInVd                     = segmentIdx & instMicroOp.uopFlowNumMask
200  val issueInstType                   = Cat(true.B, instMicroOp.uop.fuOpType(6, 5)) // always segment instruction
201  val issueUopFlowNumLog2             = GenRealFlowLog2(issueInstType, issueEmul, issueLmul, issueEew, issueSew, true) // max element number log2 in vd
202  val issueVlMax                      = instMicroOp.uopFlowNum // max elementIdx in vd
203  val issueMaxIdxInIndex              = GenVLMAX(Mux(issueEmul.asSInt > 0.S, 0.U, issueEmul), issueEew(1, 0)) // index element index in index register
204  val issueMaxIdxInIndexMask          = GenVlMaxMask(issueMaxIdxInIndex, elemIdxBits)
205  val issueMaxIdxInIndexLog2          = GenVLMAXLog2(Mux(issueEmul.asSInt > 0.S, 0.U, issueEmul), issueEew(1, 0))
206  val issueIndexIdx                   = segmentIdx & issueMaxIdxInIndexMask
207  val segmentActive                   = (mask & UIntToOH(segmentIdx)).orR
208
209  // sbuffer write interface
210  val sbufferOut                      = Wire(Decoupled(new DCacheWordReqWithVaddrAndPfFlag))
211
212
213  // segment fof instrction buffer
214  val fofBuffer                       = RegInit(0.U.asTypeOf(new DynInst))
215  val fofBufferValid                  = RegInit(false.B)
216
217
218  // Segment instruction's FSM
219  /*
220  * s_idle: wait request
221  * s_flush_sbuffer_req: flush sbuffer
222  * s_wait_flush_sbuffer_resp: wait sbuffer empty
223  * s_tlb_req: request tlb
224  * s_wait_tlb_resp: wait tlb resp
225  * s_pm: check pmp
226  * s_cache_req: request cache
227  * s_cache_resp: wait cache resp
228  * s_latch_and_merge_data: for read data
229  * s_send_data: for send write data
230  * s_wait_to_sbuffer: Wait for data from the sbufferOut pipelayer to be sent to the sbuffer
231  * s_finish:
232  * s_fof_fix_vl: Writeback the uop of the fof instruction to modify vl.
233  * */
234  val s_idle :: s_flush_sbuffer_req :: s_wait_flush_sbuffer_resp :: s_tlb_req :: s_wait_tlb_resp :: s_pm ::s_cache_req :: s_cache_resp :: s_latch_and_merge_data :: s_send_data :: s_wait_to_sbuffer :: s_finish :: s_fof_fix_vl :: Nil = Enum(13)
235  val state             = RegInit(s_idle)
236  val stateNext         = WireInit(s_idle)
237  val sbufferEmpty      = io.flush_sbuffer.empty
238  val isVSegLoad        = FuType.isVSegLoad(instMicroOp.uop.fuType)
239  val isEnqfof          = io.in.bits.uop.fuOpType === VlduType.vleff && io.in.valid
240  val isEnqFixVlUop     = isEnqfof && io.in.bits.uop.vpu.lastUop
241
242  /**
243   * state update
244   */
245  state  := stateNext
246
247  /**
248   * state transfer
249   */
250  when(state === s_idle){
251    stateNext := Mux(isAfter(enqPtr, deqPtr), s_flush_sbuffer_req, s_idle)
252  }.elsewhen(state === s_flush_sbuffer_req){
253    stateNext := Mux(sbufferEmpty, s_tlb_req, s_wait_flush_sbuffer_resp) // if sbuffer is empty, go to query tlb
254
255  }.elsewhen(state === s_wait_flush_sbuffer_resp){
256    stateNext := Mux(sbufferEmpty, s_tlb_req, s_wait_flush_sbuffer_resp)
257
258  }.elsewhen(state === s_tlb_req){
259    stateNext := Mux(segmentActive, s_wait_tlb_resp, Mux(isVSegLoad, s_latch_and_merge_data, s_send_data))
260
261  }.elsewhen(state === s_wait_tlb_resp){
262    stateNext := Mux(io.dtlb.resp.fire,
263                      Mux(!io.dtlb.resp.bits.miss,
264                          s_pm,
265                          s_tlb_req),
266                      s_wait_tlb_resp)
267
268  }.elsewhen(state === s_pm){
269    /* if is vStore, send data to sbuffer, so don't need query dcache */
270    stateNext := Mux(exception_pa || exception_va || exception_gpa,
271                     s_finish,
272                     Mux(isVSegLoad, s_cache_req, s_send_data))
273
274  }.elsewhen(state === s_cache_req){
275    stateNext := Mux(io.rdcache.req.fire, s_cache_resp, s_cache_req)
276
277  }.elsewhen(state === s_cache_resp){
278    when(io.rdcache.resp.fire) {
279      when(io.rdcache.resp.bits.miss || io.rdcache.s2_bank_conflict) {
280        stateNext := s_cache_req
281      }.otherwise {
282        stateNext := Mux(isVSegLoad, s_latch_and_merge_data, s_send_data)
283      }
284    }.otherwise{
285      stateNext := s_cache_resp
286    }
287    /* if segment is inactive, don't need to wait access all of the field */
288  }.elsewhen(state === s_latch_and_merge_data) {
289    when((segmentIdx === maxSegIdx) && (fieldIdx === maxNfields) ||
290      ((segmentIdx === maxSegIdx) && !segmentActive)) {
291
292      stateNext := s_finish // segment instruction finish
293    }.otherwise {
294      stateNext := s_tlb_req // need continue
295    }
296    /* if segment is inactive, don't need to wait access all of the field */
297  }.elsewhen(state === s_send_data) { // when sbuffer accept data
298    when(!sbufferOut.fire && segmentActive) {
299      stateNext := s_send_data
300    }.elsewhen(segmentIdx === maxSegIdx && (fieldIdx === maxNfields && sbufferOut.fire || !segmentActive && io.sbuffer.valid && !io.sbuffer.ready)) {
301      stateNext := s_wait_to_sbuffer
302    }.elsewhen(segmentIdx === maxSegIdx && !segmentActive){
303      stateNext := s_finish // segment instruction finish
304    }.otherwise {
305      stateNext := s_tlb_req // need continue
306    }
307
308  }.elsewhen(state === s_wait_to_sbuffer){
309    stateNext := Mux(io.sbuffer.fire, s_finish, s_wait_to_sbuffer)
310
311  }.elsewhen(state === s_finish){ // writeback uop
312    stateNext := Mux(
313      distanceBetween(enqPtr, deqPtr) === 0.U,
314      Mux(fofBufferValid, s_fof_fix_vl, s_idle),
315      s_finish
316    )
317  }.elsewhen(state === s_fof_fix_vl){ // writeback uop
318    stateNext := Mux(!fofBufferValid, s_idle, s_fof_fix_vl)
319
320  }.otherwise{
321    stateNext := s_idle
322    XSError(true.B, s"Unknown state!\n")
323  }
324
325  /*************************************************************************
326   *                            enqueue logic
327   *************************************************************************/
328  io.in.ready                         := true.B
329  val fuOpType                         = io.in.bits.uop.fuOpType
330  val vtype                            = io.in.bits.uop.vpu.vtype
331  val mop                              = fuOpType(6, 5)
332  val instType                         = Cat(true.B, mop)
333  val eew                              = io.in.bits.uop.vpu.veew
334  val sew                              = vtype.vsew
335  val lmul                             = vtype.vlmul
336  val emul                             = EewLog2(eew) - sew + lmul
337  val vl                               = instMicroOp.vl
338  val vm                               = instMicroOp.uop.vpu.vm
339  val vstart                           = instMicroOp.uop.vpu.vstart
340  val srcMask                          = GenFlowMask(Mux(vm, Fill(VLEN, 1.U(1.W)), io.in.bits.src_mask), vstart, vl, true)
341  // first uop enqueue, we need to latch microOp of segment instruction
342  when(io.in.fire && !instMicroOpValid && !isEnqFixVlUop){
343    // element number in a vd
344    // TODO Rewrite it in a more elegant way.
345    val uopFlowNum                    = ZeroExt(GenRealFlowNum(instType, emul, lmul, eew, sew, true), elemIdxBits)
346    instMicroOp.baseVaddr             := io.in.bits.src_rs1
347    instMicroOpValid                  := true.B // if is first uop
348    instMicroOp.alignedType           := Mux(isIndexed(instType), sew(1, 0), eew)
349    instMicroOp.uop                   := io.in.bits.uop
350    instMicroOp.mask                  := srcMask
351    instMicroOp.vstart                := 0.U
352    instMicroOp.uopFlowNum            := uopFlowNum
353    instMicroOp.uopFlowNumMask        := GenVlMaxMask(uopFlowNum, elemIdxBits) // for merge data
354    instMicroOp.vl                    := io.in.bits.src_vl.asTypeOf(VConfig()).vl
355    instMicroOp.exceptionVl           := io.in.bits.src_vl.asTypeOf(VConfig()).vl
356    segmentOffset                     := 0.U
357    instMicroOp.isFof                 := (fuOpType === VlduType.vleff) && FuType.isVLoad(fuType)
358  }
359  // latch data
360  when(io.in.fire && !isEnqFixVlUop){
361    data(enqPtr.value)                := io.in.bits.src_vs3
362    stride(enqPtr.value)              := io.in.bits.src_stride
363    uopq(enqPtr.value).uop            := io.in.bits.uop
364  }
365
366  // update enqptr, only 1 port
367  when(io.in.fire && !isEnqFixVlUop){
368    enqPtr                            := enqPtr + 1.U
369  }
370
371  /*************************************************************************
372   *                            output logic
373   *************************************************************************/
374
375  val indexStride                     = IndexAddr( // index for indexed instruction
376                                                    index = stride(stridePtr.value),
377                                                    flow_inner_idx = issueIndexIdx,
378                                                    eew = issueEew
379                                                  )
380  val realSegmentOffset               = Mux(isIndexed(issueInstType),
381                                            indexStride,
382                                            segmentOffset)
383  val vaddr                           = baseVaddr + (fieldIdx << alignedType).asUInt + realSegmentOffset
384
385  //latch vaddr
386  when(state === s_tlb_req){
387    latchVaddr := vaddr(VAddrBits - 1, 0)
388  }
389  /**
390   * tlb req and tlb resq
391   */
392
393  // query DTLB IO Assign
394  io.dtlb.req                         := DontCare
395  io.dtlb.resp.ready                  := true.B
396  io.dtlb.req.valid                   := state === s_tlb_req && segmentActive
397  io.dtlb.req.bits.cmd                := Mux(FuType.isVLoad(fuType), TlbCmd.read, TlbCmd.write)
398  io.dtlb.req.bits.vaddr              := vaddr(VAddrBits - 1, 0)
399  io.dtlb.req.bits.fullva             := vaddr
400  io.dtlb.req.bits.checkfullva        := true.B
401  io.dtlb.req.bits.size               := instMicroOp.alignedType(2,0)
402  io.dtlb.req.bits.memidx.is_ld       := FuType.isVLoad(fuType)
403  io.dtlb.req.bits.memidx.is_st       := FuType.isVStore(fuType)
404  io.dtlb.req.bits.debug.robIdx       := instMicroOp.uop.robIdx
405  io.dtlb.req.bits.no_translate       := false.B
406  io.dtlb.req.bits.debug.pc           := instMicroOp.uop.pc
407  io.dtlb.req.bits.debug.isFirstIssue := DontCare
408  io.dtlb.req_kill                    := false.B
409
410  val canTriggerException              = segmentIdx === 0.U || !instMicroOp.isFof // only elementIdx = 0 or is not fof can trigger
411
412  val segmentTrigger = Module(new VSegmentTrigger)
413  segmentTrigger.io.fromCsrTrigger.tdataVec             := io.fromCsrTrigger.tdataVec
414  segmentTrigger.io.fromCsrTrigger.tEnableVec           := io.fromCsrTrigger.tEnableVec
415  segmentTrigger.io.fromCsrTrigger.triggerCanRaiseBpExp := io.fromCsrTrigger.triggerCanRaiseBpExp
416  segmentTrigger.io.fromCsrTrigger.debugMode            := io.fromCsrTrigger.debugMode
417  segmentTrigger.io.memType                             := isVSegLoad
418  segmentTrigger.io.fromLoadStore.vaddr                 := latchVaddr
419  segmentTrigger.io.fromLoadStore.isVectorUnitStride    := false.B
420  segmentTrigger.io.fromLoadStore.mask                  := 0.U
421
422  val triggerAction = segmentTrigger.io.toLoadStore.triggerAction
423  val triggerDebugMode = TriggerAction.isDmode(triggerAction)
424  val triggerBreakpoint = TriggerAction.isExp(triggerAction)
425
426  // tlb resp
427  when(io.dtlb.resp.fire && state === s_wait_tlb_resp){
428      exceptionVec(storePageFault)      := io.dtlb.resp.bits.excp(0).pf.st
429      exceptionVec(loadPageFault)       := io.dtlb.resp.bits.excp(0).pf.ld
430      exceptionVec(storeGuestPageFault) := io.dtlb.resp.bits.excp(0).gpf.st
431      exceptionVec(loadGuestPageFault)  := io.dtlb.resp.bits.excp(0).gpf.ld
432      exceptionVec(storeAccessFault)    := io.dtlb.resp.bits.excp(0).af.st
433      exceptionVec(loadAccessFault)     := io.dtlb.resp.bits.excp(0).af.ld
434      when(!io.dtlb.resp.bits.miss){
435        instMicroOp.paddr             := io.dtlb.resp.bits.paddr(0)
436        instMicroOp.exceptionGpaddr   := io.dtlb.resp.bits.gpaddr(0)
437        instMicroOp.exceptionIsForVSnonLeafPTE  := io.dtlb.resp.bits.isForVSnonLeafPTE
438      }
439  }
440  // pmp
441  // NOTE: only handle load/store exception here, if other exception happens, don't send here
442  val exceptionWithPf = exceptionVec(storePageFault) || exceptionVec(loadPageFault) || exceptionVec(storeGuestPageFault) || exceptionVec(loadGuestPageFault)
443  val pmp = (io.pmpResp.asUInt & Fill(io.pmpResp.asUInt.getWidth, !exceptionWithPf)).asTypeOf(new PMPRespBundle())
444  when(state === s_pm) {
445    val addr_aligned = LookupTree(Mux(isIndexed(issueInstType), issueSew(1, 0), issueEew(1, 0)), List(
446      "b00".U   -> true.B,                   //b
447      "b01".U   -> (vaddr(0)    === 0.U), //h
448      "b10".U   -> (vaddr(1, 0) === 0.U), //w
449      "b11".U   -> (vaddr(2, 0) === 0.U)  //d
450    ))
451    val missAligned = !addr_aligned
452    exceptionVec(loadAddrMisaligned)  := missAligned && FuType.isVSegLoad(fuType)  && canTriggerException
453    exceptionVec(storeAddrMisaligned) := missAligned && FuType.isVSegStore(fuType) && canTriggerException
454
455    exception_va  := exceptionVec(storePageFault) || exceptionVec(loadPageFault) ||
456                     exceptionVec(storeAccessFault) || exceptionVec(loadAccessFault) ||
457                     exceptionVec(breakPoint) || triggerDebugMode || missAligned
458    exception_gpa := exceptionVec(storeGuestPageFault) || exceptionVec(loadGuestPageFault)
459    exception_pa  := pmp.st || pmp.ld || pmp.mmio
460
461    instMicroOp.exception_pa  := exception_pa
462    instMicroOp.exception_va  := exception_va
463    instMicroOp.exception_gpa := exception_gpa
464    // update storeAccessFault bit. Currently, we don't support vector MMIO
465    exceptionVec(loadAccessFault)  := (exceptionVec(loadAccessFault) || pmp.ld || pmp.mmio)   && FuType.isVSegLoad(fuType)  && canTriggerException
466    exceptionVec(storeAccessFault) := (exceptionVec(storeAccessFault) || pmp.st || pmp.mmio)  && FuType.isVSegStore(fuType) && canTriggerException
467    exceptionVec(breakPoint)       := triggerBreakpoint && canTriggerException
468
469    exceptionVec(storePageFault)      := exceptionVec(storePageFault)      && FuType.isVSegStore(fuType) && canTriggerException
470    exceptionVec(loadPageFault)       := exceptionVec(loadPageFault)       && FuType.isVSegLoad(fuType)  && canTriggerException
471    exceptionVec(storeGuestPageFault) := exceptionVec(storeGuestPageFault) && FuType.isVSegStore(fuType) && canTriggerException
472    exceptionVec(loadGuestPageFault)  := exceptionVec(loadGuestPageFault)  && FuType.isVSegLoad(fuType)  && canTriggerException
473
474    when(exception_va || exception_gpa || exception_pa) {
475      when(canTriggerException) {
476        instMicroOp.exceptionVaddr  := vaddr
477        instMicroOp.exceptionVstart := segmentIdx // for exception
478      }.otherwise {
479        instMicroOp.exceptionVl     := segmentIdx
480      }
481    }
482
483    when(exceptionVec(breakPoint) || triggerDebugMode) {
484      instMicroOp.uop.trigger := triggerAction
485    }
486  }
487
488  /**
489   * flush sbuffer IO Assign
490   */
491  io.flush_sbuffer.valid           := !sbufferEmpty && (state === s_flush_sbuffer_req)
492
493
494  /**
495   * merge data for load
496   */
497  val cacheData = LookupTree(latchVaddr(3,0), List(
498    "b0000".U -> io.rdcache.resp.bits.data_delayed(63,    0),
499    "b0001".U -> io.rdcache.resp.bits.data_delayed(63,    8),
500    "b0010".U -> io.rdcache.resp.bits.data_delayed(63,   16),
501    "b0011".U -> io.rdcache.resp.bits.data_delayed(63,   24),
502    "b0100".U -> io.rdcache.resp.bits.data_delayed(63,   32),
503    "b0101".U -> io.rdcache.resp.bits.data_delayed(63,   40),
504    "b0110".U -> io.rdcache.resp.bits.data_delayed(63,   48),
505    "b0111".U -> io.rdcache.resp.bits.data_delayed(63,   56),
506    "b1000".U -> io.rdcache.resp.bits.data_delayed(127,  64),
507    "b1001".U -> io.rdcache.resp.bits.data_delayed(127,  72),
508    "b1010".U -> io.rdcache.resp.bits.data_delayed(127,  80),
509    "b1011".U -> io.rdcache.resp.bits.data_delayed(127,  88),
510    "b1100".U -> io.rdcache.resp.bits.data_delayed(127,  96),
511    "b1101".U -> io.rdcache.resp.bits.data_delayed(127, 104),
512    "b1110".U -> io.rdcache.resp.bits.data_delayed(127, 112),
513    "b1111".U -> io.rdcache.resp.bits.data_delayed(127, 120)
514  ))
515  val pickData  = rdataVecHelper(alignedType(1,0), cacheData)
516  val mergedData = mergeDataWithElemIdx(
517    oldData = data(splitPtr.value),
518    newData = Seq(pickData),
519    alignedType = alignedType(1,0),
520    elemIdx = Seq(elemIdxInVd),
521    valids = Seq(true.B)
522  )
523  when(state === s_latch_and_merge_data && segmentActive){
524    data(splitPtr.value) := mergedData
525  }
526  /**
527   * split data for store
528   * */
529  val splitData = genVSData(
530    data = data(splitPtr.value),
531    elemIdx = elemIdxInVd,
532    alignedType = alignedType
533  )
534  val flowData  = genVWdata(splitData, alignedType) // TODO: connect vstd, pass vector data
535  val wmask     = genVWmask(latchVaddr, alignedType(1, 0)) & Fill(VLENB, segmentActive)
536
537  /**
538   * rdcache req, write request don't need to query dcache, because we write element to sbuffer
539   */
540  io.rdcache.req                    := DontCare
541  io.rdcache.req.valid              := state === s_cache_req && FuType.isVLoad(fuType)
542  io.rdcache.req.bits.cmd           := MemoryOpConstants.M_XRD
543  io.rdcache.req.bits.vaddr         := latchVaddr
544  io.rdcache.req.bits.mask          := mask
545  io.rdcache.req.bits.data          := flowData
546  io.rdcache.pf_source              := LOAD_SOURCE.U
547  io.rdcache.req.bits.id            := DontCare
548  io.rdcache.resp.ready             := true.B
549  io.rdcache.s1_paddr_dup_lsu       := instMicroOp.paddr
550  io.rdcache.s1_paddr_dup_dcache    := instMicroOp.paddr
551  io.rdcache.s1_kill                := false.B
552  io.rdcache.s1_kill_data_read      := false.B
553  io.rdcache.s2_kill                := false.B
554  if (env.FPGAPlatform){
555    io.rdcache.s0_pc                := DontCare
556    io.rdcache.s1_pc                := DontCare
557    io.rdcache.s2_pc                := DontCare
558  }else{
559    io.rdcache.s0_pc                := instMicroOp.uop.pc
560    io.rdcache.s1_pc                := instMicroOp.uop.pc
561    io.rdcache.s2_pc                := instMicroOp.uop.pc
562  }
563  io.rdcache.replacementUpdated     := false.B
564  io.rdcache.is128Req               := false.B
565
566
567  /**
568   * write data to sbuffer
569   * */
570  sbufferOut.bits                  := DontCare
571  sbufferOut.valid                 := state === s_send_data && segmentActive
572  sbufferOut.bits.vecValid         := state === s_send_data && segmentActive
573  sbufferOut.bits.mask             := wmask
574  sbufferOut.bits.data             := flowData
575  sbufferOut.bits.vaddr            := latchVaddr
576  sbufferOut.bits.cmd              := MemoryOpConstants.M_XWR
577  sbufferOut.bits.id               := DontCare
578  sbufferOut.bits.addr             := instMicroOp.paddr
579
580  NewPipelineConnect(
581    sbufferOut, io.sbuffer, io.sbuffer.fire,
582    false.B,
583    Option(s"VSegmentUnitPipelineConnect")
584  )
585
586  io.vecDifftestInfo.valid         := io.sbuffer.valid
587  io.vecDifftestInfo.bits          := uopq(deqPtr.value).uop
588
589  /**
590   * update ptr
591   * */
592  private val fieldActiveWirteFinish = sbufferOut.fire && segmentActive // writedata finish and is a active segment
593  XSError(sbufferOut.fire && !segmentActive, "Attempt write inactive segment to sbuffer, something wrong!\n")
594
595  private val segmentInactiveFinish = ((state === s_latch_and_merge_data) || (state === s_send_data)) && !segmentActive
596
597  val splitPtrOffset = Mux(
598    isIndexed(instType),
599    Mux(lmul.asSInt < 0.S, 1.U, (1.U << lmul).asUInt),
600    Mux(emul.asSInt < 0.S, 1.U, (1.U << emul).asUInt)
601  )
602  splitPtrNext :=
603    Mux(fieldIdx === maxNfields || !segmentActive, // if segment is active, need to complete this segment, otherwise jump to next segment
604      // segment finish, By shifting 'issueUopFlowNumLog2' to the right to ensure that emul != 1 can correctly generate lateral offset.
605     (deqPtr + ((segmentIdx +& 1.U) >> issueUopFlowNumLog2).asUInt),
606      // next field.
607     (splitPtr + splitPtrOffset)
608    )
609
610  dontTouch(issueUopFlowNumLog2)
611  dontTouch(issueEmul)
612  dontTouch(splitPtrNext)
613  dontTouch(stridePtr)
614  dontTouch(segmentActive)
615
616  // update splitPtr
617  when(state === s_latch_and_merge_data || (state === s_send_data && (fieldActiveWirteFinish || !segmentActive))){
618    splitPtr := splitPtrNext
619  }.elsewhen(io.in.fire && !instMicroOpValid){
620    splitPtr := deqPtr // initial splitPtr
621  }
622
623  // update stridePtr, only use in index
624  val strideOffset = Mux(isIndexed(issueInstType), segmentIdx >> issueMaxIdxInIndexLog2, 0.U)
625  stridePtr       := deqPtr + strideOffset
626
627  // update fieldIdx
628  when(io.in.fire && !instMicroOpValid){ // init
629    fieldIdx := 0.U
630  }.elsewhen(state === s_latch_and_merge_data && segmentActive ||
631            (state === s_send_data && fieldActiveWirteFinish)){ // only if segment is active
632
633    /* next segment, only if segment complete */
634    fieldIdx := Mux(fieldIdx === maxNfields, 0.U, fieldIdx + 1.U)
635  }.elsewhen(segmentInactiveFinish){ // segment is inactive, go to next segment
636    fieldIdx := 0.U
637  }
638  //update segmentIdx
639  when(io.in.fire && !instMicroOpValid){
640    segmentIdx := 0.U
641  }.elsewhen(fieldIdx === maxNfields && (state === s_latch_and_merge_data || (state === s_send_data && fieldActiveWirteFinish)) &&
642             segmentIdx =/= maxSegIdx){ // next segment, only if segment is active
643
644    segmentIdx := segmentIdx + 1.U
645  }.elsewhen(segmentInactiveFinish && segmentIdx =/= maxSegIdx){ // if segment is inactive, go to next segment
646    segmentIdx := segmentIdx + 1.U
647  }
648
649  //update segmentOffset
650  /* when segment is active or segment is inactive, increase segmentOffset */
651  when((fieldIdx === maxNfields && (state === s_latch_and_merge_data || (state === s_send_data && fieldActiveWirteFinish))) ||
652       segmentInactiveFinish){
653
654    segmentOffset := segmentOffset + Mux(isUnitStride(issueInstType), (maxNfields +& 1.U) << issueEew(1, 0), stride(stridePtr.value))
655  }
656
657  //update deqPtr
658  when((state === s_finish) && !isEmpty(enqPtr, deqPtr)){
659    deqPtr := deqPtr + 1.U
660  }
661
662
663  /*************************************************************************
664   *                            fof logic
665   *************************************************************************/
666
667  //Enq
668  when(isEnqFixVlUop && !fofBufferValid) { fofBuffer := io.in.bits.uop }
669  when(isEnqFixVlUop && !fofBufferValid) { fofBufferValid := true.B }
670
671  //Deq
672  val fofFixVlValid                    = state === s_fof_fix_vl && fofBufferValid
673
674  when(fofFixVlValid) { fofBuffer      := 0.U.asTypeOf(new DynInst) }
675  when(fofFixVlValid) { fofBufferValid := false.B }
676
677
678  /*************************************************************************
679   *                            dequeue logic
680   *************************************************************************/
681  val vdIdxInField = GenUopIdxInField(Mux(isIndexed(instType), issueLmul, issueEmul), uopq(deqPtr.value).uop.vpu.vuopIdx)
682  /*select mask of vd, maybe remove in feature*/
683  val realEw        = Mux(isIndexed(issueInstType), issueSew(1, 0), issueEew(1, 0))
684  val maskDataVec: Vec[UInt] = VecDataToMaskDataVec(instMicroOp.mask, realEw)
685  val maskUsed      = maskDataVec(vdIdxInField)
686
687  when(stateNext === s_idle){
688    instMicroOpValid := false.B
689  }
690  // writeback to backend
691  val writebackOut                     = WireInit(io.uopwriteback.bits)
692  val writebackValid                   = (state === s_finish) && !isEmpty(enqPtr, deqPtr) || fofFixVlValid
693
694  when(fofFixVlValid) {
695    writebackOut.uop                    := fofBuffer
696    writebackOut.uop.vpu.vl             := instMicroOp.exceptionVl
697    writebackOut.data                   := instMicroOp.exceptionVl
698    writebackOut.mask.get               := Fill(VLEN, 1.U)
699    writebackOut.uop.vpu.vmask          := Fill(VLEN, 1.U)
700  }.otherwise{
701    writebackOut.uop                    := uopq(deqPtr.value).uop
702    writebackOut.uop.vpu                := instMicroOp.uop.vpu
703    writebackOut.uop.exceptionVec       := instMicroOp.uop.exceptionVec
704    writebackOut.mask.get               := instMicroOp.mask
705    writebackOut.data                   := data(deqPtr.value)
706    writebackOut.vdIdx.get              := vdIdxInField
707    writebackOut.uop.vpu.vl             := instMicroOp.vl
708    writebackOut.uop.vpu.vstart         := Mux(instMicroOp.uop.exceptionVec.asUInt.orR, instMicroOp.exceptionVstart, instMicroOp.vstart)
709    writebackOut.uop.vpu.vmask          := maskUsed
710    writebackOut.uop.vpu.vuopIdx        := uopq(deqPtr.value).uop.vpu.vuopIdx
711    writebackOut.debug                  := DontCare
712    writebackOut.vdIdxInField.get       := vdIdxInField
713    writebackOut.uop.robIdx             := instMicroOp.uop.robIdx
714    writebackOut.uop.fuOpType           := instMicroOp.uop.fuOpType
715  }
716
717  io.uopwriteback.valid               := RegNext(writebackValid)
718  io.uopwriteback.bits                := RegEnable(writebackOut, writebackValid)
719
720  dontTouch(writebackValid)
721
722  //to RS
723  val feedbackOut                      = WireInit(0.U.asTypeOf(io.feedback.bits))
724  val feedbackValid                    = state === s_finish && !isEmpty(enqPtr, deqPtr)
725  feedbackOut.hit                     := true.B
726  feedbackOut.robIdx                  := instMicroOp.uop.robIdx
727  feedbackOut.sourceType              := DontCare
728  feedbackOut.flushState              := DontCare
729  feedbackOut.dataInvalidSqIdx        := DontCare
730  feedbackOut.sqIdx                   := uopq(deqPtr.value).uop.sqIdx
731  feedbackOut.lqIdx                   := uopq(deqPtr.value).uop.lqIdx
732
733  io.feedback.valid                   := RegNext(feedbackValid)
734  io.feedback.bits                    := RegEnable(feedbackOut, feedbackValid)
735
736  dontTouch(feedbackValid)
737
738  // exception
739  io.exceptionInfo                    := DontCare
740  io.exceptionInfo.bits.robidx        := instMicroOp.uop.robIdx
741  io.exceptionInfo.bits.uopidx        := uopq(deqPtr.value).uop.vpu.vuopIdx
742  io.exceptionInfo.bits.vstart        := instMicroOp.exceptionVstart
743  io.exceptionInfo.bits.vaddr         := instMicroOp.exceptionVaddr
744  io.exceptionInfo.bits.gpaddr        := instMicroOp.exceptionGpaddr
745  io.exceptionInfo.bits.isForVSnonLeafPTE := instMicroOp.exceptionIsForVSnonLeafPTE
746  io.exceptionInfo.bits.vl            := instMicroOp.exceptionVl
747  io.exceptionInfo.valid              := (state === s_finish) && instMicroOp.uop.exceptionVec.asUInt.orR && !isEmpty(enqPtr, deqPtr)
748}
749
750