xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 7b7232f9835c5d30c12e3212e9676f79b283dccd)
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_except_pf    = VecInit((0 until PortNumber).map(i => fromICache(i).bits.tlbExcp.pageFault))
380  val f2_except_gpf   = VecInit((0 until PortNumber).map(i => fromICache(i).bits.tlbExcp.guestPageFault))
381  val f2_except_af    = VecInit((0 until PortNumber).map(i => fromICache(i).bits.tlbExcp.accessFault))
382  // paddr and gpaddr of [startAddr, nextLineAddr]
383  val f2_paddrs       = VecInit((0 until PortNumber).map(i => fromICache(i).bits.paddr))
384  val f2_gpaddr       = fromICache(0).bits.gpaddr
385  val f2_mmio         = fromICache(0).bits.tlbExcp.mmio &&
386    !fromICache(0).bits.tlbExcp.accessFault &&
387    !fromICache(0).bits.tlbExcp.pageFault   &&
388    !fromICache(0).bits.tlbExcp.guestPageFault
389
390  /**
391    * reduce the number of registers, origin code
392    * f2_pc = RegEnable(f1_pc, f1_fire)
393    */
394  val f2_pc_lower_result        = RegEnable(f1_pc_lower_result, f1_fire)
395  val f2_pc_high                = RegEnable(f1_pc_high, f1_fire)
396  val f2_pc_high_plus1          = RegEnable(f1_pc_high_plus1, f1_fire)
397  val f2_pc                     = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
398
399  val f2_cut_ptr                = RegEnable(f1_cut_ptr, f1_fire)
400  val f2_resend_vaddr           = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
401
402  def isNextLine(pc: UInt, startAddr: UInt) = {
403    startAddr(blockOffBits) ^ pc(blockOffBits)
404  }
405
406  def isLastInLine(pc: UInt) = {
407    pc(blockOffBits - 1, 0) === "b111110".U
408  }
409
410  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits-1,1), MemPredPCWidth)))
411  val f2_jump_range = Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
412  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)
413  val f2_instr_range = f2_jump_range & f2_ftr_range
414  val f2_pf_vec = VecInit((0 until PredictWidth).map(i => (!isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_except_pf(0)   ||  isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine &&  f2_except_pf(1))))
415  val f2_af_vec = VecInit((0 until PredictWidth).map(i => (!isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_except_af(0)   ||  isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine && f2_except_af(1))))
416  val f2_gpf_vec = VecInit((0 until PredictWidth).map(i => (!isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_except_gpf(0) || isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine && f2_except_gpf(1))))
417  val f2_perf_info    = io.icachePerfInfo
418
419  def cut(cacheline: UInt, cutPtr: Vec[UInt]) : Vec[UInt] ={
420    require(HasCExtension)
421    // if(HasCExtension){
422      val result   = Wire(Vec(PredictWidth + 1, UInt(16.W)))
423      val dataVec  = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) //32 16-bit data vector
424      (0 until PredictWidth + 1).foreach( i =>
425        result(i) := dataVec(cutPtr(i)) //the max ptr is 3*blockBytes/4-1
426      )
427      result
428    // } else {
429    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
430    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
431    //   (0 until PredictWidth).foreach( i =>
432    //     result(i) := dataVec(cutPtr(i))
433    //   )
434    //   result
435    // }
436  }
437
438  val f2_cache_response_data = fromICache.map(_.bits.data)
439  val f2_data_2_cacheline = Cat(f2_cache_response_data(0), f2_cache_response_data(0))
440
441  val f2_cut_data   = cut(f2_data_2_cacheline, f2_cut_ptr)
442
443  /** predecode (include RVC expander) */
444  // preDecoderRegIn.data := f2_reg_cut_data
445  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
446  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
447  // preDecoderRegIn.pc  := f2_pc
448
449  val preDecoderIn  = preDecoder.io.in
450  preDecoderIn.valid := f2_valid
451  preDecoderIn.bits.data := f2_cut_data
452  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
453  preDecoderIn.bits.pc  := f2_pc
454  val preDecoderOut = preDecoder.io.out
455
456  //val f2_expd_instr     = preDecoderOut.expInstr
457  val f2_instr          = preDecoderOut.instr
458  val f2_pd             = preDecoderOut.pd
459  val f2_jump_offset    = preDecoderOut.jumpOffset
460  val f2_hasHalfValid   =  preDecoderOut.hasHalfValid
461  val f2_crossPageFault = VecInit((0 until PredictWidth).map(i => isLastInLine(f2_pc(i)) && !f2_except_pf(0) && f2_doubleLine &&  f2_except_pf(1) && !f2_pd(i).isRVC ))
462  val f2_crossGuestPageFault = VecInit((0 until PredictWidth).map(i => isLastInLine(f2_pc(i)) && !f2_except_gpf(0) && f2_doubleLine && f2_except_gpf(1) && !f2_pd(i).isRVC ))
463  XSPerfAccumulate("fetch_bubble_icache_not_resp",   f2_valid && !icacheRespAllValid )
464
465
466  /**
467    ******************************************************************************
468    * IFU Stage 3
469    * - handle MMIO instruciton
470    *  -send request to Uncache fetch Unit
471    *  -every packet include 1 MMIO instruction
472    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
473    *  -flush to snpc (send ifu_redirect to Ftq)
474    * - Ibuffer enqueue
475    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
476    * - handle last half RVI instruction
477    ******************************************************************************
478    */
479
480  val f3_valid          = RegInit(false.B)
481  val f3_ftq_req        = RegEnable(f2_ftq_req,    f2_fire)
482  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
483  val f3_doubleLine     = RegEnable(f2_doubleLine, f2_fire)
484  val f3_fire           = io.toIbuffer.fire
485
486  val f3_cut_data       = RegEnable(f2_cut_data, f2_fire)
487
488  val f3_except_pf      = RegEnable(f2_except_pf,  f2_fire)
489  val f3_except_af      = RegEnable(f2_except_af,  f2_fire)
490  val f3_except_gpf     = RegEnable(f2_except_gpf,  f2_fire)
491  val f3_mmio           = RegEnable(f2_mmio   ,  f2_fire)
492
493  //val f3_expd_instr     = RegEnable(f2_expd_instr,  f2_fire)
494  val f3_instr          = RegEnable(f2_instr, f2_fire)
495  val f3_expd_instr     = VecInit((0 until PredictWidth).map{ i =>
496    val expander       = Module(new RVCExpander)
497    expander.io.in := f3_instr(i)
498    expander.io.out.bits
499  })
500
501  val f3_pd_wire        = RegEnable(f2_pd,          f2_fire)
502  val f3_pd             = WireInit(f3_pd_wire)
503  val f3_jump_offset    = RegEnable(f2_jump_offset, f2_fire)
504  val f3_af_vec         = RegEnable(f2_af_vec,      f2_fire)
505  val f3_pf_vec         = RegEnable(f2_pf_vec ,     f2_fire)
506  val f3_gpf_vec        = RegEnable(f2_gpf_vec,     f2_fire)
507
508  val f3_pc_lower_result        = RegEnable(f2_pc_lower_result, f2_fire)
509  val f3_pc_high                = RegEnable(f2_pc_high, f2_fire)
510  val f3_pc_high_plus1          = RegEnable(f2_pc_high_plus1, f2_fire)
511  val f3_pc             = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
512
513  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
514  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
515  //val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
516
517  /**
518    ***********************************************************************
519    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
520    ***********************************************************************
521    */
522  val f3_half_snpc      = Wire(Vec(PredictWidth,UInt(VAddrBits.W)))
523  for(i <- 0 until PredictWidth){
524    if(i == (PredictWidth - 2)){
525      f3_half_snpc(i)   := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
526    } else if (i == (PredictWidth - 1)){
527      f3_half_snpc(i)   := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
528    } else {
529      f3_half_snpc(i)   := f3_pc(i+2)
530    }
531  }
532
533  val f3_instr_range    = RegEnable(f2_instr_range, f2_fire)
534  val f3_foldpc         = RegEnable(f2_foldpc,      f2_fire)
535  val f3_crossPageFault = RegEnable(f2_crossPageFault,           f2_fire)
536  val f3_crossGuestPageFault = RegEnable(f2_crossGuestPageFault, f2_fire)
537  val f3_hasHalfValid   = RegEnable(f2_hasHalfValid,             f2_fire)
538  val f3_except         = VecInit((0 until 2).map{i => f3_except_pf(i) || f3_except_af(i) || f3_except_gpf(i)})
539  val f3_has_except     = f3_valid && (f3_except_af.reduce(_||_) || f3_except_pf.reduce(_||_) || f3_except_gpf.reduce(_||_))
540  val f3_paddrs         = RegEnable(f2_paddrs,  f2_fire)
541  val f3_gpaddr         = RegEnable(f2_gpaddr,  f2_fire)
542  val f3_resend_vaddr   = RegEnable(f2_resend_vaddr,             f2_fire)
543
544  // Expand 1 bit to prevent overflow when assert
545  val f3_ftq_req_startAddr      = Cat(0.U(1.W), f3_ftq_req.startAddr)
546  val f3_ftq_req_nextStartAddr  = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
547  // brType, isCall and isRet generation is delayed to f3 stage
548  val f3Predecoder = Module(new F3Predecoder)
549
550  f3Predecoder.io.in.instr := f3_instr
551
552  f3_pd.zipWithIndex.map{ case (pd,i) =>
553    pd.brType := f3Predecoder.io.out.pd(i).brType
554    pd.isCall := f3Predecoder.io.out.pd(i).isCall
555    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
556  }
557
558  val f3PdDiff = f3_pd_wire.zip(f3_pd).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_)
559  XSError(f3_valid && f3PdDiff, "f3 pd diff")
560
561  when(f3_valid && !f3_ftq_req.ftqOffset.valid){
562    assert(f3_ftq_req_startAddr + (2*PredictWidth).U >= f3_ftq_req_nextStartAddr, s"More tha ${2*PredictWidth} Bytes fetch is not allowed!")
563  }
564
565  /*** MMIO State Machine***/
566  val f3_mmio_data       = Reg(Vec(2, UInt(16.W)))
567  val mmio_is_RVC        = RegInit(false.B)
568  val mmio_resend_addr   = RegInit(0.U(PAddrBits.W))
569  val mmio_resend_af     = RegInit(false.B)
570  val mmio_resend_pf     = RegInit(false.B)
571  val mmio_resend_gpf    = RegInit(false.B)
572  val mmio_resend_gpaddr = RegInit(0.U(GPAddrBits.W))
573
574  //last instuction finish
575  val is_first_instr = RegInit(true.B)
576  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
577  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
578
579  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)
580  val mmio_state = RegInit(m_idle)
581
582  val f3_req_is_mmio     = f3_mmio && f3_valid
583  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
584  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
585
586  val f3_mmio_to_commit =  f3_req_is_mmio && mmio_state === m_waitCommit
587  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
588  val f3_mmio_can_go      = f3_mmio_to_commit && !f3_mmio_to_commit_next
589
590  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
591  fromFtqRedirectReg.bits := RegEnable(fromFtq.redirect.bits, 0.U.asTypeOf(fromFtq.redirect.bits), fromFtq.redirect.valid)
592  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
593  val mmioF3Flush           = RegNext(f3_flush,init = false.B)
594  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
595  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
596
597  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
598
599  /**
600    **********************************************************************************
601    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
602    * This is the exception when the first instruction is an MMIO instruction.
603    **********************************************************************************
604    */
605  when(is_first_instr && f3_fire){
606    is_first_instr := false.B
607  }
608
609  when(f3_flush && !f3_req_is_mmio)                                                 {f3_valid := false.B}
610  .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)                    {f3_valid := false.B}
611  .elsewhen(f2_fire && !f2_flush )                                                  {f3_valid := true.B }
612  .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)                                   {f3_valid := false.B}
613  .elsewhen{f3_req_is_mmio && f3_mmio_req_commit}                                   {f3_valid := false.B}
614
615  val f3_mmio_use_seq_pc = RegInit(false.B)
616
617  val (redirect_ftqIdx, redirect_ftqOffset)  = (fromFtqRedirectReg.bits.ftqIdx,fromFtqRedirectReg.bits.ftqOffset)
618  val redirect_mmio_req = fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
619
620  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)        { f3_mmio_use_seq_pc := true.B  }
621  .elsewhen(redirect_mmio_req)                                 { f3_mmio_use_seq_pc := false.B }
622
623  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
624
625  // mmio state machine
626  switch(mmio_state){
627    is(m_idle){
628      when(f3_req_is_mmio){
629        mmio_state := m_waitLastCmt
630      }
631    }
632
633    is(m_waitLastCmt){
634      when(is_first_instr){
635        mmio_state := m_sendReq
636      }.otherwise{
637        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
638      }
639    }
640
641    is(m_sendReq){
642      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
643    }
644
645    is(m_waitResp){
646      when(fromUncache.fire){
647          val isRVC = fromUncache.bits.data(1,0) =/= 3.U
648          val needResend = !isRVC && f3_paddrs(0)(2,1) === 3.U
649          mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
650          mmio_is_RVC     := isRVC
651          f3_mmio_data(0) := fromUncache.bits.data(15,0)
652          f3_mmio_data(1) := fromUncache.bits.data(31,16)
653      }
654    }
655
656    is(m_sendTLB){
657      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
658    }
659
660    is(m_tlbResp){
661      when(io.iTLBInter.resp.fire) {
662        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
663        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
664        val tlbExcp = io.iTLBInter.resp.bits.excp(0).pf.instr ||
665                      io.iTLBInter.resp.bits.excp(0).af.instr ||
666                      io.iTLBInter.resp.bits.excp(0).gpf.instr
667        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
668        mmio_state         := Mux(tlbExcp, m_waitCommit, m_sendPMP)
669        // also save itlb response
670        mmio_resend_addr   := io.iTLBInter.resp.bits.paddr(0)
671        mmio_resend_af     := mmio_resend_af || io.iTLBInter.resp.bits.excp(0).af.instr
672        mmio_resend_pf     := mmio_resend_pf || io.iTLBInter.resp.bits.excp(0).pf.instr
673        mmio_resend_gpf    := mmio_resend_gpf || io.iTLBInter.resp.bits.excp(0).gpf.instr
674        mmio_resend_gpaddr := io.iTLBInter.resp.bits.gpaddr(0)
675      }
676    }
677
678    is(m_sendPMP){
679      val pmpExcpAF = io.pmp.resp.instr || !io.pmp.resp.mmio
680      mmio_state     := Mux(pmpExcpAF, m_waitCommit, m_resendReq)
681      mmio_resend_af := mmio_resend_af || pmpExcpAF
682    }
683
684    is(m_resendReq){
685      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
686    }
687
688    is(m_waitResendResp) {
689      when(fromUncache.fire) {
690        mmio_state      := m_waitCommit
691        f3_mmio_data(1) := fromUncache.bits.data(15,0)
692      }
693    }
694
695    is(m_waitCommit) {
696      mmio_state := Mux(mmio_commit, m_commited, m_waitCommit)
697    }
698
699    //normal mmio instruction
700    is(m_commited) {
701      mmio_state         := m_idle
702      mmio_is_RVC        := false.B
703      mmio_resend_addr   := 0.U
704      mmio_resend_af     := false.B
705      mmio_resend_pf     := false.B
706      mmio_resend_gpf    := false.B
707      mmio_resend_gpaddr := 0.U
708    }
709  }
710
711  // Exception or flush by older branch prediction
712  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
713  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
714    mmio_state         := m_idle
715    mmio_is_RVC        := false.B
716    mmio_resend_addr   := 0.U
717    mmio_resend_af     := false.B
718    mmio_resend_pf     := false.B
719    mmio_resend_gpf    := false.B
720    mmio_resend_gpaddr := 0.U
721    f3_mmio_data.map(_ := 0.U)
722  }
723
724  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
725  toUncache.bits.addr := Mux((mmio_state === m_resendReq), mmio_resend_addr, f3_paddrs(0))
726  fromUncache.ready   := true.B
727
728  // send itlb request in m_sendTLB state
729  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
730  io.iTLBInter.req.bits.size               := 3.U
731  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
732  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
733  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
734  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
735  io.iTLBInter.req.bits.no_translate       := false.B
736  io.iTLBInter.req.bits.hyperinst          := DontCare
737  io.iTLBInter.req.bits.hlvx               := DontCare
738  io.iTLBInter.req.bits.memidx             := DontCare
739  io.iTLBInter.req.bits.debug.robIdx       := DontCare
740  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
741  io.iTLBInter.req.bits.pmp_addr           := DontCare
742  // whats the difference between req_kill and req.bits.kill?
743  io.iTLBInter.req_kill := false.B
744  // wait for itlb response in m_tlbResp state
745  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
746
747  io.pmp.req.valid := (mmio_state === m_sendPMP) && f3_req_is_mmio
748  io.pmp.req.bits.addr  := mmio_resend_addr
749  io.pmp.req.bits.size  := 3.U
750  io.pmp.req.bits.cmd   := TlbCmd.exec
751
752  val f3_lastHalf       = RegInit(0.U.asTypeOf(new LastHalfInfo))
753
754  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
755  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if(i ==0) true.B else false.B))
756  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
757
758  /*** prediction result check   ***/
759  checkerIn.ftqOffset   := f3_ftq_req.ftqOffset
760  checkerIn.jumpOffset  := f3_jump_offset
761  checkerIn.target      := f3_ftq_req.nextStartAddr
762  checkerIn.instrRange  := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
763  checkerIn.instrValid  := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
764  checkerIn.pds         := f3_pd
765  checkerIn.pc          := f3_pc
766  checkerIn.fire_in     := RegNext(f2_fire, init = false.B)
767
768  /*** handle half RVI in the last 2 Bytes  ***/
769
770  def hasLastHalf(idx: UInt) = {
771    //!f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
772    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && ! f3_req_is_mmio
773  }
774
775  val f3_last_validIdx       = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
776
777  val f3_hasLastHalf         = hasLastHalf((PredictWidth - 1).U)
778  val f3_false_lastHalf      = hasLastHalf(f3_last_validIdx)
779  val f3_false_snpc          = f3_half_snpc(f3_last_validIdx)
780
781  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map( i => if(i ==0) false.B else true.B )).asUInt
782  val f3_lastHalf_disable = RegInit(false.B)
783
784  when(f3_flush || (f3_fire && f3_lastHalf_disable)){
785    f3_lastHalf_disable := false.B
786  }
787
788  when (f3_flush) {
789    f3_lastHalf.valid := false.B
790  }.elsewhen (f3_fire) {
791    f3_lastHalf.valid := f3_hasLastHalf && !f3_lastHalf_disable
792    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
793  }
794
795  f3_instr_valid := Mux(f3_lastHalf.valid,f3_hasHalfValid ,VecInit(f3_pd.map(inst => inst.valid)))
796
797  /*** frontend Trigger  ***/
798  frontendTrigger.io.pds  := f3_pd
799  frontendTrigger.io.pc   := f3_pc
800  frontendTrigger.io.data   := f3_cut_data
801
802  frontendTrigger.io.frontendTrigger  := io.frontendTrigger
803
804  val f3_triggered = frontendTrigger.io.triggered
805  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
806
807  /*** send to Ibuffer  ***/
808  io.toIbuffer.valid            := f3_toIbuffer_valid
809  io.toIbuffer.bits.instrs      := f3_expd_instr
810  io.toIbuffer.bits.valid       := f3_instr_valid.asUInt
811  io.toIbuffer.bits.enqEnable   := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
812  io.toIbuffer.bits.pd          := f3_pd
813  io.toIbuffer.bits.ftqPtr      := f3_ftq_req.ftqIdx
814  io.toIbuffer.bits.pc          := f3_pc
815  io.toIbuffer.bits.ftqOffset.zipWithIndex.map{case(a, i) => a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio}
816  io.toIbuffer.bits.foldpc      := f3_foldpc
817  io.toIbuffer.bits.exceptionType := (0 until PredictWidth).map(i => MuxCase(ExceptionType.none, Seq(
818    (f3_pf_vec(i) || f3_crossPageFault(i)) -> ExceptionType.ipf,
819    (f3_gpf_vec(i) || f3_crossGuestPageFault(i)) -> ExceptionType.igpf,
820    f3_af_vec(i) -> ExceptionType.acf
821  )))
822  io.toIbuffer.bits.crossPageIPFFix := (0 until PredictWidth).map(i => f3_crossPageFault(i) || f3_crossGuestPageFault(i))
823  io.toIbuffer.bits.triggered   := f3_triggered
824
825  when(f3_lastHalf.valid){
826    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
827    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
828  }
829
830  /** to backend */
831  // f3_gpaddr is valid iff gpf is detected
832  io.toBackend.gpaddrMem_wen   := f3_toIbuffer_valid && Mux(
833    f3_req_is_mmio,
834    mmio_resend_gpf,
835    f3_gpf_vec.asUInt.orR || f3_crossGuestPageFault.asUInt.orR
836  )
837  io.toBackend.gpaddrMem_waddr := f3_ftq_req.ftqIdx.value
838  io.toBackend.gpaddrMem_wdata := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
839
840  //Write back to Ftq
841  val f3_cache_fetch = f3_valid && !(f2_fire && !f2_flush)
842  val finishFetchMaskReg = RegNext(f3_cache_fetch)
843
844  val mmioFlushWb = Wire(Valid(new PredecodeWritebackBundle))
845  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
846  f3_mmio_missOffset.valid := f3_req_is_mmio
847  f3_mmio_missOffset.bits  := 0.U
848
849  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
850  // When backend redirect, mmio_state reset after 1 cycle.
851  // In this case, mask .valid to avoid overriding backend redirect
852  mmioFlushWb.valid           := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
853    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
854  mmioFlushWb.bits.pc         := f3_pc
855  mmioFlushWb.bits.pd         := f3_pd
856  mmioFlushWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid :=  f3_mmio_range(i)}
857  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
858  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
859  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
860  mmioFlushWb.bits.cfiOffset  := DontCare
861  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U , f3_ftq_req.startAddr + 4.U)
862  mmioFlushWb.bits.jalTarget  := DontCare
863  mmioFlushWb.bits.instrRange := f3_mmio_range
864
865  /** external predecode for MMIO instruction */
866  when(f3_req_is_mmio){
867    val inst  = Cat(f3_mmio_data(1), f3_mmio_data(0))
868    val currentIsRVC   = isRVC(inst)
869
870    val brType::isCall::isRet::Nil = brInfo(inst)
871    val jalOffset = jal_offset(inst, currentIsRVC)
872    val brOffset  = br_offset(inst, currentIsRVC)
873
874    io.toIbuffer.bits.instrs(0) := new RVCDecoder(inst, XLEN, fLen, useAddiForMv = true).decode.bits
875
876
877    io.toIbuffer.bits.pd(0).valid   := true.B
878    io.toIbuffer.bits.pd(0).isRVC   := currentIsRVC
879    io.toIbuffer.bits.pd(0).brType  := brType
880    io.toIbuffer.bits.pd(0).isCall  := isCall
881    io.toIbuffer.bits.pd(0).isRet   := isRet
882
883    when (mmio_resend_af) {
884      io.toIbuffer.bits.exceptionType(0) := ExceptionType.acf
885    } .elsewhen (mmio_resend_pf) {
886      io.toIbuffer.bits.exceptionType(0) := ExceptionType.ipf
887    } .elsewhen (mmio_resend_gpf) {
888      io.toIbuffer.bits.exceptionType(0) := ExceptionType.igpf
889    }
890    io.toIbuffer.bits.crossPageIPFFix(0) := mmio_resend_pf
891
892    io.toIbuffer.bits.enqEnable   := f3_mmio_range.asUInt
893
894    mmioFlushWb.bits.pd(0).valid   := true.B
895    mmioFlushWb.bits.pd(0).isRVC   := currentIsRVC
896    mmioFlushWb.bits.pd(0).brType  := brType
897    mmioFlushWb.bits.pd(0).isCall  := isCall
898    mmioFlushWb.bits.pd(0).isRet   := isRet
899  }
900
901  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire)  && f3_mmio_use_seq_pc)
902
903  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready",   io.toIbuffer.valid && !io.toIbuffer.ready )
904
905
906  /**
907    ******************************************************************************
908    * IFU Write Back Stage
909    * - write back predecode information to Ftq to update
910    * - redirect if found fault prediction
911    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
912    ******************************************************************************
913    */
914  val wb_enable         = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
915  val wb_valid          = RegNext(wb_enable, init = false.B)
916  val wb_ftq_req        = RegEnable(f3_ftq_req, wb_enable)
917
918  val wb_check_result_stage1   = RegEnable(checkerOutStage1, wb_enable)
919  val wb_check_result_stage2   = checkerOutStage2
920  val wb_instr_range    = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
921
922  val wb_pc_lower_result        = RegEnable(f3_pc_lower_result, wb_enable)
923  val wb_pc_high                = RegEnable(f3_pc_high, wb_enable)
924  val wb_pc_high_plus1          = RegEnable(f3_pc_high_plus1, wb_enable)
925  val wb_pc                     = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
926
927  //val wb_pc             = RegEnable(f3_pc, wb_enable)
928  val wb_pd             = RegEnable(f3_pd, wb_enable)
929  val wb_instr_valid    = RegEnable(f3_instr_valid, wb_enable)
930
931  /* false hit lastHalf */
932  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
933  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
934  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
935
936  val wb_half_flush = wb_false_lastHalf
937  val wb_half_target = wb_false_target
938
939  /* false oversize */
940  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth,Bool())).last  && wb_pd.last.isRVC
941  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth,Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
942  val lastTaken = wb_check_result_stage1.fixedTaken.last
943
944  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
945
946  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
947    * we set a flag to notify f3 that the last half flag need not to be set.
948    */
949  //f3_fire is after wb_valid
950  when(wb_valid && RegNext(f3_hasLastHalf,init = false.B)
951        && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire  && !RegNext(f3_fire,init = false.B) && !f3_flush
952      ){
953    f3_lastHalf_disable := true.B
954  }
955
956  //wb_valid and f3_fire are in same cycle
957  when(wb_valid && RegNext(f3_hasLastHalf,init = false.B)
958        && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire
959      ){
960    f3_lastHalf.valid := false.B
961  }
962
963  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
964  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map{case (pd, v) => v && pd.isJal }))
965  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
966  checkFlushWb.valid                  := wb_valid
967  checkFlushWb.bits.pc                := wb_pc
968  checkFlushWb.bits.pd                := wb_pd
969  checkFlushWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid := wb_instr_valid(i)}
970  checkFlushWb.bits.ftqIdx            := wb_ftq_req.ftqIdx
971  checkFlushWb.bits.ftqOffset         := wb_ftq_req.ftqOffset.bits
972  checkFlushWb.bits.misOffset.valid   := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
973  checkFlushWb.bits.misOffset.bits    := Mux(wb_half_flush, wb_lastIdx, ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred))
974  checkFlushWb.bits.cfiOffset.valid   := ParallelOR(wb_check_result_stage1.fixedTaken)
975  checkFlushWb.bits.cfiOffset.bits    := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
976  checkFlushWb.bits.target            := Mux(wb_half_flush, wb_half_target, wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx))
977  checkFlushWb.bits.jalTarget         := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
978  checkFlushWb.bits.instrRange        := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
979
980  toFtq.pdWb := Mux(wb_valid, checkFlushWb,  mmioFlushWb)
981
982  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
983
984  /*write back flush type*/
985  val checkFaultType = wb_check_result_stage2.faultType
986  val checkJalFault =  wb_valid && checkFaultType.map(_.isjalFault).reduce(_||_)
987  val checkRetFault =  wb_valid && checkFaultType.map(_.isRetFault).reduce(_||_)
988  val checkTargetFault =  wb_valid && checkFaultType.map(_.istargetFault).reduce(_||_)
989  val checkNotCFIFault =  wb_valid && checkFaultType.map(_.notCFIFault).reduce(_||_)
990  val checkInvalidTaken =  wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_||_)
991
992
993  XSPerfAccumulate("predecode_flush_jalFault",   checkJalFault )
994  XSPerfAccumulate("predecode_flush_retFault",   checkRetFault )
995  XSPerfAccumulate("predecode_flush_targetFault",   checkTargetFault )
996  XSPerfAccumulate("predecode_flush_notCFIFault",   checkNotCFIFault )
997  XSPerfAccumulate("predecode_flush_incalidTakenFault",   checkInvalidTaken )
998
999  when(checkRetFault){
1000    XSDebug("startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1001        wb_ftq_req.startAddr, wb_ftq_req.nextStartAddr, wb_ftq_req.ftqOffset.valid, wb_ftq_req.ftqOffset.bits)
1002  }
1003
1004
1005  /** performance counter */
1006  val f3_perf_info     = RegEnable(f2_perf_info,  f2_fire)
1007  val f3_req_0    = io.toIbuffer.fire
1008  val f3_req_1    = io.toIbuffer.fire && f3_doubleLine
1009  val f3_hit_0    = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1010  val f3_hit_1    = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
1011  val f3_hit      = f3_perf_info.hit
1012  val perfEvents = Seq(
1013    ("frontendFlush                ", wb_redirect                                ),
1014    ("ifu_req                      ", io.toIbuffer.fire                        ),
1015    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit   ),
1016    ("ifu_req_cacheline_0          ", f3_req_0                                   ),
1017    ("ifu_req_cacheline_1          ", f3_req_1                                   ),
1018    ("ifu_req_cacheline_0_hit      ", f3_hit_1                                   ),
1019    ("ifu_req_cacheline_1_hit      ", f3_hit_1                                   ),
1020    ("only_0_hit                   ", f3_perf_info.only_0_hit       && io.toIbuffer.fire ),
1021    ("only_0_miss                  ", f3_perf_info.only_0_miss      && io.toIbuffer.fire ),
1022    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1      && io.toIbuffer.fire ),
1023    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1     && io.toIbuffer.fire ),
1024    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1     && io.toIbuffer.fire ),
1025    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1    && io.toIbuffer.fire ),
1026  )
1027  generatePerfEvent()
1028
1029  XSPerfAccumulate("ifu_req",   io.toIbuffer.fire )
1030  XSPerfAccumulate("ifu_miss",  io.toIbuffer.fire && !f3_hit )
1031  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0  )
1032  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1  )
1033  XSPerfAccumulate("ifu_req_cacheline_0_hit",   f3_hit_0 )
1034  XSPerfAccumulate("ifu_req_cacheline_1_hit",   f3_hit_1 )
1035  XSPerfAccumulate("frontendFlush",  wb_redirect )
1036  XSPerfAccumulate("only_0_hit",      f3_perf_info.only_0_hit   && io.toIbuffer.fire  )
1037  XSPerfAccumulate("only_0_miss",     f3_perf_info.only_0_miss  && io.toIbuffer.fire  )
1038  XSPerfAccumulate("hit_0_hit_1",     f3_perf_info.hit_0_hit_1  && io.toIbuffer.fire  )
1039  XSPerfAccumulate("hit_0_miss_1",    f3_perf_info.hit_0_miss_1  && io.toIbuffer.fire  )
1040  XSPerfAccumulate("miss_0_hit_1",    f3_perf_info.miss_0_hit_1   && io.toIbuffer.fire )
1041  XSPerfAccumulate("miss_0_miss_1",   f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire )
1042  XSPerfAccumulate("hit_0_except_1",   f3_perf_info.hit_0_except_1 && io.toIbuffer.fire )
1043  XSPerfAccumulate("miss_0_except_1",   f3_perf_info.miss_0_except_1 && io.toIbuffer.fire )
1044  XSPerfAccumulate("except_0",   f3_perf_info.except_0 && io.toIbuffer.fire )
1045  XSPerfHistogram("ifu2ibuffer_validCnt", PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable), io.toIbuffer.fire, 0, PredictWidth + 1, 1)
1046
1047  val hartId = p(XSCoreParamsKey).HartId
1048  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1049  val isWriteIfuWbToFtqTable = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1050  val fetchToIBufferTable = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1051  val ifuWbToFtqTable = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
1052
1053  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
1054  fetchIBufferDumpData.start_addr := f3_ftq_req.startAddr
1055  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1056  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)
1057  fetchIBufferDumpData.is_cache_hit := f3_hit
1058
1059  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
1060  ifuWbToFtqDumpData.start_addr := wb_ftq_req.startAddr
1061  ifuWbToFtqDumpData.is_miss_pred := checkFlushWb.bits.misOffset.valid
1062  ifuWbToFtqDumpData.miss_pred_offset := checkFlushWb.bits.misOffset.bits
1063  ifuWbToFtqDumpData.checkJalFault := checkJalFault
1064  ifuWbToFtqDumpData.checkRetFault := checkRetFault
1065  ifuWbToFtqDumpData.checkTargetFault := checkTargetFault
1066  ifuWbToFtqDumpData.checkNotCFIFault := checkNotCFIFault
1067  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
1068
1069  fetchToIBufferTable.log(
1070    data = fetchIBufferDumpData,
1071    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
1072    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1073    clock = clock,
1074    reset = reset
1075  )
1076  ifuWbToFtqTable.log(
1077    data = ifuWbToFtqDumpData,
1078    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
1079    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1080    clock = clock,
1081    reset = reset
1082  )
1083
1084}
1085