xref: /XiangShan/src/main/scala/xiangshan/mem/vector/VecCommon.scala (revision 8fd7c6dca865112367dcca346cb7c9897ca9fd6c)
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.backend.fu.FuType
28
29/**
30  * Common used parameters or functions in vlsu
31  */
32trait VLSUConstants {
33  val VLEN = 128
34  //for pack unit-stride flow
35  val AlignedNum = 4 // 1/2/4/8
36  def VLENB = VLEN/8
37  def vOffsetBits = log2Up(VLENB) // bits-width to index offset inside a vector reg
38  lazy val vlmBindexBits = 8 //will be overrided later
39  lazy val vsmBindexBits = 8 // will be overrided later
40
41  def alignTypes = 5 // eew/sew = 1/2/4/8, last indicate 128 bit element
42  def alignTypeBits = log2Up(alignTypes)
43  def maxMUL = 8
44  def maxFields = 8
45  /**
46    * In the most extreme cases like a segment indexed instruction, eew=64, emul=8, sew=8, lmul=1,
47    * and nf=8, each data reg is mapped with 8 index regs and there are 8 data regs in total,
48    * each for a field. Therefore an instruction can be divided into 64 uops at most.
49    */
50  def maxUopNum = maxMUL * maxFields // 64
51  def maxFlowNum = 16
52  def maxElemNum = maxMUL * maxFlowNum // 128
53  // def uopIdxBits = log2Up(maxUopNum) // to index uop inside an robIdx
54  def elemIdxBits = log2Up(maxElemNum) + 1 // to index which element in an instruction
55  def flowIdxBits = log2Up(maxFlowNum) + 1 // to index which flow in a uop
56  def fieldBits = log2Up(maxFields) + 1 // 4-bits to indicate 1~8
57
58  def ewBits = 3 // bits-width of EEW/SEW
59  def mulBits = 3 // bits-width of emul/lmul
60
61  def getSlice(data: UInt, i: Int, alignBits: Int): UInt = {
62    require(data.getWidth >= (i+1) * alignBits)
63    data((i+1) * alignBits - 1, i * alignBits)
64  }
65  def getNoAlignedSlice(data: UInt, i: Int, alignBits: Int): UInt = {
66    data(i * 8 + alignBits - 1, i * 8)
67  }
68
69  def getByte(data: UInt, i: Int = 0) = getSlice(data, i, 8)
70  def getHalfWord(data: UInt, i: Int = 0) = getSlice(data, i, 16)
71  def getWord(data: UInt, i: Int = 0) = getSlice(data, i, 32)
72  def getDoubleWord(data: UInt, i: Int = 0) = getSlice(data, i, 64)
73  def getDoubleDoubleWord(data: UInt, i: Int = 0) = getSlice(data, i, 128)
74}
75
76trait HasVLSUParameters extends HasXSParameter with VLSUConstants {
77  override val VLEN = coreParams.VLEN
78  override lazy val vlmBindexBits = log2Up(coreParams.VlMergeBufferSize)
79  override lazy val vsmBindexBits = log2Up(coreParams.VsMergeBufferSize)
80  def isUnitStride(instType: UInt) = instType(1, 0) === "b00".U
81  def isStrided(instType: UInt) = instType(1, 0) === "b10".U
82  def isIndexed(instType: UInt) = instType(0) === "b1".U
83  def isNotIndexed(instType: UInt) = instType(0) === "b0".U
84  def isSegment(instType: UInt) = instType(2) === "b1".U
85  def is128Bit(alignedType: UInt) = alignedType(2) === "b1".U
86
87  def mergeDataWithMask(oldData: UInt, newData: UInt, mask: UInt): Vec[UInt] = {
88    require(oldData.getWidth == newData.getWidth)
89    require(oldData.getWidth == mask.getWidth * 8)
90    VecInit(mask.asBools.zipWithIndex.map { case (en, i) =>
91      Mux(en, getByte(newData, i), getByte(oldData, i))
92    })
93  }
94
95  // def asBytes(data: UInt) = {
96  //   require(data.getWidth % 8 == 0)
97  //   (0 until data.getWidth/8).map(i => getByte(data, i))
98  // }
99
100  def mergeDataWithElemIdx(
101    oldData: UInt,
102    newData: Seq[UInt],
103    alignedType: UInt,
104    elemIdx: Seq[UInt],
105    valids: Seq[Bool]
106  ): UInt = {
107    require(newData.length == elemIdx.length)
108    require(newData.length == valids.length)
109    LookupTree(alignedType, List(
110      "b00".U -> VecInit(elemIdx.map(e => UIntToOH(e(3, 0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
111        ParallelPosteriorityMux(
112          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
113          getByte(oldData, i) +: newData.map(getByte(_))
114        )}).asUInt,
115      "b01".U -> VecInit(elemIdx.map(e => UIntToOH(e(2, 0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
116        ParallelPosteriorityMux(
117          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
118          getHalfWord(oldData, i) +: newData.map(getHalfWord(_))
119        )}).asUInt,
120      "b10".U -> VecInit(elemIdx.map(e => UIntToOH(e(1, 0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
121        ParallelPosteriorityMux(
122          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
123          getWord(oldData, i) +: newData.map(getWord(_))
124        )}).asUInt,
125      "b11".U -> VecInit(elemIdx.map(e => UIntToOH(e(0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
126        ParallelPosteriorityMux(
127          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
128          getDoubleWord(oldData, i) +: newData.map(getDoubleWord(_))
129        )}).asUInt
130    ))
131  }
132
133  def mergeDataWithElemIdx(oldData: UInt, newData: UInt, alignedType: UInt, elemIdx: UInt): UInt = {
134    mergeDataWithElemIdx(oldData, Seq(newData), alignedType, Seq(elemIdx), Seq(true.B))
135  }
136  /**
137    * for merge 128-bits data of unit-stride
138    */
139  object mergeDataByByte{
140    def apply(oldData: UInt, newData: UInt, mask: UInt): UInt = {
141      val selVec = Seq(mask).map(_.asBools).transpose
142      VecInit(selVec.zipWithIndex.map{ case (selV, i) =>
143        ParallelPosteriorityMux(
144          true.B +: selV.map(x => x),
145          getByte(oldData, i) +: Seq(getByte(newData, i))
146        )}).asUInt
147    }
148  }
149
150  /**
151    * for merge Unit-Stride data to 256-bits
152    * merge 128-bits data to 256-bits
153    * if have 3 port,
154    *   if is port0, it is 6 to 1 Multiplexer -> (128'b0, data) or (data, 128'b0) or (data, port2data) or (port2data, data) or (data, port3data) or (port3data, data)
155    *   if is port1, it is 4 to 1 Multiplexer -> (128'b0, data) or (data, 128'b0) or (data, port3data) or (port3data, data)
156    *   if is port3, it is 2 to 1 Multiplexer -> (128'b0, data) or (data, 128'b0)
157    *
158    */
159  object mergeDataByIndex{
160    def apply(data:  Seq[UInt], mask: Seq[UInt], index: UInt, valids: Seq[Bool]): (UInt, UInt) = {
161      require(data.length == valids.length)
162      require(data.length == mask.length)
163      val muxLength = data.length
164      val selDataMatrix = Wire(Vec(muxLength, Vec(2, UInt((VLEN * 2).W)))) // 3 * 2 * 256
165      val selMaskMatrix = Wire(Vec(muxLength, Vec(2, UInt((VLENB * 2).W)))) // 3 * 2 * 16
166      dontTouch(selDataMatrix)
167      dontTouch(selMaskMatrix)
168      for(i <- 0 until muxLength){
169        if(i == 0){
170          selDataMatrix(i)(0) := Cat(0.U(VLEN.W), data(i))
171          selDataMatrix(i)(1) := Cat(data(i), 0.U(VLEN.W))
172          selMaskMatrix(i)(0) := Cat(0.U(VLENB.W), mask(i))
173          selMaskMatrix(i)(1) := Cat(mask(i), 0.U(VLENB.W))
174        }
175        else{
176          selDataMatrix(i)(0) := Cat(data(i), data(0))
177          selDataMatrix(i)(1) := Cat(data(0), data(i))
178          selMaskMatrix(i)(0) := Cat(mask(i), mask(0))
179          selMaskMatrix(i)(1) := Cat(mask(0), mask(i))
180        }
181      }
182      val selIdxVec = (0 until muxLength).map(_.U)
183      val selIdx    = PriorityMux(valids.reverse, selIdxVec.reverse)
184
185      val selData = Mux(index === 0.U,
186                        selDataMatrix(selIdx)(0),
187                        selDataMatrix(selIdx)(1))
188      val selMask = Mux(index === 0.U,
189                        selMaskMatrix(selIdx)(0),
190                        selMaskMatrix(selIdx)(1))
191      (selData, selMask)
192    }
193  }
194  def mergeDataByIndex(data:  UInt, mask: UInt, index: UInt): (UInt, UInt) = {
195    mergeDataByIndex(Seq(data), Seq(mask), index, Seq(true.B))
196  }
197}
198abstract class VLSUModule(implicit p: Parameters) extends XSModule
199  with HasVLSUParameters
200  with HasCircularQueuePtrHelper
201abstract class VLSUBundle(implicit p: Parameters) extends XSBundle
202  with HasVLSUParameters
203
204class VLSUBundleWithMicroOp(implicit p: Parameters) extends VLSUBundle {
205  val uop = new DynInst
206}
207
208class OnlyVecExuOutput(implicit p: Parameters) extends VLSUBundle {
209  val isvec = Bool()
210  val vecdata = UInt(VLEN.W)
211  val mask = UInt(VLENB.W)
212  // val rob_idx_valid = Vec(2, Bool())
213  // val inner_idx = Vec(2, UInt(3.W))
214  // val rob_idx = Vec(2, new RobPtr)
215  // val offset = Vec(2, UInt(4.W))
216  val reg_offset = UInt(vOffsetBits.W)
217  val vecActive = Bool() // 1: vector active element, 0: vector not active element
218  val is_first_ele = Bool()
219  val elemIdx = UInt(elemIdxBits.W) // element index
220  val elemIdxInsideVd = UInt(elemIdxBits.W) // element index in scope of vd
221  // val uopQueuePtr = new VluopPtr
222  // val flowPtr = new VlflowPtr
223}
224
225class VecExuOutput(implicit p: Parameters) extends MemExuOutput with HasVLSUParameters {
226  val vec = new OnlyVecExuOutput
227  val alignedType       = UInt(alignTypeBits.W)
228   // feedback
229  val vecFeedback       = Bool()
230}
231
232// class VecStoreExuOutput(implicit p: Parameters) extends MemExuOutput with HasVLSUParameters {
233//   val elemIdx = UInt(elemIdxBits.W)
234//   val uopQueuePtr = new VsUopPtr
235//   val fieldIdx = UInt(fieldBits.W)
236//   val segmentIdx = UInt(elemIdxBits.W)
237//   val vaddr = UInt(VAddrBits.W)
238//   // pack
239//   val isPackage         = Bool()
240//   val packageNum        = UInt((log2Up(VLENB) + 1).W)
241//   val originAlignedType = UInt(alignTypeBits.W)
242//   val alignedType       = UInt(alignTypeBits.W)
243// }
244
245class VecUopBundle(implicit p: Parameters) extends VLSUBundleWithMicroOp {
246  val flowMask       = UInt(VLENB.W) // each bit for a flow
247  val byteMask       = UInt(VLENB.W) // each bit for a byte
248  val data           = UInt(VLEN.W)
249  // val fof            = Bool() // fof is only used for vector loads
250  val excp_eew_index = UInt(elemIdxBits.W)
251  // val exceptionVec   = ExceptionVec() // uop has exceptionVec
252  val baseAddr = UInt(VAddrBits.W)
253  val stride = UInt(VLEN.W)
254  val flow_counter = UInt(flowIdxBits.W)
255
256  // instruction decode result
257  val flowNum = UInt(flowIdxBits.W) // # of flows in a uop
258  // val flowNumLog2 = UInt(log2Up(flowIdxBits).W) // log2(flowNum), for better timing of multiplication
259  val nfields = UInt(fieldBits.W) // NFIELDS
260  val vm = Bool() // whether vector masking is enabled
261  val usWholeReg = Bool() // unit-stride, whole register load
262  val usMaskReg = Bool() // unit-stride, masked store/load
263  val eew = UInt(ewBits.W) // size of memory elements
264  val sew = UInt(ewBits.W)
265  val emul = UInt(mulBits.W)
266  val lmul = UInt(mulBits.W)
267  val vlmax = UInt(elemIdxBits.W)
268  val instType = UInt(3.W)
269  val vd_last_uop = Bool()
270  val vd_first_uop = Bool()
271}
272
273class VecFlowBundle(implicit p: Parameters) extends VLSUBundleWithMicroOp {
274  val vaddr             = UInt(VAddrBits.W)
275  val mask              = UInt(VLENB.W)
276  val alignedType       = UInt(alignTypeBits.W)
277  val vecActive         = Bool()
278  val elemIdx           = UInt(elemIdxBits.W)
279  val is_first_ele      = Bool()
280
281  // pack
282  val isPackage         = Bool()
283  val packageNum        = UInt((log2Up(VLENB) + 1).W)
284  val originAlignedType = UInt(alignTypeBits.W)
285}
286
287class VecMemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends VLSUBundle{
288  val output = new MemExuOutput(isVector)
289  val vecFeedback = Bool()
290  val mmio = Bool()
291  val usSecondInv = Bool()
292  val elemIdx = UInt(elemIdxBits.W)
293  val alignedType = UInt(alignTypeBits.W)
294  val mbIndex     = UInt(vsmBindexBits.W)
295  val mask        = UInt(VLENB.W)
296}
297
298object MulNum {
299  def apply (mul: UInt): UInt = { //mul means emul or lmul
300    (LookupTree(mul,List(
301      "b101".U -> 1.U , // 1/8
302      "b110".U -> 1.U , // 1/4
303      "b111".U -> 1.U , // 1/2
304      "b000".U -> 1.U , // 1
305      "b001".U -> 2.U , // 2
306      "b010".U -> 4.U , // 4
307      "b011".U -> 8.U   // 8
308    )))}
309}
310/**
311  * when emul is greater than or equal to 1, this means the entire register needs to be written;
312  * otherwise, only write the specified number of bytes */
313object MulDataSize {
314  def apply (mul: UInt): UInt = { //mul means emul or lmul
315    (LookupTree(mul,List(
316      "b101".U -> 2.U  , // 1/8
317      "b110".U -> 4.U  , // 1/4
318      "b111".U -> 8.U  , // 1/2
319      "b000".U -> 16.U , // 1
320      "b001".U -> 16.U , // 2
321      "b010".U -> 16.U , // 4
322      "b011".U -> 16.U   // 8
323    )))}
324}
325
326object OneRegNum {
327  def apply (eew: UInt): UInt = { //mul means emul or lmul
328    (LookupTree(eew,List(
329      "b000".U -> 16.U , // 1
330      "b101".U -> 8.U , // 2
331      "b110".U -> 4.U , // 4
332      "b111".U -> 2.U   // 8
333    )))}
334}
335
336//index inst read data byte
337object SewDataSize {
338  def apply (sew: UInt): UInt = {
339    (LookupTree(sew,List(
340      "b000".U -> 1.U , // 1
341      "b001".U -> 2.U , // 2
342      "b010".U -> 4.U , // 4
343      "b011".U -> 8.U   // 8
344    )))}
345}
346
347// strided inst read data byte
348object EewDataSize {
349  def apply (eew: UInt): UInt = {
350    (LookupTree(eew,List(
351      "b000".U -> 1.U , // 1
352      "b101".U -> 2.U , // 2
353      "b110".U -> 4.U , // 4
354      "b111".U -> 8.U   // 8
355    )))}
356}
357
358object loadDataSize {
359  def apply (instType: UInt, emul: UInt, eew: UInt, sew: UInt): UInt = {
360    (LookupTree(instType,List(
361      "b000".U ->  MulDataSize(emul), // unit-stride
362      "b010".U ->  EewDataSize(eew)  , // strided
363      "b001".U ->  SewDataSize(sew)  , // indexed-unordered
364      "b011".U ->  SewDataSize(sew)  , // indexed-ordered
365      "b100".U ->  EewDataSize(eew)  , // segment unit-stride
366      "b110".U ->  EewDataSize(eew)  , // segment strided
367      "b101".U ->  SewDataSize(sew)  , // segment indexed-unordered
368      "b111".U ->  SewDataSize(sew)    // segment indexed-ordered
369    )))}
370}
371
372object storeDataSize {
373  def apply (instType: UInt, eew: UInt, sew: UInt): UInt = {
374    (LookupTree(instType,List(
375      "b000".U ->  EewDataSize(eew)  , // unit-stride, do not use
376      "b010".U ->  EewDataSize(eew)  , // strided
377      "b001".U ->  SewDataSize(sew)  , // indexed-unordered
378      "b011".U ->  SewDataSize(sew)  , // indexed-ordered
379      "b100".U ->  EewDataSize(eew)  , // segment unit-stride
380      "b110".U ->  EewDataSize(eew)  , // segment strided
381      "b101".U ->  SewDataSize(sew)  , // segment indexed-unordered
382      "b111".U ->  SewDataSize(sew)    // segment indexed-ordered
383    )))}
384}
385
386object GenVecStoreMask {
387  def apply (instType: UInt, eew: UInt, sew: UInt): UInt = {
388    val mask = Wire(UInt(16.W))
389    mask := UIntToOH(storeDataSize(instType = instType, eew = eew, sew = sew)) - 1.U
390    mask
391  }
392}
393
394/**
395  * these are used to obtain immediate addresses for  index instruction */
396object EewEq8 {
397  def apply(index:UInt, flow_inner_idx: UInt): UInt = {
398    (LookupTree(flow_inner_idx,List(
399      0.U  -> index(7 ,0   ),
400      1.U  -> index(15,8   ),
401      2.U  -> index(23,16  ),
402      3.U  -> index(31,24  ),
403      4.U  -> index(39,32  ),
404      5.U  -> index(47,40  ),
405      6.U  -> index(55,48  ),
406      7.U  -> index(63,56  ),
407      8.U  -> index(71,64  ),
408      9.U  -> index(79,72  ),
409      10.U -> index(87,80  ),
410      11.U -> index(95,88  ),
411      12.U -> index(103,96 ),
412      13.U -> index(111,104),
413      14.U -> index(119,112),
414      15.U -> index(127,120)
415    )))}
416}
417
418object EewEq16 {
419  def apply(index: UInt, flow_inner_idx: UInt): UInt = {
420    (LookupTree(flow_inner_idx, List(
421      0.U -> index(15, 0),
422      1.U -> index(31, 16),
423      2.U -> index(47, 32),
424      3.U -> index(63, 48),
425      4.U -> index(79, 64),
426      5.U -> index(95, 80),
427      6.U -> index(111, 96),
428      7.U -> index(127, 112)
429    )))}
430}
431
432object EewEq32 {
433  def apply(index: UInt, flow_inner_idx: UInt): UInt = {
434    (LookupTree(flow_inner_idx, List(
435      0.U -> index(31, 0),
436      1.U -> index(63, 32),
437      2.U -> index(95, 64),
438      3.U -> index(127, 96)
439    )))}
440}
441
442object EewEq64 {
443  def apply (index: UInt, flow_inner_idx: UInt): UInt = {
444    (LookupTree(flow_inner_idx, List(
445      0.U -> index(63, 0),
446      1.U -> index(127, 64)
447    )))}
448}
449
450object IndexAddr {
451  def apply (index: UInt, flow_inner_idx: UInt, eew: UInt): UInt = {
452    (LookupTree(eew,List(
453      "b000".U -> EewEq8 (index = index, flow_inner_idx = flow_inner_idx ), // Imm is 1 Byte // TODO: index maybe cross register
454      "b101".U -> EewEq16(index = index, flow_inner_idx = flow_inner_idx ), // Imm is 2 Byte
455      "b110".U -> EewEq32(index = index, flow_inner_idx = flow_inner_idx ), // Imm is 4 Byte
456      "b111".U -> EewEq64(index = index, flow_inner_idx = flow_inner_idx )  // Imm is 8 Byte
457    )))}
458}
459
460object Log2Num {
461  def apply (num: UInt): UInt = {
462    (LookupTree(num,List(
463      16.U -> 4.U,
464      8.U  -> 3.U,
465      4.U  -> 2.U,
466      2.U  -> 1.U,
467      1.U  -> 0.U
468    )))}
469}
470
471object GenUopIdxInField {
472  def apply (instType: UInt, emul: UInt, lmul: UInt, uopIdx: UInt): UInt = {
473    val isIndexed = instType(0)
474    val mulInField = Mux(
475      isIndexed,
476      Mux(lmul.asSInt > emul.asSInt, lmul, emul),
477      emul
478    )
479    LookupTree(mulInField, List(
480      "b101".U -> 0.U,
481      "b110".U -> 0.U,
482      "b111".U -> 0.U,
483      "b000".U -> 0.U,
484      "b001".U -> uopIdx(0),
485      "b010".U -> uopIdx(1, 0),
486      "b011".U -> uopIdx(2, 0)
487    ))
488  }
489}
490
491//eew decode
492object EewLog2 extends VLSUConstants {
493  // def apply (eew: UInt): UInt = {
494  //   (LookupTree(eew,List(
495  //     "b000".U -> "b000".U , // 1
496  //     "b101".U -> "b001".U , // 2
497  //     "b110".U -> "b010".U , // 4
498  //     "b111".U -> "b011".U   // 8
499  //   )))}
500  def apply(eew: UInt): UInt = ZeroExt(eew(1, 0), ewBits)
501}
502
503/**
504  * unit-stride instructions don't use this method;
505  * other instructions generate realFlowNum by EmulDataSize >> eew(1,0),
506  * EmulDataSize means the number of bytes that need to be written to the register,
507  * eew(1,0) means the number of bytes written at once*/
508object GenRealFlowNum {
509  def apply (instType: UInt, emul: UInt, lmul: UInt, eew: UInt, sew: UInt): UInt = {
510    require(instType.getWidth == 3, "The instType width must be 3, (isSegment, mop)")
511    (LookupTree(instType,List(
512      "b000".U ->  (MulDataSize(emul) >> eew(1,0)).asUInt, // store use, load do not use
513      "b010".U ->  (MulDataSize(emul) >> eew(1,0)).asUInt, // strided
514      "b001".U ->  Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew(1,0)).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt), // indexed-unordered
515      "b011".U ->  Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew(1,0)).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt), // indexed-ordered
516      "b100".U ->  (MulDataSize(emul) >> eew(1,0)).asUInt, // segment unit-stride
517      "b110".U ->  (MulDataSize(emul) >> eew(1,0)).asUInt, // segment strided
518      "b101".U ->  Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew(1,0)).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt), // segment indexed-unordered
519      "b111".U ->  Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew(1,0)).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt)  // segment indexed-ordered
520    )))}
521}
522
523/**
524  * GenRealFlowLog2 = Log2(GenRealFlowNum)
525  */
526object GenRealFlowLog2 extends VLSUConstants {
527  def apply(instType: UInt, emul: UInt, lmul: UInt, eew: UInt, sew: UInt): UInt = {
528    require(instType.getWidth == 3, "The instType width must be 3, (isSegment, mop)")
529    val emulLog2 = Mux(emul.asSInt >= 0.S, 0.U, emul)
530    val lmulLog2 = Mux(lmul.asSInt >= 0.S, 0.U, lmul)
531    val eewRealFlowLog2 = emulLog2 + log2Up(VLENB).U - eew(1, 0)
532    val sewRealFlowLog2 = lmulLog2 + log2Up(VLENB).U - sew(1, 0)
533    (LookupTree(instType, List(
534      "b000".U -> eewRealFlowLog2, // unit-stride
535      "b010".U -> eewRealFlowLog2, // strided
536      "b001".U -> Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2), // indexed-unordered
537      "b011".U -> Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2), // indexed-ordered
538      "b100".U -> eewRealFlowLog2, // segment unit-stride
539      "b110".U -> eewRealFlowLog2, // segment strided
540      "b101".U -> Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2), // segment indexed-unordered
541      "b111".U -> Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2), // segment indexed-ordered
542    )))
543  }
544}
545
546/**
547  * GenElemIdx generals an element index within an instruction, given a certain uopIdx and a known flowIdx
548  * inside the uop.
549  */
550object GenElemIdx extends VLSUConstants {
551  def apply(instType: UInt, emul: UInt, lmul: UInt, eew: UInt, sew: UInt,
552    uopIdx: UInt, flowIdx: UInt): UInt = {
553    val isIndexed = instType(0).asBool
554    val eewUopFlowsLog2 = Mux(emul.asSInt > 0.S, 0.U, emul) + log2Up(VLENB).U - eew(1, 0)
555    val sewUopFlowsLog2 = Mux(lmul.asSInt > 0.S, 0.U, lmul) + log2Up(VLENB).U - sew(1, 0)
556    val uopFlowsLog2 = Mux(
557      isIndexed,
558      Mux(emul.asSInt > lmul.asSInt, eewUopFlowsLog2, sewUopFlowsLog2),
559      eewUopFlowsLog2
560    )
561    LookupTree(uopFlowsLog2, List(
562      0.U -> uopIdx,
563      1.U -> uopIdx ## flowIdx(0),
564      2.U -> uopIdx ## flowIdx(1, 0),
565      3.U -> uopIdx ## flowIdx(2, 0),
566      4.U -> uopIdx ## flowIdx(3, 0)
567    ))
568  }
569}
570
571/**
572  * GenVLMAX calculates VLMAX, which equals MUL * ew
573  */
574object GenVLMAXLog2 extends VLSUConstants {
575  def apply(lmul: UInt, sew: UInt): UInt = lmul + log2Up(VLENB).U - sew
576}
577object GenVLMAX {
578  def apply(lmul: UInt, sew: UInt): UInt = 1.U << GenVLMAXLog2(lmul, sew)
579}
580
581object GenUSWholeRegVL extends VLSUConstants {
582  def apply(nfields: UInt, eew: UInt): UInt = {
583    LookupTree(eew(1, 0), List(
584      "b00".U -> (nfields << (log2Up(VLENB) - 0)),
585      "b01".U -> (nfields << (log2Up(VLENB) - 1)),
586      "b10".U -> (nfields << (log2Up(VLENB) - 2)),
587      "b11".U -> (nfields << (log2Up(VLENB) - 3))
588    ))
589  }
590}
591object GenUSWholeEmul extends VLSUConstants{
592  def apply(nf: UInt): UInt={
593    LookupTree(nf,List(
594      "b000".U -> "b000".U(mulBits.W),
595      "b001".U -> "b001".U(mulBits.W),
596      "b011".U -> "b010".U(mulBits.W),
597      "b111".U -> "b011".U(mulBits.W)
598    ))
599  }
600}
601
602
603object GenUSMaskRegVL extends VLSUConstants {
604  def apply(vl: UInt): UInt = {
605    Mux(vl(2,0) === 0.U , (vl >> 3.U), ((vl >> 3.U) + 1.U))
606  }
607}
608
609object GenUopByteMask {
610  def apply(flowMask: UInt, alignedType: UInt): UInt = {
611    LookupTree(alignedType, List(
612      "b000".U -> flowMask,
613      "b001".U -> FillInterleaved(2, flowMask),
614      "b010".U -> FillInterleaved(4, flowMask),
615      "b011".U -> FillInterleaved(8, flowMask),
616      "b100".U -> FillInterleaved(16, flowMask)
617    ))
618  }
619}
620
621object GenVdIdxInField extends VLSUConstants {
622  def apply(instType: UInt, emul: UInt, lmul: UInt, uopIdx: UInt): UInt = {
623    val vdIdx = Wire(UInt(log2Up(maxMUL).W))
624    when (instType(1,0) === "b00".U || instType(1,0) === "b10".U || lmul.asSInt > emul.asSInt) {
625      // Unit-stride or Strided, or indexed with lmul >= emul
626      vdIdx := uopIdx
627    }.otherwise {
628      // Indexed with lmul <= emul
629      val multiple = emul - lmul
630      val uopIdxWidth = uopIdx.getWidth
631      vdIdx := LookupTree(multiple, List(
632        0.U -> uopIdx,
633        1.U -> (uopIdx >> 1),
634        2.U -> (uopIdx >> 2),
635        3.U -> (uopIdx >> 3)
636      ))
637    }
638    vdIdx
639  }
640}
641/**
642* Use start and vl to generate flow activative mask
643* mod = true fill 0
644* mod = false fill 1
645*/
646object GenFlowMask extends VLSUConstants {
647  def apply(elementMask: UInt, start: UInt, vl: UInt , mod: Boolean): UInt = {
648    val startMask = ~UIntToMask(start, VLEN)
649    val vlMask = UIntToMask(vl, VLEN)
650    val maskVlStart = vlMask & startMask
651    if(mod){
652      elementMask & maskVlStart
653    }
654    else{
655      (~elementMask).asUInt & maskVlStart
656    }
657  }
658}
659
660object CheckAligned extends VLSUConstants {
661  def apply(addr: UInt): UInt = {
662    val aligned_16 = (addr(0) === 0.U) // 16-bit
663    val aligned_32 = (addr(1,0) === 0.U) // 32-bit
664    val aligned_64 = (addr(2,0) === 0.U) // 64-bit
665    val aligned_128 = (addr(3,0) === 0.U) // 128-bit
666    Cat(true.B, aligned_16, aligned_32, aligned_64, aligned_128)
667  }
668}
669
670/**
671  search if mask have continue 'len' bit '1'
672  mask: source mask
673  len: search length
674*/
675object GenPackMask{
676  def leadX(mask: Seq[Bool], len: Int): Bool = {
677    if(len == 1){
678      mask.head
679    }
680    else{
681      leadX(mask.drop(1),len-1) & mask.head
682    }
683  }
684  def leadOneVec(shiftMask: Seq[Bool]): UInt = {
685    // max is 64-bit, so the max num of flow to pack is 8
686
687    val lead1 = leadX(shiftMask, 1) // continue 1 bit
688    val lead2 = leadX(shiftMask, 2) // continue 2 bit
689    val lead4 = leadX(shiftMask, 4) // continue 4 bit
690    val lead8 = leadX(shiftMask, 8) // continue 8 bit
691    val lead16 = leadX(shiftMask, 16) // continue 16 bit
692    Cat(lead1, lead2, lead4, lead8, lead16)
693  }
694
695  def apply(shiftMask: UInt) = {
696    // pack mask
697    val packMask = leadOneVec(shiftMask.asBools)
698    packMask
699  }
700}
701/**
702PackEnable = (LeadXVec >> eew) & alignedVec, where the 0th bit represents the ability to merge into a 64 bit flow, the second bit represents the ability to merge into a 32 bit flow, and so on.
703
704example:
705  addr = 0x0, activeMask = b00011100101111, flowIdx = 0, eew = 0(8-bit)
706
707  step 0 : addrAlignedVec = (1, 1, 1, 1) elemIdxAligned = (1, 1, 1, 1)
708  step 1 : activePackVec = (1, 1, 1, 0), inactivePackVec = (0, 0, 0, 0)
709  step 2 : activePackEnable = (1, 1, 1, 0), inactivePackVec = (0, 0, 0, 0)
710
711  we can package 4 8-bit activative flows into a 32-bit flow.
712*/
713object GenPackVec extends VLSUConstants{
714  def apply(addr: UInt, shiftMask: UInt, eew: UInt, elemIdx: UInt): UInt = {
715    val addrAlignedVec = CheckAligned(addr)
716    val elemIdxAligned = CheckAligned(elemIdx)
717    val packMask = GenPackMask(shiftMask)
718    // generate packVec
719    val packVec = addrAlignedVec & elemIdxAligned & (packMask.asUInt >> eew)
720
721    packVec
722  }
723}
724
725object GenPackAlignedType extends VLSUConstants{
726  def apply(packVec: UInt): UInt = {
727    val packAlignedType = PriorityMux(Seq(
728      packVec(0) -> "b100".U,
729      packVec(1) -> "b011".U,
730      packVec(2) -> "b010".U,
731      packVec(3) -> "b001".U,
732      packVec(4) -> "b000".U
733    ))
734    packAlignedType
735  }
736}
737
738object GenPackNum extends VLSUConstants{
739  def apply(alignedType: UInt, packAlignedType: UInt): UInt = {
740    (1.U << (packAlignedType - alignedType)).asUInt
741  }
742}
743
744object genVWmask128 {
745  def apply(addr: UInt, sizeEncode: UInt): UInt = {
746    (LookupTree(sizeEncode, List(
747      "b000".U -> 0x1.U, //0001 << addr(2:0)
748      "b001".U -> 0x3.U, //0011
749      "b010".U -> 0xf.U, //1111
750      "b011".U -> 0xff.U, //11111111
751      "b100".U -> 0xffff.U //1111111111111111
752    )) << addr(3, 0)).asUInt
753  }
754}
755/*
756* only use in max length is 128
757*/
758object genVWdata {
759  def apply(data: UInt, sizeEncode: UInt): UInt = {
760    LookupTree(sizeEncode, List(
761      "b000".U -> Fill(16, data(7, 0)),
762      "b001".U -> Fill(8, data(15, 0)),
763      "b010".U -> Fill(4, data(31, 0)),
764      "b011".U -> Fill(2, data(63,0)),
765      "b100".U -> data(127,0)
766    ))
767  }
768}
769
770object genUSSplitAddr{
771  def apply(addr: UInt, index: UInt): UInt = {
772    val tmpAddr = Cat(addr(38, 4), 0.U(4.W))
773    val nextCacheline = tmpAddr + 16.U
774    LookupTree(index, List(
775      0.U -> tmpAddr,
776      1.U -> nextCacheline
777    ))
778  }
779}
780
781object genUSSplitMask{
782  def apply(mask: UInt, index: UInt, addrOffset: UInt): UInt = {
783    val tmpMask = Cat(0.U(16.W),mask) << addrOffset // 32-bits
784    LookupTree(index, List(
785      0.U -> tmpMask(15, 0),
786      1.U -> tmpMask(31, 16),
787    ))
788  }
789}
790
791object genUSSplitData{
792  def apply(data: UInt, index: UInt, addrOffset: UInt): UInt = {
793    val tmpData = WireInit(0.U(256.W))
794    val lookupTable = (0 until 16).map{case i =>
795      if(i == 0){
796        i.U -> Cat(0.U(128.W), data)
797      }else{
798        i.U -> Cat(0.U(((16-i)*8).W), data, 0.U((i*8).W))
799      }
800    }
801    tmpData := LookupTree(addrOffset, lookupTable).asUInt
802
803    LookupTree(index, List(
804      0.U -> tmpData(127, 0),
805      1.U -> tmpData(255, 128)
806    ))
807  }
808}
809
810object genVSData extends VLSUConstants {
811  def apply(data: UInt, elemIdx: UInt, alignedType: UInt): UInt = {
812    LookupTree(alignedType, List(
813      "b000".U -> ZeroExt(LookupTree(elemIdx(3, 0), List.tabulate(VLEN/8)(i => i.U -> getByte(data, i))), VLEN),
814      "b001".U -> ZeroExt(LookupTree(elemIdx(2, 0), List.tabulate(VLEN/16)(i => i.U -> getHalfWord(data, i))), VLEN),
815      "b010".U -> ZeroExt(LookupTree(elemIdx(1, 0), List.tabulate(VLEN/32)(i => i.U -> getWord(data, i))), VLEN),
816      "b011".U -> ZeroExt(LookupTree(elemIdx(0), List.tabulate(VLEN/64)(i => i.U -> getDoubleWord(data, i))), VLEN),
817      "b100".U -> data // if have wider element, it will broken
818    ))
819  }
820}
821
822// TODO: more elegant
823object genVStride extends VLSUConstants {
824  def apply(uopIdx: UInt, stride: UInt): UInt = {
825    LookupTree(uopIdx, List(
826      0.U -> 0.U,
827      1.U -> stride,
828      2.U -> (stride << 1),
829      3.U -> ((stride << 1).asUInt + stride),
830      4.U -> (stride << 2),
831      5.U -> ((stride << 2).asUInt + stride),
832      6.U -> ((stride << 2).asUInt + (stride << 1)),
833      7.U -> ((stride << 2).asUInt + (stride << 1) + stride)
834    ))
835  }
836}
837/**
838 * generate uopOffset, not used in segment instruction
839 * */
840object genVUopOffset extends VLSUConstants {
841  def apply(instType: UInt, isfof: Bool, uopidx: UInt, nf: UInt, eew: UInt, stride: UInt, alignedType: UInt): UInt = {
842    val uopInsidefield = (uopidx >> nf).asUInt // when nf == 0, is uopidx
843
844    val fofVUopOffset = (LookupTree(instType,List(
845      "b000".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // unit-stride fof
846      "b100".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // segment unit-stride fof
847    ))).asUInt
848
849    val otherVUopOffset = (LookupTree(instType,List(
850      "b000".U -> ( uopInsidefield << alignedType                                   ) , // unit-stride
851      "b010".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // strided
852      "b001".U -> ( 0.U                                                             ) , // indexed-unordered
853      "b011".U -> ( 0.U                                                             ) , // indexed-ordered
854      "b100".U -> ( uopInsidefield << alignedType                                   ) , // segment unit-stride
855      "b110".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // segment strided
856      "b101".U -> ( 0.U                                                             ) , // segment indexed-unordered
857      "b111".U -> ( 0.U                                                             )   // segment indexed-ordered
858    ))).asUInt
859
860    Mux(isfof, fofVUopOffset, otherVUopOffset)
861  }
862}
863