xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 35850f172eb3c1413f47a6462b00ad04dbda154e)
109c6f1ddSLingrui98/***************************************************************************************
2e3da8badSTang Haojin* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3e3da8badSTang Haojin* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
409c6f1ddSLingrui98* Copyright (c) 2020-2021 Peng Cheng Laboratory
509c6f1ddSLingrui98*
609c6f1ddSLingrui98* XiangShan is licensed under Mulan PSL v2.
709c6f1ddSLingrui98* You can use this software according to the terms and conditions of the Mulan PSL v2.
809c6f1ddSLingrui98* You may obtain a copy of Mulan PSL v2 at:
909c6f1ddSLingrui98*          http://license.coscl.org.cn/MulanPSL2
1009c6f1ddSLingrui98*
1109c6f1ddSLingrui98* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
1209c6f1ddSLingrui98* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
1309c6f1ddSLingrui98* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
1409c6f1ddSLingrui98*
1509c6f1ddSLingrui98* See the Mulan PSL v2 for more details.
1609c6f1ddSLingrui98***************************************************************************************/
1709c6f1ddSLingrui98
1809c6f1ddSLingrui98package xiangshan.frontend
1909c6f1ddSLingrui98
2009c6f1ddSLingrui98import chisel3._
2109c6f1ddSLingrui98import chisel3.util._
22cf7d6b7aSMuziimport org.chipsalliance.cde.config.Parameters
23cf7d6b7aSMuziimport utility._
24cf7d6b7aSMuziimport utility.ChiselDB
2509c6f1ddSLingrui98import xiangshan._
26cf7d6b7aSMuziimport xiangshan.backend.GPAMemEntry
2709c6f1ddSLingrui98import xiangshan.cache.mmu._
281d8f4dcbSJayimport xiangshan.frontend.icache._
2909c6f1ddSLingrui98
3009c6f1ddSLingrui98trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst {
3109c6f1ddSLingrui98  def mmioBusWidth = 64
3209c6f1ddSLingrui98  def mmioBusBytes = mmioBusWidth / 8
330be662e4SJay  def maxInstrLen  = 32
3409c6f1ddSLingrui98}
3509c6f1ddSLingrui98
3609c6f1ddSLingrui98trait HasIFUConst extends HasXSParameter {
37cf7d6b7aSMuzi  def addrAlign(addr: UInt, bytes: Int, highest: Int): UInt =
38cf7d6b7aSMuzi    Cat(addr(highest - 1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
391d8f4dcbSJay  def fetchQueueSize = 2
401d8f4dcbSJay
412a3050c2SJay  def getBasicBlockIdx(pc: UInt, start: UInt): UInt = {
422a3050c2SJay    val byteOffset = pc - start
432a3050c2SJay    (byteOffset - instBytes.U)(log2Ceil(PredictWidth), instOffsetBits)
441d8f4dcbSJay  }
4509c6f1ddSLingrui98}
4609c6f1ddSLingrui98
4709c6f1ddSLingrui98class IfuToFtqIO(implicit p: Parameters) extends XSBundle {
4809c6f1ddSLingrui98  val pdWb = Valid(new PredecodeWritebackBundle)
4909c6f1ddSLingrui98}
5009c6f1ddSLingrui98
51d7ac23a3SEaston Manclass IfuToBackendIO(implicit p: Parameters) extends XSBundle {
52d7ac23a3SEaston Man  // write to backend gpaddr mem
53d7ac23a3SEaston Man  val gpaddrMem_wen   = Output(Bool())
54d7ac23a3SEaston Man  val gpaddrMem_waddr = Output(UInt(log2Ceil(FtqSize).W)) // Ftq Ptr
55d7ac23a3SEaston Man  // 2 gpaddrs, correspond to startAddr & nextLineAddr in bundle FtqICacheInfo
56d7ac23a3SEaston Man  // TODO: avoid cross page entry in Ftq
57ad415ae0SXiaokun-Pei  val gpaddrMem_wdata = Output(new GPAMemEntry)
58d7ac23a3SEaston Man}
59d7ac23a3SEaston Man
6009c6f1ddSLingrui98class FtqInterface(implicit p: Parameters) extends XSBundle {
6109c6f1ddSLingrui98  val fromFtq = Flipped(new FtqToIfuIO)
6209c6f1ddSLingrui98  val toFtq   = new IfuToFtqIO
6309c6f1ddSLingrui98}
6409c6f1ddSLingrui98
650be662e4SJayclass UncacheInterface(implicit p: Parameters) extends XSBundle {
660be662e4SJay  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
670be662e4SJay  val toUncache   = DecoupledIO(new InsUncacheReq)
680be662e4SJay}
691d1e6d4dSJenius
7009c6f1ddSLingrui98class NewIFUIO(implicit p: Parameters) extends XSBundle {
7109c6f1ddSLingrui98  val ftqInter        = new FtqInterface
7250780602SJenius  val icacheInter     = Flipped(new IFUICacheIO)
731d8f4dcbSJay  val icacheStop      = Output(Bool())
741d8f4dcbSJay  val icachePerfInfo  = Input(new ICachePerfInfo)
7509c6f1ddSLingrui98  val toIbuffer       = Decoupled(new FetchToIBuffer)
76d7ac23a3SEaston Man  val toBackend       = new IfuToBackendIO
770be662e4SJay  val uncacheInter    = new UncacheInterface
7872951335SLi Qianruo  val frontendTrigger = Flipped(new FrontendTdataDistributeIO)
79a37fbf10SJay  val rob_commits     = Flipped(Vec(CommitWidth, Valid(new RobCommitInfo)))
80f1fe8698SLemover  val iTLBInter       = new TlbRequestIO
8156788a33SJinYue  val pmp             = new ICachePMPBundle
821d1e6d4dSJenius  val mmioCommitRead  = new mmioCommitRead
8371b6c42eSxu_zh  val csr_fsIsOff     = Input(Bool())
8409c6f1ddSLingrui98}
8509c6f1ddSLingrui98
8609c6f1ddSLingrui98// record the situation in which fallThruAddr falls into
8709c6f1ddSLingrui98// the middle of an RVI inst
8809c6f1ddSLingrui98class LastHalfInfo(implicit p: Parameters) extends XSBundle {
8909c6f1ddSLingrui98  val valid    = Bool()
9009c6f1ddSLingrui98  val middlePC = UInt(VAddrBits.W)
9109c6f1ddSLingrui98  def matchThisBlock(startAddr: UInt) = valid && middlePC === startAddr
9209c6f1ddSLingrui98}
9309c6f1ddSLingrui98
9409c6f1ddSLingrui98class IfuToPreDecode(implicit p: Parameters) extends XSBundle {
9509c6f1ddSLingrui98  val data            = if (HasCExtension) Vec(PredictWidth + 1, UInt(16.W)) else Vec(PredictWidth, UInt(32.W))
9672951335SLi Qianruo  val frontendTrigger = new FrontendTdataDistributeIO
972a3050c2SJay  val pc              = Vec(PredictWidth, UInt(VAddrBits.W))
9809c6f1ddSLingrui98}
9909c6f1ddSLingrui98
1002a3050c2SJayclass IfuToPredChecker(implicit p: Parameters) extends XSBundle {
1012a3050c2SJay  val ftqOffset  = Valid(UInt(log2Ceil(PredictWidth).W))
1022a3050c2SJay  val jumpOffset = Vec(PredictWidth, UInt(XLEN.W))
1032a3050c2SJay  val target     = UInt(VAddrBits.W)
1042a3050c2SJay  val instrRange = Vec(PredictWidth, Bool())
1052a3050c2SJay  val instrValid = Vec(PredictWidth, Bool())
1062a3050c2SJay  val pds        = Vec(PredictWidth, new PreDecodeInfo)
1072a3050c2SJay  val pc         = Vec(PredictWidth, UInt(VAddrBits.W))
1080c70648eSEaston Man  val fire_in    = Bool()
1092a3050c2SJay}
1102a3050c2SJay
11151532d8bSGuokai Chenclass FetchToIBufferDB extends Bundle {
11251532d8bSGuokai Chen  val start_addr   = UInt(39.W)
11351532d8bSGuokai Chen  val instr_count  = UInt(32.W)
11451532d8bSGuokai Chen  val exception    = Bool()
11551532d8bSGuokai Chen  val is_cache_hit = Bool()
11651532d8bSGuokai Chen}
11751532d8bSGuokai Chen
11851532d8bSGuokai Chenclass IfuWbToFtqDB extends Bundle {
11951532d8bSGuokai Chen  val start_addr        = UInt(39.W)
12051532d8bSGuokai Chen  val is_miss_pred      = Bool()
12151532d8bSGuokai Chen  val miss_pred_offset  = UInt(32.W)
12251532d8bSGuokai Chen  val checkJalFault     = Bool()
12351532d8bSGuokai Chen  val checkRetFault     = Bool()
12451532d8bSGuokai Chen  val checkTargetFault  = Bool()
12551532d8bSGuokai Chen  val checkNotCFIFault  = Bool()
12651532d8bSGuokai Chen  val checkInvalidTaken = Bool()
12751532d8bSGuokai Chen}
12851532d8bSGuokai Chen
1292a3050c2SJayclass NewIFU(implicit p: Parameters) extends XSModule
1302a3050c2SJay    with HasICacheParameters
131aeedc8eeSGuokai Chen    with HasXSParameter
1322a3050c2SJay    with HasIFUConst
1332a3050c2SJay    with HasPdConst
134167bcd01SJay    with HasCircularQueuePtrHelper
1352a3050c2SJay    with HasPerfEvents
136cf7d6b7aSMuzi    with HasTlbConst {
13709c6f1ddSLingrui98  val io                       = IO(new NewIFUIO)
13809c6f1ddSLingrui98  val (toFtq, fromFtq)         = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
139c5c5edaeSJenius  val fromICache               = io.icacheInter.resp
1400be662e4SJay  val (toUncache, fromUncache) = (io.uncacheInter.toUncache, io.uncacheInter.fromUncache)
14109c6f1ddSLingrui98
14209c6f1ddSLingrui98  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
14309c6f1ddSLingrui98
144d2b20d1aSTang Haojin  def numOfStage = 3
145e4d2f6a9Smy-mayfly  // equal lower_result overflow bit
146e4d2f6a9Smy-mayfly  def PcCutPoint = (VAddrBits / 4) - 1
147cf7d6b7aSMuzi  def CatPC(low: UInt, high: UInt, high1: UInt): UInt =
148e4d2f6a9Smy-mayfly    Mux(
149e4d2f6a9Smy-mayfly      low(PcCutPoint),
150e4d2f6a9Smy-mayfly      Cat(high1, low(PcCutPoint - 1, 0)),
151e4d2f6a9Smy-mayfly      Cat(high, low(PcCutPoint - 1, 0))
152e4d2f6a9Smy-mayfly    )
153e4d2f6a9Smy-mayfly  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
154d2b20d1aSTang Haojin  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
155d2b20d1aSTang Haojin  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
156d2b20d1aSTang Haojin  // bubble events in IFU, only happen in stage 1
157d2b20d1aSTang Haojin  val icacheMissBubble = Wire(Bool())
158d2b20d1aSTang Haojin  val itlbMissBubble   = Wire(Bool())
159d2b20d1aSTang Haojin
160d2b20d1aSTang Haojin  // only driven by clock, not valid-ready
161d2b20d1aSTang Haojin  topdown_stages(0) := fromFtq.req.bits.topdown_info
162d2b20d1aSTang Haojin  for (i <- 1 until numOfStage) {
163d2b20d1aSTang Haojin    topdown_stages(i) := topdown_stages(i - 1)
164d2b20d1aSTang Haojin  }
165d2b20d1aSTang Haojin  when(icacheMissBubble) {
166d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
167d2b20d1aSTang Haojin  }
168d2b20d1aSTang Haojin  when(itlbMissBubble) {
169d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
170d2b20d1aSTang Haojin  }
171d2b20d1aSTang Haojin  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
172d2b20d1aSTang Haojin  when(fromFtq.topdown_redirect.valid) {
173d2b20d1aSTang Haojin    // only redirect from backend, IFU redirect itself is handled elsewhere
174d2b20d1aSTang Haojin    when(fromFtq.topdown_redirect.bits.debugIsCtrl) {
175d2b20d1aSTang Haojin      /*
176d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
177d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
178d2b20d1aSTang Haojin      }
179d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
180d2b20d1aSTang Haojin       */
181d2b20d1aSTang Haojin      when(fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
182d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
183d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
184d2b20d1aSTang Haojin        }
185d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
186d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.TAGEMissBubble) {
187d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
188d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
189d2b20d1aSTang Haojin        }
190d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
191d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.SCMissBubble) {
192d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
193d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
194d2b20d1aSTang Haojin        }
195d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
196d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
197d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
198d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
199d2b20d1aSTang Haojin        }
200d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
201d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.RASMissBubble) {
202d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
203d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
204d2b20d1aSTang Haojin        }
205d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
206d2b20d1aSTang Haojin      }
207d2b20d1aSTang Haojin    }.elsewhen(fromFtq.topdown_redirect.bits.debugIsMemVio) {
208d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
209d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
210d2b20d1aSTang Haojin      }
211d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
212d2b20d1aSTang Haojin    }.otherwise {
213d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
214d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
215d2b20d1aSTang Haojin      }
216d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
217d2b20d1aSTang Haojin    }
218d2b20d1aSTang Haojin  }
219d2b20d1aSTang Haojin
2201d8f4dcbSJay  class TlbExept(implicit p: Parameters) extends XSBundle {
2211d8f4dcbSJay    val pageFault   = Bool()
2221d8f4dcbSJay    val accessFault = Bool()
2231d8f4dcbSJay    val mmio        = Bool()
224b005f7c6SJay  }
22509c6f1ddSLingrui98
226a61a35e0Sssszwic  val preDecoder = Module(new PreDecode)
227dc270d3bSJenius
2282a3050c2SJay  val predChecker     = Module(new PredChecker)
2292a3050c2SJay  val frontendTrigger = Module(new FrontendTrigger)
230cf7d6b7aSMuzi  val (checkerIn, checkerOutStage1, checkerOutStage2) =
231cf7d6b7aSMuzi    (predChecker.io.in, predChecker.io.out.stage1Out, predChecker.io.out.stage2Out)
2321d8f4dcbSJay
23358dbdfc2SJay  /**
23458dbdfc2SJay    ******************************************************************************
23558dbdfc2SJay    * IFU Stage 0
23658dbdfc2SJay    * - send cacheline fetch request to ICacheMainPipe
23758dbdfc2SJay    ******************************************************************************
23858dbdfc2SJay    */
23909c6f1ddSLingrui98
24009c6f1ddSLingrui98  val f0_valid      = fromFtq.req.valid
24109c6f1ddSLingrui98  val f0_ftq_req    = fromFtq.req.bits
2426ce52296SJinYue  val f0_doubleLine = fromFtq.req.bits.crossCacheline
243cf7d6b7aSMuzi  val f0_vSetIdx    = VecInit(get_idx(f0_ftq_req.startAddr), get_idx(f0_ftq_req.nextlineStart))
244935edac4STang Haojin  val f0_fire       = fromFtq.req.fire
24509c6f1ddSLingrui98
24609c6f1ddSLingrui98  val f0_flush, f1_flush, f2_flush, f3_flush                                     = WireInit(false.B)
24709c6f1ddSLingrui98  val from_bpu_f0_flush, from_bpu_f1_flush, from_bpu_f2_flush, from_bpu_f3_flush = WireInit(false.B)
24809c6f1ddSLingrui98
249cb4f77ceSLingrui98  from_bpu_f0_flush := fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
250cb4f77ceSLingrui98    fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
25109c6f1ddSLingrui98
2522a3050c2SJay  val wb_redirect, mmio_redirect, backend_redirect = WireInit(false.B)
2532a3050c2SJay  val f3_wb_not_flush                              = WireInit(false.B)
2542a3050c2SJay
2552a3050c2SJay  backend_redirect := fromFtq.redirect.valid
2562a3050c2SJay  f3_flush         := backend_redirect || (wb_redirect && !f3_wb_not_flush)
2572a3050c2SJay  f2_flush         := backend_redirect || mmio_redirect || wb_redirect
25809c6f1ddSLingrui98  f1_flush         := f2_flush || from_bpu_f1_flush
25909c6f1ddSLingrui98  f0_flush         := f1_flush || from_bpu_f0_flush
26009c6f1ddSLingrui98
26109c6f1ddSLingrui98  val f1_ready, f2_ready, f3_ready = WireInit(false.B)
26209c6f1ddSLingrui98
26350780602SJenius  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
26409c6f1ddSLingrui98
265d2b20d1aSTang Haojin  when(wb_redirect) {
266d2b20d1aSTang Haojin    when(f3_wb_not_flush) {
267d2b20d1aSTang Haojin      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
268d2b20d1aSTang Haojin    }
269d2b20d1aSTang Haojin    for (i <- 0 until numOfStage - 1) {
270d2b20d1aSTang Haojin      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
271d2b20d1aSTang Haojin    }
272d2b20d1aSTang Haojin  }
273d2b20d1aSTang Haojin
27458dbdfc2SJay  /** <PERF> f0 fetch bubble */
275f7c29b0aSJinYue
27600240ba6SJay  XSPerfAccumulate("fetch_bubble_ftq_not_valid", !fromFtq.req.valid && fromFtq.req.ready)
277c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
278c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
279c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
28000240ba6SJay  XSPerfAccumulate("fetch_flush_backend_redirect", backend_redirect)
28100240ba6SJay  XSPerfAccumulate("fetch_flush_wb_redirect", wb_redirect)
28200240ba6SJay  XSPerfAccumulate("fetch_flush_bpu_f1_flush", from_bpu_f1_flush)
28300240ba6SJay  XSPerfAccumulate("fetch_flush_bpu_f0_flush", from_bpu_f0_flush)
28458dbdfc2SJay
28558dbdfc2SJay  /**
28658dbdfc2SJay    ******************************************************************************
28758dbdfc2SJay    * IFU Stage 1
28858dbdfc2SJay    * - calculate pc/half_pc/cut_ptr for every instruction
28958dbdfc2SJay    ******************************************************************************
29058dbdfc2SJay    */
29109c6f1ddSLingrui98
29209c6f1ddSLingrui98  val f1_valid   = RegInit(false.B)
293005e809bSJiuyang Liu  val f1_ftq_req = RegEnable(f0_ftq_req, f0_fire)
294005e809bSJiuyang Liu  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
295005e809bSJiuyang Liu  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
296005e809bSJiuyang Liu  val f1_vSetIdx    = RegEnable(f0_vSetIdx, f0_fire)
297625ecd17SJenius  val f1_fire       = f1_valid && f2_ready
29809c6f1ddSLingrui98
299625ecd17SJenius  f1_ready := f1_fire || !f1_valid
30009c6f1ddSLingrui98
3010d756c48SJinYue  from_bpu_f1_flush := fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid
302cb4f77ceSLingrui98  // from_bpu_f1_flush := false.B
30309c6f1ddSLingrui98
304cf7d6b7aSMuzi  when(f1_flush)(f1_valid := false.B)
305cf7d6b7aSMuzi    .elsewhen(f0_fire && !f0_flush)(f1_valid := true.B)
306cf7d6b7aSMuzi    .elsewhen(f1_fire)(f1_valid := false.B)
30709c6f1ddSLingrui98
308e4d2f6a9Smy-mayfly  val f1_pc_high       = f1_ftq_req.startAddr(VAddrBits - 1, PcCutPoint)
309f2f493deSstride  val f1_pc_high_plus1 = f1_pc_high + 1.U
310f2f493deSstride
311e4d2f6a9Smy-mayfly  /**
312e4d2f6a9Smy-mayfly   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
313e4d2f6a9Smy-mayfly   * code of original logic, this code has been deprecated
314e4d2f6a9Smy-mayfly   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
315e4d2f6a9Smy-mayfly   *  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)))})
316e4d2f6a9Smy-mayfly   */
317cf7d6b7aSMuzi  val f1_pc_lower_result = VecInit((0 until PredictWidth).map(i =>
318cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + (i * 2).U
319cf7d6b7aSMuzi  )) // cat with overflow bit
320f2f493deSstride
321e4d2f6a9Smy-mayfly  val f1_pc = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
322e4d2f6a9Smy-mayfly
323cf7d6b7aSMuzi  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i =>
324cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + ((i + 2) * 2).U
325cf7d6b7aSMuzi  )) // cat with overflow bit
326e4d2f6a9Smy-mayfly  val f1_half_snpc = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
327f2f493deSstride
328f2f493deSstride  if (env.FPGAPlatform) {
329f2f493deSstride    val f1_pc_diff        = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
330f2f493deSstride    val f1_half_snpc_diff = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i + 2) * 2).U))
331f2f493deSstride
332cf7d6b7aSMuzi    XSError(
333cf7d6b7aSMuzi      f1_pc.zip(f1_pc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
334cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
335cf7d6b7aSMuzi    )
336cf7d6b7aSMuzi    XSError(
337cf7d6b7aSMuzi      f1_half_snpc.zip(f1_half_snpc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
338cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
339cf7d6b7aSMuzi    )
340f2f493deSstride  }
341f2f493deSstride
342cf7d6b7aSMuzi  val f1_cut_ptr = if (HasCExtension)
343cf7d6b7aSMuzi    VecInit((0 until PredictWidth + 1).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 1)) + i.U))
344b92f8445Sssszwic  else VecInit((0 until PredictWidth).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 2)) + i.U))
34509c6f1ddSLingrui98
34658dbdfc2SJay  /**
34758dbdfc2SJay    ******************************************************************************
34858dbdfc2SJay    * IFU Stage 2
34958dbdfc2SJay    * - icache response data (latched for pipeline stop)
35058dbdfc2SJay    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
35158dbdfc2SJay    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
35258dbdfc2SJay    * - cut data from cachlines to packet instruction code
35358dbdfc2SJay    * - instruction predecode and RVC expand
35458dbdfc2SJay    ******************************************************************************
35558dbdfc2SJay    */
35658dbdfc2SJay
3571d8f4dcbSJay  val icacheRespAllValid = WireInit(false.B)
35809c6f1ddSLingrui98
35909c6f1ddSLingrui98  val f2_valid   = RegInit(false.B)
360005e809bSJiuyang Liu  val f2_ftq_req = RegEnable(f1_ftq_req, f1_fire)
361005e809bSJiuyang Liu  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
362005e809bSJiuyang Liu  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
363005e809bSJiuyang Liu  val f2_vSetIdx    = RegEnable(f1_vSetIdx, f1_fire)
364625ecd17SJenius  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
3651d8f4dcbSJay
366625ecd17SJenius  f2_ready := f2_fire || !f2_valid
3671d8f4dcbSJay  // TODO: addr compare may be timing critical
368cf7d6b7aSMuzi  val f2_icache_all_resp_wire =
3694690c88aSxu_zh    fromICache.valid &&
3704690c88aSxu_zh      fromICache.bits.vaddr(0) === f2_ftq_req.startAddr &&
3714690c88aSxu_zh      (fromICache.bits.doubleline && fromICache.bits.vaddr(1) === f2_ftq_req.nextlineStart || !f2_doubleLine)
3721d8f4dcbSJay  val f2_icache_all_resp_reg = RegInit(false.B)
3731d8f4dcbSJay
3741d8f4dcbSJay  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
3751d8f4dcbSJay
376d2b20d1aSTang Haojin  icacheMissBubble := io.icacheInter.topdownIcacheMiss
377d2b20d1aSTang Haojin  itlbMissBubble   := io.icacheInter.topdownItlbMiss
378d2b20d1aSTang Haojin
3791d8f4dcbSJay  io.icacheStop := !f3_ready
3801d8f4dcbSJay
381cf7d6b7aSMuzi  when(f2_flush)(f2_icache_all_resp_reg := false.B)
382cf7d6b7aSMuzi    .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready)(f2_icache_all_resp_reg := true.B)
383cf7d6b7aSMuzi    .elsewhen(f2_fire && f2_icache_all_resp_reg)(f2_icache_all_resp_reg := false.B)
38409c6f1ddSLingrui98
385cf7d6b7aSMuzi  when(f2_flush)(f2_valid := false.B)
386cf7d6b7aSMuzi    .elsewhen(f1_fire && !f1_flush)(f2_valid := true.B)
387cf7d6b7aSMuzi    .elsewhen(f2_fire)(f2_valid := false.B)
38809c6f1ddSLingrui98
3894690c88aSxu_zh  val f2_exception_in     = fromICache.bits.exception
3904690c88aSxu_zh  val f2_backendException = fromICache.bits.backendException
391d7ac23a3SEaston Man  // paddr and gpaddr of [startAddr, nextLineAddr]
3924690c88aSxu_zh  val f2_paddrs            = fromICache.bits.paddr
3934690c88aSxu_zh  val f2_gpaddr            = fromICache.bits.gpaddr
3944690c88aSxu_zh  val f2_isForVSnonLeafPTE = fromICache.bits.isForVSnonLeafPTE
395002c10a4SYanqin Li
396211986abSxu_zh  // FIXME: raise af if one fetch block crosses the cacheable-noncacheable boundary, might not correct
397*35850f17Sxu_zh  val f2_mmio_mismatch_exception = VecInit(Seq(
398*35850f17Sxu_zh    ExceptionType.none, // mark the exception only on the second line
399*35850f17Sxu_zh    Mux(
400211986abSxu_zh      // not double-line, skip check
4014690c88aSxu_zh      !fromICache.bits.doubleline || (
402211986abSxu_zh        // is double-line, ask for consistent pmp_mmio and itlb_pbmt value
4034690c88aSxu_zh        fromICache.bits.pmp_mmio(0) === fromICache.bits.pmp_mmio(1) &&
4044690c88aSxu_zh          fromICache.bits.itlb_pbmt(0) === fromICache.bits.itlb_pbmt(1)
4054690c88aSxu_zh      ),
406211986abSxu_zh      ExceptionType.none,
407211986abSxu_zh      ExceptionType.af
408*35850f17Sxu_zh    )
409*35850f17Sxu_zh  ))
410211986abSxu_zh
411211986abSxu_zh  // merge exceptions
412211986abSxu_zh  val f2_exception = ExceptionType.merge(f2_exception_in, f2_mmio_mismatch_exception)
413211986abSxu_zh
414211986abSxu_zh  // we need only the first port, as the second is asked to be the same
4154690c88aSxu_zh  val f2_pmp_mmio  = fromICache.bits.pmp_mmio(0)
4164690c88aSxu_zh  val f2_itlb_pbmt = fromICache.bits.itlb_pbmt(0)
417002c10a4SYanqin Li
418e4d2f6a9Smy-mayfly  /**
419e4d2f6a9Smy-mayfly    * reduce the number of registers, origin code
420e4d2f6a9Smy-mayfly    * f2_pc = RegEnable(f1_pc, f1_fire)
421e4d2f6a9Smy-mayfly    */
422e4d2f6a9Smy-mayfly  val f2_pc_lower_result = RegEnable(f1_pc_lower_result, f1_fire)
423e4d2f6a9Smy-mayfly  val f2_pc_high         = RegEnable(f1_pc_high, f1_fire)
424e4d2f6a9Smy-mayfly  val f2_pc_high_plus1   = RegEnable(f1_pc_high_plus1, f1_fire)
425e4d2f6a9Smy-mayfly  val f2_pc              = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
426a37fbf10SJay
427e4d2f6a9Smy-mayfly  val f2_cut_ptr      = RegEnable(f1_cut_ptr, f1_fire)
428005e809bSJiuyang Liu  val f2_resend_vaddr = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
4292a3050c2SJay
430cf7d6b7aSMuzi  def isNextLine(pc: UInt, startAddr: UInt) =
4312a3050c2SJay    startAddr(blockOffBits) ^ pc(blockOffBits)
43209c6f1ddSLingrui98
433cf7d6b7aSMuzi  def isLastInLine(pc: UInt) =
4342a3050c2SJay    pc(blockOffBits - 1, 0) === "b111110".U
43509c6f1ddSLingrui98
4362a3050c2SJay  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits - 1, 1), MemPredPCWidth)))
437cf7d6b7aSMuzi  val f2_jump_range =
438cf7d6b7aSMuzi    Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
439cf7d6b7aSMuzi  val f2_ftr_range = Fill(PredictWidth, f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(
440cf7d6b7aSMuzi    f2_ftq_req.nextStartAddr,
441cf7d6b7aSMuzi    f2_ftq_req.startAddr
442cf7d6b7aSMuzi  )
4432a3050c2SJay  val f2_instr_range = f2_jump_range & f2_ftr_range
444cf7d6b7aSMuzi  val f2_exception_vec = VecInit((0 until PredictWidth).map(i =>
445cf7d6b7aSMuzi    MuxCase(
446cf7d6b7aSMuzi      ExceptionType.none,
447cf7d6b7aSMuzi      Seq(
44888895b11Sxu_zh        !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
44988895b11Sxu_zh        (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
450cf7d6b7aSMuzi      )
451cf7d6b7aSMuzi    )
452cf7d6b7aSMuzi  ))
4531d8f4dcbSJay  val f2_perf_info = io.icachePerfInfo
45409c6f1ddSLingrui98
4552a3050c2SJay  def cut(cacheline: UInt, cutPtr: Vec[UInt]): Vec[UInt] = {
456d558bd61SJenius    require(HasCExtension)
457d558bd61SJenius    // if(HasCExtension){
45809c6f1ddSLingrui98    val result  = Wire(Vec(PredictWidth + 1, UInt(16.W)))
459b92f8445Sssszwic    val dataVec = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) // 32 16-bit data vector
46009c6f1ddSLingrui98    (0 until PredictWidth + 1).foreach(i =>
461d558bd61SJenius      result(i) := dataVec(cutPtr(i)) // the max ptr is 3*blockBytes/4-1
46209c6f1ddSLingrui98    )
46309c6f1ddSLingrui98    result
464d558bd61SJenius    // } else {
465d558bd61SJenius    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
466d558bd61SJenius    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
467d558bd61SJenius    //   (0 until PredictWidth).foreach( i =>
468d558bd61SJenius    //     result(i) := dataVec(cutPtr(i))
469d558bd61SJenius    //   )
470d558bd61SJenius    //   result
471d558bd61SJenius    // }
47209c6f1ddSLingrui98  }
47309c6f1ddSLingrui98
4744690c88aSxu_zh  /* NOTE: the following `Cat(_data, _data)` *is* intentional.
47596d0318bSxu_zh   * Explanation:
47696d0318bSxu_zh   * In the old design, IFU is responsible for selecting requested data from two adjacent cachelines,
47796d0318bSxu_zh   *    so IFU has to receive 2*64B (2cacheline * 64B) data from ICache, and do `Cat(_data(1), _data(0))` here.
47896d0318bSxu_zh   * However, a fetch block is 34B at max, sending 2*64B is quiet a waste of power.
47996d0318bSxu_zh   * In current design (2024.06~), ICacheDataArray is responsible for selecting data from two adjacent cachelines,
4804690c88aSxu_zh   *    so IFU only need to receive 40B (5bank * 8B) valid data, and use only one port is enough.
48196d0318bSxu_zh   * For example, when pc falls on the 6th bank in cacheline0(so this is a doubleline request):
48296d0318bSxu_zh   *                                MSB                                         LSB
48396d0318bSxu_zh   *                  cacheline 1 || 1-7 | 1-6 | 1-5 | 1-4 | 1-3 | 1-2 | 1-1 | 1-0 ||
48496d0318bSxu_zh   *                  cacheline 0 || 0-7 | 0-6 | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | 0-0 ||
48596d0318bSxu_zh   *    and ICacheDataArray will respond:
4864690c88aSxu_zh   *         fromICache.bits.data || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
48796d0318bSxu_zh   *    therefore simply make a copy of the response and `Cat` together, and obtain the requested data from centre:
48896d0318bSxu_zh   *          f2_data_2_cacheline || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 | 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
48996d0318bSxu_zh   *                                             requested data: ^-----------------------------^
49096d0318bSxu_zh   * For another example, pc falls on the 1st bank in cacheline 0, we have:
4914690c88aSxu_zh   *         fromICache.bits.data || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
49296d0318bSxu_zh   *          f2_data_2_cacheline || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx | xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
49396d0318bSxu_zh   *                                                                           requested data: ^-----------------------------^
49496d0318bSxu_zh   * Each "| x-y |" block is a 8B bank from cacheline(x).bank(y)
49596d0318bSxu_zh   * Please also refer to:
49696d0318bSxu_zh   * - DataArray selects data:
49796d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L355-L381
49896d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L149-L161
49996d0318bSxu_zh   * - ICache respond to IFU:
50096d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala#L473
50196d0318bSxu_zh   */
5024690c88aSxu_zh  val f2_data_2_cacheline = Cat(fromICache.bits.data, fromICache.bits.data)
503dc270d3bSJenius
504a61a35e0Sssszwic  val f2_cut_data = cut(f2_data_2_cacheline, f2_cut_ptr)
50509c6f1ddSLingrui98
50658dbdfc2SJay  /** predecode (include RVC expander) */
507dc270d3bSJenius  // preDecoderRegIn.data := f2_reg_cut_data
508dc270d3bSJenius  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
509dc270d3bSJenius  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
510dc270d3bSJenius  // preDecoderRegIn.pc  := f2_pc
511dc270d3bSJenius
512a61a35e0Sssszwic  val preDecoderIn = preDecoder.io.in
5139afa8a47STang Haojin  preDecoderIn.valid                := f2_valid
5149afa8a47STang Haojin  preDecoderIn.bits.data            := f2_cut_data
5159afa8a47STang Haojin  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
5169afa8a47STang Haojin  preDecoderIn.bits.pc              := f2_pc
517a61a35e0Sssszwic  val preDecoderOut = preDecoder.io.out
51809c6f1ddSLingrui98
51948a62719SJenius  // val f2_expd_instr     = preDecoderOut.expInstr
52048a62719SJenius  val f2_instr        = preDecoderOut.instr
5212a3050c2SJay  val f2_pd           = preDecoderOut.pd
5222a3050c2SJay  val f2_jump_offset  = preDecoderOut.jumpOffset
5232a3050c2SJay  val f2_hasHalfValid = preDecoderOut.hasHalfValid
524a2568a60Sxu_zh  /* if there is a cross-page RVI instruction, and the former page has no exception,
525a2568a60Sxu_zh   * whether it has exception is actually depends on the latter page
526a2568a60Sxu_zh   */
527cf7d6b7aSMuzi  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i =>
528cf7d6b7aSMuzi    Mux(
529dd02bc3fSxu_zh      isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && !ExceptionType.hasException(f2_exception(0)),
530a2568a60Sxu_zh      f2_exception(1),
531a2568a60Sxu_zh      ExceptionType.none
532cf7d6b7aSMuzi    )
533cf7d6b7aSMuzi  })
53400240ba6SJay  XSPerfAccumulate("fetch_bubble_icache_not_resp", f2_valid && !icacheRespAllValid)
53500240ba6SJay
53658dbdfc2SJay  /**
53758dbdfc2SJay    ******************************************************************************
53858dbdfc2SJay    * IFU Stage 3
53958dbdfc2SJay    * - handle MMIO instruciton
54058dbdfc2SJay    *  -send request to Uncache fetch Unit
54158dbdfc2SJay    *  -every packet include 1 MMIO instruction
54258dbdfc2SJay    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
54358dbdfc2SJay    *  -flush to snpc (send ifu_redirect to Ftq)
54458dbdfc2SJay    * - Ibuffer enqueue
54558dbdfc2SJay    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
54658dbdfc2SJay    * - handle last half RVI instruction
54758dbdfc2SJay    ******************************************************************************
54858dbdfc2SJay    */
54958dbdfc2SJay
55092c61038SXuan Hu  val expanders = Seq.fill(PredictWidth)(Module(new RVCExpander))
55192c61038SXuan Hu
55209c6f1ddSLingrui98  val f3_valid   = RegInit(false.B)
553005e809bSJiuyang Liu  val f3_ftq_req = RegEnable(f2_ftq_req, f2_fire)
554005e809bSJiuyang Liu  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
555005e809bSJiuyang Liu  val f3_doubleLine = RegEnable(f2_doubleLine, f2_fire)
556935edac4STang Haojin  val f3_fire       = io.toIbuffer.fire
5571d8f4dcbSJay
558a61a35e0Sssszwic  val f3_cut_data = RegEnable(f2_cut_data, f2_fire)
5591d8f4dcbSJay
56088895b11Sxu_zh  val f3_exception        = RegEnable(f2_exception, f2_fire)
561211986abSxu_zh  val f3_pmp_mmio         = RegEnable(f2_pmp_mmio, f2_fire)
562211986abSxu_zh  val f3_itlb_pbmt        = RegEnable(f2_itlb_pbmt, f2_fire)
563fbdb359dSMuzi  val f3_backendException = RegEnable(f2_backendException, f2_fire)
56409c6f1ddSLingrui98
565935edac4STang Haojin  val f3_instr = RegEnable(f2_instr, f2_fire)
566aeedc8eeSGuokai Chen
56792c61038SXuan Hu  expanders.zipWithIndex.foreach { case (expander, i) =>
56892c61038SXuan Hu    expander.io.in      := f3_instr(i)
56971b6c42eSxu_zh    expander.io.fsIsOff := io.csr_fsIsOff
57092c61038SXuan Hu  }
57192c61038SXuan Hu  // Use expanded instruction only when input is legal.
57292c61038SXuan Hu  // Otherwise use origin illegal RVC instruction.
57392c61038SXuan Hu  val f3_expd_instr = VecInit(expanders.map { expander: RVCExpander =>
57492c61038SXuan Hu    Mux(expander.io.ill, expander.io.in, expander.io.out.bits)
57592c61038SXuan Hu  })
57692c61038SXuan Hu  val f3_ill = VecInit(expanders.map(_.io.ill))
57748a62719SJenius
578935edac4STang Haojin  val f3_pd_wire                 = RegEnable(f2_pd, f2_fire)
579330aad7fSGuokai Chen  val f3_pd                      = WireInit(f3_pd_wire)
580935edac4STang Haojin  val f3_jump_offset             = RegEnable(f2_jump_offset, f2_fire)
58188895b11Sxu_zh  val f3_exception_vec           = RegEnable(f2_exception_vec, f2_fire)
582a2568a60Sxu_zh  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
583e4d2f6a9Smy-mayfly
584e4d2f6a9Smy-mayfly  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
585e4d2f6a9Smy-mayfly  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
586e4d2f6a9Smy-mayfly  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
587e4d2f6a9Smy-mayfly  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
588e4d2f6a9Smy-mayfly
589e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
590e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
591e4d2f6a9Smy-mayfly  // val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
592e4d2f6a9Smy-mayfly
593e4d2f6a9Smy-mayfly  /**
594e4d2f6a9Smy-mayfly    ***********************************************************************
595e4d2f6a9Smy-mayfly    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
596e4d2f6a9Smy-mayfly    ***********************************************************************
597e4d2f6a9Smy-mayfly    */
598e4d2f6a9Smy-mayfly  val f3_half_snpc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
599e4d2f6a9Smy-mayfly  for (i <- 0 until PredictWidth) {
600e4d2f6a9Smy-mayfly    if (i == (PredictWidth - 2)) {
601e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
602e4d2f6a9Smy-mayfly    } else if (i == (PredictWidth - 1)) {
603e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
604e4d2f6a9Smy-mayfly    } else {
605e4d2f6a9Smy-mayfly      f3_half_snpc(i) := f3_pc(i + 2)
606e4d2f6a9Smy-mayfly    }
607e4d2f6a9Smy-mayfly  }
608e4d2f6a9Smy-mayfly
609935edac4STang Haojin  val f3_instr_range       = RegEnable(f2_instr_range, f2_fire)
610935edac4STang Haojin  val f3_foldpc            = RegEnable(f2_foldpc, f2_fire)
611935edac4STang Haojin  val f3_hasHalfValid      = RegEnable(f2_hasHalfValid, f2_fire)
612d7ac23a3SEaston Man  val f3_paddrs            = RegEnable(f2_paddrs, f2_fire)
61391946104Sxu_zh  val f3_gpaddr            = RegEnable(f2_gpaddr, f2_fire)
614ad415ae0SXiaokun-Pei  val f3_isForVSnonLeafPTE = RegEnable(f2_isForVSnonLeafPTE, f2_fire)
615005e809bSJiuyang Liu  val f3_resend_vaddr      = RegEnable(f2_resend_vaddr, f2_fire)
616ee175d78SJay
617cb6e5d3cSssszwic  // Expand 1 bit to prevent overflow when assert
618cb6e5d3cSssszwic  val f3_ftq_req_startAddr     = Cat(0.U(1.W), f3_ftq_req.startAddr)
619cb6e5d3cSssszwic  val f3_ftq_req_nextStartAddr = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
620330aad7fSGuokai Chen  // brType, isCall and isRet generation is delayed to f3 stage
621330aad7fSGuokai Chen  val f3Predecoder = Module(new F3Predecoder)
622330aad7fSGuokai Chen
623330aad7fSGuokai Chen  f3Predecoder.io.in.instr := f3_instr
624330aad7fSGuokai Chen
625330aad7fSGuokai Chen  f3_pd.zipWithIndex.map { case (pd, i) =>
626330aad7fSGuokai Chen    pd.brType := f3Predecoder.io.out.pd(i).brType
627330aad7fSGuokai Chen    pd.isCall := f3Predecoder.io.out.pd(i).isCall
628330aad7fSGuokai Chen    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
629330aad7fSGuokai Chen  }
630330aad7fSGuokai Chen
631330aad7fSGuokai Chen  val f3PdDiff = f3_pd_wire.zip(f3_pd).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _)
632330aad7fSGuokai Chen  XSError(f3_valid && f3PdDiff, "f3 pd diff")
633330aad7fSGuokai Chen
6341d011975SJinYue  when(f3_valid && !f3_ftq_req.ftqOffset.valid) {
635cf7d6b7aSMuzi    assert(
636cf7d6b7aSMuzi      f3_ftq_req_startAddr + (2 * PredictWidth).U >= f3_ftq_req_nextStartAddr,
637cf7d6b7aSMuzi      s"More tha ${2 * PredictWidth} Bytes fetch is not allowed!"
638cf7d6b7aSMuzi    )
6391d011975SJinYue  }
640a1351e5dSJay
6412a3050c2SJay  /*** MMIO State Machine***/
642ee175d78SJay  val f3_mmio_data          = Reg(Vec(2, UInt(16.W)))
643ee175d78SJay  val mmio_is_RVC           = RegInit(false.B)
644ee175d78SJay  val mmio_resend_addr      = RegInit(0.U(PAddrBits.W))
64588895b11Sxu_zh  val mmio_resend_exception = RegInit(0.U(ExceptionType.width.W))
646dd980d61SXu, Zefan  // NOTE: we dont use GPAddrBits here, refer to ICacheMainPipe.scala L43-48 and PR#3795
647dd980d61SXu, Zefan  val mmio_resend_gpaddr            = RegInit(0.U(PAddrBitsMax.W))
648ad415ae0SXiaokun-Pei  val mmio_resend_isForVSnonLeafPTE = RegInit(false.B)
649c3b2d83aSJay
6501d1e6d4dSJenius  // last instuction finish
6511d1e6d4dSJenius  val is_first_instr = RegInit(true.B)
652cf7d6b7aSMuzi
653ba5ba1dcSmy-mayfly  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
654ba5ba1dcSmy-mayfly  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
655a37fbf10SJay
656cf7d6b7aSMuzi  val m_idle :: m_waitLastCmt :: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil =
657cf7d6b7aSMuzi    Enum(11)
658ee175d78SJay  val mmio_state = RegInit(m_idle)
659a37fbf10SJay
660211986abSxu_zh  // do mmio fetch only when pmp/pbmt shows it is a uncacheable address and no exception occurs
661211986abSxu_zh  /* FIXME: we do not distinguish pbmt is NC or IO now
662211986abSxu_zh   *        but we actually can do speculative execution if pbmt is NC, maybe fix this later for performance
663211986abSxu_zh   */
664211986abSxu_zh  val f3_req_is_mmio =
665211986abSxu_zh    f3_valid && (f3_pmp_mmio || Pbmt.isUncache(f3_itlb_pbmt)) && !ExceptionType.hasException(f3_exception)
666cf7d6b7aSMuzi  val mmio_commit = VecInit(io.rob_commits.map { commit =>
667cf7d6b7aSMuzi    commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx && commit.bits.ftqOffset === 0.U
668cf7d6b7aSMuzi  }).asUInt.orR
669ee175d78SJay  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
670a37fbf10SJay
671ee175d78SJay  val f3_mmio_to_commit      = f3_req_is_mmio && mmio_state === m_waitCommit
672a37fbf10SJay  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
673a37fbf10SJay  val f3_mmio_can_go         = f3_mmio_to_commit && !f3_mmio_to_commit_next
674a37fbf10SJay
6750c70648eSEaston Man  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
676cf7d6b7aSMuzi  fromFtqRedirectReg.bits := RegEnable(
677cf7d6b7aSMuzi    fromFtq.redirect.bits,
678cf7d6b7aSMuzi    0.U.asTypeOf(fromFtq.redirect.bits),
679cf7d6b7aSMuzi    fromFtq.redirect.valid
680cf7d6b7aSMuzi  )
6810c70648eSEaston Man  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
6824a74a727SJenius  val mmioF3Flush           = RegNext(f3_flush, init = false.B)
68356788a33SJinYue  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
68456788a33SJinYue  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
6859bae7d6eSJay
68656788a33SJinYue  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
6879bae7d6eSJay
688ba5ba1dcSmy-mayfly  /**
689ba5ba1dcSmy-mayfly    **********************************************************************************
690ba5ba1dcSmy-mayfly    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
691ba5ba1dcSmy-mayfly    * This is the exception when the first instruction is an MMIO instruction.
692ba5ba1dcSmy-mayfly    **********************************************************************************
693ba5ba1dcSmy-mayfly    */
694ba5ba1dcSmy-mayfly  when(is_first_instr && f3_fire) {
6951d1e6d4dSJenius    is_first_instr := false.B
6961d1e6d4dSJenius  }
6971d1e6d4dSJenius
698cf7d6b7aSMuzi  when(f3_flush && !f3_req_is_mmio)(f3_valid := false.B)
699cf7d6b7aSMuzi    .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)(f3_valid := false.B)
700cf7d6b7aSMuzi    .elsewhen(f2_fire && !f2_flush)(f3_valid := true.B)
701cf7d6b7aSMuzi    .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)(f3_valid := false.B)
702cf7d6b7aSMuzi    .elsewhen(f3_req_is_mmio && f3_mmio_req_commit)(f3_valid := false.B)
703a37fbf10SJay
704a37fbf10SJay  val f3_mmio_use_seq_pc = RegInit(false.B)
705a37fbf10SJay
70656788a33SJinYue  val (redirect_ftqIdx, redirect_ftqOffset) = (fromFtqRedirectReg.bits.ftqIdx, fromFtqRedirectReg.bits.ftqOffset)
707cf7d6b7aSMuzi  val redirect_mmio_req =
708cf7d6b7aSMuzi    fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
709a37fbf10SJay
710cf7d6b7aSMuzi  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)(f3_mmio_use_seq_pc := true.B)
711cf7d6b7aSMuzi    .elsewhen(redirect_mmio_req)(f3_mmio_use_seq_pc := false.B)
712a37fbf10SJay
7138c192ff7Sxu_zh  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
714a37fbf10SJay
7151d1e6d4dSJenius  // mmio state machine
716a37fbf10SJay  switch(mmio_state) {
717ee175d78SJay    is(m_idle) {
7189bae7d6eSJay      when(f3_req_is_mmio) {
7191d1e6d4dSJenius        mmio_state := m_waitLastCmt
7201d1e6d4dSJenius      }
7211d1e6d4dSJenius    }
7221d1e6d4dSJenius
7231d1e6d4dSJenius    is(m_waitLastCmt) {
7241d1e6d4dSJenius      when(is_first_instr) {
725ee175d78SJay        mmio_state := m_sendReq
7261d1e6d4dSJenius      }.otherwise {
7271d1e6d4dSJenius        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
728a37fbf10SJay      }
729a37fbf10SJay    }
730a37fbf10SJay
731ee175d78SJay    is(m_sendReq) {
732935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
733a37fbf10SJay    }
734a37fbf10SJay
735ee175d78SJay    is(m_waitResp) {
736935edac4STang Haojin      when(fromUncache.fire) {
737a37fbf10SJay        val isRVC      = fromUncache.bits.data(1, 0) =/= 3.U
738d7ac23a3SEaston Man        val needResend = !isRVC && f3_paddrs(0)(2, 1) === 3.U
739ee175d78SJay        mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
740ee175d78SJay        mmio_is_RVC     := isRVC
741ee175d78SJay        f3_mmio_data(0) := fromUncache.bits.data(15, 0)
742ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(31, 16)
743a37fbf10SJay      }
744a37fbf10SJay    }
745a37fbf10SJay
746ee175d78SJay    is(m_sendTLB) {
7477b7232f9Sxu_zh      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
748c3b2d83aSJay    }
749a37fbf10SJay
750ee175d78SJay    is(m_tlbResp) {
7517b7232f9Sxu_zh      when(io.iTLBInter.resp.fire) {
7527b7232f9Sxu_zh        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
7537b7232f9Sxu_zh        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
75488895b11Sxu_zh        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
755211986abSxu_zh        // if itlb re-check respond pbmt mismatch with previous check, must be access fault
756211986abSxu_zh        val pbmt_mismatch_exception = Mux(
757211986abSxu_zh          io.iTLBInter.resp.bits.pbmt(0) =/= f3_itlb_pbmt,
758211986abSxu_zh          ExceptionType.af,
759211986abSxu_zh          ExceptionType.none
760211986abSxu_zh        )
761211986abSxu_zh        val exception = ExceptionType.merge(tlb_exception, pbmt_mismatch_exception)
7627b7232f9Sxu_zh        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
763211986abSxu_zh        mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_sendPMP)
7647b7232f9Sxu_zh        // also save itlb response
76503efd994Shappy-lx        mmio_resend_addr              := io.iTLBInter.resp.bits.paddr(0)
766211986abSxu_zh        mmio_resend_exception         := exception
767b5a614b9Sxu_zh        mmio_resend_gpaddr            := io.iTLBInter.resp.bits.gpaddr(0)
768ad415ae0SXiaokun-Pei        mmio_resend_isForVSnonLeafPTE := io.iTLBInter.resp.bits.isForVSnonLeafPTE(0)
769ee175d78SJay      }
7707b7232f9Sxu_zh    }
771ee175d78SJay
772ee175d78SJay    is(m_sendPMP) {
773211986abSxu_zh      val pmp_exception = ExceptionType.fromPMPResp(io.pmp.resp)
774211986abSxu_zh      // if pmp re-check respond mismatch with previous check, must be access fault
775211986abSxu_zh      val mmio_mismatch_exception = Mux(
776211986abSxu_zh        io.pmp.resp.mmio =/= f3_pmp_mmio,
777211986abSxu_zh        ExceptionType.af,
778211986abSxu_zh        ExceptionType.none
779211986abSxu_zh      )
780211986abSxu_zh      val exception = ExceptionType.merge(pmp_exception, mmio_mismatch_exception)
78188895b11Sxu_zh      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
782211986abSxu_zh      mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_resendReq)
78388895b11Sxu_zh      // also save pmp response
784211986abSxu_zh      mmio_resend_exception := exception
785ee175d78SJay    }
786ee175d78SJay
787ee175d78SJay    is(m_resendReq) {
788935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
789ee175d78SJay    }
790ee175d78SJay
791ee175d78SJay    is(m_waitResendResp) {
792935edac4STang Haojin      when(fromUncache.fire) {
793ee175d78SJay        mmio_state      := m_waitCommit
794ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(15, 0)
795a37fbf10SJay      }
796a37fbf10SJay    }
797a37fbf10SJay
798ee175d78SJay    is(m_waitCommit) {
7997b7232f9Sxu_zh      mmio_state := Mux(mmio_commit, m_commited, m_waitCommit)
800a37fbf10SJay    }
8012a3050c2SJay
802ee175d78SJay    // normal mmio instruction
803ee175d78SJay    is(m_commited) {
804ee175d78SJay      mmio_state                    := m_idle
805ee175d78SJay      mmio_is_RVC                   := false.B
806ee175d78SJay      mmio_resend_addr              := 0.U
80788895b11Sxu_zh      mmio_resend_exception         := ExceptionType.none
808b5a614b9Sxu_zh      mmio_resend_gpaddr            := 0.U
809ad415ae0SXiaokun-Pei      mmio_resend_isForVSnonLeafPTE := false.B
8102a3050c2SJay    }
811a37fbf10SJay  }
812a37fbf10SJay
8138abe1810SEaston Man  // Exception or flush by older branch prediction
8148abe1810SEaston Man  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
815167bcd01SJay  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
816ee175d78SJay    mmio_state                    := m_idle
817ee175d78SJay    mmio_is_RVC                   := false.B
818ee175d78SJay    mmio_resend_addr              := 0.U
81988895b11Sxu_zh    mmio_resend_exception         := ExceptionType.none
820b5a614b9Sxu_zh    mmio_resend_gpaddr            := 0.U
821ad415ae0SXiaokun-Pei    mmio_resend_isForVSnonLeafPTE := false.B
822ee175d78SJay    f3_mmio_data.map(_ := 0.U)
8239bae7d6eSJay  }
8249bae7d6eSJay
825ee175d78SJay  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
826cf7d6b7aSMuzi  toUncache.bits.addr := Mux(mmio_state === m_resendReq, mmio_resend_addr, f3_paddrs(0))
827a37fbf10SJay  fromUncache.ready   := true.B
828a37fbf10SJay
8297b7232f9Sxu_zh  // send itlb request in m_sendTLB state
830ee175d78SJay  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
831ee175d78SJay  io.iTLBInter.req.bits.size               := 3.U
832ee175d78SJay  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
833ee175d78SJay  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
8347b7232f9Sxu_zh  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
8358a4dab4dSHaoyuan Feng  io.iTLBInter.req.bits.isPrefetch         := false.B
8367b7232f9Sxu_zh  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
8377b7232f9Sxu_zh  io.iTLBInter.req.bits.no_translate       := false.B
838db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.fullva             := 0.U
839db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.checkfullva        := false.B
840d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hyperinst          := DontCare
841d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hlvx               := DontCare
8428744445eSMaxpicca-Li  io.iTLBInter.req.bits.memidx             := DontCare
843f1fe8698SLemover  io.iTLBInter.req.bits.debug.robIdx       := DontCare
844ee175d78SJay  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
845149a2326Sweiding liu  io.iTLBInter.req.bits.pmp_addr           := DontCare
8467b7232f9Sxu_zh  // whats the difference between req_kill and req.bits.kill?
8477b7232f9Sxu_zh  io.iTLBInter.req_kill := false.B
8487b7232f9Sxu_zh  // wait for itlb response in m_tlbResp state
8497b7232f9Sxu_zh  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
850ee175d78SJay
851ee175d78SJay  io.pmp.req.valid     := (mmio_state === m_sendPMP) && f3_req_is_mmio
852ee175d78SJay  io.pmp.req.bits.addr := mmio_resend_addr
853ee175d78SJay  io.pmp.req.bits.size := 3.U
854ee175d78SJay  io.pmp.req.bits.cmd  := TlbCmd.exec
855f7c29b0aSJinYue
8562a3050c2SJay  val f3_lastHalf = RegInit(0.U.asTypeOf(new LastHalfInfo))
85709c6f1ddSLingrui98
85809c6f1ddSLingrui98  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
8590be662e4SJay  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if (i == 0) true.B else false.B))
8602a3050c2SJay  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
86109c6f1ddSLingrui98
8622a3050c2SJay  /*** prediction result check   ***/
8632a3050c2SJay  checkerIn.ftqOffset  := f3_ftq_req.ftqOffset
8642a3050c2SJay  checkerIn.jumpOffset := f3_jump_offset
8656ce52296SJinYue  checkerIn.target     := f3_ftq_req.nextStartAddr
8662a3050c2SJay  checkerIn.instrRange := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
8672a3050c2SJay  checkerIn.instrValid := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
8682a3050c2SJay  checkerIn.pds        := f3_pd
8692a3050c2SJay  checkerIn.pc         := f3_pc
8700c70648eSEaston Man  checkerIn.fire_in    := RegNext(f2_fire, init = false.B)
8712a3050c2SJay
87258dbdfc2SJay  /*** handle half RVI in the last 2 Bytes  ***/
8732a3050c2SJay
874cf7d6b7aSMuzi  def hasLastHalf(idx: UInt) =
8755995c9e7SJenius    // !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
876cf7d6b7aSMuzi    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(
877cf7d6b7aSMuzi      idx
878cf7d6b7aSMuzi    ) && !f3_req_is_mmio
8792a3050c2SJay
880b665b650STang Haojin  val f3_last_validIdx = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
8812a3050c2SJay
8822a3050c2SJay  val f3_hasLastHalf    = hasLastHalf((PredictWidth - 1).U)
8832a3050c2SJay  val f3_false_lastHalf = hasLastHalf(f3_last_validIdx)
8842a3050c2SJay  val f3_false_snpc     = f3_half_snpc(f3_last_validIdx)
8852a3050c2SJay
886935edac4STang Haojin  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map(i => if (i == 0) false.B else true.B)).asUInt
8873f785aa3SJenius  val f3_lastHalf_disable = RegInit(false.B)
8882a3050c2SJay
889804985a5SJenius  when(f3_flush || (f3_fire && f3_lastHalf_disable)) {
890804985a5SJenius    f3_lastHalf_disable := false.B
891804985a5SJenius  }
892804985a5SJenius
8932a3050c2SJay  when(f3_flush) {
8942a3050c2SJay    f3_lastHalf.valid := false.B
8952a3050c2SJay  }.elsewhen(f3_fire) {
8963f785aa3SJenius    f3_lastHalf.valid    := f3_hasLastHalf && !f3_lastHalf_disable
8976ce52296SJinYue    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
8982a3050c2SJay  }
8992a3050c2SJay
9002a3050c2SJay  f3_instr_valid := Mux(f3_lastHalf.valid, f3_hasHalfValid, VecInit(f3_pd.map(inst => inst.valid)))
9012a3050c2SJay
9022a3050c2SJay  /*** frontend Trigger  ***/
9032a3050c2SJay  frontendTrigger.io.pds  := f3_pd
9042a3050c2SJay  frontendTrigger.io.pc   := f3_pc
9052a3050c2SJay  frontendTrigger.io.data := f3_cut_data
9062a3050c2SJay
9072a3050c2SJay  frontendTrigger.io.frontendTrigger := io.frontendTrigger
9082a3050c2SJay
9092a3050c2SJay  val f3_triggered       = frontendTrigger.io.triggered
91091946104Sxu_zh  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
9112a3050c2SJay
9122a3050c2SJay  /*** send to Ibuffer  ***/
91391946104Sxu_zh  io.toIbuffer.valid          := f3_toIbuffer_valid
9142a3050c2SJay  io.toIbuffer.bits.instrs    := f3_expd_instr
9152a3050c2SJay  io.toIbuffer.bits.valid     := f3_instr_valid.asUInt
9165995c9e7SJenius  io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
9172a3050c2SJay  io.toIbuffer.bits.pd        := f3_pd
91809c6f1ddSLingrui98  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
9192a3050c2SJay  io.toIbuffer.bits.pc        := f3_pc
920c72c955dSEaston Man  // Find last using PriorityMux
921948e8159SEaston Man  io.toIbuffer.bits.isLastInFtqEntry := Reverse(PriorityEncoderOH(Reverse(io.toIbuffer.bits.enqEnable))).asBools
922cf7d6b7aSMuzi  io.toIbuffer.bits.ftqOffset.zipWithIndex.map { case (a, i) =>
923cf7d6b7aSMuzi    a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio
924cf7d6b7aSMuzi  }
9252a3050c2SJay  io.toIbuffer.bits.foldpc        := f3_foldpc
926a2568a60Sxu_zh  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
927fbdb359dSMuzi  // backendException only needs to be set for the first instruction.
928c1b28b66STang Haojin  // Other instructions in the same block may have pf or af set,
929c1b28b66STang Haojin  // which is a side effect of the first instruction and actually not necessary.
930fbdb359dSMuzi  io.toIbuffer.bits.backendException := (0 until PredictWidth).map {
931fbdb359dSMuzi    case 0 => f3_backendException
932c1b28b66STang Haojin    case _ => false.B
933c1b28b66STang Haojin  }
934dd02bc3fSxu_zh  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(ExceptionType.hasException)
93592c61038SXuan Hu  io.toIbuffer.bits.illegalInstr    := f3_ill
9362a3050c2SJay  io.toIbuffer.bits.triggered       := f3_triggered
9372a3050c2SJay
9382a3050c2SJay  when(f3_lastHalf.valid) {
9395995c9e7SJenius    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
9402a3050c2SJay    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
9412a3050c2SJay  }
9422a3050c2SJay
943d7ac23a3SEaston Man  /** to backend */
94491946104Sxu_zh  // f3_gpaddr is valid iff gpf is detected
945b5a614b9Sxu_zh  io.toBackend.gpaddrMem_wen := f3_toIbuffer_valid && Mux(
946b5a614b9Sxu_zh    f3_req_is_mmio,
94788895b11Sxu_zh    mmio_resend_exception === ExceptionType.gpf,
94888895b11Sxu_zh    f3_exception.map(_ === ExceptionType.gpf).reduce(_ || _)
949b5a614b9Sxu_zh  )
950d7ac23a3SEaston Man  io.toBackend.gpaddrMem_waddr        := f3_ftq_req.ftqIdx.value
951ad415ae0SXiaokun-Pei  io.toBackend.gpaddrMem_wdata.gpaddr := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
952cf7d6b7aSMuzi  io.toBackend.gpaddrMem_wdata.isForVSnonLeafPTE := Mux(
953cf7d6b7aSMuzi    f3_req_is_mmio,
954cf7d6b7aSMuzi    mmio_resend_isForVSnonLeafPTE,
955cf7d6b7aSMuzi    f3_isForVSnonLeafPTE
956cf7d6b7aSMuzi  )
95709c6f1ddSLingrui98
95809c6f1ddSLingrui98  // Write back to Ftq
959a37fbf10SJay  val f3_cache_fetch     = f3_valid && !(f2_fire && !f2_flush)
960a37fbf10SJay  val finishFetchMaskReg = RegNext(f3_cache_fetch)
961a37fbf10SJay
9622a3050c2SJay  val mmioFlushWb        = Wire(Valid(new PredecodeWritebackBundle))
9630be662e4SJay  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
964a37fbf10SJay  f3_mmio_missOffset.valid := f3_req_is_mmio
9650be662e4SJay  f3_mmio_missOffset.bits  := 0.U
9660be662e4SJay
9678abe1810SEaston Man  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
9688abe1810SEaston Man  // When backend redirect, mmio_state reset after 1 cycle.
9698abe1810SEaston Man  // In this case, mask .valid to avoid overriding backend redirect
9708abe1810SEaston Man  mmioFlushWb.valid := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
9718abe1810SEaston Man    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
9722a3050c2SJay  mmioFlushWb.bits.pc := f3_pc
9732a3050c2SJay  mmioFlushWb.bits.pd := f3_pd
9742a3050c2SJay  mmioFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := f3_mmio_range(i) }
9752a3050c2SJay  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
9762a3050c2SJay  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
9772a3050c2SJay  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
9782a3050c2SJay  mmioFlushWb.bits.cfiOffset  := DontCare
979ee175d78SJay  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U, f3_ftq_req.startAddr + 4.U)
9802a3050c2SJay  mmioFlushWb.bits.jalTarget  := DontCare
9812a3050c2SJay  mmioFlushWb.bits.instrRange := f3_mmio_range
98209c6f1ddSLingrui98
98373e96011SXuan Hu  val mmioRVCExpander = Module(new RVCExpander)
98473e96011SXuan Hu  mmioRVCExpander.io.in      := Mux(f3_req_is_mmio, Cat(f3_mmio_data(1), f3_mmio_data(0)), 0.U)
98571b6c42eSxu_zh  mmioRVCExpander.io.fsIsOff := io.csr_fsIsOff
98673e96011SXuan Hu
9872dfa9e76SJenius  /** external predecode for MMIO instruction */
9882dfa9e76SJenius  when(f3_req_is_mmio) {
9892dfa9e76SJenius    val inst         = Cat(f3_mmio_data(1), f3_mmio_data(0))
9902dfa9e76SJenius    val currentIsRVC = isRVC(inst)
9912dfa9e76SJenius
9922dfa9e76SJenius    val brType :: isCall :: isRet :: Nil = brInfo(inst)
9932dfa9e76SJenius    val jalOffset                        = jal_offset(inst, currentIsRVC)
9942dfa9e76SJenius    val brOffset                         = br_offset(inst, currentIsRVC)
9952dfa9e76SJenius
99673e96011SXuan Hu    io.toIbuffer.bits.instrs(0) := Mux(mmioRVCExpander.io.ill, mmioRVCExpander.io.in, mmioRVCExpander.io.out.bits)
9972dfa9e76SJenius
9982dfa9e76SJenius    io.toIbuffer.bits.pd(0).valid  := true.B
9992dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRVC  := currentIsRVC
10002dfa9e76SJenius    io.toIbuffer.bits.pd(0).brType := brType
10012dfa9e76SJenius    io.toIbuffer.bits.pd(0).isCall := isCall
10022dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRet  := isRet
10032dfa9e76SJenius
100488895b11Sxu_zh    io.toIbuffer.bits.exceptionType(0)   := mmio_resend_exception
1005dd02bc3fSxu_zh    io.toIbuffer.bits.crossPageIPFFix(0) := ExceptionType.hasException(mmio_resend_exception)
100673e96011SXuan Hu    io.toIbuffer.bits.illegalInstr(0)    := mmioRVCExpander.io.ill
10072dfa9e76SJenius
10082dfa9e76SJenius    io.toIbuffer.bits.enqEnable := f3_mmio_range.asUInt
10092dfa9e76SJenius
10102dfa9e76SJenius    mmioFlushWb.bits.pd(0).valid  := true.B
10112dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRVC  := currentIsRVC
10122dfa9e76SJenius    mmioFlushWb.bits.pd(0).brType := brType
10132dfa9e76SJenius    mmioFlushWb.bits.pd(0).isCall := isCall
10142dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRet  := isRet
10152dfa9e76SJenius  }
10162dfa9e76SJenius
1017935edac4STang Haojin  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) && f3_mmio_use_seq_pc)
101809c6f1ddSLingrui98
101900240ba6SJay  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready", io.toIbuffer.valid && !io.toIbuffer.ready)
102000240ba6SJay
102158dbdfc2SJay  /**
102258dbdfc2SJay    ******************************************************************************
102358dbdfc2SJay    * IFU Write Back Stage
102458dbdfc2SJay    * - write back predecode information to Ftq to update
102558dbdfc2SJay    * - redirect if found fault prediction
102658dbdfc2SJay    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
102758dbdfc2SJay    ******************************************************************************
10282a3050c2SJay    */
10290c70648eSEaston Man  val wb_enable  = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
10300c70648eSEaston Man  val wb_valid   = RegNext(wb_enable, init = false.B)
10310c70648eSEaston Man  val wb_ftq_req = RegEnable(f3_ftq_req, wb_enable)
103258dbdfc2SJay
10330c70648eSEaston Man  val wb_check_result_stage1 = RegEnable(checkerOutStage1, wb_enable)
10345995c9e7SJenius  val wb_check_result_stage2 = checkerOutStage2
10350c70648eSEaston Man  val wb_instr_range         = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
1036e4d2f6a9Smy-mayfly
1037e4d2f6a9Smy-mayfly  val wb_pc_lower_result = RegEnable(f3_pc_lower_result, wb_enable)
1038e4d2f6a9Smy-mayfly  val wb_pc_high         = RegEnable(f3_pc_high, wb_enable)
1039e4d2f6a9Smy-mayfly  val wb_pc_high_plus1   = RegEnable(f3_pc_high_plus1, wb_enable)
1040e4d2f6a9Smy-mayfly  val wb_pc              = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
1041e4d2f6a9Smy-mayfly
1042e4d2f6a9Smy-mayfly  // val wb_pc             = RegEnable(f3_pc, wb_enable)
10430c70648eSEaston Man  val wb_pd          = RegEnable(f3_pd, wb_enable)
10440c70648eSEaston Man  val wb_instr_valid = RegEnable(f3_instr_valid, wb_enable)
10452a3050c2SJay
10462a3050c2SJay  /* false hit lastHalf */
10470c70648eSEaston Man  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
10480c70648eSEaston Man  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
10490c70648eSEaston Man  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
10502a3050c2SJay
10512a3050c2SJay  val wb_half_flush  = wb_false_lastHalf
10522a3050c2SJay  val wb_half_target = wb_false_target
10532a3050c2SJay
1054a1351e5dSJay  /* false oversize */
1055a1351e5dSJay  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool())).last && wb_pd.last.isRVC
1056a1351e5dSJay  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
10575995c9e7SJenius  val lastTaken = wb_check_result_stage1.fixedTaken.last
1058a1351e5dSJay
10592a3050c2SJay  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
10602a3050c2SJay
10613f785aa3SJenius  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
10623f785aa3SJenius    * we set a flag to notify f3 that the last half flag need not to be set.
10633f785aa3SJenius    */
1064804985a5SJenius  // f3_fire is after wb_valid
1065076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1066cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire && !RegNext(
1067cf7d6b7aSMuzi      f3_fire,
1068cf7d6b7aSMuzi      init = false.B
1069cf7d6b7aSMuzi    ) && !f3_flush) {
10703f785aa3SJenius    f3_lastHalf_disable := true.B
1071ab6202e2SJenius  }
1072ab6202e2SJenius
1073804985a5SJenius  // wb_valid and f3_fire are in same cycle
1074076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1075cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire) {
1076804985a5SJenius    f3_lastHalf.valid := false.B
1077804985a5SJenius  }
1078804985a5SJenius
10792a3050c2SJay  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
1080cf7d6b7aSMuzi  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map { case (pd, v) =>
1081cf7d6b7aSMuzi    v && pd.isJal
1082cf7d6b7aSMuzi  }))
1083b665b650STang Haojin  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
10842a3050c2SJay  checkFlushWb.valid   := wb_valid
10852a3050c2SJay  checkFlushWb.bits.pc := wb_pc
10862a3050c2SJay  checkFlushWb.bits.pd := wb_pd
10872a3050c2SJay  checkFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := wb_instr_valid(i) }
10882a3050c2SJay  checkFlushWb.bits.ftqIdx          := wb_ftq_req.ftqIdx
10892a3050c2SJay  checkFlushWb.bits.ftqOffset       := wb_ftq_req.ftqOffset.bits
10905995c9e7SJenius  checkFlushWb.bits.misOffset.valid := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
1091cf7d6b7aSMuzi  checkFlushWb.bits.misOffset.bits := Mux(
1092cf7d6b7aSMuzi    wb_half_flush,
1093cf7d6b7aSMuzi    wb_lastIdx,
1094cf7d6b7aSMuzi    ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1095cf7d6b7aSMuzi  )
10965995c9e7SJenius  checkFlushWb.bits.cfiOffset.valid := ParallelOR(wb_check_result_stage1.fixedTaken)
10975995c9e7SJenius  checkFlushWb.bits.cfiOffset.bits  := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
1098cf7d6b7aSMuzi  checkFlushWb.bits.target := Mux(
1099cf7d6b7aSMuzi    wb_half_flush,
1100cf7d6b7aSMuzi    wb_half_target,
1101cf7d6b7aSMuzi    wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx)
1102cf7d6b7aSMuzi  )
1103d10ddd67SGuokai Chen  checkFlushWb.bits.jalTarget  := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
11042a3050c2SJay  checkFlushWb.bits.instrRange := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
11052a3050c2SJay
1106bccc5520SJenius  toFtq.pdWb := Mux(wb_valid, checkFlushWb, mmioFlushWb)
11072a3050c2SJay
11082a3050c2SJay  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
110909c6f1ddSLingrui98
11105b3c20f7SJinYue  /*write back flush type*/
11115995c9e7SJenius  val checkFaultType    = wb_check_result_stage2.faultType
11125b3c20f7SJinYue  val checkJalFault     = wb_valid && checkFaultType.map(_.isjalFault).reduce(_ || _)
11135b3c20f7SJinYue  val checkRetFault     = wb_valid && checkFaultType.map(_.isRetFault).reduce(_ || _)
11145b3c20f7SJinYue  val checkTargetFault  = wb_valid && checkFaultType.map(_.istargetFault).reduce(_ || _)
11155b3c20f7SJinYue  val checkNotCFIFault  = wb_valid && checkFaultType.map(_.notCFIFault).reduce(_ || _)
11165b3c20f7SJinYue  val checkInvalidTaken = wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_ || _)
11175b3c20f7SJinYue
11185b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_jalFault", checkJalFault)
11195b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_retFault", checkRetFault)
11205b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_targetFault", checkTargetFault)
11215b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_notCFIFault", checkNotCFIFault)
11225b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_incalidTakenFault", checkInvalidTaken)
11235b3c20f7SJinYue
11245b3c20f7SJinYue  when(checkRetFault) {
1125cf7d6b7aSMuzi    XSDebug(
1126cf7d6b7aSMuzi      "startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1127cf7d6b7aSMuzi      wb_ftq_req.startAddr,
1128cf7d6b7aSMuzi      wb_ftq_req.nextStartAddr,
1129cf7d6b7aSMuzi      wb_ftq_req.ftqOffset.valid,
1130cf7d6b7aSMuzi      wb_ftq_req.ftqOffset.bits
1131cf7d6b7aSMuzi    )
11325b3c20f7SJinYue  }
11335b3c20f7SJinYue
11341d8f4dcbSJay  /** performance counter */
1135005e809bSJiuyang Liu  val f3_perf_info = RegEnable(f2_perf_info, f2_fire)
1136935edac4STang Haojin  val f3_req_0     = io.toIbuffer.fire
1137935edac4STang Haojin  val f3_req_1     = io.toIbuffer.fire && f3_doubleLine
1138935edac4STang Haojin  val f3_hit_0     = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1139935edac4STang Haojin  val f3_hit_1     = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
11401d8f4dcbSJay  val f3_hit       = f3_perf_info.hit
1141cd365d4cSrvcoresjw  val perfEvents = Seq(
11422a3050c2SJay    ("frontendFlush                ", wb_redirect),
1143935edac4STang Haojin    ("ifu_req                      ", io.toIbuffer.fire),
1144935edac4STang Haojin    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit),
1145cd365d4cSrvcoresjw    ("ifu_req_cacheline_0          ", f3_req_0),
1146cd365d4cSrvcoresjw    ("ifu_req_cacheline_1          ", f3_req_1),
1147cd365d4cSrvcoresjw    ("ifu_req_cacheline_0_hit      ", f3_hit_1),
1148cd365d4cSrvcoresjw    ("ifu_req_cacheline_1_hit      ", f3_hit_1),
1149935edac4STang Haojin    ("only_0_hit                   ", f3_perf_info.only_0_hit && io.toIbuffer.fire),
1150935edac4STang Haojin    ("only_0_miss                  ", f3_perf_info.only_0_miss && io.toIbuffer.fire),
1151935edac4STang Haojin    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire),
1152935edac4STang Haojin    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire),
1153935edac4STang Haojin    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire),
1154cf7d6b7aSMuzi    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1155cd365d4cSrvcoresjw  )
11561ca0e4f3SYinan Xu  generatePerfEvent()
115709c6f1ddSLingrui98
1158935edac4STang Haojin  XSPerfAccumulate("ifu_req", io.toIbuffer.fire)
1159935edac4STang Haojin  XSPerfAccumulate("ifu_miss", io.toIbuffer.fire && !f3_hit)
1160f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0)
1161f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1)
1162f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0_hit", f3_hit_0)
1163f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1_hit", f3_hit_1)
11642a3050c2SJay  XSPerfAccumulate("frontendFlush", wb_redirect)
1165935edac4STang Haojin  XSPerfAccumulate("only_0_hit", f3_perf_info.only_0_hit && io.toIbuffer.fire)
1166935edac4STang Haojin  XSPerfAccumulate("only_0_miss", f3_perf_info.only_0_miss && io.toIbuffer.fire)
1167935edac4STang Haojin  XSPerfAccumulate("hit_0_hit_1", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire)
1168935edac4STang Haojin  XSPerfAccumulate("hit_0_miss_1", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire)
1169935edac4STang Haojin  XSPerfAccumulate("miss_0_hit_1", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire)
1170935edac4STang Haojin  XSPerfAccumulate("miss_0_miss_1", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1171935edac4STang Haojin  XSPerfAccumulate("hit_0_except_1", f3_perf_info.hit_0_except_1 && io.toIbuffer.fire)
1172935edac4STang Haojin  XSPerfAccumulate("miss_0_except_1", f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1173935edac4STang Haojin  XSPerfAccumulate("except_0", f3_perf_info.except_0 && io.toIbuffer.fire)
1174cf7d6b7aSMuzi  XSPerfHistogram(
1175cf7d6b7aSMuzi    "ifu2ibuffer_validCnt",
1176cf7d6b7aSMuzi    PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable),
1177cf7d6b7aSMuzi    io.toIbuffer.fire,
1178cf7d6b7aSMuzi    0,
1179cf7d6b7aSMuzi    PredictWidth + 1,
1180cf7d6b7aSMuzi    1
1181cf7d6b7aSMuzi  )
118251532d8bSGuokai Chen
1183c686adcdSYinan Xu  val hartId                     = p(XSCoreParamsKey).HartId
1184c686adcdSYinan Xu  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1185c686adcdSYinan Xu  val isWriteIfuWbToFtqTable     = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1186c686adcdSYinan Xu  val fetchToIBufferTable        = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1187c686adcdSYinan Xu  val ifuWbToFtqTable            = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
118851532d8bSGuokai Chen
118951532d8bSGuokai Chen  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
119051532d8bSGuokai Chen  fetchIBufferDumpData.start_addr  := f3_ftq_req.startAddr
119151532d8bSGuokai Chen  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1192935edac4STang Haojin  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)
119351532d8bSGuokai Chen  fetchIBufferDumpData.is_cache_hit := f3_hit
119451532d8bSGuokai Chen
119551532d8bSGuokai Chen  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
119651532d8bSGuokai Chen  ifuWbToFtqDumpData.start_addr        := wb_ftq_req.startAddr
119751532d8bSGuokai Chen  ifuWbToFtqDumpData.is_miss_pred      := checkFlushWb.bits.misOffset.valid
119851532d8bSGuokai Chen  ifuWbToFtqDumpData.miss_pred_offset  := checkFlushWb.bits.misOffset.bits
119951532d8bSGuokai Chen  ifuWbToFtqDumpData.checkJalFault     := checkJalFault
120051532d8bSGuokai Chen  ifuWbToFtqDumpData.checkRetFault     := checkRetFault
120151532d8bSGuokai Chen  ifuWbToFtqDumpData.checkTargetFault  := checkTargetFault
120251532d8bSGuokai Chen  ifuWbToFtqDumpData.checkNotCFIFault  := checkNotCFIFault
120351532d8bSGuokai Chen  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
120451532d8bSGuokai Chen
120551532d8bSGuokai Chen  fetchToIBufferTable.log(
120651532d8bSGuokai Chen    data = fetchIBufferDumpData,
1207da3bf434SMaxpicca-Li    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
120851532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
120951532d8bSGuokai Chen    clock = clock,
121051532d8bSGuokai Chen    reset = reset
121151532d8bSGuokai Chen  )
121251532d8bSGuokai Chen  ifuWbToFtqTable.log(
121351532d8bSGuokai Chen    data = ifuWbToFtqDumpData,
1214da3bf434SMaxpicca-Li    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
121551532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
121651532d8bSGuokai Chen    clock = clock,
121751532d8bSGuokai Chen    reset = reset
121851532d8bSGuokai Chen  )
121951532d8bSGuokai Chen
122009c6f1ddSLingrui98}
1221