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