xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 6f9d483270d76b59c45187bb0889ae8a74ac7dc2)
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
248*6f9d4832SHuSipeng  val f0_flush_from_bpu = fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
249cb4f77ceSLingrui98    fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
25009c6f1ddSLingrui98
2512a3050c2SJay  val wb_redirect, mmio_redirect, backend_redirect = WireInit(false.B)
2522a3050c2SJay  val f3_wb_not_flush                              = WireInit(false.B)
2532a3050c2SJay
2542a3050c2SJay  backend_redirect := fromFtq.redirect.valid
2552a3050c2SJay  f3_flush         := backend_redirect || (wb_redirect && !f3_wb_not_flush)
2562a3050c2SJay  f2_flush         := backend_redirect || mmio_redirect || wb_redirect
257*6f9d4832SHuSipeng  f1_flush         := f2_flush
258*6f9d4832SHuSipeng  f0_flush         := f1_flush || f0_flush_from_bpu
25909c6f1ddSLingrui98
26009c6f1ddSLingrui98  val f1_ready, f2_ready, f3_ready = WireInit(false.B)
26109c6f1ddSLingrui98
26250780602SJenius  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
26309c6f1ddSLingrui98
264d2b20d1aSTang Haojin  when(wb_redirect) {
265d2b20d1aSTang Haojin    when(f3_wb_not_flush) {
266d2b20d1aSTang Haojin      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
267d2b20d1aSTang Haojin    }
268d2b20d1aSTang Haojin    for (i <- 0 until numOfStage - 1) {
269d2b20d1aSTang Haojin      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
270d2b20d1aSTang Haojin    }
271d2b20d1aSTang Haojin  }
272d2b20d1aSTang Haojin
27358dbdfc2SJay  /** <PERF> f0 fetch bubble */
274f7c29b0aSJinYue
27500240ba6SJay  XSPerfAccumulate("fetch_bubble_ftq_not_valid", !fromFtq.req.valid && fromFtq.req.ready)
276c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
277c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
278c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
27900240ba6SJay  XSPerfAccumulate("fetch_flush_backend_redirect", backend_redirect)
28000240ba6SJay  XSPerfAccumulate("fetch_flush_wb_redirect", wb_redirect)
281*6f9d4832SHuSipeng  XSPerfAccumulate("fetch_flush_f0_flush_from_bpu", f0_flush_from_bpu)
28258dbdfc2SJay
28358dbdfc2SJay  /**
28458dbdfc2SJay    ******************************************************************************
28558dbdfc2SJay    * IFU Stage 1
28658dbdfc2SJay    * - calculate pc/half_pc/cut_ptr for every instruction
28758dbdfc2SJay    ******************************************************************************
28858dbdfc2SJay    */
28909c6f1ddSLingrui98
29009c6f1ddSLingrui98  val f1_valid   = RegInit(false.B)
291005e809bSJiuyang Liu  val f1_ftq_req = RegEnable(f0_ftq_req, f0_fire)
292005e809bSJiuyang Liu  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
293005e809bSJiuyang Liu  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
294005e809bSJiuyang Liu  val f1_vSetIdx    = RegEnable(f0_vSetIdx, f0_fire)
295625ecd17SJenius  val f1_fire       = f1_valid && f2_ready
29609c6f1ddSLingrui98
297625ecd17SJenius  f1_ready := f1_fire || !f1_valid
29809c6f1ddSLingrui98
299*6f9d4832SHuSipeng  assert(!(fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid))
30009c6f1ddSLingrui98
301cf7d6b7aSMuzi  when(f1_flush)(f1_valid := false.B)
302cf7d6b7aSMuzi    .elsewhen(f0_fire && !f0_flush)(f1_valid := true.B)
303cf7d6b7aSMuzi    .elsewhen(f1_fire)(f1_valid := false.B)
30409c6f1ddSLingrui98
305e4d2f6a9Smy-mayfly  val f1_pc_high       = f1_ftq_req.startAddr(VAddrBits - 1, PcCutPoint)
306f2f493deSstride  val f1_pc_high_plus1 = f1_pc_high + 1.U
307f2f493deSstride
308e4d2f6a9Smy-mayfly  /**
309e4d2f6a9Smy-mayfly   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
310e4d2f6a9Smy-mayfly   * code of original logic, this code has been deprecated
311e4d2f6a9Smy-mayfly   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
312e4d2f6a9Smy-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)))})
313e4d2f6a9Smy-mayfly   */
314cf7d6b7aSMuzi  val f1_pc_lower_result = VecInit((0 until PredictWidth).map(i =>
315cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + (i * 2).U
316cf7d6b7aSMuzi  )) // cat with overflow bit
317f2f493deSstride
318e4d2f6a9Smy-mayfly  val f1_pc = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
319e4d2f6a9Smy-mayfly
320cf7d6b7aSMuzi  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i =>
321cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + ((i + 2) * 2).U
322cf7d6b7aSMuzi  )) // cat with overflow bit
323e4d2f6a9Smy-mayfly  val f1_half_snpc = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
324f2f493deSstride
325f2f493deSstride  if (env.FPGAPlatform) {
326f2f493deSstride    val f1_pc_diff        = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
327f2f493deSstride    val f1_half_snpc_diff = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i + 2) * 2).U))
328f2f493deSstride
329cf7d6b7aSMuzi    XSError(
330cf7d6b7aSMuzi      f1_pc.zip(f1_pc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
331cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
332cf7d6b7aSMuzi    )
333cf7d6b7aSMuzi    XSError(
334cf7d6b7aSMuzi      f1_half_snpc.zip(f1_half_snpc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
335cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
336cf7d6b7aSMuzi    )
337f2f493deSstride  }
338f2f493deSstride
339cf7d6b7aSMuzi  val f1_cut_ptr = if (HasCExtension)
340cf7d6b7aSMuzi    VecInit((0 until PredictWidth + 1).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 1)) + i.U))
341b92f8445Sssszwic  else VecInit((0 until PredictWidth).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 2)) + i.U))
34209c6f1ddSLingrui98
34358dbdfc2SJay  /**
34458dbdfc2SJay    ******************************************************************************
34558dbdfc2SJay    * IFU Stage 2
34658dbdfc2SJay    * - icache response data (latched for pipeline stop)
34758dbdfc2SJay    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
34858dbdfc2SJay    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
34958dbdfc2SJay    * - cut data from cachlines to packet instruction code
35058dbdfc2SJay    * - instruction predecode and RVC expand
35158dbdfc2SJay    ******************************************************************************
35258dbdfc2SJay    */
35358dbdfc2SJay
3541d8f4dcbSJay  val icacheRespAllValid = WireInit(false.B)
35509c6f1ddSLingrui98
35609c6f1ddSLingrui98  val f2_valid   = RegInit(false.B)
357005e809bSJiuyang Liu  val f2_ftq_req = RegEnable(f1_ftq_req, f1_fire)
358005e809bSJiuyang Liu  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
359005e809bSJiuyang Liu  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
360005e809bSJiuyang Liu  val f2_vSetIdx    = RegEnable(f1_vSetIdx, f1_fire)
361625ecd17SJenius  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
3621d8f4dcbSJay
363625ecd17SJenius  f2_ready := f2_fire || !f2_valid
3641d8f4dcbSJay  // TODO: addr compare may be timing critical
365cf7d6b7aSMuzi  val f2_icache_all_resp_wire =
3664690c88aSxu_zh    fromICache.valid &&
3674690c88aSxu_zh      fromICache.bits.vaddr(0) === f2_ftq_req.startAddr &&
3684690c88aSxu_zh      (fromICache.bits.doubleline && fromICache.bits.vaddr(1) === f2_ftq_req.nextlineStart || !f2_doubleLine)
3691d8f4dcbSJay  val f2_icache_all_resp_reg = RegInit(false.B)
3701d8f4dcbSJay
3711d8f4dcbSJay  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
3721d8f4dcbSJay
373d2b20d1aSTang Haojin  icacheMissBubble := io.icacheInter.topdownIcacheMiss
374d2b20d1aSTang Haojin  itlbMissBubble   := io.icacheInter.topdownItlbMiss
375d2b20d1aSTang Haojin
3761d8f4dcbSJay  io.icacheStop := !f3_ready
3771d8f4dcbSJay
378cf7d6b7aSMuzi  when(f2_flush)(f2_icache_all_resp_reg := false.B)
379cf7d6b7aSMuzi    .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready)(f2_icache_all_resp_reg := true.B)
380cf7d6b7aSMuzi    .elsewhen(f2_fire && f2_icache_all_resp_reg)(f2_icache_all_resp_reg := false.B)
38109c6f1ddSLingrui98
382cf7d6b7aSMuzi  when(f2_flush)(f2_valid := false.B)
383cf7d6b7aSMuzi    .elsewhen(f1_fire && !f1_flush)(f2_valid := true.B)
384cf7d6b7aSMuzi    .elsewhen(f2_fire)(f2_valid := false.B)
38509c6f1ddSLingrui98
3864690c88aSxu_zh  val f2_exception_in     = fromICache.bits.exception
3874690c88aSxu_zh  val f2_backendException = fromICache.bits.backendException
388d7ac23a3SEaston Man  // paddr and gpaddr of [startAddr, nextLineAddr]
3894690c88aSxu_zh  val f2_paddrs            = fromICache.bits.paddr
3904690c88aSxu_zh  val f2_gpaddr            = fromICache.bits.gpaddr
3914690c88aSxu_zh  val f2_isForVSnonLeafPTE = fromICache.bits.isForVSnonLeafPTE
392002c10a4SYanqin Li
393211986abSxu_zh  // FIXME: raise af if one fetch block crosses the cacheable-noncacheable boundary, might not correct
39435850f17Sxu_zh  val f2_mmio_mismatch_exception = VecInit(Seq(
39535850f17Sxu_zh    ExceptionType.none, // mark the exception only on the second line
39635850f17Sxu_zh    Mux(
397211986abSxu_zh      // not double-line, skip check
3984690c88aSxu_zh      !fromICache.bits.doubleline || (
399211986abSxu_zh        // is double-line, ask for consistent pmp_mmio and itlb_pbmt value
4004690c88aSxu_zh        fromICache.bits.pmp_mmio(0) === fromICache.bits.pmp_mmio(1) &&
4014690c88aSxu_zh          fromICache.bits.itlb_pbmt(0) === fromICache.bits.itlb_pbmt(1)
4024690c88aSxu_zh      ),
403211986abSxu_zh      ExceptionType.none,
404211986abSxu_zh      ExceptionType.af
40535850f17Sxu_zh    )
40635850f17Sxu_zh  ))
407211986abSxu_zh
408211986abSxu_zh  // merge exceptions
409211986abSxu_zh  val f2_exception = ExceptionType.merge(f2_exception_in, f2_mmio_mismatch_exception)
410211986abSxu_zh
411211986abSxu_zh  // we need only the first port, as the second is asked to be the same
4124690c88aSxu_zh  val f2_pmp_mmio  = fromICache.bits.pmp_mmio(0)
4134690c88aSxu_zh  val f2_itlb_pbmt = fromICache.bits.itlb_pbmt(0)
414002c10a4SYanqin Li
415e4d2f6a9Smy-mayfly  /**
416e4d2f6a9Smy-mayfly    * reduce the number of registers, origin code
417e4d2f6a9Smy-mayfly    * f2_pc = RegEnable(f1_pc, f1_fire)
418e4d2f6a9Smy-mayfly    */
419e4d2f6a9Smy-mayfly  val f2_pc_lower_result = RegEnable(f1_pc_lower_result, f1_fire)
420e4d2f6a9Smy-mayfly  val f2_pc_high         = RegEnable(f1_pc_high, f1_fire)
421e4d2f6a9Smy-mayfly  val f2_pc_high_plus1   = RegEnable(f1_pc_high_plus1, f1_fire)
422e4d2f6a9Smy-mayfly  val f2_pc              = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
423a37fbf10SJay
424e4d2f6a9Smy-mayfly  val f2_cut_ptr      = RegEnable(f1_cut_ptr, f1_fire)
425005e809bSJiuyang Liu  val f2_resend_vaddr = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
4262a3050c2SJay
427cf7d6b7aSMuzi  def isNextLine(pc: UInt, startAddr: UInt) =
4282a3050c2SJay    startAddr(blockOffBits) ^ pc(blockOffBits)
42909c6f1ddSLingrui98
430cf7d6b7aSMuzi  def isLastInLine(pc: UInt) =
4312a3050c2SJay    pc(blockOffBits - 1, 0) === "b111110".U
43209c6f1ddSLingrui98
4332a3050c2SJay  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits - 1, 1), MemPredPCWidth)))
434cf7d6b7aSMuzi  val f2_jump_range =
435cf7d6b7aSMuzi    Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
4364d53e0efSzhou tao  require(
4374d53e0efSzhou tao    isPow2(PredictWidth),
4384d53e0efSzhou tao    "If PredictWidth does not satisfy the power of 2," +
4394d53e0efSzhou tao      "expression: Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits is not right !!"
4404d53e0efSzhou tao  )
441cf7d6b7aSMuzi  val f2_ftr_range = Fill(PredictWidth, f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(
442cf7d6b7aSMuzi    f2_ftq_req.nextStartAddr,
443cf7d6b7aSMuzi    f2_ftq_req.startAddr
444cf7d6b7aSMuzi  )
4452a3050c2SJay  val f2_instr_range = f2_jump_range & f2_ftr_range
446cf7d6b7aSMuzi  val f2_exception_vec = VecInit((0 until PredictWidth).map(i =>
447cf7d6b7aSMuzi    MuxCase(
448cf7d6b7aSMuzi      ExceptionType.none,
449cf7d6b7aSMuzi      Seq(
45088895b11Sxu_zh        !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
45188895b11Sxu_zh        (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
452cf7d6b7aSMuzi      )
453cf7d6b7aSMuzi    )
454cf7d6b7aSMuzi  ))
4551d8f4dcbSJay  val f2_perf_info = io.icachePerfInfo
45609c6f1ddSLingrui98
4572a3050c2SJay  def cut(cacheline: UInt, cutPtr: Vec[UInt]): Vec[UInt] = {
458d558bd61SJenius    require(HasCExtension)
459d558bd61SJenius    // if(HasCExtension){
46009c6f1ddSLingrui98    val result  = Wire(Vec(PredictWidth + 1, UInt(16.W)))
461b92f8445Sssszwic    val dataVec = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) // 32 16-bit data vector
46209c6f1ddSLingrui98    (0 until PredictWidth + 1).foreach(i =>
463d558bd61SJenius      result(i) := dataVec(cutPtr(i)) // the max ptr is 3*blockBytes/4-1
46409c6f1ddSLingrui98    )
46509c6f1ddSLingrui98    result
466d558bd61SJenius    // } else {
467d558bd61SJenius    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
468d558bd61SJenius    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
469d558bd61SJenius    //   (0 until PredictWidth).foreach( i =>
470d558bd61SJenius    //     result(i) := dataVec(cutPtr(i))
471d558bd61SJenius    //   )
472d558bd61SJenius    //   result
473d558bd61SJenius    // }
47409c6f1ddSLingrui98  }
47509c6f1ddSLingrui98
4764690c88aSxu_zh  /* NOTE: the following `Cat(_data, _data)` *is* intentional.
47796d0318bSxu_zh   * Explanation:
47896d0318bSxu_zh   * In the old design, IFU is responsible for selecting requested data from two adjacent cachelines,
47996d0318bSxu_zh   *    so IFU has to receive 2*64B (2cacheline * 64B) data from ICache, and do `Cat(_data(1), _data(0))` here.
48096d0318bSxu_zh   * However, a fetch block is 34B at max, sending 2*64B is quiet a waste of power.
48196d0318bSxu_zh   * In current design (2024.06~), ICacheDataArray is responsible for selecting data from two adjacent cachelines,
4824690c88aSxu_zh   *    so IFU only need to receive 40B (5bank * 8B) valid data, and use only one port is enough.
48396d0318bSxu_zh   * For example, when pc falls on the 6th bank in cacheline0(so this is a doubleline request):
48496d0318bSxu_zh   *                                MSB                                         LSB
48596d0318bSxu_zh   *                  cacheline 1 || 1-7 | 1-6 | 1-5 | 1-4 | 1-3 | 1-2 | 1-1 | 1-0 ||
48696d0318bSxu_zh   *                  cacheline 0 || 0-7 | 0-6 | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | 0-0 ||
48796d0318bSxu_zh   *    and ICacheDataArray will respond:
4884690c88aSxu_zh   *         fromICache.bits.data || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
48996d0318bSxu_zh   *    therefore simply make a copy of the response and `Cat` together, and obtain the requested data from centre:
49096d0318bSxu_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 ||
49196d0318bSxu_zh   *                                             requested data: ^-----------------------------^
49296d0318bSxu_zh   * For another example, pc falls on the 1st bank in cacheline 0, we have:
4934690c88aSxu_zh   *         fromICache.bits.data || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
49496d0318bSxu_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 ||
49596d0318bSxu_zh   *                                                                           requested data: ^-----------------------------^
49696d0318bSxu_zh   * Each "| x-y |" block is a 8B bank from cacheline(x).bank(y)
49796d0318bSxu_zh   * Please also refer to:
49896d0318bSxu_zh   * - DataArray selects data:
49996d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L355-L381
50096d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L149-L161
50196d0318bSxu_zh   * - ICache respond to IFU:
50296d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala#L473
50396d0318bSxu_zh   */
5044690c88aSxu_zh  val f2_data_2_cacheline = Cat(fromICache.bits.data, fromICache.bits.data)
505dc270d3bSJenius
506a61a35e0Sssszwic  val f2_cut_data = cut(f2_data_2_cacheline, f2_cut_ptr)
50709c6f1ddSLingrui98
50858dbdfc2SJay  /** predecode (include RVC expander) */
509dc270d3bSJenius  // preDecoderRegIn.data := f2_reg_cut_data
510dc270d3bSJenius  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
511dc270d3bSJenius  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
512dc270d3bSJenius  // preDecoderRegIn.pc  := f2_pc
513dc270d3bSJenius
514a61a35e0Sssszwic  val preDecoderIn = preDecoder.io.in
5159afa8a47STang Haojin  preDecoderIn.valid                := f2_valid
5169afa8a47STang Haojin  preDecoderIn.bits.data            := f2_cut_data
5179afa8a47STang Haojin  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
5189afa8a47STang Haojin  preDecoderIn.bits.pc              := f2_pc
519a61a35e0Sssszwic  val preDecoderOut = preDecoder.io.out
52009c6f1ddSLingrui98
52148a62719SJenius  // val f2_expd_instr     = preDecoderOut.expInstr
52248a62719SJenius  val f2_instr        = preDecoderOut.instr
5232a3050c2SJay  val f2_pd           = preDecoderOut.pd
5242a3050c2SJay  val f2_jump_offset  = preDecoderOut.jumpOffset
5252a3050c2SJay  val f2_hasHalfValid = preDecoderOut.hasHalfValid
526a2568a60Sxu_zh  /* if there is a cross-page RVI instruction, and the former page has no exception,
527a2568a60Sxu_zh   * whether it has exception is actually depends on the latter page
528a2568a60Sxu_zh   */
529cf7d6b7aSMuzi  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i =>
530cf7d6b7aSMuzi    Mux(
531dd02bc3fSxu_zh      isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && !ExceptionType.hasException(f2_exception(0)),
532a2568a60Sxu_zh      f2_exception(1),
533a2568a60Sxu_zh      ExceptionType.none
534cf7d6b7aSMuzi    )
535cf7d6b7aSMuzi  })
53600240ba6SJay  XSPerfAccumulate("fetch_bubble_icache_not_resp", f2_valid && !icacheRespAllValid)
53700240ba6SJay
53858dbdfc2SJay  /**
53958dbdfc2SJay    ******************************************************************************
54058dbdfc2SJay    * IFU Stage 3
54158dbdfc2SJay    * - handle MMIO instruciton
54258dbdfc2SJay    *  -send request to Uncache fetch Unit
54358dbdfc2SJay    *  -every packet include 1 MMIO instruction
54458dbdfc2SJay    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
54558dbdfc2SJay    *  -flush to snpc (send ifu_redirect to Ftq)
54658dbdfc2SJay    * - Ibuffer enqueue
54758dbdfc2SJay    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
54858dbdfc2SJay    * - handle last half RVI instruction
54958dbdfc2SJay    ******************************************************************************
55058dbdfc2SJay    */
55158dbdfc2SJay
55292c61038SXuan Hu  val expanders = Seq.fill(PredictWidth)(Module(new RVCExpander))
55392c61038SXuan Hu
55409c6f1ddSLingrui98  val f3_valid   = RegInit(false.B)
555005e809bSJiuyang Liu  val f3_ftq_req = RegEnable(f2_ftq_req, f2_fire)
556005e809bSJiuyang Liu  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
557005e809bSJiuyang Liu  val f3_doubleLine = RegEnable(f2_doubleLine, f2_fire)
558935edac4STang Haojin  val f3_fire       = io.toIbuffer.fire
5591d8f4dcbSJay
560a61a35e0Sssszwic  val f3_cut_data = RegEnable(f2_cut_data, f2_fire)
5611d8f4dcbSJay
56288895b11Sxu_zh  val f3_exception        = RegEnable(f2_exception, f2_fire)
563211986abSxu_zh  val f3_pmp_mmio         = RegEnable(f2_pmp_mmio, f2_fire)
564211986abSxu_zh  val f3_itlb_pbmt        = RegEnable(f2_itlb_pbmt, f2_fire)
565fbdb359dSMuzi  val f3_backendException = RegEnable(f2_backendException, f2_fire)
56609c6f1ddSLingrui98
567935edac4STang Haojin  val f3_instr = RegEnable(f2_instr, f2_fire)
568aeedc8eeSGuokai Chen
56992c61038SXuan Hu  expanders.zipWithIndex.foreach { case (expander, i) =>
57092c61038SXuan Hu    expander.io.in      := f3_instr(i)
57171b6c42eSxu_zh    expander.io.fsIsOff := io.csr_fsIsOff
57292c61038SXuan Hu  }
57392c61038SXuan Hu  // Use expanded instruction only when input is legal.
57492c61038SXuan Hu  // Otherwise use origin illegal RVC instruction.
57592c61038SXuan Hu  val f3_expd_instr = VecInit(expanders.map { expander: RVCExpander =>
57692c61038SXuan Hu    Mux(expander.io.ill, expander.io.in, expander.io.out.bits)
57792c61038SXuan Hu  })
57892c61038SXuan Hu  val f3_ill = VecInit(expanders.map(_.io.ill))
57948a62719SJenius
580935edac4STang Haojin  val f3_pd_wire                 = RegEnable(f2_pd, f2_fire)
581330aad7fSGuokai Chen  val f3_pd                      = WireInit(f3_pd_wire)
582935edac4STang Haojin  val f3_jump_offset             = RegEnable(f2_jump_offset, f2_fire)
58388895b11Sxu_zh  val f3_exception_vec           = RegEnable(f2_exception_vec, f2_fire)
584a2568a60Sxu_zh  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
585e4d2f6a9Smy-mayfly
586e4d2f6a9Smy-mayfly  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
587e4d2f6a9Smy-mayfly  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
588e4d2f6a9Smy-mayfly  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
589e4d2f6a9Smy-mayfly  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
590e4d2f6a9Smy-mayfly
591e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
592e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
593e4d2f6a9Smy-mayfly  // val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
594e4d2f6a9Smy-mayfly
595e4d2f6a9Smy-mayfly  /**
596e4d2f6a9Smy-mayfly    ***********************************************************************
597e4d2f6a9Smy-mayfly    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
598e4d2f6a9Smy-mayfly    ***********************************************************************
599e4d2f6a9Smy-mayfly    */
600e4d2f6a9Smy-mayfly  val f3_half_snpc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
601e4d2f6a9Smy-mayfly  for (i <- 0 until PredictWidth) {
602e4d2f6a9Smy-mayfly    if (i == (PredictWidth - 2)) {
603e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
604e4d2f6a9Smy-mayfly    } else if (i == (PredictWidth - 1)) {
605e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
606e4d2f6a9Smy-mayfly    } else {
607e4d2f6a9Smy-mayfly      f3_half_snpc(i) := f3_pc(i + 2)
608e4d2f6a9Smy-mayfly    }
609e4d2f6a9Smy-mayfly  }
610e4d2f6a9Smy-mayfly
611935edac4STang Haojin  val f3_instr_range       = RegEnable(f2_instr_range, f2_fire)
612935edac4STang Haojin  val f3_foldpc            = RegEnable(f2_foldpc, f2_fire)
613935edac4STang Haojin  val f3_hasHalfValid      = RegEnable(f2_hasHalfValid, f2_fire)
614d7ac23a3SEaston Man  val f3_paddrs            = RegEnable(f2_paddrs, f2_fire)
61591946104Sxu_zh  val f3_gpaddr            = RegEnable(f2_gpaddr, f2_fire)
616ad415ae0SXiaokun-Pei  val f3_isForVSnonLeafPTE = RegEnable(f2_isForVSnonLeafPTE, f2_fire)
617005e809bSJiuyang Liu  val f3_resend_vaddr      = RegEnable(f2_resend_vaddr, f2_fire)
618ee175d78SJay
619cb6e5d3cSssszwic  // Expand 1 bit to prevent overflow when assert
620cb6e5d3cSssszwic  val f3_ftq_req_startAddr     = Cat(0.U(1.W), f3_ftq_req.startAddr)
621cb6e5d3cSssszwic  val f3_ftq_req_nextStartAddr = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
622330aad7fSGuokai Chen  // brType, isCall and isRet generation is delayed to f3 stage
623330aad7fSGuokai Chen  val f3Predecoder = Module(new F3Predecoder)
624330aad7fSGuokai Chen
625330aad7fSGuokai Chen  f3Predecoder.io.in.instr := f3_instr
626330aad7fSGuokai Chen
627330aad7fSGuokai Chen  f3_pd.zipWithIndex.map { case (pd, i) =>
628330aad7fSGuokai Chen    pd.brType := f3Predecoder.io.out.pd(i).brType
629330aad7fSGuokai Chen    pd.isCall := f3Predecoder.io.out.pd(i).isCall
630330aad7fSGuokai Chen    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
631330aad7fSGuokai Chen  }
632330aad7fSGuokai Chen
633330aad7fSGuokai Chen  val f3PdDiff = f3_pd_wire.zip(f3_pd).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _)
634330aad7fSGuokai Chen  XSError(f3_valid && f3PdDiff, "f3 pd diff")
635330aad7fSGuokai Chen
6361d011975SJinYue  when(f3_valid && !f3_ftq_req.ftqOffset.valid) {
637cf7d6b7aSMuzi    assert(
638cf7d6b7aSMuzi      f3_ftq_req_startAddr + (2 * PredictWidth).U >= f3_ftq_req_nextStartAddr,
639cf7d6b7aSMuzi      s"More tha ${2 * PredictWidth} Bytes fetch is not allowed!"
640cf7d6b7aSMuzi    )
6411d011975SJinYue  }
642a1351e5dSJay
6432a3050c2SJay  /*** MMIO State Machine***/
644ee175d78SJay  val f3_mmio_data          = Reg(Vec(2, UInt(16.W)))
645ee175d78SJay  val mmio_is_RVC           = RegInit(false.B)
646ee175d78SJay  val mmio_resend_addr      = RegInit(0.U(PAddrBits.W))
64788895b11Sxu_zh  val mmio_resend_exception = RegInit(0.U(ExceptionType.width.W))
648dd980d61SXu, Zefan  // NOTE: we dont use GPAddrBits here, refer to ICacheMainPipe.scala L43-48 and PR#3795
649dd980d61SXu, Zefan  val mmio_resend_gpaddr            = RegInit(0.U(PAddrBitsMax.W))
650ad415ae0SXiaokun-Pei  val mmio_resend_isForVSnonLeafPTE = RegInit(false.B)
651c3b2d83aSJay
6521d1e6d4dSJenius  // last instuction finish
6531d1e6d4dSJenius  val is_first_instr = RegInit(true.B)
654cf7d6b7aSMuzi
655ba5ba1dcSmy-mayfly  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
656ba5ba1dcSmy-mayfly  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
657a37fbf10SJay
658cf7d6b7aSMuzi  val m_idle :: m_waitLastCmt :: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil =
659cf7d6b7aSMuzi    Enum(11)
660ee175d78SJay  val mmio_state = RegInit(m_idle)
661a37fbf10SJay
662211986abSxu_zh  // do mmio fetch only when pmp/pbmt shows it is a uncacheable address and no exception occurs
663211986abSxu_zh  /* FIXME: we do not distinguish pbmt is NC or IO now
664211986abSxu_zh   *        but we actually can do speculative execution if pbmt is NC, maybe fix this later for performance
665211986abSxu_zh   */
666211986abSxu_zh  val f3_req_is_mmio =
667211986abSxu_zh    f3_valid && (f3_pmp_mmio || Pbmt.isUncache(f3_itlb_pbmt)) && !ExceptionType.hasException(f3_exception)
668cf7d6b7aSMuzi  val mmio_commit = VecInit(io.rob_commits.map { commit =>
669cf7d6b7aSMuzi    commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx && commit.bits.ftqOffset === 0.U
670cf7d6b7aSMuzi  }).asUInt.orR
671ee175d78SJay  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
672a37fbf10SJay
673ee175d78SJay  val f3_mmio_to_commit      = f3_req_is_mmio && mmio_state === m_waitCommit
674a37fbf10SJay  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
675a37fbf10SJay  val f3_mmio_can_go         = f3_mmio_to_commit && !f3_mmio_to_commit_next
676a37fbf10SJay
6770c70648eSEaston Man  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
678cf7d6b7aSMuzi  fromFtqRedirectReg.bits := RegEnable(
679cf7d6b7aSMuzi    fromFtq.redirect.bits,
680cf7d6b7aSMuzi    0.U.asTypeOf(fromFtq.redirect.bits),
681cf7d6b7aSMuzi    fromFtq.redirect.valid
682cf7d6b7aSMuzi  )
6830c70648eSEaston Man  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
6844a74a727SJenius  val mmioF3Flush           = RegNext(f3_flush, init = false.B)
68556788a33SJinYue  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
68656788a33SJinYue  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
6879bae7d6eSJay
68856788a33SJinYue  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
6899bae7d6eSJay
690ba5ba1dcSmy-mayfly  /**
691ba5ba1dcSmy-mayfly    **********************************************************************************
692ba5ba1dcSmy-mayfly    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
693ba5ba1dcSmy-mayfly    * This is the exception when the first instruction is an MMIO instruction.
694ba5ba1dcSmy-mayfly    **********************************************************************************
695ba5ba1dcSmy-mayfly    */
696ba5ba1dcSmy-mayfly  when(is_first_instr && f3_fire) {
6971d1e6d4dSJenius    is_first_instr := false.B
6981d1e6d4dSJenius  }
6991d1e6d4dSJenius
700cf7d6b7aSMuzi  when(f3_flush && !f3_req_is_mmio)(f3_valid := false.B)
701cf7d6b7aSMuzi    .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)(f3_valid := false.B)
702cf7d6b7aSMuzi    .elsewhen(f2_fire && !f2_flush)(f3_valid := true.B)
703cf7d6b7aSMuzi    .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)(f3_valid := false.B)
704cf7d6b7aSMuzi    .elsewhen(f3_req_is_mmio && f3_mmio_req_commit)(f3_valid := false.B)
705a37fbf10SJay
706a37fbf10SJay  val f3_mmio_use_seq_pc = RegInit(false.B)
707a37fbf10SJay
70856788a33SJinYue  val (redirect_ftqIdx, redirect_ftqOffset) = (fromFtqRedirectReg.bits.ftqIdx, fromFtqRedirectReg.bits.ftqOffset)
709cf7d6b7aSMuzi  val redirect_mmio_req =
710cf7d6b7aSMuzi    fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
711a37fbf10SJay
712cf7d6b7aSMuzi  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)(f3_mmio_use_seq_pc := true.B)
713cf7d6b7aSMuzi    .elsewhen(redirect_mmio_req)(f3_mmio_use_seq_pc := false.B)
714a37fbf10SJay
7158c192ff7Sxu_zh  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
716a37fbf10SJay
7171d1e6d4dSJenius  // mmio state machine
718a37fbf10SJay  switch(mmio_state) {
719ee175d78SJay    is(m_idle) {
7209bae7d6eSJay      when(f3_req_is_mmio) {
7217d889d88Sxu_zh        // in idempotent spaces, we can send request directly (i.e. can do speculative fetch)
7227d889d88Sxu_zh        mmio_state := Mux(f3_itlb_pbmt === Pbmt.nc, m_sendReq, m_waitLastCmt)
7231d1e6d4dSJenius      }
7241d1e6d4dSJenius    }
7251d1e6d4dSJenius
7261d1e6d4dSJenius    is(m_waitLastCmt) {
7271d1e6d4dSJenius      when(is_first_instr) {
728ee175d78SJay        mmio_state := m_sendReq
7291d1e6d4dSJenius      }.otherwise {
7301d1e6d4dSJenius        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
731a37fbf10SJay      }
732a37fbf10SJay    }
733a37fbf10SJay
734ee175d78SJay    is(m_sendReq) {
735935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
736a37fbf10SJay    }
737a37fbf10SJay
738ee175d78SJay    is(m_waitResp) {
739935edac4STang Haojin      when(fromUncache.fire) {
740a37fbf10SJay        val isRVC      = fromUncache.bits.data(1, 0) =/= 3.U
741d7ac23a3SEaston Man        val needResend = !isRVC && f3_paddrs(0)(2, 1) === 3.U
742ee175d78SJay        mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
743ee175d78SJay        mmio_is_RVC     := isRVC
744ee175d78SJay        f3_mmio_data(0) := fromUncache.bits.data(15, 0)
745ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(31, 16)
746a37fbf10SJay      }
747a37fbf10SJay    }
748a37fbf10SJay
749ee175d78SJay    is(m_sendTLB) {
7507b7232f9Sxu_zh      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
751c3b2d83aSJay    }
752a37fbf10SJay
753ee175d78SJay    is(m_tlbResp) {
7547b7232f9Sxu_zh      when(io.iTLBInter.resp.fire) {
7557b7232f9Sxu_zh        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
7567b7232f9Sxu_zh        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
75788895b11Sxu_zh        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
758211986abSxu_zh        // if itlb re-check respond pbmt mismatch with previous check, must be access fault
759211986abSxu_zh        val pbmt_mismatch_exception = Mux(
760211986abSxu_zh          io.iTLBInter.resp.bits.pbmt(0) =/= f3_itlb_pbmt,
761211986abSxu_zh          ExceptionType.af,
762211986abSxu_zh          ExceptionType.none
763211986abSxu_zh        )
764211986abSxu_zh        val exception = ExceptionType.merge(tlb_exception, pbmt_mismatch_exception)
7657b7232f9Sxu_zh        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
766211986abSxu_zh        mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_sendPMP)
7677b7232f9Sxu_zh        // also save itlb response
76803efd994Shappy-lx        mmio_resend_addr              := io.iTLBInter.resp.bits.paddr(0)
769211986abSxu_zh        mmio_resend_exception         := exception
770b5a614b9Sxu_zh        mmio_resend_gpaddr            := io.iTLBInter.resp.bits.gpaddr(0)
771ad415ae0SXiaokun-Pei        mmio_resend_isForVSnonLeafPTE := io.iTLBInter.resp.bits.isForVSnonLeafPTE(0)
772ee175d78SJay      }
7737b7232f9Sxu_zh    }
774ee175d78SJay
775ee175d78SJay    is(m_sendPMP) {
776211986abSxu_zh      val pmp_exception = ExceptionType.fromPMPResp(io.pmp.resp)
777211986abSxu_zh      // if pmp re-check respond mismatch with previous check, must be access fault
778211986abSxu_zh      val mmio_mismatch_exception = Mux(
779211986abSxu_zh        io.pmp.resp.mmio =/= f3_pmp_mmio,
780211986abSxu_zh        ExceptionType.af,
781211986abSxu_zh        ExceptionType.none
782211986abSxu_zh      )
783211986abSxu_zh      val exception = ExceptionType.merge(pmp_exception, mmio_mismatch_exception)
78488895b11Sxu_zh      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
785211986abSxu_zh      mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_resendReq)
78688895b11Sxu_zh      // also save pmp response
787211986abSxu_zh      mmio_resend_exception := exception
788ee175d78SJay    }
789ee175d78SJay
790ee175d78SJay    is(m_resendReq) {
791935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
792ee175d78SJay    }
793ee175d78SJay
794ee175d78SJay    is(m_waitResendResp) {
795935edac4STang Haojin      when(fromUncache.fire) {
796ee175d78SJay        mmio_state      := m_waitCommit
797ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(15, 0)
798a37fbf10SJay      }
799a37fbf10SJay    }
800a37fbf10SJay
801ee175d78SJay    is(m_waitCommit) {
8027d889d88Sxu_zh      // in idempotent spaces, we can skip waiting for commit (i.e. can do speculative fetch)
8037d889d88Sxu_zh      // but we do not skip m_waitCommit state, as other signals (e.g. f3_mmio_can_go relies on this)
8047d889d88Sxu_zh      mmio_state := Mux(mmio_commit || f3_itlb_pbmt === Pbmt.nc, m_commited, m_waitCommit)
805a37fbf10SJay    }
8062a3050c2SJay
807ee175d78SJay    // normal mmio instruction
808ee175d78SJay    is(m_commited) {
809ee175d78SJay      mmio_state                    := m_idle
810ee175d78SJay      mmio_is_RVC                   := false.B
811ee175d78SJay      mmio_resend_addr              := 0.U
81288895b11Sxu_zh      mmio_resend_exception         := ExceptionType.none
813b5a614b9Sxu_zh      mmio_resend_gpaddr            := 0.U
814ad415ae0SXiaokun-Pei      mmio_resend_isForVSnonLeafPTE := false.B
8152a3050c2SJay    }
816a37fbf10SJay  }
817a37fbf10SJay
8188abe1810SEaston Man  // Exception or flush by older branch prediction
8198abe1810SEaston Man  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
820167bcd01SJay  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
821ee175d78SJay    mmio_state                    := m_idle
822ee175d78SJay    mmio_is_RVC                   := false.B
823ee175d78SJay    mmio_resend_addr              := 0.U
82488895b11Sxu_zh    mmio_resend_exception         := ExceptionType.none
825b5a614b9Sxu_zh    mmio_resend_gpaddr            := 0.U
826ad415ae0SXiaokun-Pei    mmio_resend_isForVSnonLeafPTE := false.B
827ee175d78SJay    f3_mmio_data.map(_ := 0.U)
8289bae7d6eSJay  }
8299bae7d6eSJay
830ee175d78SJay  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
831cf7d6b7aSMuzi  toUncache.bits.addr := Mux(mmio_state === m_resendReq, mmio_resend_addr, f3_paddrs(0))
832a37fbf10SJay  fromUncache.ready   := true.B
833a37fbf10SJay
8347b7232f9Sxu_zh  // send itlb request in m_sendTLB state
835ee175d78SJay  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
836ee175d78SJay  io.iTLBInter.req.bits.size               := 3.U
837ee175d78SJay  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
838ee175d78SJay  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
8397b7232f9Sxu_zh  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
8408a4dab4dSHaoyuan Feng  io.iTLBInter.req.bits.isPrefetch         := false.B
8417b7232f9Sxu_zh  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
8427b7232f9Sxu_zh  io.iTLBInter.req.bits.no_translate       := false.B
843db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.fullva             := 0.U
844db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.checkfullva        := false.B
845d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hyperinst          := DontCare
846d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hlvx               := DontCare
8478744445eSMaxpicca-Li  io.iTLBInter.req.bits.memidx             := DontCare
848f1fe8698SLemover  io.iTLBInter.req.bits.debug.robIdx       := DontCare
849ee175d78SJay  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
850149a2326Sweiding liu  io.iTLBInter.req.bits.pmp_addr           := DontCare
8517b7232f9Sxu_zh  // whats the difference between req_kill and req.bits.kill?
8527b7232f9Sxu_zh  io.iTLBInter.req_kill := false.B
8537b7232f9Sxu_zh  // wait for itlb response in m_tlbResp state
8547b7232f9Sxu_zh  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
855ee175d78SJay
856ee175d78SJay  io.pmp.req.valid     := (mmio_state === m_sendPMP) && f3_req_is_mmio
857ee175d78SJay  io.pmp.req.bits.addr := mmio_resend_addr
858ee175d78SJay  io.pmp.req.bits.size := 3.U
859ee175d78SJay  io.pmp.req.bits.cmd  := TlbCmd.exec
860f7c29b0aSJinYue
8612a3050c2SJay  val f3_lastHalf = RegInit(0.U.asTypeOf(new LastHalfInfo))
86209c6f1ddSLingrui98
86309c6f1ddSLingrui98  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
8640be662e4SJay  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if (i == 0) true.B else false.B))
8652a3050c2SJay  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
86609c6f1ddSLingrui98
8672a3050c2SJay  /*** prediction result check   ***/
8682a3050c2SJay  checkerIn.ftqOffset  := f3_ftq_req.ftqOffset
8692a3050c2SJay  checkerIn.jumpOffset := f3_jump_offset
8706ce52296SJinYue  checkerIn.target     := f3_ftq_req.nextStartAddr
8712a3050c2SJay  checkerIn.instrRange := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
8722a3050c2SJay  checkerIn.instrValid := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
8732a3050c2SJay  checkerIn.pds        := f3_pd
8742a3050c2SJay  checkerIn.pc         := f3_pc
8750c70648eSEaston Man  checkerIn.fire_in    := RegNext(f2_fire, init = false.B)
8762a3050c2SJay
87758dbdfc2SJay  /*** handle half RVI in the last 2 Bytes  ***/
8782a3050c2SJay
879cf7d6b7aSMuzi  def hasLastHalf(idx: UInt) =
8805995c9e7SJenius    // !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
881cf7d6b7aSMuzi    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(
882cf7d6b7aSMuzi      idx
883cf7d6b7aSMuzi    ) && !f3_req_is_mmio
8842a3050c2SJay
885b665b650STang Haojin  val f3_last_validIdx = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
8862a3050c2SJay
8872a3050c2SJay  val f3_hasLastHalf    = hasLastHalf((PredictWidth - 1).U)
8882a3050c2SJay  val f3_false_lastHalf = hasLastHalf(f3_last_validIdx)
8892a3050c2SJay  val f3_false_snpc     = f3_half_snpc(f3_last_validIdx)
8902a3050c2SJay
891935edac4STang Haojin  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map(i => if (i == 0) false.B else true.B)).asUInt
8923f785aa3SJenius  val f3_lastHalf_disable = RegInit(false.B)
8932a3050c2SJay
894804985a5SJenius  when(f3_flush || (f3_fire && f3_lastHalf_disable)) {
895804985a5SJenius    f3_lastHalf_disable := false.B
896804985a5SJenius  }
897804985a5SJenius
8982a3050c2SJay  when(f3_flush) {
8992a3050c2SJay    f3_lastHalf.valid := false.B
9002a3050c2SJay  }.elsewhen(f3_fire) {
9013f785aa3SJenius    f3_lastHalf.valid    := f3_hasLastHalf && !f3_lastHalf_disable
9026ce52296SJinYue    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
9032a3050c2SJay  }
9042a3050c2SJay
9052a3050c2SJay  f3_instr_valid := Mux(f3_lastHalf.valid, f3_hasHalfValid, VecInit(f3_pd.map(inst => inst.valid)))
9062a3050c2SJay
9072a3050c2SJay  /*** frontend Trigger  ***/
9082a3050c2SJay  frontendTrigger.io.pds  := f3_pd
9092a3050c2SJay  frontendTrigger.io.pc   := f3_pc
9102a3050c2SJay  frontendTrigger.io.data := f3_cut_data
9112a3050c2SJay
9122a3050c2SJay  frontendTrigger.io.frontendTrigger := io.frontendTrigger
9132a3050c2SJay
9142a3050c2SJay  val f3_triggered       = frontendTrigger.io.triggered
91591946104Sxu_zh  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
9162a3050c2SJay
9172a3050c2SJay  /*** send to Ibuffer  ***/
91891946104Sxu_zh  io.toIbuffer.valid          := f3_toIbuffer_valid
9192a3050c2SJay  io.toIbuffer.bits.instrs    := f3_expd_instr
9202a3050c2SJay  io.toIbuffer.bits.valid     := f3_instr_valid.asUInt
9215995c9e7SJenius  io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
9222a3050c2SJay  io.toIbuffer.bits.pd        := f3_pd
92309c6f1ddSLingrui98  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
9242a3050c2SJay  io.toIbuffer.bits.pc        := f3_pc
925c72c955dSEaston Man  // Find last using PriorityMux
926948e8159SEaston Man  io.toIbuffer.bits.isLastInFtqEntry := Reverse(PriorityEncoderOH(Reverse(io.toIbuffer.bits.enqEnable))).asBools
927cf7d6b7aSMuzi  io.toIbuffer.bits.ftqOffset.zipWithIndex.map { case (a, i) =>
928cf7d6b7aSMuzi    a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio
929cf7d6b7aSMuzi  }
9302a3050c2SJay  io.toIbuffer.bits.foldpc        := f3_foldpc
931a2568a60Sxu_zh  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
932fbdb359dSMuzi  // backendException only needs to be set for the first instruction.
933c1b28b66STang Haojin  // Other instructions in the same block may have pf or af set,
934c1b28b66STang Haojin  // which is a side effect of the first instruction and actually not necessary.
935fbdb359dSMuzi  io.toIbuffer.bits.backendException := (0 until PredictWidth).map {
936fbdb359dSMuzi    case 0 => f3_backendException
937c1b28b66STang Haojin    case _ => false.B
938c1b28b66STang Haojin  }
939dd02bc3fSxu_zh  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(ExceptionType.hasException)
94092c61038SXuan Hu  io.toIbuffer.bits.illegalInstr    := f3_ill
9412a3050c2SJay  io.toIbuffer.bits.triggered       := f3_triggered
9422a3050c2SJay
9432a3050c2SJay  when(f3_lastHalf.valid) {
9445995c9e7SJenius    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
9452a3050c2SJay    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
9462a3050c2SJay  }
9472a3050c2SJay
948d7ac23a3SEaston Man  /** to backend */
94991946104Sxu_zh  // f3_gpaddr is valid iff gpf is detected
950b5a614b9Sxu_zh  io.toBackend.gpaddrMem_wen := f3_toIbuffer_valid && Mux(
951b5a614b9Sxu_zh    f3_req_is_mmio,
95288895b11Sxu_zh    mmio_resend_exception === ExceptionType.gpf,
95388895b11Sxu_zh    f3_exception.map(_ === ExceptionType.gpf).reduce(_ || _)
954b5a614b9Sxu_zh  )
955d7ac23a3SEaston Man  io.toBackend.gpaddrMem_waddr        := f3_ftq_req.ftqIdx.value
956ad415ae0SXiaokun-Pei  io.toBackend.gpaddrMem_wdata.gpaddr := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
957cf7d6b7aSMuzi  io.toBackend.gpaddrMem_wdata.isForVSnonLeafPTE := Mux(
958cf7d6b7aSMuzi    f3_req_is_mmio,
959cf7d6b7aSMuzi    mmio_resend_isForVSnonLeafPTE,
960cf7d6b7aSMuzi    f3_isForVSnonLeafPTE
961cf7d6b7aSMuzi  )
96209c6f1ddSLingrui98
96309c6f1ddSLingrui98  // Write back to Ftq
964a37fbf10SJay  val f3_cache_fetch     = f3_valid && !(f2_fire && !f2_flush)
965a37fbf10SJay  val finishFetchMaskReg = RegNext(f3_cache_fetch)
966a37fbf10SJay
9672a3050c2SJay  val mmioFlushWb        = Wire(Valid(new PredecodeWritebackBundle))
9680be662e4SJay  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
969a37fbf10SJay  f3_mmio_missOffset.valid := f3_req_is_mmio
9700be662e4SJay  f3_mmio_missOffset.bits  := 0.U
9710be662e4SJay
9728abe1810SEaston Man  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
9738abe1810SEaston Man  // When backend redirect, mmio_state reset after 1 cycle.
9748abe1810SEaston Man  // In this case, mask .valid to avoid overriding backend redirect
9758abe1810SEaston Man  mmioFlushWb.valid := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
9768abe1810SEaston Man    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
9772a3050c2SJay  mmioFlushWb.bits.pc := f3_pc
9782a3050c2SJay  mmioFlushWb.bits.pd := f3_pd
9792a3050c2SJay  mmioFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := f3_mmio_range(i) }
9802a3050c2SJay  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
9812a3050c2SJay  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
9822a3050c2SJay  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
9832a3050c2SJay  mmioFlushWb.bits.cfiOffset  := DontCare
984ee175d78SJay  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U, f3_ftq_req.startAddr + 4.U)
9852a3050c2SJay  mmioFlushWb.bits.jalTarget  := DontCare
9862a3050c2SJay  mmioFlushWb.bits.instrRange := f3_mmio_range
98709c6f1ddSLingrui98
98873e96011SXuan Hu  val mmioRVCExpander = Module(new RVCExpander)
98973e96011SXuan Hu  mmioRVCExpander.io.in      := Mux(f3_req_is_mmio, Cat(f3_mmio_data(1), f3_mmio_data(0)), 0.U)
99071b6c42eSxu_zh  mmioRVCExpander.io.fsIsOff := io.csr_fsIsOff
99173e96011SXuan Hu
9922dfa9e76SJenius  /** external predecode for MMIO instruction */
9932dfa9e76SJenius  when(f3_req_is_mmio) {
9942dfa9e76SJenius    val inst         = Cat(f3_mmio_data(1), f3_mmio_data(0))
9952dfa9e76SJenius    val currentIsRVC = isRVC(inst)
9962dfa9e76SJenius
9972dfa9e76SJenius    val brType :: isCall :: isRet :: Nil = brInfo(inst)
9982dfa9e76SJenius    val jalOffset                        = jal_offset(inst, currentIsRVC)
9992dfa9e76SJenius    val brOffset                         = br_offset(inst, currentIsRVC)
10002dfa9e76SJenius
100173e96011SXuan Hu    io.toIbuffer.bits.instrs(0) := Mux(mmioRVCExpander.io.ill, mmioRVCExpander.io.in, mmioRVCExpander.io.out.bits)
10022dfa9e76SJenius
10032dfa9e76SJenius    io.toIbuffer.bits.pd(0).valid  := true.B
10042dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRVC  := currentIsRVC
10052dfa9e76SJenius    io.toIbuffer.bits.pd(0).brType := brType
10062dfa9e76SJenius    io.toIbuffer.bits.pd(0).isCall := isCall
10072dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRet  := isRet
10082dfa9e76SJenius
100988895b11Sxu_zh    io.toIbuffer.bits.exceptionType(0)   := mmio_resend_exception
1010dd02bc3fSxu_zh    io.toIbuffer.bits.crossPageIPFFix(0) := ExceptionType.hasException(mmio_resend_exception)
101173e96011SXuan Hu    io.toIbuffer.bits.illegalInstr(0)    := mmioRVCExpander.io.ill
10122dfa9e76SJenius
10132dfa9e76SJenius    io.toIbuffer.bits.enqEnable := f3_mmio_range.asUInt
10142dfa9e76SJenius
10152dfa9e76SJenius    mmioFlushWb.bits.pd(0).valid  := true.B
10162dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRVC  := currentIsRVC
10172dfa9e76SJenius    mmioFlushWb.bits.pd(0).brType := brType
10182dfa9e76SJenius    mmioFlushWb.bits.pd(0).isCall := isCall
10192dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRet  := isRet
10202dfa9e76SJenius  }
10212dfa9e76SJenius
1022935edac4STang Haojin  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) && f3_mmio_use_seq_pc)
102309c6f1ddSLingrui98
102400240ba6SJay  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready", io.toIbuffer.valid && !io.toIbuffer.ready)
102500240ba6SJay
102658dbdfc2SJay  /**
102758dbdfc2SJay    ******************************************************************************
102858dbdfc2SJay    * IFU Write Back Stage
102958dbdfc2SJay    * - write back predecode information to Ftq to update
103058dbdfc2SJay    * - redirect if found fault prediction
103158dbdfc2SJay    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
103258dbdfc2SJay    ******************************************************************************
10332a3050c2SJay    */
10340c70648eSEaston Man  val wb_enable  = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
10350c70648eSEaston Man  val wb_valid   = RegNext(wb_enable, init = false.B)
10360c70648eSEaston Man  val wb_ftq_req = RegEnable(f3_ftq_req, wb_enable)
103758dbdfc2SJay
10380c70648eSEaston Man  val wb_check_result_stage1 = RegEnable(checkerOutStage1, wb_enable)
10395995c9e7SJenius  val wb_check_result_stage2 = checkerOutStage2
10400c70648eSEaston Man  val wb_instr_range         = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
1041e4d2f6a9Smy-mayfly
1042e4d2f6a9Smy-mayfly  val wb_pc_lower_result = RegEnable(f3_pc_lower_result, wb_enable)
1043e4d2f6a9Smy-mayfly  val wb_pc_high         = RegEnable(f3_pc_high, wb_enable)
1044e4d2f6a9Smy-mayfly  val wb_pc_high_plus1   = RegEnable(f3_pc_high_plus1, wb_enable)
1045e4d2f6a9Smy-mayfly  val wb_pc              = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
1046e4d2f6a9Smy-mayfly
1047e4d2f6a9Smy-mayfly  // val wb_pc             = RegEnable(f3_pc, wb_enable)
10480c70648eSEaston Man  val wb_pd          = RegEnable(f3_pd, wb_enable)
10490c70648eSEaston Man  val wb_instr_valid = RegEnable(f3_instr_valid, wb_enable)
10502a3050c2SJay
10512a3050c2SJay  /* false hit lastHalf */
10520c70648eSEaston Man  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
10530c70648eSEaston Man  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
10540c70648eSEaston Man  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
10552a3050c2SJay
10562a3050c2SJay  val wb_half_flush  = wb_false_lastHalf
10572a3050c2SJay  val wb_half_target = wb_false_target
10582a3050c2SJay
1059a1351e5dSJay  /* false oversize */
1060a1351e5dSJay  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool())).last && wb_pd.last.isRVC
1061a1351e5dSJay  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
10625995c9e7SJenius  val lastTaken = wb_check_result_stage1.fixedTaken.last
1063a1351e5dSJay
10642a3050c2SJay  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
10652a3050c2SJay
10663f785aa3SJenius  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
10673f785aa3SJenius    * we set a flag to notify f3 that the last half flag need not to be set.
10683f785aa3SJenius    */
1069804985a5SJenius  // f3_fire is after wb_valid
1070076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1071cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire && !RegNext(
1072cf7d6b7aSMuzi      f3_fire,
1073cf7d6b7aSMuzi      init = false.B
1074cf7d6b7aSMuzi    ) && !f3_flush) {
10753f785aa3SJenius    f3_lastHalf_disable := true.B
1076ab6202e2SJenius  }
1077ab6202e2SJenius
1078804985a5SJenius  // wb_valid and f3_fire are in same cycle
1079076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1080cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire) {
1081804985a5SJenius    f3_lastHalf.valid := false.B
1082804985a5SJenius  }
1083804985a5SJenius
10842a3050c2SJay  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
1085cf7d6b7aSMuzi  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map { case (pd, v) =>
1086cf7d6b7aSMuzi    v && pd.isJal
1087cf7d6b7aSMuzi  }))
1088b665b650STang Haojin  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
10892a3050c2SJay  checkFlushWb.valid   := wb_valid
10902a3050c2SJay  checkFlushWb.bits.pc := wb_pc
10912a3050c2SJay  checkFlushWb.bits.pd := wb_pd
10922a3050c2SJay  checkFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := wb_instr_valid(i) }
10932a3050c2SJay  checkFlushWb.bits.ftqIdx          := wb_ftq_req.ftqIdx
10942a3050c2SJay  checkFlushWb.bits.ftqOffset       := wb_ftq_req.ftqOffset.bits
10955995c9e7SJenius  checkFlushWb.bits.misOffset.valid := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
1096cf7d6b7aSMuzi  checkFlushWb.bits.misOffset.bits := Mux(
1097cf7d6b7aSMuzi    wb_half_flush,
1098cf7d6b7aSMuzi    wb_lastIdx,
1099cf7d6b7aSMuzi    ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1100cf7d6b7aSMuzi  )
11015995c9e7SJenius  checkFlushWb.bits.cfiOffset.valid := ParallelOR(wb_check_result_stage1.fixedTaken)
11025995c9e7SJenius  checkFlushWb.bits.cfiOffset.bits  := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
1103cf7d6b7aSMuzi  checkFlushWb.bits.target := Mux(
1104cf7d6b7aSMuzi    wb_half_flush,
1105cf7d6b7aSMuzi    wb_half_target,
1106cf7d6b7aSMuzi    wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx)
1107cf7d6b7aSMuzi  )
1108d10ddd67SGuokai Chen  checkFlushWb.bits.jalTarget  := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
11092a3050c2SJay  checkFlushWb.bits.instrRange := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
11102a3050c2SJay
1111bccc5520SJenius  toFtq.pdWb := Mux(wb_valid, checkFlushWb, mmioFlushWb)
11122a3050c2SJay
11132a3050c2SJay  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
111409c6f1ddSLingrui98
11155b3c20f7SJinYue  /*write back flush type*/
11165995c9e7SJenius  val checkFaultType    = wb_check_result_stage2.faultType
11175b3c20f7SJinYue  val checkJalFault     = wb_valid && checkFaultType.map(_.isjalFault).reduce(_ || _)
11185b3c20f7SJinYue  val checkRetFault     = wb_valid && checkFaultType.map(_.isRetFault).reduce(_ || _)
11195b3c20f7SJinYue  val checkTargetFault  = wb_valid && checkFaultType.map(_.istargetFault).reduce(_ || _)
11205b3c20f7SJinYue  val checkNotCFIFault  = wb_valid && checkFaultType.map(_.notCFIFault).reduce(_ || _)
11215b3c20f7SJinYue  val checkInvalidTaken = wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_ || _)
11225b3c20f7SJinYue
11235b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_jalFault", checkJalFault)
11245b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_retFault", checkRetFault)
11255b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_targetFault", checkTargetFault)
11265b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_notCFIFault", checkNotCFIFault)
11275b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_incalidTakenFault", checkInvalidTaken)
11285b3c20f7SJinYue
1129cf7d6b7aSMuzi  XSDebug(
11308b33cd30Sklin02    checkRetFault,
1131cf7d6b7aSMuzi    "startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1132cf7d6b7aSMuzi    wb_ftq_req.startAddr,
1133cf7d6b7aSMuzi    wb_ftq_req.nextStartAddr,
1134cf7d6b7aSMuzi    wb_ftq_req.ftqOffset.valid,
1135cf7d6b7aSMuzi    wb_ftq_req.ftqOffset.bits
1136cf7d6b7aSMuzi  )
11375b3c20f7SJinYue
11381d8f4dcbSJay  /** performance counter */
1139005e809bSJiuyang Liu  val f3_perf_info = RegEnable(f2_perf_info, f2_fire)
1140935edac4STang Haojin  val f3_req_0     = io.toIbuffer.fire
1141935edac4STang Haojin  val f3_req_1     = io.toIbuffer.fire && f3_doubleLine
1142935edac4STang Haojin  val f3_hit_0     = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1143935edac4STang Haojin  val f3_hit_1     = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
11441d8f4dcbSJay  val f3_hit       = f3_perf_info.hit
1145cd365d4cSrvcoresjw  val perfEvents = Seq(
11462a3050c2SJay    ("frontendFlush                ", wb_redirect),
1147935edac4STang Haojin    ("ifu_req                      ", io.toIbuffer.fire),
1148935edac4STang Haojin    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit),
1149cd365d4cSrvcoresjw    ("ifu_req_cacheline_0          ", f3_req_0),
1150cd365d4cSrvcoresjw    ("ifu_req_cacheline_1          ", f3_req_1),
1151cd365d4cSrvcoresjw    ("ifu_req_cacheline_0_hit      ", f3_hit_1),
1152cd365d4cSrvcoresjw    ("ifu_req_cacheline_1_hit      ", f3_hit_1),
1153935edac4STang Haojin    ("only_0_hit                   ", f3_perf_info.only_0_hit && io.toIbuffer.fire),
1154935edac4STang Haojin    ("only_0_miss                  ", f3_perf_info.only_0_miss && io.toIbuffer.fire),
1155935edac4STang Haojin    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire),
1156935edac4STang Haojin    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire),
1157935edac4STang Haojin    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire),
1158cf7d6b7aSMuzi    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1159cd365d4cSrvcoresjw  )
11601ca0e4f3SYinan Xu  generatePerfEvent()
116109c6f1ddSLingrui98
1162935edac4STang Haojin  XSPerfAccumulate("ifu_req", io.toIbuffer.fire)
1163935edac4STang Haojin  XSPerfAccumulate("ifu_miss", io.toIbuffer.fire && !f3_hit)
1164f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0)
1165f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1)
1166f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0_hit", f3_hit_0)
1167f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1_hit", f3_hit_1)
11682a3050c2SJay  XSPerfAccumulate("frontendFlush", wb_redirect)
1169935edac4STang Haojin  XSPerfAccumulate("only_0_hit", f3_perf_info.only_0_hit && io.toIbuffer.fire)
1170935edac4STang Haojin  XSPerfAccumulate("only_0_miss", f3_perf_info.only_0_miss && io.toIbuffer.fire)
1171935edac4STang Haojin  XSPerfAccumulate("hit_0_hit_1", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire)
1172935edac4STang Haojin  XSPerfAccumulate("hit_0_miss_1", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire)
1173935edac4STang Haojin  XSPerfAccumulate("miss_0_hit_1", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire)
1174935edac4STang Haojin  XSPerfAccumulate("miss_0_miss_1", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1175935edac4STang Haojin  XSPerfAccumulate("hit_0_except_1", f3_perf_info.hit_0_except_1 && io.toIbuffer.fire)
1176935edac4STang Haojin  XSPerfAccumulate("miss_0_except_1", f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1177935edac4STang Haojin  XSPerfAccumulate("except_0", f3_perf_info.except_0 && io.toIbuffer.fire)
1178cf7d6b7aSMuzi  XSPerfHistogram(
1179cf7d6b7aSMuzi    "ifu2ibuffer_validCnt",
1180cf7d6b7aSMuzi    PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable),
1181cf7d6b7aSMuzi    io.toIbuffer.fire,
1182cf7d6b7aSMuzi    0,
1183cf7d6b7aSMuzi    PredictWidth + 1,
1184cf7d6b7aSMuzi    1
1185cf7d6b7aSMuzi  )
118651532d8bSGuokai Chen
1187c686adcdSYinan Xu  val hartId                     = p(XSCoreParamsKey).HartId
1188c686adcdSYinan Xu  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1189c686adcdSYinan Xu  val isWriteIfuWbToFtqTable     = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1190c686adcdSYinan Xu  val fetchToIBufferTable        = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1191c686adcdSYinan Xu  val ifuWbToFtqTable            = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
119251532d8bSGuokai Chen
119351532d8bSGuokai Chen  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
119451532d8bSGuokai Chen  fetchIBufferDumpData.start_addr  := f3_ftq_req.startAddr
119551532d8bSGuokai Chen  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1196935edac4STang 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)
119751532d8bSGuokai Chen  fetchIBufferDumpData.is_cache_hit := f3_hit
119851532d8bSGuokai Chen
119951532d8bSGuokai Chen  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
120051532d8bSGuokai Chen  ifuWbToFtqDumpData.start_addr        := wb_ftq_req.startAddr
120151532d8bSGuokai Chen  ifuWbToFtqDumpData.is_miss_pred      := checkFlushWb.bits.misOffset.valid
120251532d8bSGuokai Chen  ifuWbToFtqDumpData.miss_pred_offset  := checkFlushWb.bits.misOffset.bits
120351532d8bSGuokai Chen  ifuWbToFtqDumpData.checkJalFault     := checkJalFault
120451532d8bSGuokai Chen  ifuWbToFtqDumpData.checkRetFault     := checkRetFault
120551532d8bSGuokai Chen  ifuWbToFtqDumpData.checkTargetFault  := checkTargetFault
120651532d8bSGuokai Chen  ifuWbToFtqDumpData.checkNotCFIFault  := checkNotCFIFault
120751532d8bSGuokai Chen  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
120851532d8bSGuokai Chen
120951532d8bSGuokai Chen  fetchToIBufferTable.log(
121051532d8bSGuokai Chen    data = fetchIBufferDumpData,
1211da3bf434SMaxpicca-Li    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
121251532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
121351532d8bSGuokai Chen    clock = clock,
121451532d8bSGuokai Chen    reset = reset
121551532d8bSGuokai Chen  )
121651532d8bSGuokai Chen  ifuWbToFtqTable.log(
121751532d8bSGuokai Chen    data = ifuWbToFtqDumpData,
1218da3bf434SMaxpicca-Li    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
121951532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
122051532d8bSGuokai Chen    clock = clock,
122151532d8bSGuokai Chen    reset = reset
122251532d8bSGuokai Chen  )
122351532d8bSGuokai Chen
122409c6f1ddSLingrui98}
1225