xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 211986abe9d7b13883472dc6ef5e93171a92e689)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16***************************************************************************************/
17
18package xiangshan.frontend
19
20import chisel3._
21import chisel3.util._
22import org.chipsalliance.cde.config.Parameters
23import utility._
24import utility.ChiselDB
25import xiangshan._
26import xiangshan.backend.GPAMemEntry
27import xiangshan.cache.mmu._
28import xiangshan.frontend.icache._
29
30trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst {
31  def mmioBusWidth = 64
32  def mmioBusBytes = mmioBusWidth / 8
33  def maxInstrLen  = 32
34}
35
36trait HasIFUConst extends HasXSParameter {
37  def addrAlign(addr: UInt, bytes: Int, highest: Int): UInt =
38    Cat(addr(highest - 1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
39  def fetchQueueSize = 2
40
41  def getBasicBlockIdx(pc: UInt, start: UInt): UInt = {
42    val byteOffset = pc - start
43    (byteOffset - instBytes.U)(log2Ceil(PredictWidth), instOffsetBits)
44  }
45}
46
47class IfuToFtqIO(implicit p: Parameters) extends XSBundle {
48  val pdWb = Valid(new PredecodeWritebackBundle)
49}
50
51class IfuToBackendIO(implicit p: Parameters) extends XSBundle {
52  // write to backend gpaddr mem
53  val gpaddrMem_wen   = Output(Bool())
54  val gpaddrMem_waddr = Output(UInt(log2Ceil(FtqSize).W)) // Ftq Ptr
55  // 2 gpaddrs, correspond to startAddr & nextLineAddr in bundle FtqICacheInfo
56  // TODO: avoid cross page entry in Ftq
57  val gpaddrMem_wdata = Output(new GPAMemEntry)
58}
59
60class FtqInterface(implicit p: Parameters) extends XSBundle {
61  val fromFtq = Flipped(new FtqToIfuIO)
62  val toFtq   = new IfuToFtqIO
63}
64
65class UncacheInterface(implicit p: Parameters) extends XSBundle {
66  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
67  val toUncache   = DecoupledIO(new InsUncacheReq)
68}
69
70class NewIFUIO(implicit p: Parameters) extends XSBundle {
71  val ftqInter        = new FtqInterface
72  val icacheInter     = Flipped(new IFUICacheIO)
73  val icacheStop      = Output(Bool())
74  val icachePerfInfo  = Input(new ICachePerfInfo)
75  val toIbuffer       = Decoupled(new FetchToIBuffer)
76  val toBackend       = new IfuToBackendIO
77  val uncacheInter    = new UncacheInterface
78  val frontendTrigger = Flipped(new FrontendTdataDistributeIO)
79  val rob_commits     = Flipped(Vec(CommitWidth, Valid(new RobCommitInfo)))
80  val iTLBInter       = new TlbRequestIO
81  val pmp             = new ICachePMPBundle
82  val mmioCommitRead  = new mmioCommitRead
83  val csr_fsIsOff     = Input(Bool())
84}
85
86// record the situation in which fallThruAddr falls into
87// the middle of an RVI inst
88class LastHalfInfo(implicit p: Parameters) extends XSBundle {
89  val valid    = Bool()
90  val middlePC = UInt(VAddrBits.W)
91  def matchThisBlock(startAddr: UInt) = valid && middlePC === startAddr
92}
93
94class IfuToPreDecode(implicit p: Parameters) extends XSBundle {
95  val data            = if (HasCExtension) Vec(PredictWidth + 1, UInt(16.W)) else Vec(PredictWidth, UInt(32.W))
96  val frontendTrigger = new FrontendTdataDistributeIO
97  val pc              = Vec(PredictWidth, UInt(VAddrBits.W))
98}
99
100class IfuToPredChecker(implicit p: Parameters) extends XSBundle {
101  val ftqOffset  = Valid(UInt(log2Ceil(PredictWidth).W))
102  val jumpOffset = Vec(PredictWidth, UInt(XLEN.W))
103  val target     = UInt(VAddrBits.W)
104  val instrRange = Vec(PredictWidth, Bool())
105  val instrValid = Vec(PredictWidth, Bool())
106  val pds        = Vec(PredictWidth, new PreDecodeInfo)
107  val pc         = Vec(PredictWidth, UInt(VAddrBits.W))
108  val fire_in    = Bool()
109}
110
111class FetchToIBufferDB extends Bundle {
112  val start_addr   = UInt(39.W)
113  val instr_count  = UInt(32.W)
114  val exception    = Bool()
115  val is_cache_hit = Bool()
116}
117
118class IfuWbToFtqDB extends Bundle {
119  val start_addr        = UInt(39.W)
120  val is_miss_pred      = Bool()
121  val miss_pred_offset  = UInt(32.W)
122  val checkJalFault     = Bool()
123  val checkRetFault     = Bool()
124  val checkTargetFault  = Bool()
125  val checkNotCFIFault  = Bool()
126  val checkInvalidTaken = Bool()
127}
128
129class NewIFU(implicit p: Parameters) extends XSModule
130    with HasICacheParameters
131    with HasXSParameter
132    with HasIFUConst
133    with HasPdConst
134    with HasCircularQueuePtrHelper
135    with HasPerfEvents
136    with HasTlbConst {
137  val io                       = IO(new NewIFUIO)
138  val (toFtq, fromFtq)         = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
139  val fromICache               = io.icacheInter.resp
140  val (toUncache, fromUncache) = (io.uncacheInter.toUncache, io.uncacheInter.fromUncache)
141
142  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
143
144  def numOfStage = 3
145  // equal lower_result overflow bit
146  def PcCutPoint = (VAddrBits / 4) - 1
147  def CatPC(low: UInt, high: UInt, high1: UInt): UInt =
148    Mux(
149      low(PcCutPoint),
150      Cat(high1, low(PcCutPoint - 1, 0)),
151      Cat(high, low(PcCutPoint - 1, 0))
152    )
153  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
154  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
155  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
156  // bubble events in IFU, only happen in stage 1
157  val icacheMissBubble = Wire(Bool())
158  val itlbMissBubble   = Wire(Bool())
159
160  // only driven by clock, not valid-ready
161  topdown_stages(0) := fromFtq.req.bits.topdown_info
162  for (i <- 1 until numOfStage) {
163    topdown_stages(i) := topdown_stages(i - 1)
164  }
165  when(icacheMissBubble) {
166    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
167  }
168  when(itlbMissBubble) {
169    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
170  }
171  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
172  when(fromFtq.topdown_redirect.valid) {
173    // only redirect from backend, IFU redirect itself is handled elsewhere
174    when(fromFtq.topdown_redirect.bits.debugIsCtrl) {
175      /*
176      for (i <- 0 until numOfStage) {
177        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
178      }
179      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
180       */
181      when(fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
182        for (i <- 0 until numOfStage) {
183          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
184        }
185        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
186      }.elsewhen(fromFtq.topdown_redirect.bits.TAGEMissBubble) {
187        for (i <- 0 until numOfStage) {
188          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
189        }
190        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
191      }.elsewhen(fromFtq.topdown_redirect.bits.SCMissBubble) {
192        for (i <- 0 until numOfStage) {
193          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
194        }
195        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
196      }.elsewhen(fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
197        for (i <- 0 until numOfStage) {
198          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
199        }
200        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
201      }.elsewhen(fromFtq.topdown_redirect.bits.RASMissBubble) {
202        for (i <- 0 until numOfStage) {
203          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
204        }
205        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
206      }
207    }.elsewhen(fromFtq.topdown_redirect.bits.debugIsMemVio) {
208      for (i <- 0 until numOfStage) {
209        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
210      }
211      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
212    }.otherwise {
213      for (i <- 0 until numOfStage) {
214        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
215      }
216      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
217    }
218  }
219
220  class TlbExept(implicit p: Parameters) extends XSBundle {
221    val pageFault   = Bool()
222    val accessFault = Bool()
223    val mmio        = Bool()
224  }
225
226  val preDecoder = Module(new PreDecode)
227
228  val predChecker     = Module(new PredChecker)
229  val frontendTrigger = Module(new FrontendTrigger)
230  val (checkerIn, checkerOutStage1, checkerOutStage2) =
231    (predChecker.io.in, predChecker.io.out.stage1Out, predChecker.io.out.stage2Out)
232
233  /**
234    ******************************************************************************
235    * IFU Stage 0
236    * - send cacheline fetch request to ICacheMainPipe
237    ******************************************************************************
238    */
239
240  val f0_valid      = fromFtq.req.valid
241  val f0_ftq_req    = fromFtq.req.bits
242  val f0_doubleLine = fromFtq.req.bits.crossCacheline
243  val f0_vSetIdx    = VecInit(get_idx(f0_ftq_req.startAddr), get_idx(f0_ftq_req.nextlineStart))
244  val f0_fire       = fromFtq.req.fire
245
246  val f0_flush, f1_flush, f2_flush, f3_flush                                     = WireInit(false.B)
247  val from_bpu_f0_flush, from_bpu_f1_flush, from_bpu_f2_flush, from_bpu_f3_flush = WireInit(false.B)
248
249  from_bpu_f0_flush := fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
250    fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
251
252  val wb_redirect, mmio_redirect, backend_redirect = WireInit(false.B)
253  val f3_wb_not_flush                              = WireInit(false.B)
254
255  backend_redirect := fromFtq.redirect.valid
256  f3_flush         := backend_redirect || (wb_redirect && !f3_wb_not_flush)
257  f2_flush         := backend_redirect || mmio_redirect || wb_redirect
258  f1_flush         := f2_flush || from_bpu_f1_flush
259  f0_flush         := f1_flush || from_bpu_f0_flush
260
261  val f1_ready, f2_ready, f3_ready = WireInit(false.B)
262
263  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
264
265  when(wb_redirect) {
266    when(f3_wb_not_flush) {
267      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
268    }
269    for (i <- 0 until numOfStage - 1) {
270      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
271    }
272  }
273
274  /** <PERF> f0 fetch bubble */
275
276  XSPerfAccumulate("fetch_bubble_ftq_not_valid", !fromFtq.req.valid && fromFtq.req.ready)
277  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
278  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
279  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
280  XSPerfAccumulate("fetch_flush_backend_redirect", backend_redirect)
281  XSPerfAccumulate("fetch_flush_wb_redirect", wb_redirect)
282  XSPerfAccumulate("fetch_flush_bpu_f1_flush", from_bpu_f1_flush)
283  XSPerfAccumulate("fetch_flush_bpu_f0_flush", from_bpu_f0_flush)
284
285  /**
286    ******************************************************************************
287    * IFU Stage 1
288    * - calculate pc/half_pc/cut_ptr for every instruction
289    ******************************************************************************
290    */
291
292  val f1_valid   = RegInit(false.B)
293  val f1_ftq_req = RegEnable(f0_ftq_req, f0_fire)
294  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
295  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
296  val f1_vSetIdx    = RegEnable(f0_vSetIdx, f0_fire)
297  val f1_fire       = f1_valid && f2_ready
298
299  f1_ready := f1_fire || !f1_valid
300
301  from_bpu_f1_flush := fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid
302  // from_bpu_f1_flush := false.B
303
304  when(f1_flush)(f1_valid := false.B)
305    .elsewhen(f0_fire && !f0_flush)(f1_valid := true.B)
306    .elsewhen(f1_fire)(f1_valid := false.B)
307
308  val f1_pc_high       = f1_ftq_req.startAddr(VAddrBits - 1, PcCutPoint)
309  val f1_pc_high_plus1 = f1_pc_high + 1.U
310
311  /**
312   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
313   * code of original logic, this code has been deprecated
314   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
315   *  Mux(i(f1_pc_adder_cut_point), Cat(f1_pc_high_plus1,i(f1_pc_adder_cut_point-1,0)), Cat(f1_pc_high,i(f1_pc_adder_cut_point-1,0)))})
316   */
317  val f1_pc_lower_result = VecInit((0 until PredictWidth).map(i =>
318    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + (i * 2).U
319  )) // cat with overflow bit
320
321  val f1_pc = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
322
323  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i =>
324    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + ((i + 2) * 2).U
325  )) // cat with overflow bit
326  val f1_half_snpc = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
327
328  if (env.FPGAPlatform) {
329    val f1_pc_diff        = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
330    val f1_half_snpc_diff = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i + 2) * 2).U))
331
332    XSError(
333      f1_pc.zip(f1_pc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
334      "f1_half_snpc adder cut fail"
335    )
336    XSError(
337      f1_half_snpc.zip(f1_half_snpc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
338      "f1_half_snpc adder cut fail"
339    )
340  }
341
342  val f1_cut_ptr = if (HasCExtension)
343    VecInit((0 until PredictWidth + 1).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 1)) + i.U))
344  else VecInit((0 until PredictWidth).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 2)) + i.U))
345
346  /**
347    ******************************************************************************
348    * IFU Stage 2
349    * - icache response data (latched for pipeline stop)
350    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
351    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
352    * - cut data from cachlines to packet instruction code
353    * - instruction predecode and RVC expand
354    ******************************************************************************
355    */
356
357  val icacheRespAllValid = WireInit(false.B)
358
359  val f2_valid   = RegInit(false.B)
360  val f2_ftq_req = RegEnable(f1_ftq_req, f1_fire)
361  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
362  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
363  val f2_vSetIdx    = RegEnable(f1_vSetIdx, f1_fire)
364  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
365
366  f2_ready := f2_fire || !f2_valid
367  // TODO: addr compare may be timing critical
368  val f2_icache_all_resp_wire =
369    fromICache(0).valid && (fromICache(0).bits.vaddr === f2_ftq_req.startAddr) && ((fromICache(1).valid && (fromICache(
370      1
371    ).bits.vaddr === f2_ftq_req.nextlineStart)) || !f2_doubleLine)
372  val f2_icache_all_resp_reg = RegInit(false.B)
373
374  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
375
376  icacheMissBubble := io.icacheInter.topdownIcacheMiss
377  itlbMissBubble   := io.icacheInter.topdownItlbMiss
378
379  io.icacheStop := !f3_ready
380
381  when(f2_flush)(f2_icache_all_resp_reg := false.B)
382    .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready)(f2_icache_all_resp_reg := true.B)
383    .elsewhen(f2_fire && f2_icache_all_resp_reg)(f2_icache_all_resp_reg := false.B)
384
385  when(f2_flush)(f2_valid := false.B)
386    .elsewhen(f1_fire && !f1_flush)(f2_valid := true.B)
387    .elsewhen(f2_fire)(f2_valid := false.B)
388
389  val f2_exception_in     = VecInit((0 until PortNumber).map(i => fromICache(i).bits.exception))
390  val f2_backendException = fromICache(0).bits.backendException
391  // paddr and gpaddr of [startAddr, nextLineAddr]
392  val f2_paddrs            = VecInit((0 until PortNumber).map(i => fromICache(i).bits.paddr))
393  val f2_gpaddr            = fromICache(0).bits.gpaddr
394  val f2_isForVSnonLeafPTE = fromICache(0).bits.isForVSnonLeafPTE
395
396  // FIXME: raise af if one fetch block crosses the cacheable-noncacheable boundary, might not correct
397  val f2_mmio_mismatch_exception = VecInit(Seq.fill(2)(Mux(
398    // not double-line, skip check
399    !fromICache(1).valid ||
400      // is double-line, ask for consistent pmp_mmio and itlb_pbmt value
401      fromICache(0).bits.pmp_mmio === fromICache(1).bits.pmp_mmio &&
402      fromICache(0).bits.itlb_pbmt === fromICache(1).bits.itlb_pbmt,
403    ExceptionType.none,
404    ExceptionType.af
405  )))
406
407  // merge exceptions
408  val f2_exception = ExceptionType.merge(f2_exception_in, f2_mmio_mismatch_exception)
409
410  // we need only the first port, as the second is asked to be the same
411  val f2_pmp_mmio  = fromICache(0).bits.pmp_mmio
412  val f2_itlb_pbmt = fromICache(0).bits.itlb_pbmt
413
414  /**
415    * reduce the number of registers, origin code
416    * f2_pc = RegEnable(f1_pc, f1_fire)
417    */
418  val f2_pc_lower_result = RegEnable(f1_pc_lower_result, f1_fire)
419  val f2_pc_high         = RegEnable(f1_pc_high, f1_fire)
420  val f2_pc_high_plus1   = RegEnable(f1_pc_high_plus1, f1_fire)
421  val f2_pc              = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
422
423  val f2_cut_ptr      = RegEnable(f1_cut_ptr, f1_fire)
424  val f2_resend_vaddr = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
425
426  def isNextLine(pc: UInt, startAddr: UInt) =
427    startAddr(blockOffBits) ^ pc(blockOffBits)
428
429  def isLastInLine(pc: UInt) =
430    pc(blockOffBits - 1, 0) === "b111110".U
431
432  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits - 1, 1), MemPredPCWidth)))
433  val f2_jump_range =
434    Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
435  val f2_ftr_range = Fill(PredictWidth, f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(
436    f2_ftq_req.nextStartAddr,
437    f2_ftq_req.startAddr
438  )
439  val f2_instr_range = f2_jump_range & f2_ftr_range
440  val f2_exception_vec = VecInit((0 until PredictWidth).map(i =>
441    MuxCase(
442      ExceptionType.none,
443      Seq(
444        !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
445        (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
446      )
447    )
448  ))
449  val f2_perf_info = io.icachePerfInfo
450
451  def cut(cacheline: UInt, cutPtr: Vec[UInt]): Vec[UInt] = {
452    require(HasCExtension)
453    // if(HasCExtension){
454    val result  = Wire(Vec(PredictWidth + 1, UInt(16.W)))
455    val dataVec = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) // 32 16-bit data vector
456    (0 until PredictWidth + 1).foreach(i =>
457      result(i) := dataVec(cutPtr(i)) // the max ptr is 3*blockBytes/4-1
458    )
459    result
460    // } else {
461    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
462    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
463    //   (0 until PredictWidth).foreach( i =>
464    //     result(i) := dataVec(cutPtr(i))
465    //   )
466    //   result
467    // }
468  }
469
470  val f2_cache_response_data = fromICache.map(_.bits.data)
471  val f2_data_2_cacheline    = Cat(f2_cache_response_data(0), f2_cache_response_data(0))
472
473  val f2_cut_data = cut(f2_data_2_cacheline, f2_cut_ptr)
474
475  /** predecode (include RVC expander) */
476  // preDecoderRegIn.data := f2_reg_cut_data
477  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
478  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
479  // preDecoderRegIn.pc  := f2_pc
480
481  val preDecoderIn = preDecoder.io.in
482  preDecoderIn.valid                := f2_valid
483  preDecoderIn.bits.data            := f2_cut_data
484  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
485  preDecoderIn.bits.pc              := f2_pc
486  val preDecoderOut = preDecoder.io.out
487
488  // val f2_expd_instr     = preDecoderOut.expInstr
489  val f2_instr        = preDecoderOut.instr
490  val f2_pd           = preDecoderOut.pd
491  val f2_jump_offset  = preDecoderOut.jumpOffset
492  val f2_hasHalfValid = preDecoderOut.hasHalfValid
493  /* if there is a cross-page RVI instruction, and the former page has no exception,
494   * whether it has exception is actually depends on the latter page
495   */
496  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i =>
497    Mux(
498      isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && !ExceptionType.hasException(f2_exception(0)),
499      f2_exception(1),
500      ExceptionType.none
501    )
502  })
503  XSPerfAccumulate("fetch_bubble_icache_not_resp", f2_valid && !icacheRespAllValid)
504
505  /**
506    ******************************************************************************
507    * IFU Stage 3
508    * - handle MMIO instruciton
509    *  -send request to Uncache fetch Unit
510    *  -every packet include 1 MMIO instruction
511    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
512    *  -flush to snpc (send ifu_redirect to Ftq)
513    * - Ibuffer enqueue
514    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
515    * - handle last half RVI instruction
516    ******************************************************************************
517    */
518
519  val expanders = Seq.fill(PredictWidth)(Module(new RVCExpander))
520
521  val f3_valid   = RegInit(false.B)
522  val f3_ftq_req = RegEnable(f2_ftq_req, f2_fire)
523  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
524  val f3_doubleLine = RegEnable(f2_doubleLine, f2_fire)
525  val f3_fire       = io.toIbuffer.fire
526
527  val f3_cut_data = RegEnable(f2_cut_data, f2_fire)
528
529  val f3_exception        = RegEnable(f2_exception, f2_fire)
530  val f3_pmp_mmio         = RegEnable(f2_pmp_mmio, f2_fire)
531  val f3_itlb_pbmt        = RegEnable(f2_itlb_pbmt, f2_fire)
532  val f3_backendException = RegEnable(f2_backendException, f2_fire)
533
534  val f3_instr = RegEnable(f2_instr, f2_fire)
535
536  expanders.zipWithIndex.foreach { case (expander, i) =>
537    expander.io.in      := f3_instr(i)
538    expander.io.fsIsOff := io.csr_fsIsOff
539  }
540  // Use expanded instruction only when input is legal.
541  // Otherwise use origin illegal RVC instruction.
542  val f3_expd_instr = VecInit(expanders.map { expander: RVCExpander =>
543    Mux(expander.io.ill, expander.io.in, expander.io.out.bits)
544  })
545  val f3_ill = VecInit(expanders.map(_.io.ill))
546
547  val f3_pd_wire                 = RegEnable(f2_pd, f2_fire)
548  val f3_pd                      = WireInit(f3_pd_wire)
549  val f3_jump_offset             = RegEnable(f2_jump_offset, f2_fire)
550  val f3_exception_vec           = RegEnable(f2_exception_vec, f2_fire)
551  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
552
553  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
554  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
555  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
556  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
557
558  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
559  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
560  // val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
561
562  /**
563    ***********************************************************************
564    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
565    ***********************************************************************
566    */
567  val f3_half_snpc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
568  for (i <- 0 until PredictWidth) {
569    if (i == (PredictWidth - 2)) {
570      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
571    } else if (i == (PredictWidth - 1)) {
572      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
573    } else {
574      f3_half_snpc(i) := f3_pc(i + 2)
575    }
576  }
577
578  val f3_instr_range       = RegEnable(f2_instr_range, f2_fire)
579  val f3_foldpc            = RegEnable(f2_foldpc, f2_fire)
580  val f3_hasHalfValid      = RegEnable(f2_hasHalfValid, f2_fire)
581  val f3_paddrs            = RegEnable(f2_paddrs, f2_fire)
582  val f3_gpaddr            = RegEnable(f2_gpaddr, f2_fire)
583  val f3_isForVSnonLeafPTE = RegEnable(f2_isForVSnonLeafPTE, f2_fire)
584  val f3_resend_vaddr      = RegEnable(f2_resend_vaddr, f2_fire)
585
586  // Expand 1 bit to prevent overflow when assert
587  val f3_ftq_req_startAddr     = Cat(0.U(1.W), f3_ftq_req.startAddr)
588  val f3_ftq_req_nextStartAddr = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
589  // brType, isCall and isRet generation is delayed to f3 stage
590  val f3Predecoder = Module(new F3Predecoder)
591
592  f3Predecoder.io.in.instr := f3_instr
593
594  f3_pd.zipWithIndex.map { case (pd, i) =>
595    pd.brType := f3Predecoder.io.out.pd(i).brType
596    pd.isCall := f3Predecoder.io.out.pd(i).isCall
597    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
598  }
599
600  val f3PdDiff = f3_pd_wire.zip(f3_pd).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _)
601  XSError(f3_valid && f3PdDiff, "f3 pd diff")
602
603  when(f3_valid && !f3_ftq_req.ftqOffset.valid) {
604    assert(
605      f3_ftq_req_startAddr + (2 * PredictWidth).U >= f3_ftq_req_nextStartAddr,
606      s"More tha ${2 * PredictWidth} Bytes fetch is not allowed!"
607    )
608  }
609
610  /*** MMIO State Machine***/
611  val f3_mmio_data                  = Reg(Vec(2, UInt(16.W)))
612  val mmio_is_RVC                   = RegInit(false.B)
613  val mmio_resend_addr              = RegInit(0.U(PAddrBits.W))
614  val mmio_resend_exception         = RegInit(0.U(ExceptionType.width.W))
615  val mmio_resend_gpaddr            = RegInit(0.U(GPAddrBits.W))
616  val mmio_resend_isForVSnonLeafPTE = RegInit(false.B)
617
618  // last instuction finish
619  val is_first_instr = RegInit(true.B)
620
621  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
622  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
623
624  val m_idle :: m_waitLastCmt :: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil =
625    Enum(11)
626  val mmio_state = RegInit(m_idle)
627
628  // do mmio fetch only when pmp/pbmt shows it is a uncacheable address and no exception occurs
629  /* FIXME: we do not distinguish pbmt is NC or IO now
630   *        but we actually can do speculative execution if pbmt is NC, maybe fix this later for performance
631   */
632  val f3_req_is_mmio =
633    f3_valid && (f3_pmp_mmio || Pbmt.isUncache(f3_itlb_pbmt)) && !ExceptionType.hasException(f3_exception)
634  val mmio_commit = VecInit(io.rob_commits.map { commit =>
635    commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx && commit.bits.ftqOffset === 0.U
636  }).asUInt.orR
637  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
638
639  val f3_mmio_to_commit      = f3_req_is_mmio && mmio_state === m_waitCommit
640  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
641  val f3_mmio_can_go         = f3_mmio_to_commit && !f3_mmio_to_commit_next
642
643  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
644  fromFtqRedirectReg.bits := RegEnable(
645    fromFtq.redirect.bits,
646    0.U.asTypeOf(fromFtq.redirect.bits),
647    fromFtq.redirect.valid
648  )
649  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
650  val mmioF3Flush           = RegNext(f3_flush, init = false.B)
651  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
652  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
653
654  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
655
656  /**
657    **********************************************************************************
658    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
659    * This is the exception when the first instruction is an MMIO instruction.
660    **********************************************************************************
661    */
662  when(is_first_instr && f3_fire) {
663    is_first_instr := false.B
664  }
665
666  when(f3_flush && !f3_req_is_mmio)(f3_valid := false.B)
667    .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)(f3_valid := false.B)
668    .elsewhen(f2_fire && !f2_flush)(f3_valid := true.B)
669    .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)(f3_valid := false.B)
670    .elsewhen(f3_req_is_mmio && f3_mmio_req_commit)(f3_valid := false.B)
671
672  val f3_mmio_use_seq_pc = RegInit(false.B)
673
674  val (redirect_ftqIdx, redirect_ftqOffset) = (fromFtqRedirectReg.bits.ftqIdx, fromFtqRedirectReg.bits.ftqOffset)
675  val redirect_mmio_req =
676    fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
677
678  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)(f3_mmio_use_seq_pc := true.B)
679    .elsewhen(redirect_mmio_req)(f3_mmio_use_seq_pc := false.B)
680
681  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
682
683  // mmio state machine
684  switch(mmio_state) {
685    is(m_idle) {
686      when(f3_req_is_mmio) {
687        mmio_state := m_waitLastCmt
688      }
689    }
690
691    is(m_waitLastCmt) {
692      when(is_first_instr) {
693        mmio_state := m_sendReq
694      }.otherwise {
695        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
696      }
697    }
698
699    is(m_sendReq) {
700      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
701    }
702
703    is(m_waitResp) {
704      when(fromUncache.fire) {
705        val isRVC      = fromUncache.bits.data(1, 0) =/= 3.U
706        val needResend = !isRVC && f3_paddrs(0)(2, 1) === 3.U
707        mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
708        mmio_is_RVC     := isRVC
709        f3_mmio_data(0) := fromUncache.bits.data(15, 0)
710        f3_mmio_data(1) := fromUncache.bits.data(31, 16)
711      }
712    }
713
714    is(m_sendTLB) {
715      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
716    }
717
718    is(m_tlbResp) {
719      when(io.iTLBInter.resp.fire) {
720        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
721        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
722        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
723        // if itlb re-check respond pbmt mismatch with previous check, must be access fault
724        val pbmt_mismatch_exception = Mux(
725          io.iTLBInter.resp.bits.pbmt(0) =/= f3_itlb_pbmt,
726          ExceptionType.af,
727          ExceptionType.none
728        )
729        val exception = ExceptionType.merge(tlb_exception, pbmt_mismatch_exception)
730        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
731        mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_sendPMP)
732        // also save itlb response
733        mmio_resend_addr              := io.iTLBInter.resp.bits.paddr(0)
734        mmio_resend_exception         := exception
735        mmio_resend_gpaddr            := io.iTLBInter.resp.bits.gpaddr(0)
736        mmio_resend_isForVSnonLeafPTE := io.iTLBInter.resp.bits.isForVSnonLeafPTE(0)
737      }
738    }
739
740    is(m_sendPMP) {
741      val pmp_exception = ExceptionType.fromPMPResp(io.pmp.resp)
742      // if pmp re-check respond mismatch with previous check, must be access fault
743      val mmio_mismatch_exception = Mux(
744        io.pmp.resp.mmio =/= f3_pmp_mmio,
745        ExceptionType.af,
746        ExceptionType.none
747      )
748      val exception = ExceptionType.merge(pmp_exception, mmio_mismatch_exception)
749      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
750      mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_resendReq)
751      // also save pmp response
752      mmio_resend_exception := exception
753    }
754
755    is(m_resendReq) {
756      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
757    }
758
759    is(m_waitResendResp) {
760      when(fromUncache.fire) {
761        mmio_state      := m_waitCommit
762        f3_mmio_data(1) := fromUncache.bits.data(15, 0)
763      }
764    }
765
766    is(m_waitCommit) {
767      mmio_state := Mux(mmio_commit, m_commited, m_waitCommit)
768    }
769
770    // normal mmio instruction
771    is(m_commited) {
772      mmio_state                    := m_idle
773      mmio_is_RVC                   := false.B
774      mmio_resend_addr              := 0.U
775      mmio_resend_exception         := ExceptionType.none
776      mmio_resend_gpaddr            := 0.U
777      mmio_resend_isForVSnonLeafPTE := false.B
778    }
779  }
780
781  // Exception or flush by older branch prediction
782  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
783  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
784    mmio_state                    := m_idle
785    mmio_is_RVC                   := false.B
786    mmio_resend_addr              := 0.U
787    mmio_resend_exception         := ExceptionType.none
788    mmio_resend_gpaddr            := 0.U
789    mmio_resend_isForVSnonLeafPTE := false.B
790    f3_mmio_data.map(_ := 0.U)
791  }
792
793  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
794  toUncache.bits.addr := Mux(mmio_state === m_resendReq, mmio_resend_addr, f3_paddrs(0))
795  fromUncache.ready   := true.B
796
797  // send itlb request in m_sendTLB state
798  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
799  io.iTLBInter.req.bits.size               := 3.U
800  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
801  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
802  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
803  io.iTLBInter.req.bits.isPrefetch         := false.B
804  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
805  io.iTLBInter.req.bits.no_translate       := false.B
806  io.iTLBInter.req.bits.fullva             := 0.U
807  io.iTLBInter.req.bits.checkfullva        := false.B
808  io.iTLBInter.req.bits.hyperinst          := DontCare
809  io.iTLBInter.req.bits.hlvx               := DontCare
810  io.iTLBInter.req.bits.memidx             := DontCare
811  io.iTLBInter.req.bits.debug.robIdx       := DontCare
812  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
813  io.iTLBInter.req.bits.pmp_addr           := DontCare
814  // whats the difference between req_kill and req.bits.kill?
815  io.iTLBInter.req_kill := false.B
816  // wait for itlb response in m_tlbResp state
817  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
818
819  io.pmp.req.valid     := (mmio_state === m_sendPMP) && f3_req_is_mmio
820  io.pmp.req.bits.addr := mmio_resend_addr
821  io.pmp.req.bits.size := 3.U
822  io.pmp.req.bits.cmd  := TlbCmd.exec
823
824  val f3_lastHalf = RegInit(0.U.asTypeOf(new LastHalfInfo))
825
826  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
827  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if (i == 0) true.B else false.B))
828  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
829
830  /*** prediction result check   ***/
831  checkerIn.ftqOffset  := f3_ftq_req.ftqOffset
832  checkerIn.jumpOffset := f3_jump_offset
833  checkerIn.target     := f3_ftq_req.nextStartAddr
834  checkerIn.instrRange := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
835  checkerIn.instrValid := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
836  checkerIn.pds        := f3_pd
837  checkerIn.pc         := f3_pc
838  checkerIn.fire_in    := RegNext(f2_fire, init = false.B)
839
840  /*** handle half RVI in the last 2 Bytes  ***/
841
842  def hasLastHalf(idx: UInt) =
843    // !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
844    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(
845      idx
846    ) && !f3_req_is_mmio
847
848  val f3_last_validIdx = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
849
850  val f3_hasLastHalf    = hasLastHalf((PredictWidth - 1).U)
851  val f3_false_lastHalf = hasLastHalf(f3_last_validIdx)
852  val f3_false_snpc     = f3_half_snpc(f3_last_validIdx)
853
854  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map(i => if (i == 0) false.B else true.B)).asUInt
855  val f3_lastHalf_disable = RegInit(false.B)
856
857  when(f3_flush || (f3_fire && f3_lastHalf_disable)) {
858    f3_lastHalf_disable := false.B
859  }
860
861  when(f3_flush) {
862    f3_lastHalf.valid := false.B
863  }.elsewhen(f3_fire) {
864    f3_lastHalf.valid    := f3_hasLastHalf && !f3_lastHalf_disable
865    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
866  }
867
868  f3_instr_valid := Mux(f3_lastHalf.valid, f3_hasHalfValid, VecInit(f3_pd.map(inst => inst.valid)))
869
870  /*** frontend Trigger  ***/
871  frontendTrigger.io.pds  := f3_pd
872  frontendTrigger.io.pc   := f3_pc
873  frontendTrigger.io.data := f3_cut_data
874
875  frontendTrigger.io.frontendTrigger := io.frontendTrigger
876
877  val f3_triggered       = frontendTrigger.io.triggered
878  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
879
880  /*** send to Ibuffer  ***/
881  io.toIbuffer.valid          := f3_toIbuffer_valid
882  io.toIbuffer.bits.instrs    := f3_expd_instr
883  io.toIbuffer.bits.valid     := f3_instr_valid.asUInt
884  io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
885  io.toIbuffer.bits.pd        := f3_pd
886  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
887  io.toIbuffer.bits.pc        := f3_pc
888  // Find last using PriorityMux
889  io.toIbuffer.bits.isLastInFtqEntry := Reverse(PriorityEncoderOH(Reverse(io.toIbuffer.bits.enqEnable))).asBools
890  io.toIbuffer.bits.ftqOffset.zipWithIndex.map { case (a, i) =>
891    a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio
892  }
893  io.toIbuffer.bits.foldpc        := f3_foldpc
894  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
895  // backendException only needs to be set for the first instruction.
896  // Other instructions in the same block may have pf or af set,
897  // which is a side effect of the first instruction and actually not necessary.
898  io.toIbuffer.bits.backendException := (0 until PredictWidth).map {
899    case 0 => f3_backendException
900    case _ => false.B
901  }
902  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(ExceptionType.hasException)
903  io.toIbuffer.bits.illegalInstr    := f3_ill
904  io.toIbuffer.bits.triggered       := f3_triggered
905
906  when(f3_lastHalf.valid) {
907    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
908    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
909  }
910
911  /** to backend */
912  // f3_gpaddr is valid iff gpf is detected
913  io.toBackend.gpaddrMem_wen := f3_toIbuffer_valid && Mux(
914    f3_req_is_mmio,
915    mmio_resend_exception === ExceptionType.gpf,
916    f3_exception.map(_ === ExceptionType.gpf).reduce(_ || _)
917  )
918  io.toBackend.gpaddrMem_waddr        := f3_ftq_req.ftqIdx.value
919  io.toBackend.gpaddrMem_wdata.gpaddr := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
920  io.toBackend.gpaddrMem_wdata.isForVSnonLeafPTE := Mux(
921    f3_req_is_mmio,
922    mmio_resend_isForVSnonLeafPTE,
923    f3_isForVSnonLeafPTE
924  )
925
926  // Write back to Ftq
927  val f3_cache_fetch     = f3_valid && !(f2_fire && !f2_flush)
928  val finishFetchMaskReg = RegNext(f3_cache_fetch)
929
930  val mmioFlushWb        = Wire(Valid(new PredecodeWritebackBundle))
931  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
932  f3_mmio_missOffset.valid := f3_req_is_mmio
933  f3_mmio_missOffset.bits  := 0.U
934
935  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
936  // When backend redirect, mmio_state reset after 1 cycle.
937  // In this case, mask .valid to avoid overriding backend redirect
938  mmioFlushWb.valid := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
939    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
940  mmioFlushWb.bits.pc := f3_pc
941  mmioFlushWb.bits.pd := f3_pd
942  mmioFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := f3_mmio_range(i) }
943  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
944  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
945  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
946  mmioFlushWb.bits.cfiOffset  := DontCare
947  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U, f3_ftq_req.startAddr + 4.U)
948  mmioFlushWb.bits.jalTarget  := DontCare
949  mmioFlushWb.bits.instrRange := f3_mmio_range
950
951  val mmioRVCExpander = Module(new RVCExpander)
952  mmioRVCExpander.io.in      := Mux(f3_req_is_mmio, Cat(f3_mmio_data(1), f3_mmio_data(0)), 0.U)
953  mmioRVCExpander.io.fsIsOff := io.csr_fsIsOff
954
955  /** external predecode for MMIO instruction */
956  when(f3_req_is_mmio) {
957    val inst         = Cat(f3_mmio_data(1), f3_mmio_data(0))
958    val currentIsRVC = isRVC(inst)
959
960    val brType :: isCall :: isRet :: Nil = brInfo(inst)
961    val jalOffset                        = jal_offset(inst, currentIsRVC)
962    val brOffset                         = br_offset(inst, currentIsRVC)
963
964    io.toIbuffer.bits.instrs(0) := Mux(mmioRVCExpander.io.ill, mmioRVCExpander.io.in, mmioRVCExpander.io.out.bits)
965
966    io.toIbuffer.bits.pd(0).valid  := true.B
967    io.toIbuffer.bits.pd(0).isRVC  := currentIsRVC
968    io.toIbuffer.bits.pd(0).brType := brType
969    io.toIbuffer.bits.pd(0).isCall := isCall
970    io.toIbuffer.bits.pd(0).isRet  := isRet
971
972    io.toIbuffer.bits.exceptionType(0)   := mmio_resend_exception
973    io.toIbuffer.bits.crossPageIPFFix(0) := ExceptionType.hasException(mmio_resend_exception)
974    io.toIbuffer.bits.illegalInstr(0)    := mmioRVCExpander.io.ill
975
976    io.toIbuffer.bits.enqEnable := f3_mmio_range.asUInt
977
978    mmioFlushWb.bits.pd(0).valid  := true.B
979    mmioFlushWb.bits.pd(0).isRVC  := currentIsRVC
980    mmioFlushWb.bits.pd(0).brType := brType
981    mmioFlushWb.bits.pd(0).isCall := isCall
982    mmioFlushWb.bits.pd(0).isRet  := isRet
983  }
984
985  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) && f3_mmio_use_seq_pc)
986
987  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready", io.toIbuffer.valid && !io.toIbuffer.ready)
988
989  /**
990    ******************************************************************************
991    * IFU Write Back Stage
992    * - write back predecode information to Ftq to update
993    * - redirect if found fault prediction
994    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
995    ******************************************************************************
996    */
997  val wb_enable  = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
998  val wb_valid   = RegNext(wb_enable, init = false.B)
999  val wb_ftq_req = RegEnable(f3_ftq_req, wb_enable)
1000
1001  val wb_check_result_stage1 = RegEnable(checkerOutStage1, wb_enable)
1002  val wb_check_result_stage2 = checkerOutStage2
1003  val wb_instr_range         = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
1004
1005  val wb_pc_lower_result = RegEnable(f3_pc_lower_result, wb_enable)
1006  val wb_pc_high         = RegEnable(f3_pc_high, wb_enable)
1007  val wb_pc_high_plus1   = RegEnable(f3_pc_high_plus1, wb_enable)
1008  val wb_pc              = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
1009
1010  // val wb_pc             = RegEnable(f3_pc, wb_enable)
1011  val wb_pd          = RegEnable(f3_pd, wb_enable)
1012  val wb_instr_valid = RegEnable(f3_instr_valid, wb_enable)
1013
1014  /* false hit lastHalf */
1015  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
1016  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
1017  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
1018
1019  val wb_half_flush  = wb_false_lastHalf
1020  val wb_half_target = wb_false_target
1021
1022  /* false oversize */
1023  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool())).last && wb_pd.last.isRVC
1024  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
1025  val lastTaken = wb_check_result_stage1.fixedTaken.last
1026
1027  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
1028
1029  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
1030    * we set a flag to notify f3 that the last half flag need not to be set.
1031    */
1032  // f3_fire is after wb_valid
1033  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1034    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire && !RegNext(
1035      f3_fire,
1036      init = false.B
1037    ) && !f3_flush) {
1038    f3_lastHalf_disable := true.B
1039  }
1040
1041  // wb_valid and f3_fire are in same cycle
1042  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1043    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire) {
1044    f3_lastHalf.valid := false.B
1045  }
1046
1047  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
1048  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map { case (pd, v) =>
1049    v && pd.isJal
1050  }))
1051  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1052  checkFlushWb.valid   := wb_valid
1053  checkFlushWb.bits.pc := wb_pc
1054  checkFlushWb.bits.pd := wb_pd
1055  checkFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := wb_instr_valid(i) }
1056  checkFlushWb.bits.ftqIdx          := wb_ftq_req.ftqIdx
1057  checkFlushWb.bits.ftqOffset       := wb_ftq_req.ftqOffset.bits
1058  checkFlushWb.bits.misOffset.valid := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
1059  checkFlushWb.bits.misOffset.bits := Mux(
1060    wb_half_flush,
1061    wb_lastIdx,
1062    ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1063  )
1064  checkFlushWb.bits.cfiOffset.valid := ParallelOR(wb_check_result_stage1.fixedTaken)
1065  checkFlushWb.bits.cfiOffset.bits  := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
1066  checkFlushWb.bits.target := Mux(
1067    wb_half_flush,
1068    wb_half_target,
1069    wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx)
1070  )
1071  checkFlushWb.bits.jalTarget  := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
1072  checkFlushWb.bits.instrRange := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
1073
1074  toFtq.pdWb := Mux(wb_valid, checkFlushWb, mmioFlushWb)
1075
1076  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
1077
1078  /*write back flush type*/
1079  val checkFaultType    = wb_check_result_stage2.faultType
1080  val checkJalFault     = wb_valid && checkFaultType.map(_.isjalFault).reduce(_ || _)
1081  val checkRetFault     = wb_valid && checkFaultType.map(_.isRetFault).reduce(_ || _)
1082  val checkTargetFault  = wb_valid && checkFaultType.map(_.istargetFault).reduce(_ || _)
1083  val checkNotCFIFault  = wb_valid && checkFaultType.map(_.notCFIFault).reduce(_ || _)
1084  val checkInvalidTaken = wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_ || _)
1085
1086  XSPerfAccumulate("predecode_flush_jalFault", checkJalFault)
1087  XSPerfAccumulate("predecode_flush_retFault", checkRetFault)
1088  XSPerfAccumulate("predecode_flush_targetFault", checkTargetFault)
1089  XSPerfAccumulate("predecode_flush_notCFIFault", checkNotCFIFault)
1090  XSPerfAccumulate("predecode_flush_incalidTakenFault", checkInvalidTaken)
1091
1092  when(checkRetFault) {
1093    XSDebug(
1094      "startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1095      wb_ftq_req.startAddr,
1096      wb_ftq_req.nextStartAddr,
1097      wb_ftq_req.ftqOffset.valid,
1098      wb_ftq_req.ftqOffset.bits
1099    )
1100  }
1101
1102  /** performance counter */
1103  val f3_perf_info = RegEnable(f2_perf_info, f2_fire)
1104  val f3_req_0     = io.toIbuffer.fire
1105  val f3_req_1     = io.toIbuffer.fire && f3_doubleLine
1106  val f3_hit_0     = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1107  val f3_hit_1     = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
1108  val f3_hit       = f3_perf_info.hit
1109  val perfEvents = Seq(
1110    ("frontendFlush                ", wb_redirect),
1111    ("ifu_req                      ", io.toIbuffer.fire),
1112    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit),
1113    ("ifu_req_cacheline_0          ", f3_req_0),
1114    ("ifu_req_cacheline_1          ", f3_req_1),
1115    ("ifu_req_cacheline_0_hit      ", f3_hit_1),
1116    ("ifu_req_cacheline_1_hit      ", f3_hit_1),
1117    ("only_0_hit                   ", f3_perf_info.only_0_hit && io.toIbuffer.fire),
1118    ("only_0_miss                  ", f3_perf_info.only_0_miss && io.toIbuffer.fire),
1119    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire),
1120    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire),
1121    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire),
1122    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1123  )
1124  generatePerfEvent()
1125
1126  XSPerfAccumulate("ifu_req", io.toIbuffer.fire)
1127  XSPerfAccumulate("ifu_miss", io.toIbuffer.fire && !f3_hit)
1128  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0)
1129  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1)
1130  XSPerfAccumulate("ifu_req_cacheline_0_hit", f3_hit_0)
1131  XSPerfAccumulate("ifu_req_cacheline_1_hit", f3_hit_1)
1132  XSPerfAccumulate("frontendFlush", wb_redirect)
1133  XSPerfAccumulate("only_0_hit", f3_perf_info.only_0_hit && io.toIbuffer.fire)
1134  XSPerfAccumulate("only_0_miss", f3_perf_info.only_0_miss && io.toIbuffer.fire)
1135  XSPerfAccumulate("hit_0_hit_1", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire)
1136  XSPerfAccumulate("hit_0_miss_1", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire)
1137  XSPerfAccumulate("miss_0_hit_1", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire)
1138  XSPerfAccumulate("miss_0_miss_1", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1139  XSPerfAccumulate("hit_0_except_1", f3_perf_info.hit_0_except_1 && io.toIbuffer.fire)
1140  XSPerfAccumulate("miss_0_except_1", f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1141  XSPerfAccumulate("except_0", f3_perf_info.except_0 && io.toIbuffer.fire)
1142  XSPerfHistogram(
1143    "ifu2ibuffer_validCnt",
1144    PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable),
1145    io.toIbuffer.fire,
1146    0,
1147    PredictWidth + 1,
1148    1
1149  )
1150
1151  val hartId                     = p(XSCoreParamsKey).HartId
1152  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1153  val isWriteIfuWbToFtqTable     = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1154  val fetchToIBufferTable        = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1155  val ifuWbToFtqTable            = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
1156
1157  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
1158  fetchIBufferDumpData.start_addr  := f3_ftq_req.startAddr
1159  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1160  fetchIBufferDumpData.exception := (f3_perf_info.except_0 && io.toIbuffer.fire) || (f3_perf_info.hit_0_except_1 && io.toIbuffer.fire) || (f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1161  fetchIBufferDumpData.is_cache_hit := f3_hit
1162
1163  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
1164  ifuWbToFtqDumpData.start_addr        := wb_ftq_req.startAddr
1165  ifuWbToFtqDumpData.is_miss_pred      := checkFlushWb.bits.misOffset.valid
1166  ifuWbToFtqDumpData.miss_pred_offset  := checkFlushWb.bits.misOffset.bits
1167  ifuWbToFtqDumpData.checkJalFault     := checkJalFault
1168  ifuWbToFtqDumpData.checkRetFault     := checkRetFault
1169  ifuWbToFtqDumpData.checkTargetFault  := checkTargetFault
1170  ifuWbToFtqDumpData.checkNotCFIFault  := checkNotCFIFault
1171  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
1172
1173  fetchToIBufferTable.log(
1174    data = fetchIBufferDumpData,
1175    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
1176    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1177    clock = clock,
1178    reset = reset
1179  )
1180  ifuWbToFtqTable.log(
1181    data = ifuWbToFtqDumpData,
1182    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
1183    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1184    clock = clock,
1185    reset = reset
1186  )
1187
1188}
1189