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