xref: /XiangShan/src/main/scala/xiangshan/backend/issue/IssueQueue.scala (revision 8d081717cfe3863e6c0d38305abd6327c65a653a)
1package xiangshan.backend.issue
2
3import org.chipsalliance.cde.config.Parameters
4import chisel3._
5import chisel3.util._
6import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
7import utility.{GTimer, HasCircularQueuePtrHelper}
8import utils._
9import xiangshan._
10import xiangshan.backend.Bundles._
11import xiangshan.backend.decode.{ImmUnion, Imm_LUI_LOAD}
12import xiangshan.backend.datapath.DataConfig._
13import xiangshan.backend.datapath.DataSource
14import xiangshan.backend.fu.{FuConfig, FuType}
15import xiangshan.mem.{MemWaitUpdateReq, SqPtr, LqPtr}
16import xiangshan.backend.rob.RobPtr
17import xiangshan.backend.datapath.NewPipelineConnect
18
19class IssueQueue(params: IssueBlockParams)(implicit p: Parameters) extends LazyModule with HasXSParameter {
20  override def shouldBeInlined: Boolean = false
21
22  implicit val iqParams = params
23  lazy val module: IssueQueueImp = iqParams.schdType match {
24    case IntScheduler() => new IssueQueueIntImp(this)
25    case VfScheduler() => new IssueQueueVfImp(this)
26    case MemScheduler() =>
27      if (iqParams.StdCnt == 0 && !iqParams.isVecMemIQ) new IssueQueueMemAddrImp(this)
28      else if (iqParams.isVecMemIQ) new IssueQueueVecMemImp(this)
29      else new IssueQueueIntImp(this)
30    case _ => null
31  }
32}
33
34class IssueQueueStatusBundle(numEnq: Int, numEntries: Int) extends Bundle {
35  val empty = Output(Bool())
36  val full = Output(Bool())
37  val validCnt = Output(UInt(log2Ceil(numEntries).W))
38  val leftVec = Output(Vec(numEnq + 1, Bool()))
39}
40
41class IssueQueueDeqRespBundle(implicit p:Parameters, params: IssueBlockParams) extends EntryDeqRespBundle
42
43class IssueQueueIO()(implicit p: Parameters, params: IssueBlockParams) extends XSBundle {
44  // Inputs
45  val flush = Flipped(ValidIO(new Redirect))
46  val enq = Vec(params.numEnq, Flipped(DecoupledIO(new DynInst)))
47
48  val deqResp = Vec(params.numDeq, Flipped(ValidIO(new IssueQueueDeqRespBundle)))
49  val og0Resp = Vec(params.numDeq, Flipped(ValidIO(new IssueQueueDeqRespBundle)))
50  val og1Resp = Vec(params.numDeq, Flipped(ValidIO(new IssueQueueDeqRespBundle)))
51  val finalIssueResp = OptionWrapper(params.LdExuCnt > 0, Vec(params.LdExuCnt, Flipped(ValidIO(new IssueQueueDeqRespBundle))))
52  val memAddrIssueResp = OptionWrapper(params.LdExuCnt > 0, Vec(params.LdExuCnt, Flipped(ValidIO(new IssueQueueDeqRespBundle))))
53  val wbBusyTableRead = Input(params.genWbFuBusyTableReadBundle())
54  val wbBusyTableWrite = Output(params.genWbFuBusyTableWriteBundle())
55  val wakeupFromWB: MixedVec[ValidIO[IssueQueueWBWakeUpBundle]] = Flipped(params.genWBWakeUpSinkValidBundle)
56  val wakeupFromIQ: MixedVec[ValidIO[IssueQueueIQWakeUpBundle]] = Flipped(params.genIQWakeUpSinkValidBundle)
57  val og0Cancel = Input(ExuOH(backendParams.numExu))
58  val og1Cancel = Input(ExuOH(backendParams.numExu))
59  val ldCancel = Vec(backendParams.LduCnt + backendParams.HyuCnt, Flipped(new LoadCancelIO))
60
61  // Outputs
62  val deq: MixedVec[DecoupledIO[IssueQueueIssueBundle]] = params.genIssueDecoupledBundle
63  val wakeupToIQ: MixedVec[ValidIO[IssueQueueIQWakeUpBundle]] = params.genIQWakeUpSourceValidBundle
64  val status = Output(new IssueQueueStatusBundle(params.numEnq, params.numEntries))
65  // val statusNext = Output(new IssueQueueStatusBundle(params.numEnq))
66
67  val fromCancelNetwork = Flipped(params.genIssueDecoupledBundle)
68  val deqDelay: MixedVec[DecoupledIO[IssueQueueIssueBundle]] = params.genIssueDecoupledBundle// = deq.cloneType
69  def allWakeUp = wakeupFromWB ++ wakeupFromIQ
70}
71
72class IssueQueueImp(override val wrapper: IssueQueue)(implicit p: Parameters, val params: IssueBlockParams)
73  extends LazyModuleImp(wrapper)
74  with HasXSParameter {
75
76  println(s"[IssueQueueImp] ${params.getIQName} wakeupFromWB(${io.wakeupFromWB.size}), " +
77    s"wakeup exu in(${params.wakeUpInExuSources.size}): ${params.wakeUpInExuSources.map(_.name).mkString("{",",","}")}, " +
78    s"wakeup exu out(${params.wakeUpOutExuSources.size}): ${params.wakeUpOutExuSources.map(_.name).mkString("{",",","}")}, " +
79    s"numEntries: ${params.numEntries}, numRegSrc: ${params.numRegSrc}")
80
81  require(params.numExu <= 2, "IssueQueue has not supported more than 2 deq ports")
82  val deqFuCfgs     : Seq[Seq[FuConfig]] = params.exuBlockParams.map(_.fuConfigs)
83  val allDeqFuCfgs  : Seq[FuConfig] = params.exuBlockParams.flatMap(_.fuConfigs)
84  val fuCfgsCnt     : Map[FuConfig, Int] = allDeqFuCfgs.groupBy(x => x).map { case (cfg, cfgSeq) => (cfg, cfgSeq.length) }
85  val commonFuCfgs  : Seq[FuConfig] = fuCfgsCnt.filter(_._2 > 1).keys.toSeq
86  val fuLatencyMaps : Seq[Map[FuType.OHType, Int]] = params.exuBlockParams.map(x => x.fuLatencyMap)
87
88  println(s"[IssueQueueImp] ${params.getIQName} fuLatencyMaps: ${fuLatencyMaps}")
89  println(s"[IssueQueueImp] ${params.getIQName} commonFuCfgs: ${commonFuCfgs.map(_.name)}")
90  lazy val io = IO(new IssueQueueIO())
91  if(backendParams.debugEn) {
92    dontTouch(io.deq)
93    dontTouch(io.deqResp)
94  }
95  // Modules
96
97  val entries = Module(new Entries)
98  val subDeqPolicies  = deqFuCfgs.map(x => if (x.nonEmpty) Some(Module(new DeqPolicy())) else None)
99  val fuBusyTableWrite = params.exuBlockParams.map { case x => OptionWrapper(x.latencyValMax > 0, Module(new FuBusyTableWrite(x.fuLatencyMap))) }
100  val fuBusyTableRead = params.exuBlockParams.map { case x => OptionWrapper(x.latencyValMax > 0, Module(new FuBusyTableRead(x.fuLatencyMap))) }
101  val intWbBusyTableWrite = params.exuBlockParams.map { case x => OptionWrapper(x.intLatencyCertain, Module(new FuBusyTableWrite(x.intFuLatencyMap))) }
102  val intWbBusyTableRead = params.exuBlockParams.map { case x => OptionWrapper(x.intLatencyCertain, Module(new FuBusyTableRead(x.intFuLatencyMap))) }
103  val vfWbBusyTableWrite = params.exuBlockParams.map { case x => OptionWrapper(x.vfLatencyCertain, Module(new FuBusyTableWrite(x.vfFuLatencyMap))) }
104  val vfWbBusyTableRead = params.exuBlockParams.map { case x => OptionWrapper(x.vfLatencyCertain, Module(new FuBusyTableRead(x.vfFuLatencyMap))) }
105
106  class WakeupQueueFlush extends Bundle {
107    val redirect = ValidIO(new Redirect)
108    val ldCancel = Vec(backendParams.LduCnt + backendParams.HyuCnt, new LoadCancelIO)
109    val og0Fail = Output(Bool())
110    val og1Fail = Output(Bool())
111  }
112
113  private def flushFunc(exuInput: ExuInput, flush: WakeupQueueFlush, stage: Int): Bool = {
114    val redirectFlush = exuInput.robIdx.needFlush(flush.redirect)
115    val loadDependencyFlush = LoadShouldCancel(exuInput.loadDependency, flush.ldCancel)
116    val ogFailFlush = stage match {
117      case 1 => flush.og0Fail
118      case 2 => flush.og1Fail
119      case _ => false.B
120    }
121    redirectFlush || loadDependencyFlush || ogFailFlush
122  }
123
124  private def modificationFunc(exuInput: ExuInput): ExuInput = {
125    val newExuInput = WireDefault(exuInput)
126    newExuInput.loadDependency match {
127      case Some(deps) => deps.zip(exuInput.loadDependency.get).foreach(x => x._1 := x._2 << 1)
128      case None =>
129    }
130    newExuInput
131  }
132
133  val wakeUpQueues: Seq[Option[MultiWakeupQueue[ExuInput, WakeupQueueFlush]]] = params.exuBlockParams.map { x => OptionWrapper(x.isIQWakeUpSource, Module(
134    new MultiWakeupQueue(new ExuInput(x), new WakeupQueueFlush, x.fuLatancySet, flushFunc, modificationFunc)
135  ))}
136
137  val intWbBusyTableIn = io.wbBusyTableRead.map(_.intWbBusyTable)
138  val vfWbBusyTableIn = io.wbBusyTableRead.map(_.vfWbBusyTable)
139  val intWbBusyTableOut = io.wbBusyTableWrite.map(_.intWbBusyTable)
140  val vfWbBusyTableOut = io.wbBusyTableWrite.map(_.vfWbBusyTable)
141  val intDeqRespSetOut = io.wbBusyTableWrite.map(_.intDeqRespSet)
142  val vfDeqRespSetOut = io.wbBusyTableWrite.map(_.vfDeqRespSet)
143  val fuBusyTableMask = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
144  val intWbBusyTableMask = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
145  val vfWbBusyTableMask = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
146  val s0_enqValidVec = io.enq.map(_.valid)
147  val s0_enqSelValidVec = Wire(Vec(params.numEnq, Bool()))
148  val s0_enqNotFlush = !io.flush.valid
149  val s0_enqBits = WireInit(VecInit(io.enq.map(_.bits)))
150  val s0_doEnqSelValidVec = s0_enqSelValidVec.map(_ && s0_enqNotFlush) //enqValid && notFlush && enqReady
151
152
153  // One deq port only need one special deq policy
154  val subDeqSelValidVec: Seq[Option[Vec[Bool]]] = subDeqPolicies.map(_.map(_ => Wire(Vec(params.numDeq, Bool()))))
155  val subDeqSelOHVec: Seq[Option[Vec[UInt]]] = subDeqPolicies.map(_.map(_ => Wire(Vec(params.numDeq, UInt(params.numEntries.W)))))
156
157  val finalDeqSelValidVec = Wire(Vec(params.numDeq, Bool()))
158  val finalDeqSelOHVec    = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
159  val finalDeqOH: IndexedSeq[UInt] = (finalDeqSelValidVec zip finalDeqSelOHVec).map { case (valid, oh) =>
160    Mux(valid, oh, 0.U)
161  }
162  val finalDeqMask: UInt = finalDeqOH.reduce(_ | _)
163
164  val deqRespVec = io.deqResp
165
166  val validVec = VecInit(entries.io.valid.asBools)
167  val canIssueVec = VecInit(entries.io.canIssue.asBools)
168  val clearVec = VecInit(entries.io.clear.asBools)
169  val deqFirstIssueVec = VecInit(entries.io.deq.map(_.isFirstIssue))
170
171  val dataSources: Vec[Vec[DataSource]] = entries.io.dataSources
172  val finalDataSources: Vec[Vec[DataSource]] = VecInit(finalDeqOH.map(oh => Mux1H(oh, dataSources)))
173  // (entryIdx)(srcIdx)(exuIdx)
174  val wakeUpL1ExuOH: Option[Vec[Vec[UInt]]] = entries.io.srcWakeUpL1ExuOH
175  val srcTimer: Option[Vec[Vec[UInt]]] = entries.io.srcTimer
176
177  // (deqIdx)(srcIdx)(exuIdx)
178  val finalWakeUpL1ExuOH: Option[Vec[Vec[UInt]]] = wakeUpL1ExuOH.map(x => VecInit(finalDeqOH.map(oh => Mux1H(oh, x))))
179  val finalSrcTimer = srcTimer.map(x => VecInit(finalDeqOH.map(oh => Mux1H(oh, x))))
180
181  val wakeupEnqSrcStateBypassFromWB: Vec[Vec[UInt]] = Wire(Vec(io.enq.size, Vec(io.enq.head.bits.srcType.size, SrcState())))
182  val wakeupEnqSrcStateBypassFromIQ: Vec[Vec[UInt]] = Wire(Vec(io.enq.size, Vec(io.enq.head.bits.srcType.size, SrcState())))
183  val srcWakeUpEnqByIQMatrix = Wire(Vec(params.numEnq, Vec(params.numRegSrc, Vec(params.numWakeupFromIQ, Bool()))))
184
185  val shiftedWakeupLoadDependencyByIQVec = Wire(Vec(params.numWakeupFromIQ, Vec(LoadPipelineWidth, UInt(3.W))))
186  shiftedWakeupLoadDependencyByIQVec
187    .zip(io.wakeupFromIQ.map(_.bits.loadDependency))
188    .zip(params.wakeUpInExuSources.map(_.name)).foreach {
189    case ((deps, originalDeps), name) => deps.zip(originalDeps).zipWithIndex.foreach {
190      case ((dep, originalDep), deqPortIdx) =>
191        if (params.backendParam.getLdExuIdx(params.backendParam.allExuParams.find(_.name == name).get) == deqPortIdx)
192          dep := (originalDep << 1).asUInt | 1.U
193        else
194          dep := originalDep << 1
195    }
196  }
197
198  for (i <- io.enq.indices) {
199    for (j <- s0_enqBits(i).srcType.indices) {
200      wakeupEnqSrcStateBypassFromWB(i)(j) := Cat(
201        io.wakeupFromWB.map(x => x.bits.wakeUp(Seq((s0_enqBits(i).psrc(j), s0_enqBits(i).srcType(j))), x.valid).head).toSeq
202      ).orR
203    }
204  }
205
206  for (i <- io.enq.indices) {
207    val numLsrc = s0_enqBits(i).srcType.size.min(entries.io.enq(i).bits.status.srcType.size)
208    for (j <- s0_enqBits(i).srcType.indices) {
209      val ldTransCancel = if (params.numWakeupFromIQ > 0 && j < numLsrc) Mux(
210        srcWakeUpEnqByIQMatrix(i)(j).asUInt.orR,
211        Mux1H(srcWakeUpEnqByIQMatrix(i)(j), io.wakeupFromIQ.map(_.bits.loadDependency).map(dep => LoadShouldCancel(Some(dep), io.ldCancel)).toSeq),
212        false.B
213      ) else false.B
214      wakeupEnqSrcStateBypassFromIQ(i)(j) := Cat(
215        io.wakeupFromIQ.map(x => x.bits.wakeUp(Seq((s0_enqBits(i).psrc(j), s0_enqBits(i).srcType(j))), x.valid).head).toSeq
216      ).orR && !ldTransCancel
217    }
218  }
219
220  srcWakeUpEnqByIQMatrix.zipWithIndex.foreach { case (wakeups: Vec[Vec[Bool]], i) =>
221    if (io.wakeupFromIQ.isEmpty) {
222      wakeups := 0.U.asTypeOf(wakeups)
223    } else {
224      val wakeupVec: IndexedSeq[IndexedSeq[Bool]] = io.wakeupFromIQ.map((bundle: ValidIO[IssueQueueIQWakeUpBundle]) =>
225        bundle.bits.wakeUp(s0_enqBits(i).psrc.take(params.numRegSrc) zip s0_enqBits(i).srcType.take(params.numRegSrc), bundle.valid)
226      ).toIndexedSeq.transpose
227      wakeups := wakeupVec.map(x => VecInit(x))
228    }
229  }
230
231  val fuTypeVec = Wire(Vec(params.numEntries, FuType()))
232  val transEntryDeqVec = Wire(Vec(params.numEnq, ValidIO(new EntryBundle)))
233  val deqEntryVec = Wire(Vec(params.numDeq, ValidIO(new EntryBundle)))
234  val transSelVec = Wire(Vec(params.numEnq, UInt((params.numEntries-params.numEnq).W)))
235
236  val enqEntryOldestSel = Wire(Vec(params.numDeq, ValidIO(UInt(params.numEnq.W))))
237  val othersEntryOldestSel = Wire(Vec(params.numDeq, ValidIO(UInt((params.numEntries - params.numEnq).W))))
238  val subDeqPolicyRequest = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
239  val canIssueMergeAllBusy = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
240
241  /**
242    * Connection of [[entries]]
243    */
244  entries.io match { case entriesIO: EntriesIO =>
245    entriesIO.flush <> io.flush
246    entriesIO.wakeUpFromWB := io.wakeupFromWB
247    entriesIO.wakeUpFromIQ := io.wakeupFromIQ
248    entriesIO.og0Cancel := io.og0Cancel
249    entriesIO.og1Cancel := io.og1Cancel
250    entriesIO.ldCancel := io.ldCancel
251    entriesIO.enq.zipWithIndex.foreach { case (enq: ValidIO[EntryBundle], i) =>
252      enq.valid := s0_doEnqSelValidVec(i)
253      val numLsrc = s0_enqBits(i).srcType.size.min(enq.bits.status.srcType.size)
254      for(j <- 0 until numLsrc) {
255        enq.bits.status.srcState(j) := s0_enqBits(i).srcState(j) |
256                                       wakeupEnqSrcStateBypassFromWB(i)(j) |
257                                       wakeupEnqSrcStateBypassFromIQ(i)(j)
258        enq.bits.status.psrc(j) := s0_enqBits(i).psrc(j)
259        enq.bits.status.srcType(j) := s0_enqBits(i).srcType(j)
260        enq.bits.status.dataSources(j).value := Mux(wakeupEnqSrcStateBypassFromIQ(i)(j).asBool, DataSource.forward, s0_enqBits(i).dataSource(j).value)
261        enq.bits.payload.debugInfo.enqRsTime := GTimer()
262      }
263      enq.bits.status.fuType := s0_enqBits(i).fuType
264      enq.bits.status.robIdx := s0_enqBits(i).robIdx
265      enq.bits.status.uopIdx.foreach(_ := s0_enqBits(i).uopIdx)
266      enq.bits.status.issueTimer := "b11".U
267      enq.bits.status.deqPortIdx := 0.U
268      enq.bits.status.issued := false.B
269      enq.bits.status.firstIssue := false.B
270      enq.bits.status.blocked := false.B
271      enq.bits.status.srcWakeUpL1ExuOH match {
272        case Some(value) => value.zip(srcWakeUpEnqByIQMatrix(i)).zipWithIndex.foreach {
273          case ((exuOH, wakeUpByIQOH), srcIdx) =>
274            when(wakeUpByIQOH.asUInt.orR) {
275              exuOH := Mux1H(wakeUpByIQOH, io.wakeupFromIQ.toSeq.map(x => MathUtils.IntToOH(x.bits.exuIdx).U(backendParams.numExu.W)))
276            }.otherwise {
277              exuOH := s0_enqBits(i).l1ExuOH(srcIdx)
278            }
279        }
280        case None =>
281      }
282      enq.bits.status.srcTimer match {
283        case Some(value) => value.zip(srcWakeUpEnqByIQMatrix(i)).zipWithIndex.foreach {
284          case ((timer, wakeUpByIQOH), srcIdx) =>
285            when(wakeUpByIQOH.asUInt.orR) {
286              timer := 1.U.asTypeOf(timer)
287            }.otherwise {
288              timer := Mux(s0_enqBits(i).dataSource(srcIdx).value === DataSource.bypass, 2.U.asTypeOf(timer), 0.U.asTypeOf(timer))
289            }
290        }
291        case None =>
292      }
293      enq.bits.status.srcLoadDependency.foreach(_.zip(srcWakeUpEnqByIQMatrix(i)).zipWithIndex.foreach {
294        case ((dep, wakeUpByIQOH), srcIdx) =>
295          dep := Mux(wakeUpByIQOH.asUInt.orR, Mux1H(wakeUpByIQOH, shiftedWakeupLoadDependencyByIQVec), 0.U.asTypeOf(dep))
296      })
297      enq.bits.imm := s0_enqBits(i).imm
298      enq.bits.payload := s0_enqBits(i)
299    }
300    entriesIO.deq.zipWithIndex.foreach { case (deq, i) =>
301      deq.enqEntryOldestSel := enqEntryOldestSel(i)
302      deq.othersEntryOldestSel := othersEntryOldestSel(i)
303      deq.subDeqPolicyRequest := { if (subDeqPolicies(i).nonEmpty) subDeqPolicyRequest(i) else 0.U }
304      deq.subDeqSelOH := subDeqSelOHVec(i).getOrElse(Seq(0.U, 0.U))
305      deq.finalDeqSelOH.valid := finalDeqSelValidVec(i)
306      deq.finalDeqSelOH.bits := finalDeqSelOHVec(i)
307    }
308    entriesIO.deqResp.zipWithIndex.foreach { case (deqResp, i) =>
309      deqResp.valid := io.deqResp(i).valid
310      deqResp.bits.robIdx := io.deqResp(i).bits.robIdx
311      deqResp.bits.uopIdx := io.deqResp(i).bits.uopIdx
312      deqResp.bits.dataInvalidSqIdx := io.deqResp(i).bits.dataInvalidSqIdx
313      deqResp.bits.respType := io.deqResp(i).bits.respType
314      deqResp.bits.rfWen := io.deqResp(i).bits.rfWen
315      deqResp.bits.fuType := io.deqResp(i).bits.fuType
316    }
317    entriesIO.og0Resp.zipWithIndex.foreach { case (og0Resp, i) =>
318      og0Resp.valid := io.og0Resp(i).valid
319      og0Resp.bits.robIdx := io.og0Resp(i).bits.robIdx
320      og0Resp.bits.uopIdx := io.og0Resp(i).bits.uopIdx
321      og0Resp.bits.dataInvalidSqIdx := io.og0Resp(i).bits.dataInvalidSqIdx
322      og0Resp.bits.respType := io.og0Resp(i).bits.respType
323      og0Resp.bits.rfWen := io.og0Resp(i).bits.rfWen
324      og0Resp.bits.fuType := io.og0Resp(i).bits.fuType
325    }
326    entriesIO.og1Resp.zipWithIndex.foreach { case (og1Resp, i) =>
327      og1Resp.valid := io.og1Resp(i).valid
328      og1Resp.bits.robIdx := io.og1Resp(i).bits.robIdx
329      og1Resp.bits.uopIdx := io.og1Resp(i).bits.uopIdx
330      og1Resp.bits.dataInvalidSqIdx := io.og1Resp(i).bits.dataInvalidSqIdx
331      og1Resp.bits.respType := io.og1Resp(i).bits.respType
332      og1Resp.bits.rfWen := io.og1Resp(i).bits.rfWen
333      og1Resp.bits.fuType := io.og1Resp(i).bits.fuType
334    }
335    entriesIO.finalIssueResp.foreach(_.zipWithIndex.foreach { case (finalIssueResp, i) =>
336      finalIssueResp := io.finalIssueResp.get(i)
337    })
338    entriesIO.memAddrIssueResp.foreach(_.zipWithIndex.foreach { case (memAddrIssueResp, i) =>
339      memAddrIssueResp := io.memAddrIssueResp.get(i)
340    })
341    transEntryDeqVec := entriesIO.transEntryDeqVec
342    deqEntryVec := entriesIO.deq.map(_.deqEntry)
343    fuTypeVec := entriesIO.fuType
344    transSelVec := entriesIO.transSelVec
345  }
346
347
348  s0_enqSelValidVec := s0_enqValidVec.zip(io.enq).map{ case (enqValid, enq) => enqValid && enq.ready}
349
350  protected val commonAccept: UInt = Cat(fuTypeVec.map(fuType =>
351    FuType.FuTypeOrR(fuType, commonFuCfgs.map(_.fuType))
352  ).reverse)
353
354  // if deq port can accept the uop
355  protected val canAcceptVec: Seq[UInt] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
356    Cat(fuTypeVec.map(fuType =>
357      FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType))
358    ).reverse)
359  }
360
361  protected val deqCanAcceptVec: Seq[IndexedSeq[Bool]] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
362    fuTypeVec.map(fuType =>
363      FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType))) // C+E0    C+E1
364  }
365
366  canIssueMergeAllBusy.zipWithIndex.foreach { case (merge, i) =>
367    val mergeFuBusy = {
368      if (fuBusyTableWrite(i).nonEmpty) canIssueVec.asUInt & (~fuBusyTableMask(i))
369      else canIssueVec.asUInt
370    }
371    val mergeIntWbBusy = {
372      if (intWbBusyTableRead(i).nonEmpty) mergeFuBusy & (~intWbBusyTableMask(i))
373      else mergeFuBusy
374    }
375    val mergeVfWbBusy = {
376      if (vfWbBusyTableRead(i).nonEmpty) mergeIntWbBusy & (~vfWbBusyTableMask(i))
377      else mergeIntWbBusy
378    }
379    merge := mergeVfWbBusy
380  }
381
382  subDeqPolicyRequest.zipWithIndex.foreach { case (req, i) =>
383    req := canIssueMergeAllBusy(i) & VecInit(deqCanAcceptVec(i)).asUInt
384  }
385
386  subDeqPolicies.zipWithIndex.foreach { case (dpOption: Option[DeqPolicy], i) =>
387    if (dpOption.nonEmpty) {
388      val dp = dpOption.get
389      dp.io.request             := subDeqPolicyRequest(i)
390      subDeqSelValidVec(i).get  := dp.io.deqSelOHVec.map(oh => oh.valid)
391      subDeqSelOHVec(i).get     := dp.io.deqSelOHVec.map(oh => oh.bits)
392    }
393  }
394
395  protected val enqCanAcceptVec: Seq[IndexedSeq[Bool]] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
396    io.enq.map(_.bits.fuType).map(fuType =>
397      FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType))) // C+E0    C+E1
398  }
399
400  protected val transCanAcceptVec: Seq[IndexedSeq[Bool]] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
401    transEntryDeqVec.map(_.bits.status.fuType).zip(transEntryDeqVec.map(_.valid)).map{ case (fuType, valid) =>
402      FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType)) && valid }
403  }
404
405  enqEntryOldestSel.zipWithIndex.foreach { case (sel, deqIdx) =>
406    sel := NewAgeDetector(numEntries = params.numEnq,
407        enq = VecInit(enqCanAcceptVec(deqIdx).zip(s0_doEnqSelValidVec).map{ case (doCanAccept, valid) => doCanAccept && valid }),
408        clear = VecInit(clearVec.take(params.numEnq)),
409        canIssue = canIssueMergeAllBusy(deqIdx)(params.numEnq-1, 0)
410      )
411  }
412
413  othersEntryOldestSel.zipWithIndex.foreach { case (sel, deqIdx) =>
414    sel := AgeDetector(numEntries = params.numEntries - params.numEnq,
415        enq = VecInit(transCanAcceptVec(deqIdx).zip(transSelVec).map{ case(doCanAccept, transSel) => Mux(doCanAccept, transSel, 0.U)}),
416        deq = VecInit(clearVec.drop(params.numEnq)).asUInt,
417        canIssue = canIssueMergeAllBusy(deqIdx)(params.numEntries-1, params.numEnq)
418      )
419  }
420
421  finalDeqSelValidVec.head := othersEntryOldestSel.head.valid || enqEntryOldestSel.head.valid || subDeqSelValidVec.head.getOrElse(Seq(false.B)).head
422  finalDeqSelOHVec.head := Mux(othersEntryOldestSel.head.valid, Cat(othersEntryOldestSel.head.bits, 0.U((params.numEnq).W)),
423                            Mux(enqEntryOldestSel.head.valid, Cat(0.U((params.numEntries-params.numEnq).W), enqEntryOldestSel.head.bits),
424                              subDeqSelOHVec.head.getOrElse(Seq(0.U)).head))
425
426  if (params.numDeq == 2) {
427    params.getFuCfgs.contains(FuConfig.FakeHystaCfg) match {
428      case true =>
429        finalDeqSelValidVec(1) := false.B
430        finalDeqSelOHVec(1) := 0.U.asTypeOf(finalDeqSelOHVec(1))
431      case false =>
432        val chooseOthersOldest = othersEntryOldestSel(1).valid && Cat(othersEntryOldestSel(1).bits, 0.U((params.numEnq).W)) =/= finalDeqSelOHVec.head
433        val chooseEnqOldest = enqEntryOldestSel(1).valid && Cat(0.U((params.numEntries-params.numEnq).W), enqEntryOldestSel(1).bits) =/= finalDeqSelOHVec.head
434        val choose1stSub = subDeqSelOHVec(1).getOrElse(Seq(0.U)).head =/= finalDeqSelOHVec.head
435
436        finalDeqSelValidVec(1) := MuxCase(subDeqSelValidVec(1).getOrElse(Seq(false.B)).last, Seq(
437          (chooseOthersOldest) -> othersEntryOldestSel(1).valid,
438          (chooseEnqOldest) -> enqEntryOldestSel(1).valid,
439          (choose1stSub) -> subDeqSelValidVec(1).getOrElse(Seq(false.B)).head)
440        )
441        finalDeqSelOHVec(1) := MuxCase(subDeqSelOHVec(1).getOrElse(Seq(0.U)).last, Seq(
442          (chooseOthersOldest) -> Cat(othersEntryOldestSel(1).bits, 0.U((params.numEnq).W)),
443          (chooseEnqOldest) -> Cat(0.U((params.numEntries-params.numEnq).W), enqEntryOldestSel(1).bits),
444          (choose1stSub) -> subDeqSelOHVec(1).getOrElse(Seq(0.U)).head)
445        )
446    }
447  }
448
449  //fuBusyTable
450  fuBusyTableWrite.zip(fuBusyTableRead).zipWithIndex.foreach { case ((busyTableWrite: Option[FuBusyTableWrite], busyTableRead: Option[FuBusyTableRead]), i) =>
451    if(busyTableWrite.nonEmpty) {
452      val btwr = busyTableWrite.get
453      val btrd = busyTableRead.get
454      btwr.io.in.deqResp := io.deqResp(i)
455      btwr.io.in.og0Resp := io.og0Resp(i)
456      btwr.io.in.og1Resp := io.og1Resp(i)
457      btrd.io.in.fuBusyTable := btwr.io.out.fuBusyTable
458      btrd.io.in.fuTypeRegVec := fuTypeVec
459      fuBusyTableMask(i) := btrd.io.out.fuBusyTableMask
460    }
461    else {
462      fuBusyTableMask(i) := 0.U(params.numEntries.W)
463    }
464  }
465
466  //wbfuBusyTable write
467  intWbBusyTableWrite.zip(intWbBusyTableOut).zip(intDeqRespSetOut).zipWithIndex.foreach { case (((busyTableWrite: Option[FuBusyTableWrite], busyTable: Option[UInt]), deqResp), i) =>
468    if(busyTableWrite.nonEmpty) {
469      val btwr = busyTableWrite.get
470      val bt = busyTable.get
471      val dq = deqResp.get
472      btwr.io.in.deqResp := io.deqResp(i)
473      btwr.io.in.og0Resp := io.og0Resp(i)
474      btwr.io.in.og1Resp := io.og1Resp(i)
475      bt := btwr.io.out.fuBusyTable
476      dq := btwr.io.out.deqRespSet
477    }
478  }
479
480  vfWbBusyTableWrite.zip(vfWbBusyTableOut).zip(vfDeqRespSetOut).zipWithIndex.foreach { case (((busyTableWrite: Option[FuBusyTableWrite], busyTable: Option[UInt]), deqResp), i) =>
481    if (busyTableWrite.nonEmpty) {
482      val btwr = busyTableWrite.get
483      val bt = busyTable.get
484      val dq = deqResp.get
485      btwr.io.in.deqResp := io.deqResp(i)
486      btwr.io.in.og0Resp := io.og0Resp(i)
487      btwr.io.in.og1Resp := io.og1Resp(i)
488      bt := btwr.io.out.fuBusyTable
489      dq := btwr.io.out.deqRespSet
490    }
491  }
492
493  //wbfuBusyTable read
494  intWbBusyTableRead.zip(intWbBusyTableIn).zipWithIndex.foreach { case ((busyTableRead: Option[FuBusyTableRead], busyTable: Option[UInt]), i) =>
495    if(busyTableRead.nonEmpty) {
496      val btrd = busyTableRead.get
497      val bt = busyTable.get
498      btrd.io.in.fuBusyTable := bt
499      btrd.io.in.fuTypeRegVec := fuTypeVec
500      intWbBusyTableMask(i) := btrd.io.out.fuBusyTableMask
501    }
502    else {
503      intWbBusyTableMask(i) := 0.U(params.numEntries.W)
504    }
505  }
506  vfWbBusyTableRead.zip(vfWbBusyTableIn).zipWithIndex.foreach { case ((busyTableRead: Option[FuBusyTableRead], busyTable: Option[UInt]), i) =>
507    if (busyTableRead.nonEmpty) {
508      val btrd = busyTableRead.get
509      val bt = busyTable.get
510      btrd.io.in.fuBusyTable := bt
511      btrd.io.in.fuTypeRegVec := fuTypeVec
512      vfWbBusyTableMask(i) := btrd.io.out.fuBusyTableMask
513    }
514    else {
515      vfWbBusyTableMask(i) := 0.U(params.numEntries.W)
516    }
517  }
518
519  wakeUpQueues.zipWithIndex.foreach { case (wakeUpQueueOption, i) =>
520    val og0RespEach = io.og0Resp(i)
521    val og1RespEach = io.og1Resp(i)
522    wakeUpQueueOption.foreach {
523      wakeUpQueue =>
524        val flush = Wire(new WakeupQueueFlush)
525        flush.redirect := io.flush
526        flush.ldCancel := io.ldCancel
527        flush.og0Fail := io.og0Resp(i).valid && RSFeedbackType.isBlocked(io.og0Resp(i).bits.respType)
528        flush.og1Fail := io.og1Resp(i).valid && RSFeedbackType.isBlocked(io.og1Resp(i).bits.respType)
529        wakeUpQueue.io.flush := flush
530        wakeUpQueue.io.enq.valid := io.deq(i).fire && !io.deq(i).bits.common.needCancel(io.og0Cancel, io.og1Cancel) && {
531          io.deq(i).bits.common.rfWen.getOrElse(false.B) && io.deq(i).bits.common.pdest =/= 0.U ||
532          io.deq(i).bits.common.fpWen.getOrElse(false.B) ||
533          io.deq(i).bits.common.vecWen.getOrElse(false.B)
534        }
535        wakeUpQueue.io.enq.bits.uop := io.deq(i).bits.common
536        wakeUpQueue.io.enq.bits.lat := getDeqLat(i, io.deq(i).bits.common.fuType)
537        wakeUpQueue.io.og0IssueFail := flush.og0Fail
538        wakeUpQueue.io.og1IssueFail := flush.og1Fail
539    }
540  }
541
542  io.deq.zipWithIndex.foreach { case (deq, i) =>
543    deq.valid                := finalDeqSelValidVec(i)
544    deq.bits.addrOH          := finalDeqSelOHVec(i)
545    deq.bits.common.isFirstIssue := deqFirstIssueVec(i)
546    deq.bits.common.iqIdx    := OHToUInt(finalDeqSelOHVec(i))
547    deq.bits.common.fuType   := deqEntryVec(i).bits.payload.fuType
548    deq.bits.common.fuOpType := deqEntryVec(i).bits.payload.fuOpType
549    deq.bits.common.rfWen.foreach(_ := deqEntryVec(i).bits.payload.rfWen)
550    deq.bits.common.fpWen.foreach(_ := deqEntryVec(i).bits.payload.fpWen)
551    deq.bits.common.vecWen.foreach(_ := deqEntryVec(i).bits.payload.vecWen)
552    deq.bits.common.flushPipe.foreach(_ := deqEntryVec(i).bits.payload.flushPipe)
553    deq.bits.common.pdest := deqEntryVec(i).bits.payload.pdest
554    deq.bits.common.robIdx := deqEntryVec(i).bits.payload.robIdx
555    deq.bits.common.dataSources.zip(finalDataSources(i)).zipWithIndex.foreach {
556      case ((sink, source), srcIdx) =>
557        sink.value := Mux(
558          SrcType.isXp(deqEntryVec(i).bits.payload.srcType(srcIdx)) && deqEntryVec(i).bits.payload.psrc(srcIdx) === 0.U,
559          DataSource.none,
560          source.value
561        )
562    }
563    if (deq.bits.common.l1ExuOH.size > 0) {
564      if (params.hasIQWakeUp) {
565        deq.bits.common.l1ExuOH := finalWakeUpL1ExuOH.get(i)
566      } else {
567        deq.bits.common.l1ExuOH := deqEntryVec(i).bits.payload.l1ExuOH.take(deq.bits.common.l1ExuOH.length)
568      }
569    }
570    deq.bits.common.srcTimer.foreach(_ := finalSrcTimer.get(i))
571    deq.bits.common.loadDependency.foreach(_ := deqEntryVec(i).bits.status.mergedLoadDependency.get)
572    deq.bits.common.deqLdExuIdx.foreach(_ := params.backendParam.getLdExuIdx(deq.bits.exuParams).U)
573    deq.bits.common.src := DontCare
574    deq.bits.common.preDecode.foreach(_ := deqEntryVec(i).bits.payload.preDecodeInfo)
575
576    deq.bits.rf.zip(deqEntryVec(i).bits.payload.psrc).foreach { case (rf, psrc) =>
577      rf.foreach(_.addr := psrc) // psrc in payload array can be pregIdx of IntRegFile or VfRegFile
578    }
579    deq.bits.rf.zip(deqEntryVec(i).bits.payload.srcType).foreach { case (rf, srcType) =>
580      rf.foreach(_.srcType := srcType) // psrc in payload array can be pregIdx of IntRegFile or VfRegFile
581    }
582    deq.bits.srcType.zip(deqEntryVec(i).bits.payload.srcType).foreach { case (sink, source) =>
583      sink := source
584    }
585    deq.bits.immType := deqEntryVec(i).bits.payload.selImm
586
587    if (params.inIntSchd && params.AluCnt > 0) {
588      // dirty code for lui+addi(w) fusion
589      val isLuiAddiFusion = deqEntryVec(i).bits.payload.isLUI32
590      val luiImm = Cat(deqEntryVec(i).bits.payload.lsrc(1), deqEntryVec(i).bits.payload.lsrc(0), deqEntryVec(i).bits.imm(ImmUnion.maxLen - 1, 0))
591      deq.bits.common.imm := Mux(isLuiAddiFusion, ImmUnion.LUI32.toImm32(luiImm), deqEntryVec(i).bits.imm)
592    }
593    else if (params.inMemSchd && params.LduCnt > 0) {
594      // dirty code for fused_lui_load
595      val isLuiLoadFusion = SrcType.isNotReg(deqEntryVec(i).bits.payload.srcType(0)) && FuType.isLoad(deqEntryVec(i).bits.payload.fuType)
596      deq.bits.common.imm := Mux(isLuiLoadFusion, Imm_LUI_LOAD().getLuiImm(deqEntryVec(i).bits.payload), deqEntryVec(i).bits.imm)
597    }
598    else {
599      deq.bits.common.imm := deqEntryVec(i).bits.imm
600    }
601
602    deq.bits.common.perfDebugInfo := deqEntryVec(i).bits.payload.debugInfo
603    deq.bits.common.perfDebugInfo.selectTime := GTimer()
604    deq.bits.common.perfDebugInfo.issueTime := GTimer() + 1.U
605  }
606
607  private val ldCancels = io.fromCancelNetwork.map(in =>
608    LoadShouldCancel(in.bits.common.loadDependency, io.ldCancel)
609  )
610  private val fromCancelNetworkShift = WireDefault(io.fromCancelNetwork)
611  fromCancelNetworkShift.zip(io.fromCancelNetwork).foreach {
612    case (shifted, original) =>
613      original.ready := shifted.ready // this will not cause combinational loop
614      shifted.bits.common.loadDependency.foreach(
615        _ := original.bits.common.loadDependency.get.map(_ << 1)
616      )
617  }
618  io.deqDelay.zip(fromCancelNetworkShift).zip(ldCancels).foreach { case ((deqDly, deq), ldCancel) =>
619    NewPipelineConnect(
620      deq, deqDly, deqDly.valid,
621      deq.bits.common.robIdx.needFlush(io.flush) || ldCancel,
622      Option("Scheduler2DataPathPipe")
623    )
624  }
625  if(backendParams.debugEn) {
626    dontTouch(io.deqDelay)
627  }
628  io.wakeupToIQ.zipWithIndex.foreach { case (wakeup, i) =>
629    if (wakeUpQueues(i).nonEmpty && finalWakeUpL1ExuOH.nonEmpty) {
630      wakeup.valid := wakeUpQueues(i).get.io.deq.valid
631      wakeup.bits.fromExuInput(wakeUpQueues(i).get.io.deq.bits, finalWakeUpL1ExuOH.get(i))
632      wakeup.bits.loadDependency := wakeUpQueues(i).get.io.deq.bits.loadDependency.getOrElse(0.U.asTypeOf(wakeup.bits.loadDependency))
633    } else if (wakeUpQueues(i).nonEmpty) {
634      wakeup.valid := wakeUpQueues(i).get.io.deq.valid
635      wakeup.bits.fromExuInput(wakeUpQueues(i).get.io.deq.bits)
636      wakeup.bits.loadDependency := wakeUpQueues(i).get.io.deq.bits.loadDependency.getOrElse(0.U.asTypeOf(wakeup.bits.loadDependency))
637    } else {
638      wakeup.valid := false.B
639      wakeup.bits := 0.U.asTypeOf(wakeup.bits)
640    }
641  }
642
643  // Todo: better counter implementation
644  private val enqHasValid = validVec.take(params.numEnq).reduce(_ | _)
645  private val enqEntryValidCnt = PopCount(validVec.take(params.numEnq))
646  private val othersValidCnt = PopCount(validVec.drop(params.numEnq))
647  io.status.leftVec(0) := validVec.drop(params.numEnq).reduce(_ & _)
648  for (i <- 0 until params.numEnq) {
649    io.status.leftVec(i + 1) := othersValidCnt === (params.numEntries - params.numEnq - (i + 1)).U
650  }
651  io.enq.foreach(_.ready := !Cat(io.status.leftVec).orR || !enqHasValid) // Todo: more efficient implementation
652  io.status.empty := !Cat(validVec).orR
653  io.status.full := Cat(io.status.leftVec).orR
654  io.status.validCnt := PopCount(validVec)
655
656  protected def getDeqLat(deqPortIdx: Int, fuType: UInt) : UInt = {
657    Mux1H(fuLatencyMaps(deqPortIdx) map { case (k, v) => (fuType(k.id), v.U) })
658  }
659
660  // issue perf counter
661  // enq count
662  XSPerfAccumulate("enq_valid_cnt", PopCount(io.enq.map(_.fire)))
663  XSPerfAccumulate("enq_fire_cnt", PopCount(io.enq.map(_.fire)))
664  // valid count
665  XSPerfHistogram("enq_entry_valid_cnt", enqEntryValidCnt, true.B, 0, params.numEnq + 1)
666  XSPerfHistogram("other_entry_valid_cnt", othersValidCnt, true.B, 0, params.numEntries - params.numEnq + 1)
667  XSPerfHistogram("valid_cnt", PopCount(validVec), true.B, 0, params.numEntries + 1)
668  // only split when more than 1 func type
669  if (params.getFuCfgs.size > 0) {
670    for (t <- FuType.functionNameMap.keys) {
671      val fuName = FuType.functionNameMap(t)
672      if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
673        XSPerfHistogram(s"valid_cnt_hist_futype_${fuName}", PopCount(validVec.zip(fuTypeVec).map { case (v, fu) => v && fu === t.U }), true.B, 0, params.numEntries, 1)
674      }
675    }
676  }
677  // ready instr count
678  private val readyEntriesCnt = PopCount(validVec.zip(canIssueVec).map(x => x._1 && x._2))
679  XSPerfHistogram("ready_cnt", readyEntriesCnt, true.B, 0, params.numEntries + 1)
680  // only split when more than 1 func type
681  if (params.getFuCfgs.size > 0) {
682    for (t <- FuType.functionNameMap.keys) {
683      val fuName = FuType.functionNameMap(t)
684      if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
685        XSPerfHistogram(s"ready_cnt_hist_futype_${fuName}", PopCount(validVec.zip(canIssueVec).zip(fuTypeVec).map { case ((v, c), fu) => v && c && fu === t.U }), true.B, 0, params.numEntries, 1)
686      }
687    }
688  }
689
690  // deq instr count
691  XSPerfAccumulate("issue_instr_pre_count", PopCount(io.deq.map(_.valid)))
692  XSPerfHistogram("issue_instr_pre_count_hist", PopCount(io.deq.map(_.valid)), true.B, 0, params.numDeq + 1, 1)
693  XSPerfAccumulate("issue_instr_count", PopCount(io.deqDelay.map(_.valid)))
694  XSPerfHistogram("issue_instr_count_hist", PopCount(io.deqDelay.map(_.valid)), true.B, 0, params.numDeq + 1, 1)
695
696  // deq instr data source count
697  XSPerfAccumulate("issue_datasource_reg", io.deq.map{ deq =>
698    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) })
699  }.reduce(_ +& _))
700  XSPerfAccumulate("issue_datasource_bypass", io.deq.map{ deq =>
701    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) })
702  }.reduce(_ +& _))
703  XSPerfAccumulate("issue_datasource_forward", io.deq.map{ deq =>
704    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) })
705  }.reduce(_ +& _))
706  XSPerfAccumulate("issue_datasource_noreg", io.deq.map{ deq =>
707    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) })
708  }.reduce(_ +& _))
709
710  XSPerfHistogram("issue_datasource_reg_hist", io.deq.map{ deq =>
711    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) })
712  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
713  XSPerfHistogram("issue_datasource_bypass_hist", io.deq.map{ deq =>
714    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) })
715  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
716  XSPerfHistogram("issue_datasource_forward_hist", io.deq.map{ deq =>
717    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) })
718  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
719  XSPerfHistogram("issue_datasource_noreg_hist", io.deq.map{ deq =>
720    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) })
721  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
722
723  // deq instr data source count for each futype
724  for (t <- FuType.functionNameMap.keys) {
725    val fuName = FuType.functionNameMap(t)
726    if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
727      XSPerfAccumulate(s"issue_datasource_reg_futype_${fuName}", io.deq.map{ deq =>
728        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
729      }.reduce(_ +& _))
730      XSPerfAccumulate(s"issue_datasource_bypass_futype_${fuName}", io.deq.map{ deq =>
731        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
732      }.reduce(_ +& _))
733      XSPerfAccumulate(s"issue_datasource_forward_futype_${fuName}", io.deq.map{ deq =>
734        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
735      }.reduce(_ +& _))
736      XSPerfAccumulate(s"issue_datasource_noreg_futype_${fuName}", io.deq.map{ deq =>
737        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
738      }.reduce(_ +& _))
739
740      XSPerfHistogram(s"issue_datasource_reg_hist_futype_${fuName}", io.deq.map{ deq =>
741        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
742      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
743      XSPerfHistogram(s"issue_datasource_bypass_hist_futype_${fuName}", io.deq.map{ deq =>
744        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
745      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
746      XSPerfHistogram(s"issue_datasource_forward_hist_futype_${fuName}", io.deq.map{ deq =>
747        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
748      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
749      XSPerfHistogram(s"issue_datasource_noreg_hist_futype_${fuName}", io.deq.map{ deq =>
750        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
751      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
752    }
753  }
754
755  // cancel instr count
756  if (params.hasIQWakeUp) {
757    val cancelVec: Vec[Bool] = entries.io.cancel.get
758    XSPerfAccumulate("cancel_instr_count", PopCount(validVec.zip(cancelVec).map(x => x._1 & x._2)))
759    XSPerfHistogram("cancel_instr_hist", PopCount(validVec.zip(cancelVec).map(x => x._1 & x._2)), true.B, 0, params.numEntries, 1)
760    for (t <- FuType.functionNameMap.keys) {
761      val fuName = FuType.functionNameMap(t)
762      if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
763        XSPerfAccumulate(s"cancel_instr_count_futype_${fuName}", PopCount(validVec.zip(cancelVec).zip(fuTypeVec).map{ case ((x, y), fu) => x & y & fu === t.U }))
764        XSPerfHistogram(s"cancel_instr_hist_futype_${fuName}", PopCount(validVec.zip(cancelVec).zip(fuTypeVec).map{ case ((x, y), fu) => x & y & fu === t.U }), true.B, 0, params.numEntries, 1)
765      }
766    }
767  }
768}
769
770class IssueQueueJumpBundle extends Bundle {
771  val pc = UInt(VAddrData().dataWidth.W)
772}
773
774class IssueQueueLoadBundle(implicit p: Parameters) extends XSBundle {
775  val fastMatch = UInt(backendParams.LduCnt.W)
776  val fastImm = UInt(12.W)
777}
778
779class IssueQueueIntIO()(implicit p: Parameters, params: IssueBlockParams) extends IssueQueueIO
780
781class IssueQueueIntImp(override val wrapper: IssueQueue)(implicit p: Parameters, iqParams: IssueBlockParams)
782  extends IssueQueueImp(wrapper)
783{
784  io.suggestName("none")
785  override lazy val io = IO(new IssueQueueIntIO).suggestName("io")
786
787  if(params.needPc) {
788    entries.io.enq.zipWithIndex.foreach { case (entriesEnq, i) =>
789      entriesEnq.bits.status.pc.foreach(_ := io.enq(i).bits.pc)
790    }
791  }
792
793  io.deq.zipWithIndex.foreach{ case (deq, i) => {
794    deq.bits.common.pc.foreach(_ := deqEntryVec(i).bits.status.pc.get)
795    deq.bits.common.preDecode.foreach(_ := deqEntryVec(i).bits.payload.preDecodeInfo)
796    deq.bits.common.ftqIdx.foreach(_ := deqEntryVec(i).bits.payload.ftqPtr)
797    deq.bits.common.ftqOffset.foreach(_ := deqEntryVec(i).bits.payload.ftqOffset)
798    deq.bits.common.predictInfo.foreach(x => {
799      x.target := DontCare
800      x.taken := deqEntryVec(i).bits.payload.pred_taken
801    })
802    // for std
803    deq.bits.common.sqIdx.foreach(_ := deqEntryVec(i).bits.payload.sqIdx)
804    // for i2f
805    deq.bits.common.fpu.foreach(_ := deqEntryVec(i).bits.payload.fpu)
806  }}
807}
808
809class IssueQueueVfImp(override val wrapper: IssueQueue)(implicit p: Parameters, iqParams: IssueBlockParams)
810  extends IssueQueueImp(wrapper)
811{
812  s0_enqBits.foreach{ x =>
813    x.srcType(3) := SrcType.vp // v0: mask src
814    x.srcType(4) := SrcType.vp // vl&vtype
815  }
816  io.deq.zipWithIndex.foreach{ case (deq, i) => {
817    deq.bits.common.fpu.foreach(_ := deqEntryVec(i).bits.payload.fpu)
818    deq.bits.common.vpu.foreach(_ := deqEntryVec(i).bits.payload.vpu)
819    deq.bits.common.vpu.foreach(_.vuopIdx := deqEntryVec(i).bits.payload.uopIdx)
820    deq.bits.common.vpu.foreach(_.lastUop := deqEntryVec(i).bits.payload.lastUop)
821  }}
822}
823
824class IssueQueueMemBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
825  val feedbackIO = Flipped(Vec(params.numDeq, new MemRSFeedbackIO))
826  val checkWait = new Bundle {
827    val stIssuePtr = Input(new SqPtr)
828    val memWaitUpdateReq = Flipped(new MemWaitUpdateReq)
829  }
830  val loadFastMatch = Output(Vec(params.LduCnt, new IssueQueueLoadBundle))
831
832  // vector
833  val sqDeqPtr = OptionWrapper(params.isVecMemIQ, Input(new SqPtr))
834  val lqDeqPtr = OptionWrapper(params.isVecMemIQ, Input(new LqPtr))
835}
836
837class IssueQueueMemIO(implicit p: Parameters, params: IssueBlockParams) extends IssueQueueIO {
838  val memIO = Some(new IssueQueueMemBundle)
839}
840
841class IssueQueueMemAddrImp(override val wrapper: IssueQueue)(implicit p: Parameters, params: IssueBlockParams)
842  extends IssueQueueImp(wrapper) with HasCircularQueuePtrHelper {
843
844  require(params.StdCnt == 0 && (params.LduCnt + params.StaCnt + params.HyuCnt + params.VlduCnt) > 0, "IssueQueueMemAddrImp can only be instance of MemAddr IQ, " +
845    s"StdCnt: ${params.StdCnt}, LduCnt: ${params.LduCnt}, StaCnt: ${params.StaCnt}, HyuCnt: ${params.HyuCnt}")
846  println(s"[IssueQueueMemAddrImp] StdCnt: ${params.StdCnt}, LduCnt: ${params.LduCnt}, StaCnt: ${params.StaCnt}, HyuCnt: ${params.HyuCnt}")
847
848  io.suggestName("none")
849  override lazy val io = IO(new IssueQueueMemIO).suggestName("io")
850  private val memIO = io.memIO.get
851
852  memIO.loadFastMatch := 0.U.asTypeOf(memIO.loadFastMatch) // TODO: is still needed?
853
854  for (i <- io.enq.indices) {
855    val blockNotReleased = isAfter(io.enq(i).bits.sqIdx, memIO.checkWait.stIssuePtr)
856    val storeAddrWaitForIsIssuing = VecInit((0 until StorePipelineWidth).map(i => {
857      memIO.checkWait.memWaitUpdateReq.robIdx(i).valid &&
858        memIO.checkWait.memWaitUpdateReq.robIdx(i).bits.value === io.enq(i).bits.waitForRobIdx.value
859    })).asUInt.orR && !io.enq(i).bits.loadWaitStrict // is waiting for store addr ready
860    s0_enqBits(i).loadWaitBit := io.enq(i).bits.loadWaitBit && !storeAddrWaitForIsIssuing && blockNotReleased
861    // when have vpu
862    if (params.VlduCnt > 0 || params.VstuCnt > 0) {
863      s0_enqBits(i).srcType(3) := SrcType.vp // v0: mask src
864      s0_enqBits(i).srcType(4) := SrcType.vp // vl&vtype
865    }
866  }
867
868  for (i <- entries.io.enq.indices) {
869    entries.io.enq(i).bits.status match { case enqData =>
870      enqData.blocked := false.B // s0_enqBits(i).loadWaitBit
871      enqData.mem.get.strictWait := s0_enqBits(i).loadWaitStrict
872      enqData.mem.get.waitForStd := false.B
873      enqData.mem.get.waitForRobIdx := s0_enqBits(i).waitForRobIdx
874      enqData.mem.get.waitForSqIdx := 0.U.asTypeOf(enqData.mem.get.waitForSqIdx) // generated by sq, will be updated later
875      enqData.mem.get.sqIdx := s0_enqBits(i).sqIdx
876    }
877
878    entries.io.fromMem.get.slowResp.zipWithIndex.foreach { case (slowResp, i) =>
879      slowResp.valid                 := memIO.feedbackIO(i).feedbackSlow.valid
880      slowResp.bits.robIdx           := memIO.feedbackIO(i).feedbackSlow.bits.robIdx
881      slowResp.bits.uopIdx           := DontCare
882      slowResp.bits.respType         := Mux(memIO.feedbackIO(i).feedbackSlow.bits.hit, RSFeedbackType.fuIdle, RSFeedbackType.feedbackInvalid)
883      slowResp.bits.dataInvalidSqIdx := memIO.feedbackIO(i).feedbackSlow.bits.dataInvalidSqIdx
884      slowResp.bits.rfWen := DontCare
885      slowResp.bits.fuType := DontCare
886    }
887
888    entries.io.fromMem.get.fastResp.zipWithIndex.foreach { case (fastResp, i) =>
889      fastResp.valid                 := memIO.feedbackIO(i).feedbackFast.valid
890      fastResp.bits.robIdx           := memIO.feedbackIO(i).feedbackFast.bits.robIdx
891      fastResp.bits.uopIdx           := DontCare
892      fastResp.bits.respType         := Mux(memIO.feedbackIO(i).feedbackFast.bits.hit, RSFeedbackType.fuIdle, memIO.feedbackIO(i).feedbackFast.bits.sourceType)
893      fastResp.bits.dataInvalidSqIdx := 0.U.asTypeOf(fastResp.bits.dataInvalidSqIdx)
894      fastResp.bits.rfWen := DontCare
895      fastResp.bits.fuType := DontCare
896    }
897
898    entries.io.fromMem.get.memWaitUpdateReq := memIO.checkWait.memWaitUpdateReq
899    entries.io.fromMem.get.stIssuePtr := memIO.checkWait.stIssuePtr
900  }
901
902  io.deq.zipWithIndex.foreach { case (deq, i) =>
903    deq.bits.common.loadWaitBit.foreach(_ := deqEntryVec(i).bits.payload.loadWaitBit)
904    deq.bits.common.waitForRobIdx.foreach(_ := deqEntryVec(i).bits.payload.waitForRobIdx)
905    deq.bits.common.storeSetHit.foreach(_ := deqEntryVec(i).bits.payload.storeSetHit)
906    deq.bits.common.loadWaitStrict.foreach(_ := deqEntryVec(i).bits.payload.loadWaitStrict)
907    deq.bits.common.ssid.foreach(_ := deqEntryVec(i).bits.payload.ssid)
908    deq.bits.common.sqIdx.get := deqEntryVec(i).bits.payload.sqIdx
909    deq.bits.common.lqIdx.get := deqEntryVec(i).bits.payload.lqIdx
910    deq.bits.common.ftqIdx.foreach(_ := deqEntryVec(i).bits.payload.ftqPtr)
911    deq.bits.common.ftqOffset.foreach(_ := deqEntryVec(i).bits.payload.ftqOffset)
912    // when have vpu
913    if (params.VlduCnt > 0 || params.VstuCnt > 0) {
914      deq.bits.common.vpu.foreach(_ := deqEntryVec(i).bits.payload.vpu)
915      deq.bits.common.vpu.foreach(_.vuopIdx := deqEntryVec(i).bits.payload.uopIdx)
916    }
917  }
918}
919
920class IssueQueueVecMemImp(override val wrapper: IssueQueue)(implicit p: Parameters, params: IssueBlockParams)
921  extends IssueQueueImp(wrapper) with HasCircularQueuePtrHelper {
922
923  require((params.VstdCnt + params.VlduCnt + params.VstaCnt) > 0, "IssueQueueVecMemImp can only be instance of VecMem IQ")
924
925  io.suggestName("none")
926  override lazy val io = IO(new IssueQueueMemIO).suggestName("io")
927  private val memIO = io.memIO.get
928
929  def selectOldUop(robIdx: Seq[RobPtr], uopIdx: Seq[UInt], valid: Seq[Bool]): Vec[Bool] = {
930    val compareVec = (0 until robIdx.length).map(i => (0 until i).map(j => isAfter(robIdx(j), robIdx(i)) || (robIdx(j).value === robIdx(i).value && uopIdx(i) < uopIdx(j))))
931    val resultOnehot = VecInit((0 until robIdx.length).map(i => Cat((0 until robIdx.length).map(j =>
932      (if (j < i) !valid(j) || compareVec(i)(j)
933      else if (j == i) valid(i)
934      else !valid(j) || !compareVec(j)(i))
935    )).andR))
936    resultOnehot
937  }
938
939  val robIdxVec = entries.io.robIdx.get
940  val uopIdxVec = entries.io.uopIdx.get
941  val allEntryOldestOH = selectOldUop(robIdxVec, uopIdxVec, validVec)
942
943  finalDeqSelValidVec.head := (allEntryOldestOH.asUInt & canIssueVec.asUInt).orR
944  finalDeqSelOHVec.head := allEntryOldestOH.asUInt & canIssueVec.asUInt
945
946  if (params.isVecMemAddrIQ) {
947    s0_enqBits.foreach{ x =>
948      x.srcType(3) := SrcType.vp // v0: mask src
949      x.srcType(4) := SrcType.vp // vl&vtype
950    }
951
952    for (i <- io.enq.indices) {
953      s0_enqBits(i).loadWaitBit := false.B
954    }
955
956    for (i <- entries.io.enq.indices) {
957      entries.io.enq(i).bits.status match { case enqData =>
958        enqData.blocked := false.B // s0_enqBits(i).loadWaitBit
959        enqData.mem.get.strictWait := s0_enqBits(i).loadWaitStrict
960        enqData.mem.get.waitForStd := false.B
961        enqData.mem.get.waitForRobIdx := s0_enqBits(i).waitForRobIdx
962        enqData.mem.get.waitForSqIdx := 0.U.asTypeOf(enqData.mem.get.waitForSqIdx) // generated by sq, will be updated later
963        enqData.mem.get.sqIdx := s0_enqBits(i).sqIdx
964      }
965
966      entries.io.fromMem.get.slowResp.zipWithIndex.foreach { case (slowResp, i) =>
967        slowResp.valid                 := memIO.feedbackIO(i).feedbackSlow.valid
968        slowResp.bits.robIdx           := memIO.feedbackIO(i).feedbackSlow.bits.robIdx
969        slowResp.bits.uopIdx           := DontCare
970        slowResp.bits.respType         := Mux(memIO.feedbackIO(i).feedbackSlow.bits.hit, RSFeedbackType.fuIdle, RSFeedbackType.feedbackInvalid)
971        slowResp.bits.dataInvalidSqIdx := memIO.feedbackIO(i).feedbackSlow.bits.dataInvalidSqIdx
972        slowResp.bits.rfWen := DontCare
973        slowResp.bits.fuType := DontCare
974      }
975
976      entries.io.fromMem.get.fastResp.zipWithIndex.foreach { case (fastResp, i) =>
977        fastResp.valid                 := memIO.feedbackIO(i).feedbackFast.valid
978        fastResp.bits.robIdx           := memIO.feedbackIO(i).feedbackFast.bits.robIdx
979        fastResp.bits.uopIdx           := DontCare
980        fastResp.bits.respType         := memIO.feedbackIO(i).feedbackFast.bits.sourceType
981        fastResp.bits.dataInvalidSqIdx := 0.U.asTypeOf(fastResp.bits.dataInvalidSqIdx)
982        fastResp.bits.rfWen := DontCare
983        fastResp.bits.fuType := DontCare
984      }
985
986      entries.io.fromMem.get.memWaitUpdateReq := memIO.checkWait.memWaitUpdateReq
987      entries.io.fromMem.get.stIssuePtr := memIO.checkWait.stIssuePtr
988    }
989  }
990
991  for (i <- entries.io.enq.indices) {
992    entries.io.enq(i).bits.status match { case enqData =>
993      enqData.vecMem.get.sqIdx := s0_enqBits(i).sqIdx
994      enqData.vecMem.get.lqIdx := s0_enqBits(i).lqIdx
995    }
996  }
997
998  entries.io.fromLsq.get.sqDeqPtr := memIO.sqDeqPtr.get
999  entries.io.fromLsq.get.lqDeqPtr := memIO.lqDeqPtr.get
1000
1001  io.deq.zipWithIndex.foreach { case (deq, i) =>
1002    deq.bits.common.sqIdx.foreach(_ := deqEntryVec(i).bits.payload.sqIdx)
1003    deq.bits.common.lqIdx.foreach(_ := deqEntryVec(i).bits.payload.lqIdx)
1004    if (params.isVecLdAddrIQ) {
1005      deq.bits.common.ftqIdx.get := deqEntryVec(i).bits.payload.ftqPtr
1006      deq.bits.common.ftqOffset.get := deqEntryVec(i).bits.payload.ftqOffset
1007    }
1008    deq.bits.common.fpu.foreach(_ := deqEntryVec(i).bits.payload.fpu)
1009    deq.bits.common.vpu.foreach(_ := deqEntryVec(i).bits.payload.vpu)
1010    deq.bits.common.vpu.foreach(_.vuopIdx := deqEntryVec(i).bits.payload.uopIdx)
1011    deq.bits.common.vpu.foreach(_.lastUop := deqEntryVec(i).bits.payload.lastUop)
1012  }
1013}
1014