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