xref: /XiangShan/src/main/scala/xiangshan/frontend/Frontend.scala (revision 10b493796be56fff4e480bef1d6f7c2e0600823f)
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.frontend
18import org.chipsalliance.cde.config.Parameters
19import chisel3._
20import chisel3.util._
21import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
22import utils._
23import utility._
24import xiangshan._
25import xiangshan.backend.fu.{PFEvent, PMP, PMPChecker, PMPReqBundle}
26import xiangshan.cache.mmu._
27import xiangshan.frontend.icache._
28
29
30class Frontend()(implicit p: Parameters) extends LazyModule with HasXSParameter {
31  override def shouldBeInlined: Boolean = false
32
33  val instrUncache  = LazyModule(new InstrUncache())
34  val icache        = LazyModule(new ICache())
35
36  lazy val module = new FrontendImp(this)
37}
38
39
40class FrontendImp (outer: Frontend) extends LazyModuleImp(outer)
41  with HasXSParameter
42  with HasPerfEvents
43{
44  val io = IO(new Bundle() {
45    val hartId = Input(UInt(hartIdLen.W))
46    val reset_vector = Input(UInt(PAddrBits.W))
47    val fencei = Input(Bool())
48    val ptw = new TlbPtwIO()
49    val backend = new FrontendToCtrlIO
50    val sfence = Input(new SfenceBundle)
51    val tlbCsr = Input(new TlbCsrBundle)
52    val csrCtrl = Input(new CustomCSRCtrlIO)
53    val error  = ValidIO(new L1CacheErrorInfo)
54    val frontendInfo = new Bundle {
55      val ibufFull  = Output(Bool())
56      val bpuInfo = new Bundle {
57        val bpRight = Output(UInt(XLEN.W))
58        val bpWrong = Output(UInt(XLEN.W))
59      }
60    }
61    val debugTopDown = new Bundle {
62      val robHeadVaddr = Flipped(Valid(UInt(VAddrBits.W)))
63    }
64  })
65
66  //decouped-frontend modules
67  val instrUncache = outer.instrUncache.module
68  val icache       = outer.icache.module
69  val bpu     = Module(new Predictor)
70  val ifu     = Module(new NewIFU)
71  val ibuffer =  Module(new IBuffer)
72  val ftq = Module(new Ftq)
73
74  val needFlush = RegNext(io.backend.toFtq.redirect.valid)
75  val FlushControlRedirect = RegNext(io.backend.toFtq.redirect.bits.debugIsCtrl)
76  val FlushMemVioRedirect = RegNext(io.backend.toFtq.redirect.bits.debugIsMemVio)
77  val FlushControlBTBMiss = Wire(Bool())
78  val FlushTAGEMiss = Wire(Bool())
79  val FlushSCMiss = Wire(Bool())
80  val FlushITTAGEMiss = Wire(Bool())
81  val FlushRASMiss = Wire(Bool())
82
83  val tlbCsr = DelayN(io.tlbCsr, 2)
84  val csrCtrl = DelayN(io.csrCtrl, 2)
85  val sfence = RegNext(RegNext(io.sfence))
86
87  // trigger
88  ifu.io.frontendTrigger := csrCtrl.frontend_trigger
89
90  // bpu ctrl
91  bpu.io.ctrl := csrCtrl.bp_ctrl
92  bpu.io.reset_vector := RegEnable(io.reset_vector, reset.asBool)
93
94// pmp
95  val PortNumber = ICacheParameters().PortNumber
96  val pmp = Module(new PMP())
97  val pmp_check = VecInit(Seq.fill(coreParams.ipmpPortNum)(Module(new PMPChecker(3, sameCycle = true)).io))
98  pmp.io.distribute_csr := csrCtrl.distribute_csr
99  val pmp_req_vec     = Wire(Vec(coreParams.ipmpPortNum, Valid(new PMPReqBundle())))
100  (0 until 2 * PortNumber).foreach(i => pmp_req_vec(i) <> icache.io.pmp(i).req)
101  pmp_req_vec.last <> ifu.io.pmp.req
102
103  for (i <- pmp_check.indices) {
104    pmp_check(i).apply(tlbCsr.priv.imode, pmp.io.pmp, pmp.io.pma, pmp_req_vec(i))
105  }
106  (0 until 2 * PortNumber).foreach(i => icache.io.pmp(i).resp <> pmp_check(i).resp)
107  ifu.io.pmp.resp <> pmp_check.last.resp
108
109  val itlb = Module(new TLB(coreParams.itlbPortNum, nRespDups = 1,
110    Seq.fill(PortNumber)(false) ++ Seq(true), itlbParams))
111  itlb.io.requestor.take(PortNumber) zip icache.io.itlb foreach {case (a,b) => a <> b}
112  itlb.io.requestor.last <> ifu.io.iTLBInter // mmio may need re-tlb, blocked
113  itlb.io.hartId := io.hartId
114  itlb.io.base_connect(sfence, tlbCsr)
115  itlb.io.flushPipe.map(_ := needFlush)
116  itlb.io.redirect := DontCare // itlb has flushpipe, don't need redirect signal
117
118  val itlb_ptw = Wire(new VectorTlbPtwIO(coreParams.itlbPortNum))
119  itlb_ptw.connect(itlb.io.ptw)
120  val itlbRepeater1 = PTWFilter(itlbParams.fenceDelay, itlb_ptw, sfence, tlbCsr, l2tlbParams.ifilterSize)
121  val itlbRepeater2 = PTWRepeaterNB(passReady = false, itlbParams.fenceDelay, itlbRepeater1.io.ptw, io.ptw, sfence, tlbCsr)
122
123  icache.io.prefetch <> ftq.io.toPrefetch
124
125
126  //IFU-Ftq
127  ifu.io.ftqInter.fromFtq <> ftq.io.toIfu
128  ftq.io.toIfu.req.ready :=  ifu.io.ftqInter.fromFtq.req.ready && icache.io.fetch.req.ready
129
130  ftq.io.fromIfu          <> ifu.io.ftqInter.toFtq
131  bpu.io.ftq_to_bpu       <> ftq.io.toBpu
132  ftq.io.fromBpu          <> bpu.io.bpu_to_ftq
133
134  ftq.io.mmioCommitRead   <> ifu.io.mmioCommitRead
135  //IFU-ICache
136
137  icache.io.fetch.req <> ftq.io.toICache.req
138  ftq.io.toICache.req.ready :=  ifu.io.ftqInter.fromFtq.req.ready && icache.io.fetch.req.ready
139
140  ifu.io.icacheInter.resp <>    icache.io.fetch.resp
141  ifu.io.icacheInter.icacheReady :=  icache.io.toIFU
142  ifu.io.icacheInter.topdownIcacheMiss := icache.io.fetch.topdownIcacheMiss
143  ifu.io.icacheInter.topdownItlbMiss := icache.io.fetch.topdownItlbMiss
144  icache.io.stop := ifu.io.icacheStop
145  icache.io.flush := ftq.io.icacheFlush
146
147  ifu.io.icachePerfInfo := icache.io.perfInfo
148
149  icache.io.csr_pf_enable     := RegNext(csrCtrl.l1I_pf_enable)
150  icache.io.csr_parity_enable := RegNext(csrCtrl.icache_parity_enable)
151
152  icache.io.fencei := RegNext(io.fencei)
153
154  //IFU-Ibuffer
155  ifu.io.toIbuffer    <> ibuffer.io.in
156
157  ftq.io.fromBackend <> io.backend.toFtq
158  io.backend.fromFtq <> ftq.io.toBackend
159  io.backend.fromIfu <> ifu.io.toBackend
160  io.frontendInfo.bpuInfo <> ftq.io.bpuInfo
161
162  val checkPcMem = Reg(Vec(FtqSize, new Ftq_RF_Components))
163  when (ftq.io.toBackend.pc_mem_wen) {
164    checkPcMem(ftq.io.toBackend.pc_mem_waddr.value) := ftq.io.toBackend.pc_mem_wdata
165  }
166
167  val checkTargetIdx = Wire(Vec(DecodeWidth, UInt(log2Up(FtqSize).W)))
168  val checkTarget = Wire(Vec(DecodeWidth, UInt(VAddrBits.W)))
169
170  for (i <- 0 until DecodeWidth) {
171    checkTargetIdx(i) := ibuffer.io.out(i).bits.ftqPtr.value
172    checkTarget(i) := Mux(ftq.io.toBackend.newest_entry_ptr.value === checkTargetIdx(i),
173                        ftq.io.toBackend.newest_entry_target,
174                        checkPcMem(checkTargetIdx(i) + 1.U).startAddr)
175  }
176
177  // commented out for this br could be the last instruction in the fetch block
178  def checkNotTakenConsecutive = {
179    val prevNotTakenValid = RegInit(0.B)
180    val prevNotTakenFtqIdx = Reg(UInt(log2Up(FtqSize).W))
181    for (i <- 0 until DecodeWidth - 1) {
182      // for instrs that is not the last, if a not-taken br, the next instr should have the same ftqPtr
183      // for instrs that is the last, record and check next request
184      when (ibuffer.io.out(i).fire && ibuffer.io.out(i).bits.pd.isBr) {
185        when (ibuffer.io.out(i+1).fire) {
186          // not last br, check now
187          XSError(checkTargetIdx(i) =/= checkTargetIdx(i+1), "not-taken br should have same ftqPtr\n")
188        } .otherwise {
189          // last br, record its info
190          prevNotTakenValid := true.B
191          prevNotTakenFtqIdx := checkTargetIdx(i)
192        }
193      }
194    }
195    when (ibuffer.io.out(DecodeWidth - 1).fire && ibuffer.io.out(DecodeWidth - 1).bits.pd.isBr) {
196      // last instr is a br, record its info
197      prevNotTakenValid := true.B
198      prevNotTakenFtqIdx := checkTargetIdx(DecodeWidth - 1)
199    }
200    when (prevNotTakenValid && ibuffer.io.out(0).fire) {
201      XSError(prevNotTakenFtqIdx =/= checkTargetIdx(0), "not-taken br should have same ftqPtr\n")
202      prevNotTakenValid := false.B
203    }
204    when (needFlush) {
205      prevNotTakenValid := false.B
206    }
207  }
208
209  def checkTakenNotConsecutive = {
210    val prevTakenValid = RegInit(0.B)
211    val prevTakenFtqIdx = Reg(UInt(log2Up(FtqSize).W))
212    for (i <- 0 until DecodeWidth - 1) {
213      // for instrs that is not the last, if a taken br, the next instr should not have the same ftqPtr
214      // for instrs that is the last, record and check next request
215      when (ibuffer.io.out(i).fire && ibuffer.io.out(i).bits.pd.isBr && ibuffer.io.out(i).bits.pred_taken) {
216        when (ibuffer.io.out(i+1).fire) {
217          // not last br, check now
218          XSError(checkTargetIdx(i) + 1.U =/= checkTargetIdx(i+1), "taken br should have consecutive ftqPtr\n")
219        } .otherwise {
220          // last br, record its info
221          prevTakenValid := true.B
222          prevTakenFtqIdx := checkTargetIdx(i)
223        }
224      }
225    }
226    when (ibuffer.io.out(DecodeWidth - 1).fire && ibuffer.io.out(DecodeWidth - 1).bits.pd.isBr && ibuffer.io.out(DecodeWidth - 1).bits.pred_taken) {
227      // last instr is a br, record its info
228      prevTakenValid := true.B
229      prevTakenFtqIdx := checkTargetIdx(DecodeWidth - 1)
230    }
231    when (prevTakenValid && ibuffer.io.out(0).fire) {
232      XSError(prevTakenFtqIdx + 1.U =/= checkTargetIdx(0), "taken br should have consecutive ftqPtr\n")
233      prevTakenValid := false.B
234    }
235    when (needFlush) {
236      prevTakenValid := false.B
237    }
238  }
239
240  def checkNotTakenPC = {
241    val prevNotTakenPC = Reg(UInt(VAddrBits.W))
242    val prevIsRVC = Reg(Bool())
243    val prevNotTakenValid = RegInit(0.B)
244
245    for (i <- 0 until DecodeWidth - 1) {
246      when (ibuffer.io.out(i).fire && ibuffer.io.out(i).bits.pd.isBr && !ibuffer.io.out(i).bits.pred_taken) {
247        when (ibuffer.io.out(i+1).fire) {
248          XSError(ibuffer.io.out(i).bits.pc + Mux(ibuffer.io.out(i).bits.pd.isRVC, 2.U, 4.U) =/= ibuffer.io.out(i+1).bits.pc, "not-taken br should have consecutive pc\n")
249        } .otherwise {
250          prevNotTakenValid := true.B
251          prevIsRVC := ibuffer.io.out(i).bits.pd.isRVC
252          prevNotTakenPC := ibuffer.io.out(i).bits.pc
253        }
254      }
255    }
256    when (ibuffer.io.out(DecodeWidth - 1).fire && ibuffer.io.out(DecodeWidth - 1).bits.pd.isBr && !ibuffer.io.out(DecodeWidth - 1).bits.pred_taken) {
257      prevNotTakenValid := true.B
258      prevIsRVC := ibuffer.io.out(DecodeWidth - 1).bits.pd.isRVC
259      prevNotTakenPC := ibuffer.io.out(DecodeWidth - 1).bits.pc
260    }
261    when (prevNotTakenValid && ibuffer.io.out(0).fire) {
262      XSError(prevNotTakenPC + Mux(prevIsRVC, 2.U, 4.U) =/= ibuffer.io.out(0).bits.pc, "not-taken br should have same pc\n")
263      prevNotTakenValid := false.B
264    }
265    when (needFlush) {
266      prevNotTakenValid := false.B
267    }
268  }
269
270  def checkTakenPC = {
271    val prevTakenFtqIdx = Reg(UInt(log2Up(FtqSize).W))
272    val prevTakenValid = RegInit(0.B)
273    val prevTakenTarget = Wire(UInt(VAddrBits.W))
274    prevTakenTarget := checkPcMem(prevTakenFtqIdx + 1.U).startAddr
275
276    for (i <- 0 until DecodeWidth - 1) {
277      when (ibuffer.io.out(i).fire && !ibuffer.io.out(i).bits.pd.notCFI && ibuffer.io.out(i).bits.pred_taken) {
278        when (ibuffer.io.out(i+1).fire) {
279          XSError(checkTarget(i) =/= ibuffer.io.out(i+1).bits.pc, "taken instr should follow target pc\n")
280        } .otherwise {
281          prevTakenValid := true.B
282          prevTakenFtqIdx := checkTargetIdx(i)
283        }
284      }
285    }
286    when (ibuffer.io.out(DecodeWidth - 1).fire && !ibuffer.io.out(DecodeWidth - 1).bits.pd.notCFI && ibuffer.io.out(DecodeWidth - 1).bits.pred_taken) {
287      prevTakenValid := true.B
288      prevTakenFtqIdx := checkTargetIdx(DecodeWidth - 1)
289    }
290    when (prevTakenValid && ibuffer.io.out(0).fire) {
291      XSError(prevTakenTarget =/= ibuffer.io.out(0).bits.pc, "taken instr should follow target pc\n")
292      prevTakenValid := false.B
293    }
294    when (needFlush) {
295      prevTakenValid := false.B
296    }
297  }
298
299  //checkNotTakenConsecutive
300  checkTakenNotConsecutive
301  checkTakenPC
302  checkNotTakenPC
303
304  ifu.io.rob_commits <> io.backend.toFtq.rob_commits
305
306  ibuffer.io.flush := needFlush
307  ibuffer.io.ControlRedirect := FlushControlRedirect
308  ibuffer.io.MemVioRedirect := FlushMemVioRedirect
309  ibuffer.io.ControlBTBMissBubble := FlushControlBTBMiss
310  ibuffer.io.TAGEMissBubble := FlushTAGEMiss
311  ibuffer.io.SCMissBubble := FlushSCMiss
312  ibuffer.io.ITTAGEMissBubble := FlushITTAGEMiss
313  ibuffer.io.RASMissBubble := FlushRASMiss
314  ibuffer.io.decodeCanAccept := io.backend.canAccept
315
316  FlushControlBTBMiss := ftq.io.ControlBTBMissBubble
317  FlushTAGEMiss := ftq.io.TAGEMissBubble
318  FlushSCMiss := ftq.io.SCMissBubble
319  FlushITTAGEMiss := ftq.io.ITTAGEMissBubble
320  FlushRASMiss := ftq.io.RASMissBubble
321
322  io.backend.cfVec <> ibuffer.io.out
323  io.backend.stallReason <> ibuffer.io.stallReason
324
325  instrUncache.io.req   <> ifu.io.uncacheInter.toUncache
326  ifu.io.uncacheInter.fromUncache <> instrUncache.io.resp
327  instrUncache.io.flush := false.B
328  io.error <> RegNext(RegNext(icache.io.error))
329
330  icache.io.hartId := io.hartId
331
332  itlbRepeater1.io.debugTopDown.robHeadVaddr := io.debugTopDown.robHeadVaddr
333
334  val frontendBubble = PopCount((0 until DecodeWidth).map(i => io.backend.cfVec(i).ready && !ibuffer.io.out(i).valid))
335  XSPerfAccumulate("FrontendBubble", frontendBubble)
336  io.frontendInfo.ibufFull := RegNext(ibuffer.io.full)
337
338  // PFEvent
339  val pfevent = Module(new PFEvent)
340  pfevent.io.distribute_csr := io.csrCtrl.distribute_csr
341  val csrevents = pfevent.io.hpmevent.take(8)
342
343  val perfFromUnits = Seq(ifu, ibuffer, icache, ftq, bpu).flatMap(_.getPerfEvents)
344  val perfFromIO    = Seq()
345  val perfBlock     = Seq()
346  // let index = 0 be no event
347  val allPerfEvents = Seq(("noEvent", 0.U)) ++ perfFromUnits ++ perfFromIO ++ perfBlock
348
349  if (printEventCoding) {
350    for (((name, inc), i) <- allPerfEvents.zipWithIndex) {
351      println("Frontend perfEvents Set", name, inc, i)
352    }
353  }
354
355  val allPerfInc = allPerfEvents.map(_._2.asTypeOf(new PerfEvent))
356  override val perfEvents = HPerfMonitor(csrevents, allPerfInc).getPerfEvents
357  generatePerfEvent()
358}
359