xref: /XiangShan/src/main/scala/xiangshan/mem/vector/VMergeBuffer.scala (revision 16c2d8bb27e9a24ed5ef5e4885693e6a30b536df)
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.ExceptionNO._
28import xiangshan.mem._
29import xiangshan.backend.fu.FuType
30import xiangshan.backend.fu.FuConfig._
31import xiangshan.backend.datapath.NewPipelineConnect
32import freechips.rocketchip.diplomacy.BufferParams
33import xiangshan.backend.fu.vector.Bundles.VType
34
35class MBufferBundle(implicit p: Parameters) extends VLSUBundle{
36  val data             = UInt(VLEN.W)
37  val mask             = UInt(VLENB.W)
38  val flowNum          = UInt(flowIdxBits.W)
39  val exceptionVec     = ExceptionVec()
40  val uop              = new DynInst
41  // val vdOffset         = UInt(vOffsetBits.W)
42  val sourceType       = VSFQFeedbackType()
43  val flushState       = Bool()
44  val vdIdx            = UInt(3.W)
45  val elemIdx          = UInt(elemIdxBits.W) // element index
46  // for exception
47  val vstart           = UInt(elemIdxBits.W)
48  val vl               = UInt(elemIdxBits.W)
49  val vaNeedExt        = Bool()
50  val vaddr            = UInt(XLEN.W)
51  val gpaddr           = UInt(GPAddrBits.W)
52  val isForVSnonLeafPTE= Bool()
53  val fof              = Bool()
54  val vlmax            = UInt(elemIdxBits.W)
55
56  def allReady(): Bool = (flowNum === 0.U)
57}
58
59abstract class BaseVMergeBuffer(isVStore: Boolean=false)(implicit p: Parameters) extends VLSUModule{
60  val io = IO(new VMergeBufferIO(isVStore))
61
62  // freeliset: store valid entries index.
63  // +---+---+--------------+-----+-----+
64  // | 0 | 1 |      ......  | n-2 | n-1 |
65  // +---+---+--------------+-----+-----+
66  val freeList: FreeList
67  val uopSize: Int
68  val enqWidth = io.fromSplit.length
69  val deqWidth = io.uopWriteback.length
70  val pipeWidth = io.fromPipeline.length
71  lazy val fuCfg = if (isVStore) VstuCfg else VlduCfg
72
73  def EnqConnect(source: MergeBufferReq, sink: MBufferBundle) = {
74    sink.data         := source.data
75    sink.mask         := source.mask
76    sink.flowNum      := source.flowNum
77    sink.exceptionVec := ExceptionNO.selectByFu(0.U.asTypeOf(ExceptionVec()), fuCfg)
78    sink.uop          := source.uop
79    sink.sourceType   := 0.U.asTypeOf(VSFQFeedbackType())
80    sink.flushState   := false.B
81    sink.vdIdx        := source.vdIdx
82    sink.elemIdx      := Fill(elemIdxBits, 1.U)
83    sink.fof          := source.fof
84    sink.vlmax        := source.vlmax
85    sink.vl           := source.uop.vpu.vl
86    sink.vaddr        := source.vaddr
87    sink.vstart       := 0.U
88  }
89  def DeqConnect(source: MBufferBundle): MemExuOutput = {
90    val sink               = WireInit(0.U.asTypeOf(new MemExuOutput(isVector = true)))
91    sink.data             := source.data
92    sink.mask.get         := source.mask
93    sink.uop              := source.uop
94    sink.uop.exceptionVec := ExceptionNO.selectByFu(source.exceptionVec, fuCfg)
95    sink.uop.vpu.vmask    := source.mask
96    sink.debug            := 0.U.asTypeOf(new DebugBundle)
97    sink.vdIdxInField.get := source.vdIdx // Mgu needs to use this.
98    sink.vdIdx.get        := source.vdIdx
99    sink.uop.vpu.vstart   := source.vstart
100    sink.uop.vpu.vl       := source.vl
101    sink
102  }
103  def ToLsqConnect(source: MBufferBundle): FeedbackToLsqIO = {
104    val sink                                 = WireInit(0.U.asTypeOf(new FeedbackToLsqIO))
105    val hasExp                               = ExceptionNO.selectByFu(source.exceptionVec, fuCfg).asUInt.orR
106    sink.robidx                             := source.uop.robIdx
107    sink.uopidx                             := source.uop.uopIdx
108    sink.feedback(VecFeedbacks.COMMIT)      := !hasExp
109    sink.feedback(VecFeedbacks.FLUSH)       := hasExp
110    sink.feedback(VecFeedbacks.LAST)        := true.B
111    sink.vstart                             := source.vstart // TODO: if lsq need vl for fof?
112    sink.vaddr                              := source.vaddr
113    sink.vaNeedExt                          := source.vaNeedExt
114    sink.gpaddr                             := source.gpaddr
115    sink.isForVSnonLeafPTE                  := source.isForVSnonLeafPTE
116    sink.vl                                 := source.vl
117    sink.exceptionVec                       := ExceptionNO.selectByFu(source.exceptionVec, fuCfg)
118    sink
119  }
120
121
122  val entries      = Reg(Vec(uopSize, new MBufferBundle))
123  val needCancel   = WireInit(VecInit(Seq.fill(uopSize)(false.B)))
124  val allocated    = RegInit(VecInit(Seq.fill(uopSize)(false.B)))
125  val freeMaskVec  = WireInit(VecInit(Seq.fill(uopSize)(false.B)))
126  val uopFinish    = RegInit(VecInit(Seq.fill(uopSize)(false.B)))
127  val needRSReplay = RegInit(VecInit(Seq.fill(uopSize)(false.B)))
128  // enq, from splitPipeline
129  // val allowEnqueue =
130  val cancelEnq    = io.fromSplit.map(_.req.bits.uop.robIdx.needFlush(io.redirect))
131  val canEnqueue   = io.fromSplit.map(_.req.valid)
132  val needEnqueue  = (0 until enqWidth).map{i =>
133    canEnqueue(i) && !cancelEnq(i)
134  }
135
136  val freeCount    = uopSize.U - freeList.io.validCount
137
138  for ((enq, i) <- io.fromSplit.zipWithIndex){
139    freeList.io.doAllocate(i) := false.B
140
141    freeList.io.allocateReq(i) := true.B
142
143    val offset    = PopCount(needEnqueue.take(i))
144    val canAccept = freeList.io.canAllocate(offset)
145    val enqIndex  = freeList.io.allocateSlot(offset)
146    enq.req.ready := freeCount >= (i + 1).U // for better timing
147
148    when(needEnqueue(i) && enq.req.ready){
149      freeList.io.doAllocate(i) := true.B
150      // enqueue
151      allocated(enqIndex)       := true.B
152      uopFinish(enqIndex)       := false.B
153      needRSReplay(enqIndex)    := false.B
154
155      EnqConnect(enq.req.bits, entries(enqIndex))// initial entry
156    }
157
158    enq.resp.bits.mBIndex := enqIndex
159    enq.resp.bits.fail    := false.B
160    enq.resp.valid        := freeCount >= (i + 1).U // for better timing
161  }
162
163  //redirect
164  for (i <- 0 until uopSize){
165    needCancel(i) := entries(i).uop.robIdx.needFlush(io.redirect) && allocated(i)
166    when (needCancel(i)) {
167      allocated(i)   := false.B
168      freeMaskVec(i) := true.B
169      uopFinish(i)   := false.B
170      needRSReplay(i):= false.B
171    }
172  }
173  freeList.io.free := freeMaskVec.asUInt
174  //pipelineWriteback
175  // handle the situation where multiple ports are going to write the same uop queue entry
176  // select the oldest exception and count the flownum of the pipeline writeback.
177  val mergePortMatrix        = Wire(Vec(pipeWidth, Vec(pipeWidth, Bool())))
178  val mergePortMatrixHasExcp = Wire(Vec(pipeWidth, Vec(pipeWidth, Bool())))
179  val mergedByPrevPortVec    = Wire(Vec(pipeWidth, Bool()))
180  (0 until pipeWidth).map{case i => (0 until pipeWidth).map{case j =>
181    val mergePortValid = (j == i).B ||
182      (j > i).B &&
183      io.fromPipeline(j).bits.mBIndex === io.fromPipeline(i).bits.mBIndex &&
184      io.fromPipeline(j).valid
185
186    mergePortMatrix(i)(j)        := mergePortValid
187    mergePortMatrixHasExcp(i)(j) := mergePortValid && io.fromPipeline(j).bits.hasException
188  }}
189  (0 until pipeWidth).map{case i =>
190    mergedByPrevPortVec(i) := (i != 0).B && Cat((0 until i).map(j =>
191      io.fromPipeline(j).bits.mBIndex === io.fromPipeline(i).bits.mBIndex &&
192      io.fromPipeline(j).valid)).orR
193  }
194
195  val mergePortMatrixWrap        = if(isVStore) mergePortMatrix else RegNext(mergePortMatrix)
196  val mergePortMatrixHasExcpWrap = if(isVStore) mergePortMatrixHasExcp else RegNext(mergePortMatrixHasExcp)
197  val mergedByPrevPortVecWrap    = if(isVStore) mergedByPrevPortVec else RegNext(mergedByPrevPortVec)
198  if (backendParams.debugEn){
199    dontTouch(mergePortMatrix)
200    dontTouch(mergePortMatrixHasExcp)
201    dontTouch(mergedByPrevPortVec)
202  }
203
204  // for exception, select exception, when multi port writeback exception, we need select oldest one
205  def selectOldest[T <: VecPipelineFeedbackIO](valid: Seq[Bool], bits: Seq[T], sel: Seq[UInt]): (Seq[Bool], Seq[T], Seq[UInt]) = {
206    assert(valid.length == bits.length)
207    assert(valid.length == sel.length)
208    if (valid.length == 0 || valid.length == 1) {
209      (valid, bits, sel)
210    } else if (valid.length == 2) {
211      val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0)))))
212      for (i <- res.indices) {
213        res(i).valid := valid(i)
214        res(i).bits := bits(i)
215      }
216      val oldest = Mux(valid(0) && valid(1),
217        Mux(sel(0) < sel(1),
218            res(0), res(1)),
219        Mux(valid(0) && !valid(1), res(0), res(1)))
220
221      val oldidx = Mux(valid(0) && valid(1),
222        Mux(sel(0) < sel(1),
223          sel(0), sel(1)),
224        Mux(valid(0) && !valid(1), sel(0), sel(1)))
225      (Seq(oldest.valid), Seq(oldest.bits), Seq(oldidx))
226    } else {
227      val left  = selectOldest(valid.take(valid.length / 2), bits.take(bits.length / 2), sel.take(sel.length / 2))
228      val right = selectOldest(valid.takeRight(valid.length - (valid.length / 2)), bits.takeRight(bits.length - (bits.length / 2)), sel.takeRight(sel.length - (sel.length / 2)))
229      selectOldest(left._1 ++ right._1, left._2 ++ right._2, left._3 ++ right._3)
230    }
231  }
232
233  val pipeValid        = io.fromPipeline.map(_.valid)
234  val pipeBits         = io.fromPipeline.map(_.bits)
235  val pipeValidReg     = io.fromPipeline.map(x => RegNext(x.valid))
236  val pipeBitsReg      = io.fromPipeline.map(x => RegEnable(x.bits, x.valid))
237  val wbElemIdx        = pipeBits.map(_.elemIdx)
238  val wbMbIndex        = pipeBits.map(_.mBIndex)
239  val wbElemIdxInField = wbElemIdx.zip(wbMbIndex).map{x =>
240    val elemIdxInField = x._1 & (entries(x._2).vlmax - 1.U)
241    if(isVStore) elemIdxInField else RegNext(elemIdxInField)
242  }
243  val selBits          = if(isVStore) pipeBits else pipeBitsReg
244
245  // this port have exception or merged port have exception
246  val portHasExcp       = mergePortMatrixHasExcpWrap.map{_.reduce(_ || _)}
247
248  for(i <- io.fromPipeline.indices){
249    val pipewbvalid         = if(isVStore) pipeValid(i) else pipeValidReg(i)
250    val pipewb              = if(isVStore) pipeBits(i)  else pipeBitsReg(i)
251    val pipeWbMbIndex       = pipewb.mBIndex
252    val entry               = entries(pipeWbMbIndex)
253    val entryVeew           = entry.uop.vpu.veew
254    val entryIsUS           = LSUOpType.isAllUS(entry.uop.fuOpType)
255    val entryHasException   = ExceptionNO.selectByFu(entry.exceptionVec, fuCfg).asUInt.orR
256    val entryExcp           = entryHasException && entry.mask.orR
257    val entryVaddr          = entry.vaddr
258    val entryVstart         = entry.vstart
259    val entryElemIdx        = entry.elemIdx
260
261    val sel                    = selectOldest(mergePortMatrixHasExcpWrap(i), selBits, wbElemIdxInField)
262    val selPort                = sel._2
263    val selElemInfield         = selPort(0).elemIdx & (entries(pipeWbMbIndex).vlmax - 1.U)
264    val selExceptionVec        = selPort(0).exceptionVec
265    val selVaddr               = selPort(0).vaddr
266    val selElemIdx             = selPort(0).elemIdx
267
268    val isUSFirstUop           = !selPort(0).elemIdx.orR
269    // Only the first unaligned uop of unit-stride needs to be offset.
270    // When unaligned, the lowest bit of mask is 0.
271    //  example: 16'b1111_1111_1111_0000
272    val firstUnmask            = genVFirstUnmask(selPort(0).mask).asUInt
273    val vaddrOffset            = Mux(entryIsUS, firstUnmask, 0.U)
274    val vaddr                  = selVaddr + vaddrOffset
275    val vstart                 = Mux(entryIsUS, selPort(0).vstart, selElemInfield)
276
277    // select oldest port to raise exception
278    when((((entryElemIdx >= selElemIdx) && entryExcp && portHasExcp(i)) || (!entryExcp && portHasExcp(i))) && pipewbvalid && !mergedByPrevPortVecWrap(i)) {
279      entry.uop.trigger     := selPort(0).trigger
280      entry.elemIdx         := selElemIdx
281      when(!entry.fof || vstart === 0.U){
282        // For fof loads, if element 0 raises an exception, vl is not modified, and the trap is taken.
283        entry.vstart       := vstart
284        entry.exceptionVec := ExceptionNO.selectByFu(selExceptionVec, fuCfg)
285        entry.vaddr        := vaddr
286        entry.vaNeedExt    := selPort(0).vaNeedExt
287        entry.gpaddr       := selPort(0).gpaddr
288        entry.isForVSnonLeafPTE := selPort(0).isForVSnonLeafPTE
289      }.otherwise{
290        entry.uop.vpu.vta  := VType.tu
291        entry.vl           := Mux(entry.vl < vstart, entry.vl, vstart)
292      }
293    }
294  }
295
296  // for pipeline writeback
297  for((pipewb, i) <- io.fromPipeline.zipWithIndex){
298    val wbIndex          = pipewb.bits.mBIndex
299    val flowNumOffset    = PopCount(mergePortMatrix(i))
300    val sourceTypeNext   = entries(wbIndex).sourceType | pipewb.bits.sourceType
301    val hasExp           = ExceptionNO.selectByFu(pipewb.bits.exceptionVec, fuCfg).asUInt.orR
302
303    // if is VLoad, need latch 1 cycle to merge data. only flowNum and wbIndex need to latch
304    val latchWbValid     = if(isVStore) pipewb.valid else RegNext(pipewb.valid)
305    val latchWbIndex     = if(isVStore) wbIndex      else RegEnable(wbIndex, pipewb.valid)
306    val latchFlowNum     = if(isVStore) flowNumOffset else RegEnable(flowNumOffset, pipewb.valid)
307    val latchMergeByPre  = if(isVStore) mergedByPrevPortVec(i) else RegEnable(mergedByPrevPortVec(i), pipewb.valid)
308    when(latchWbValid && !latchMergeByPre){
309      entries(latchWbIndex).flowNum := entries(latchWbIndex).flowNum - latchFlowNum
310    }
311
312    when(pipewb.valid){
313      entries(wbIndex).sourceType   := sourceTypeNext
314      entries(wbIndex).flushState   := pipewb.bits.flushState
315    }
316    when(pipewb.valid && !pipewb.bits.hit){
317      needRSReplay(wbIndex) := true.B
318    }
319    pipewb.ready := true.B
320    XSError((entries(latchWbIndex).flowNum - latchFlowNum > entries(latchWbIndex).flowNum) && latchWbValid && !latchMergeByPre, s"entry: $latchWbIndex, FlowWriteback overflow!!\n")
321    XSError(!allocated(latchWbIndex) && latchWbValid, s"entry: $latchWbIndex, Writeback error flow!!\n")
322  }
323
324  //uopwriteback(deq)
325  for (i <- 0 until uopSize){
326    when(allocated(i) && entries(i).allReady() && !needCancel(i)){
327      uopFinish(i) := true.B
328    }
329  }
330   val selPolicy = SelectOne("circ", uopFinish, deqWidth) // select one entry to deq
331   private val pipelineOut              = Wire(Vec(deqWidth, DecoupledIO(new MemExuOutput(isVector = true))))
332   private val writeBackOut             = Wire(Vec(deqWidth, DecoupledIO(new MemExuOutput(isVector = true))))
333   private val writeBackOutExceptionVec = writeBackOut.map(_.bits.uop.exceptionVec)
334   for(((port, lsqport), i) <- (pipelineOut zip io.toLsq).zipWithIndex){
335    val canGo    = port.ready
336    val (selValid, selOHVec) = selPolicy.getNthOH(i + 1)
337    val entryIdx = OHToUInt(selOHVec)
338    val selEntry = entries(entryIdx)
339    val selAllocated = allocated(entryIdx)
340    val selFire  = selValid && canGo
341    when(selFire){
342      freeMaskVec(entryIdx) := selAllocated
343      allocated(entryIdx)   := false.B
344      uopFinish(entryIdx)   := false.B
345      needRSReplay(entryIdx):= false.B
346    }
347    //writeback connect
348    port.valid   := selFire && selAllocated && !needRSReplay(entryIdx) && !selEntry.uop.robIdx.needFlush(io.redirect)
349    port.bits    := DeqConnect(selEntry)
350    //to lsq
351    lsqport.bits := ToLsqConnect(selEntry) // when uopwriteback, free MBuffer entry, write to lsq
352    lsqport.valid:= selFire && selAllocated && !needRSReplay(entryIdx)
353    //to RS
354    val feedbackOut                       = WireInit(0.U.asTypeOf(io.feedback(i).bits)).suggestName(s"feedbackOut_${i}")
355    val feedbackValid                     = selFire && selAllocated
356    feedbackOut.hit                      := !needRSReplay(entryIdx)
357    feedbackOut.robIdx                   := selEntry.uop.robIdx
358    feedbackOut.sourceType               := selEntry.sourceType
359    feedbackOut.flushState               := selEntry.flushState
360    feedbackOut.dataInvalidSqIdx         := DontCare
361    feedbackOut.sqIdx                    := selEntry.uop.sqIdx
362    feedbackOut.lqIdx                    := selEntry.uop.lqIdx
363
364    io.feedback(i).valid                 := RegNext(feedbackValid)
365    io.feedback(i).bits                  := RegEnable(feedbackOut, feedbackValid)
366
367    NewPipelineConnect(
368      port, writeBackOut(i), writeBackOut(i).fire,
369      Mux(port.fire,
370        selEntry.uop.robIdx.needFlush(io.redirect),
371        writeBackOut(i).bits.uop.robIdx.needFlush(io.redirect)),
372      Option(s"VMergebufferPipelineConnect${i}")
373    )
374     io.uopWriteback(i)                  <> writeBackOut(i)
375     io.uopWriteback(i).bits.uop.exceptionVec := ExceptionNO.selectByFu(writeBackOutExceptionVec(i), fuCfg)
376   }
377
378  QueuePerf(uopSize, freeList.io.validCount, freeList.io.validCount === 0.U)
379}
380
381class VLMergeBufferImp(implicit p: Parameters) extends BaseVMergeBuffer(isVStore=false){
382  override lazy val uopSize = VlMergeBufferSize
383  println(s"VLMergeBuffer Size: ${VlMergeBufferSize}")
384  override lazy val freeList = Module(new FreeList(
385    size = uopSize,
386    allocWidth = VecLoadPipelineWidth,
387    freeWidth = deqWidth,
388    enablePreAlloc = false,
389    moduleName = "VLoad MergeBuffer freelist"
390  ))
391  io.toSplit.get.threshold := freeCount <= 6.U
392
393  //merge data
394  val flowWbElemIdx     = Wire(Vec(pipeWidth, UInt(elemIdxBits.W)))
395  val flowWbElemIdxInVd = Wire(Vec(pipeWidth, UInt(elemIdxBits.W)))
396  val pipewbValidReg    = Wire(Vec(pipeWidth, Bool()))
397  val wbIndexReg        = Wire(Vec(pipeWidth, UInt(vlmBindexBits.W)))
398  val mergeDataReg      = Wire(Vec(pipeWidth, UInt(VLEN.W)))
399
400  val maskWithexceptionMask = io.fromPipeline.map{ x=>
401    Mux(
402      TriggerAction.isExp(x.bits.trigger) || TriggerAction.isDmode(x.bits.trigger),
403      ~x.bits.vecTriggerMask,
404      Fill(x.bits.mask.getWidth, !ExceptionNO.selectByFuAndUnSelect(x.bits.exceptionVec, fuCfg, Seq(breakPoint)).asUInt.orR)
405    ).asUInt & x.bits.mask
406  }
407
408  for((pipewb, i) <- io.fromPipeline.zipWithIndex){
409    /** step0 **/
410    val wbIndex = pipewb.bits.mBIndex
411    val alignedType = pipewb.bits.alignedType
412    val elemIdxInsideVd = pipewb.bits.elemIdxInsideVd
413    flowWbElemIdx(i) := pipewb.bits.elemIdx
414    flowWbElemIdxInVd(i) := elemIdxInsideVd.get
415
416    val oldData = PriorityMux(Seq(
417      (pipewbValidReg(0) && (wbIndexReg(0) === wbIndex)) -> mergeDataReg(0),
418      (pipewbValidReg(1) && (wbIndexReg(1) === wbIndex)) -> mergeDataReg(1),
419      (pipewbValidReg(2) && (wbIndexReg(2) === wbIndex)) -> mergeDataReg(2),
420      true.B                                             -> entries(wbIndex).data // default use entries_data
421    ))
422    val mergedData = mergeDataWithElemIdx(
423      oldData = oldData,
424      newData = io.fromPipeline.map(_.bits.vecdata.get),
425      alignedType = alignedType(1,0),
426      elemIdx = flowWbElemIdxInVd,
427      valids = mergePortMatrix(i)
428    )
429    /* this only for unit-stride load data merge
430     * cycle0: broden 128-bits to 256-bits (max 6 to 1)
431     * cycle1: select 128-bits data from 256-bits (16 to 1)
432     */
433    val (brodenMergeData, brodenMergeMask)     = mergeDataByIndex(
434      data    = io.fromPipeline.map(_.bits.vecdata.get).drop(i),
435      mask    = maskWithexceptionMask.drop(i),
436      index   = io.fromPipeline(i).bits.elemIdxInsideVd.get,
437      valids  = mergePortMatrix(i).drop(i)
438    )
439    /** step1 **/
440    pipewbValidReg(i)      := RegNext(pipewb.valid)
441    wbIndexReg(i)          := RegEnable(wbIndex, pipewb.valid)
442    mergeDataReg(i)        := RegEnable(mergedData, pipewb.valid) // for not Unit-stride
443    val brodenMergeDataReg  = RegEnable(brodenMergeData, pipewb.valid) // only for Unit-stride
444    val brodenMergeMaskReg  = RegEnable(brodenMergeMask, pipewb.valid)
445    val mergedByPrevPortReg = RegEnable(mergedByPrevPortVec(i), pipewb.valid)
446    val regOffsetReg        = RegEnable(pipewb.bits.reg_offset.get, pipewb.valid) // only for Unit-stride
447    val isusMerge           = RegEnable(alignedType(2), pipewb.valid)
448
449    val usSelData           = Mux1H(UIntToOH(regOffsetReg), (0 until VLENB).map{case i => getNoAlignedSlice(brodenMergeDataReg, i, 128)})
450    val usSelMask           = Mux1H(UIntToOH(regOffsetReg), (0 until VLENB).map{case i => brodenMergeMaskReg(16 + i - 1, i)})
451    val usMergeData         = mergeDataByByte(entries(wbIndexReg(i)).data, usSelData, usSelMask)
452    when(pipewbValidReg(i) && !mergedByPrevPortReg){
453      entries(wbIndexReg(i)).data := Mux(isusMerge, usMergeData, mergeDataReg(i)) // if aligned(2) == 1, is Unit-Stride inst
454    }
455  }
456}
457
458class VSMergeBufferImp(implicit p: Parameters) extends BaseVMergeBuffer(isVStore=true){
459  override lazy val uopSize = VsMergeBufferSize
460  println(s"VSMergeBuffer Size: ${VsMergeBufferSize}")
461  override lazy val freeList = Module(new FreeList(
462    size = uopSize,
463    allocWidth = VecStorePipelineWidth,
464    freeWidth = deqWidth,
465    enablePreAlloc = false,
466    moduleName = "VStore MergeBuffer freelist"
467  ))
468  override def DeqConnect(source: MBufferBundle): MemExuOutput = {
469    val sink               = Wire(new MemExuOutput(isVector = true))
470    sink.data             := DontCare
471    sink.mask.get         := DontCare
472    sink.uop              := source.uop
473    sink.uop.exceptionVec := source.exceptionVec
474    sink.debug            := 0.U.asTypeOf(new DebugBundle)
475    sink.vdIdxInField.get := DontCare
476    sink.vdIdx.get        := DontCare
477    sink.isFromLoadUnit   := DontCare
478    sink.uop.vpu.vstart   := source.vstart
479    sink
480  }
481
482  // from misalignBuffer flush
483  when(io.fromMisalignBuffer.get.flush){
484    needRSReplay(io.fromMisalignBuffer.get.mbIndex) := true.B
485  }
486}
487