xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 1592abd11eecf7bec0f1453ffe4a7617167f8ba9)
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()
123c670557fSHuSipeng  val checkJalrFault    = Bool()
12451532d8bSGuokai Chen  val checkRetFault     = Bool()
12551532d8bSGuokai Chen  val checkTargetFault  = Bool()
12651532d8bSGuokai Chen  val checkNotCFIFault  = Bool()
12751532d8bSGuokai Chen  val checkInvalidTaken = Bool()
12851532d8bSGuokai Chen}
12951532d8bSGuokai Chen
1302a3050c2SJayclass NewIFU(implicit p: Parameters) extends XSModule
1312a3050c2SJay    with HasICacheParameters
132aeedc8eeSGuokai Chen    with HasXSParameter
1332a3050c2SJay    with HasIFUConst
1342a3050c2SJay    with HasPdConst
135167bcd01SJay    with HasCircularQueuePtrHelper
1362a3050c2SJay    with HasPerfEvents
137cf7d6b7aSMuzi    with HasTlbConst {
13809c6f1ddSLingrui98  val io                       = IO(new NewIFUIO)
13909c6f1ddSLingrui98  val (toFtq, fromFtq)         = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
140c5c5edaeSJenius  val fromICache               = io.icacheInter.resp
1410be662e4SJay  val (toUncache, fromUncache) = (io.uncacheInter.toUncache, io.uncacheInter.fromUncache)
14209c6f1ddSLingrui98
14309c6f1ddSLingrui98  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
14409c6f1ddSLingrui98
145d2b20d1aSTang Haojin  def numOfStage = 3
146e4d2f6a9Smy-mayfly  // equal lower_result overflow bit
147e4d2f6a9Smy-mayfly  def PcCutPoint = (VAddrBits / 4) - 1
148cf7d6b7aSMuzi  def CatPC(low: UInt, high: UInt, high1: UInt): UInt =
149e4d2f6a9Smy-mayfly    Mux(
150e4d2f6a9Smy-mayfly      low(PcCutPoint),
151e4d2f6a9Smy-mayfly      Cat(high1, low(PcCutPoint - 1, 0)),
152e4d2f6a9Smy-mayfly      Cat(high, low(PcCutPoint - 1, 0))
153e4d2f6a9Smy-mayfly    )
154e4d2f6a9Smy-mayfly  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
155d2b20d1aSTang Haojin  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
156d2b20d1aSTang Haojin  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
157d2b20d1aSTang Haojin  // bubble events in IFU, only happen in stage 1
158d2b20d1aSTang Haojin  val icacheMissBubble = Wire(Bool())
159d2b20d1aSTang Haojin  val itlbMissBubble   = Wire(Bool())
160d2b20d1aSTang Haojin
161d2b20d1aSTang Haojin  // only driven by clock, not valid-ready
162d2b20d1aSTang Haojin  topdown_stages(0) := fromFtq.req.bits.topdown_info
163d2b20d1aSTang Haojin  for (i <- 1 until numOfStage) {
164d2b20d1aSTang Haojin    topdown_stages(i) := topdown_stages(i - 1)
165d2b20d1aSTang Haojin  }
166d2b20d1aSTang Haojin  when(icacheMissBubble) {
167d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
168d2b20d1aSTang Haojin  }
169d2b20d1aSTang Haojin  when(itlbMissBubble) {
170d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
171d2b20d1aSTang Haojin  }
172d2b20d1aSTang Haojin  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
173d2b20d1aSTang Haojin  when(fromFtq.topdown_redirect.valid) {
174d2b20d1aSTang Haojin    // only redirect from backend, IFU redirect itself is handled elsewhere
175d2b20d1aSTang Haojin    when(fromFtq.topdown_redirect.bits.debugIsCtrl) {
176d2b20d1aSTang Haojin      /*
177d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
178d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
179d2b20d1aSTang Haojin      }
180d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
181d2b20d1aSTang Haojin       */
182d2b20d1aSTang Haojin      when(fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
183d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
184d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
185d2b20d1aSTang Haojin        }
186d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
187d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.TAGEMissBubble) {
188d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
189d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
190d2b20d1aSTang Haojin        }
191d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
192d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.SCMissBubble) {
193d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
194d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
195d2b20d1aSTang Haojin        }
196d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
197d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
198d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
199d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
200d2b20d1aSTang Haojin        }
201d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
202d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.RASMissBubble) {
203d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
204d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
205d2b20d1aSTang Haojin        }
206d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
207d2b20d1aSTang Haojin      }
208d2b20d1aSTang Haojin    }.elsewhen(fromFtq.topdown_redirect.bits.debugIsMemVio) {
209d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
210d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
211d2b20d1aSTang Haojin      }
212d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
213d2b20d1aSTang Haojin    }.otherwise {
214d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
215d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
216d2b20d1aSTang Haojin      }
217d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
218d2b20d1aSTang Haojin    }
219d2b20d1aSTang Haojin  }
220d2b20d1aSTang Haojin
2211d8f4dcbSJay  class TlbExept(implicit p: Parameters) extends XSBundle {
2221d8f4dcbSJay    val pageFault   = Bool()
2231d8f4dcbSJay    val accessFault = Bool()
2241d8f4dcbSJay    val mmio        = Bool()
225b005f7c6SJay  }
22609c6f1ddSLingrui98
227a61a35e0Sssszwic  val preDecoder = Module(new PreDecode)
228dc270d3bSJenius
2292a3050c2SJay  val predChecker     = Module(new PredChecker)
2302a3050c2SJay  val frontendTrigger = Module(new FrontendTrigger)
231cf7d6b7aSMuzi  val (checkerIn, checkerOutStage1, checkerOutStage2) =
232cf7d6b7aSMuzi    (predChecker.io.in, predChecker.io.out.stage1Out, predChecker.io.out.stage2Out)
2331d8f4dcbSJay
23458dbdfc2SJay  /**
23558dbdfc2SJay    ******************************************************************************
23658dbdfc2SJay    * IFU Stage 0
23758dbdfc2SJay    * - send cacheline fetch request to ICacheMainPipe
23858dbdfc2SJay    ******************************************************************************
23958dbdfc2SJay    */
24009c6f1ddSLingrui98
24109c6f1ddSLingrui98  val f0_valid      = fromFtq.req.valid
24209c6f1ddSLingrui98  val f0_ftq_req    = fromFtq.req.bits
2436ce52296SJinYue  val f0_doubleLine = fromFtq.req.bits.crossCacheline
244cf7d6b7aSMuzi  val f0_vSetIdx    = VecInit(get_idx(f0_ftq_req.startAddr), get_idx(f0_ftq_req.nextlineStart))
245935edac4STang Haojin  val f0_fire       = fromFtq.req.fire
24609c6f1ddSLingrui98
24709c6f1ddSLingrui98  val f0_flush, f1_flush, f2_flush, f3_flush = WireInit(false.B)
24809c6f1ddSLingrui98
2496f9d4832SHuSipeng  val f0_flush_from_bpu = 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
2586f9d4832SHuSipeng  f1_flush         := f2_flush
2596f9d4832SHuSipeng  f0_flush         := f1_flush || f0_flush_from_bpu
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)
2826f9d4832SHuSipeng  XSPerfAccumulate("fetch_flush_f0_flush_from_bpu", f0_flush_from_bpu)
28358dbdfc2SJay
28458dbdfc2SJay  /**
28558dbdfc2SJay    ******************************************************************************
28658dbdfc2SJay    * IFU Stage 1
28758dbdfc2SJay    * - calculate pc/half_pc/cut_ptr for every instruction
28858dbdfc2SJay    ******************************************************************************
28958dbdfc2SJay    */
29009c6f1ddSLingrui98
29109c6f1ddSLingrui98  val f1_valid   = RegInit(false.B)
292005e809bSJiuyang Liu  val f1_ftq_req = RegEnable(f0_ftq_req, f0_fire)
293005e809bSJiuyang Liu  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
294005e809bSJiuyang Liu  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
295005e809bSJiuyang Liu  val f1_vSetIdx    = RegEnable(f0_vSetIdx, f0_fire)
296625ecd17SJenius  val f1_fire       = f1_valid && f2_ready
29709c6f1ddSLingrui98
298625ecd17SJenius  f1_ready := f1_fire || !f1_valid
29909c6f1ddSLingrui98
3006f9d4832SHuSipeng  assert(!(fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid))
30109c6f1ddSLingrui98
302cf7d6b7aSMuzi  when(f1_flush)(f1_valid := false.B)
303cf7d6b7aSMuzi    .elsewhen(f0_fire && !f0_flush)(f1_valid := true.B)
304cf7d6b7aSMuzi    .elsewhen(f1_fire)(f1_valid := false.B)
30509c6f1ddSLingrui98
306e4d2f6a9Smy-mayfly  val f1_pc_high       = f1_ftq_req.startAddr(VAddrBits - 1, PcCutPoint)
307f2f493deSstride  val f1_pc_high_plus1 = f1_pc_high + 1.U
308f2f493deSstride
309e4d2f6a9Smy-mayfly  /**
310e4d2f6a9Smy-mayfly   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
311e4d2f6a9Smy-mayfly   * code of original logic, this code has been deprecated
312e4d2f6a9Smy-mayfly   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
313e4d2f6a9Smy-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)))})
314e4d2f6a9Smy-mayfly   */
315cf7d6b7aSMuzi  val f1_pc_lower_result = VecInit((0 until PredictWidth).map(i =>
316cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + (i * 2).U
317cf7d6b7aSMuzi  )) // cat with overflow bit
318f2f493deSstride
319e4d2f6a9Smy-mayfly  val f1_pc = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
320e4d2f6a9Smy-mayfly
321cf7d6b7aSMuzi  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i =>
322cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + ((i + 2) * 2).U
323cf7d6b7aSMuzi  )) // cat with overflow bit
324e4d2f6a9Smy-mayfly  val f1_half_snpc = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
325f2f493deSstride
326f2f493deSstride  if (env.FPGAPlatform) {
327f2f493deSstride    val f1_pc_diff        = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
328f2f493deSstride    val f1_half_snpc_diff = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i + 2) * 2).U))
329f2f493deSstride
330cf7d6b7aSMuzi    XSError(
331cf7d6b7aSMuzi      f1_pc.zip(f1_pc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
332cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
333cf7d6b7aSMuzi    )
334cf7d6b7aSMuzi    XSError(
335cf7d6b7aSMuzi      f1_half_snpc.zip(f1_half_snpc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
336cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
337cf7d6b7aSMuzi    )
338f2f493deSstride  }
339f2f493deSstride
340cf7d6b7aSMuzi  val f1_cut_ptr = if (HasCExtension)
341cf7d6b7aSMuzi    VecInit((0 until PredictWidth + 1).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 1)) + i.U))
342b92f8445Sssszwic  else VecInit((0 until PredictWidth).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 2)) + i.U))
34309c6f1ddSLingrui98
34458dbdfc2SJay  /**
34558dbdfc2SJay    ******************************************************************************
34658dbdfc2SJay    * IFU Stage 2
34758dbdfc2SJay    * - icache response data (latched for pipeline stop)
34858dbdfc2SJay    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
34958dbdfc2SJay    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
35058dbdfc2SJay    * - cut data from cachlines to packet instruction code
35158dbdfc2SJay    * - instruction predecode and RVC expand
35258dbdfc2SJay    ******************************************************************************
35358dbdfc2SJay    */
35458dbdfc2SJay
3551d8f4dcbSJay  val icacheRespAllValid = WireInit(false.B)
35609c6f1ddSLingrui98
35709c6f1ddSLingrui98  val f2_valid   = RegInit(false.B)
358005e809bSJiuyang Liu  val f2_ftq_req = RegEnable(f1_ftq_req, f1_fire)
359005e809bSJiuyang Liu  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
360005e809bSJiuyang Liu  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
361005e809bSJiuyang Liu  val f2_vSetIdx    = RegEnable(f1_vSetIdx, f1_fire)
362625ecd17SJenius  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
3631d8f4dcbSJay
364625ecd17SJenius  f2_ready := f2_fire || !f2_valid
3651d8f4dcbSJay  // TODO: addr compare may be timing critical
366cf7d6b7aSMuzi  val f2_icache_all_resp_wire =
3674690c88aSxu_zh    fromICache.valid &&
3684690c88aSxu_zh      fromICache.bits.vaddr(0) === f2_ftq_req.startAddr &&
3694690c88aSxu_zh      (fromICache.bits.doubleline && fromICache.bits.vaddr(1) === f2_ftq_req.nextlineStart || !f2_doubleLine)
3701d8f4dcbSJay  val f2_icache_all_resp_reg = RegInit(false.B)
3711d8f4dcbSJay
3721d8f4dcbSJay  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
3731d8f4dcbSJay
374d2b20d1aSTang Haojin  icacheMissBubble := io.icacheInter.topdownIcacheMiss
375d2b20d1aSTang Haojin  itlbMissBubble   := io.icacheInter.topdownItlbMiss
376d2b20d1aSTang Haojin
3771d8f4dcbSJay  io.icacheStop := !f3_ready
3781d8f4dcbSJay
379cf7d6b7aSMuzi  when(f2_flush)(f2_icache_all_resp_reg := false.B)
380cf7d6b7aSMuzi    .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready)(f2_icache_all_resp_reg := true.B)
381cf7d6b7aSMuzi    .elsewhen(f2_fire && f2_icache_all_resp_reg)(f2_icache_all_resp_reg := false.B)
38209c6f1ddSLingrui98
383cf7d6b7aSMuzi  when(f2_flush)(f2_valid := false.B)
384cf7d6b7aSMuzi    .elsewhen(f1_fire && !f1_flush)(f2_valid := true.B)
385cf7d6b7aSMuzi    .elsewhen(f2_fire)(f2_valid := false.B)
38609c6f1ddSLingrui98
3874690c88aSxu_zh  val f2_exception_in     = fromICache.bits.exception
3884690c88aSxu_zh  val f2_backendException = fromICache.bits.backendException
389d7ac23a3SEaston Man  // paddr and gpaddr of [startAddr, nextLineAddr]
3904690c88aSxu_zh  val f2_paddrs            = fromICache.bits.paddr
3914690c88aSxu_zh  val f2_gpaddr            = fromICache.bits.gpaddr
3924690c88aSxu_zh  val f2_isForVSnonLeafPTE = fromICache.bits.isForVSnonLeafPTE
393002c10a4SYanqin Li
394211986abSxu_zh  // FIXME: raise af if one fetch block crosses the cacheable-noncacheable boundary, might not correct
39535850f17Sxu_zh  val f2_mmio_mismatch_exception = VecInit(Seq(
39635850f17Sxu_zh    ExceptionType.none, // mark the exception only on the second line
39735850f17Sxu_zh    Mux(
398211986abSxu_zh      // not double-line, skip check
3994690c88aSxu_zh      !fromICache.bits.doubleline || (
400211986abSxu_zh        // is double-line, ask for consistent pmp_mmio and itlb_pbmt value
4014690c88aSxu_zh        fromICache.bits.pmp_mmio(0) === fromICache.bits.pmp_mmio(1) &&
4024690c88aSxu_zh          fromICache.bits.itlb_pbmt(0) === fromICache.bits.itlb_pbmt(1)
4034690c88aSxu_zh      ),
404211986abSxu_zh      ExceptionType.none,
405211986abSxu_zh      ExceptionType.af
40635850f17Sxu_zh    )
40735850f17Sxu_zh  ))
408211986abSxu_zh
409211986abSxu_zh  // merge exceptions
410211986abSxu_zh  val f2_exception = ExceptionType.merge(f2_exception_in, f2_mmio_mismatch_exception)
411211986abSxu_zh
412211986abSxu_zh  // we need only the first port, as the second is asked to be the same
4134690c88aSxu_zh  val f2_pmp_mmio  = fromICache.bits.pmp_mmio(0)
4144690c88aSxu_zh  val f2_itlb_pbmt = fromICache.bits.itlb_pbmt(0)
415002c10a4SYanqin Li
416e4d2f6a9Smy-mayfly  /**
417e4d2f6a9Smy-mayfly    * reduce the number of registers, origin code
418e4d2f6a9Smy-mayfly    * f2_pc = RegEnable(f1_pc, f1_fire)
419e4d2f6a9Smy-mayfly    */
420e4d2f6a9Smy-mayfly  val f2_pc_lower_result = RegEnable(f1_pc_lower_result, f1_fire)
421e4d2f6a9Smy-mayfly  val f2_pc_high         = RegEnable(f1_pc_high, f1_fire)
422e4d2f6a9Smy-mayfly  val f2_pc_high_plus1   = RegEnable(f1_pc_high_plus1, f1_fire)
423e4d2f6a9Smy-mayfly  val f2_pc              = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
424a37fbf10SJay
425e4d2f6a9Smy-mayfly  val f2_cut_ptr      = RegEnable(f1_cut_ptr, f1_fire)
426005e809bSJiuyang Liu  val f2_resend_vaddr = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
4272a3050c2SJay
428cf7d6b7aSMuzi  def isNextLine(pc: UInt, startAddr: UInt) =
4292a3050c2SJay    startAddr(blockOffBits) ^ pc(blockOffBits)
43009c6f1ddSLingrui98
431cf7d6b7aSMuzi  def isLastInLine(pc: UInt) =
4322a3050c2SJay    pc(blockOffBits - 1, 0) === "b111110".U
43309c6f1ddSLingrui98
4342a3050c2SJay  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits - 1, 1), MemPredPCWidth)))
435cf7d6b7aSMuzi  val f2_jump_range =
436cf7d6b7aSMuzi    Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
4374d53e0efSzhou tao  require(
4384d53e0efSzhou tao    isPow2(PredictWidth),
4394d53e0efSzhou tao    "If PredictWidth does not satisfy the power of 2," +
4404d53e0efSzhou tao      "expression: Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits is not right !!"
4414d53e0efSzhou tao  )
442cf7d6b7aSMuzi  val f2_ftr_range = Fill(PredictWidth, f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(
443cf7d6b7aSMuzi    f2_ftq_req.nextStartAddr,
444cf7d6b7aSMuzi    f2_ftq_req.startAddr
445cf7d6b7aSMuzi  )
4462a3050c2SJay  val f2_instr_range = f2_jump_range & f2_ftr_range
447cf7d6b7aSMuzi  val f2_exception_vec = VecInit((0 until PredictWidth).map(i =>
448cf7d6b7aSMuzi    MuxCase(
449cf7d6b7aSMuzi      ExceptionType.none,
450cf7d6b7aSMuzi      Seq(
45188895b11Sxu_zh        !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
45288895b11Sxu_zh        (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
453cf7d6b7aSMuzi      )
454cf7d6b7aSMuzi    )
455cf7d6b7aSMuzi  ))
4561d8f4dcbSJay  val f2_perf_info = io.icachePerfInfo
45709c6f1ddSLingrui98
4582a3050c2SJay  def cut(cacheline: UInt, cutPtr: Vec[UInt]): Vec[UInt] = {
459d558bd61SJenius    require(HasCExtension)
460d558bd61SJenius    // if(HasCExtension){
46109c6f1ddSLingrui98    val result  = Wire(Vec(PredictWidth + 1, UInt(16.W)))
462b92f8445Sssszwic    val dataVec = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) // 32 16-bit data vector
46309c6f1ddSLingrui98    (0 until PredictWidth + 1).foreach(i =>
464d558bd61SJenius      result(i) := dataVec(cutPtr(i)) // the max ptr is 3*blockBytes/4-1
46509c6f1ddSLingrui98    )
46609c6f1ddSLingrui98    result
467d558bd61SJenius    // } else {
468d558bd61SJenius    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
469d558bd61SJenius    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
470d558bd61SJenius    //   (0 until PredictWidth).foreach( i =>
471d558bd61SJenius    //     result(i) := dataVec(cutPtr(i))
472d558bd61SJenius    //   )
473d558bd61SJenius    //   result
474d558bd61SJenius    // }
47509c6f1ddSLingrui98  }
47609c6f1ddSLingrui98
4774690c88aSxu_zh  /* NOTE: the following `Cat(_data, _data)` *is* intentional.
47896d0318bSxu_zh   * Explanation:
47996d0318bSxu_zh   * In the old design, IFU is responsible for selecting requested data from two adjacent cachelines,
48096d0318bSxu_zh   *    so IFU has to receive 2*64B (2cacheline * 64B) data from ICache, and do `Cat(_data(1), _data(0))` here.
48196d0318bSxu_zh   * However, a fetch block is 34B at max, sending 2*64B is quiet a waste of power.
48296d0318bSxu_zh   * In current design (2024.06~), ICacheDataArray is responsible for selecting data from two adjacent cachelines,
4834690c88aSxu_zh   *    so IFU only need to receive 40B (5bank * 8B) valid data, and use only one port is enough.
48496d0318bSxu_zh   * For example, when pc falls on the 6th bank in cacheline0(so this is a doubleline request):
48596d0318bSxu_zh   *                                MSB                                         LSB
48696d0318bSxu_zh   *                  cacheline 1 || 1-7 | 1-6 | 1-5 | 1-4 | 1-3 | 1-2 | 1-1 | 1-0 ||
48796d0318bSxu_zh   *                  cacheline 0 || 0-7 | 0-6 | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | 0-0 ||
48896d0318bSxu_zh   *    and ICacheDataArray will respond:
4894690c88aSxu_zh   *         fromICache.bits.data || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
49096d0318bSxu_zh   *    therefore simply make a copy of the response and `Cat` together, and obtain the requested data from centre:
49196d0318bSxu_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 ||
49296d0318bSxu_zh   *                                             requested data: ^-----------------------------^
49396d0318bSxu_zh   * For another example, pc falls on the 1st bank in cacheline 0, we have:
4944690c88aSxu_zh   *         fromICache.bits.data || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
49596d0318bSxu_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 ||
49696d0318bSxu_zh   *                                                                           requested data: ^-----------------------------^
49796d0318bSxu_zh   * Each "| x-y |" block is a 8B bank from cacheline(x).bank(y)
49896d0318bSxu_zh   * Please also refer to:
49996d0318bSxu_zh   * - DataArray selects data:
50096d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L355-L381
50196d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L149-L161
50296d0318bSxu_zh   * - ICache respond to IFU:
50396d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala#L473
50496d0318bSxu_zh   */
5054690c88aSxu_zh  val f2_data_2_cacheline = Cat(fromICache.bits.data, fromICache.bits.data)
506dc270d3bSJenius
507a61a35e0Sssszwic  val f2_cut_data = cut(f2_data_2_cacheline, f2_cut_ptr)
50809c6f1ddSLingrui98
50958dbdfc2SJay  /** predecode (include RVC expander) */
510dc270d3bSJenius  // preDecoderRegIn.data := f2_reg_cut_data
511dc270d3bSJenius  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
512dc270d3bSJenius  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
513dc270d3bSJenius  // preDecoderRegIn.pc  := f2_pc
514dc270d3bSJenius
515a61a35e0Sssszwic  val preDecoderIn = preDecoder.io.in
5169afa8a47STang Haojin  preDecoderIn.valid                := f2_valid
5179afa8a47STang Haojin  preDecoderIn.bits.data            := f2_cut_data
5189afa8a47STang Haojin  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
5199afa8a47STang Haojin  preDecoderIn.bits.pc              := f2_pc
520a61a35e0Sssszwic  val preDecoderOut = preDecoder.io.out
52109c6f1ddSLingrui98
52248a62719SJenius  // val f2_expd_instr     = preDecoderOut.expInstr
52348a62719SJenius  val f2_instr        = preDecoderOut.instr
5242a3050c2SJay  val f2_pd           = preDecoderOut.pd
5252a3050c2SJay  val f2_jump_offset  = preDecoderOut.jumpOffset
5262a3050c2SJay  val f2_hasHalfValid = preDecoderOut.hasHalfValid
527a2568a60Sxu_zh  /* if there is a cross-page RVI instruction, and the former page has no exception,
528a2568a60Sxu_zh   * whether it has exception is actually depends on the latter page
529a2568a60Sxu_zh   */
530cf7d6b7aSMuzi  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i =>
531cf7d6b7aSMuzi    Mux(
532dd02bc3fSxu_zh      isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && !ExceptionType.hasException(f2_exception(0)),
533a2568a60Sxu_zh      f2_exception(1),
534a2568a60Sxu_zh      ExceptionType.none
535cf7d6b7aSMuzi    )
536cf7d6b7aSMuzi  })
53700240ba6SJay  XSPerfAccumulate("fetch_bubble_icache_not_resp", f2_valid && !icacheRespAllValid)
53800240ba6SJay
53958dbdfc2SJay  /**
54058dbdfc2SJay    ******************************************************************************
54158dbdfc2SJay    * IFU Stage 3
54258dbdfc2SJay    * - handle MMIO instruciton
54358dbdfc2SJay    *  -send request to Uncache fetch Unit
54458dbdfc2SJay    *  -every packet include 1 MMIO instruction
54558dbdfc2SJay    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
54658dbdfc2SJay    *  -flush to snpc (send ifu_redirect to Ftq)
54758dbdfc2SJay    * - Ibuffer enqueue
54858dbdfc2SJay    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
54958dbdfc2SJay    * - handle last half RVI instruction
55058dbdfc2SJay    ******************************************************************************
55158dbdfc2SJay    */
55258dbdfc2SJay
55392c61038SXuan Hu  val expanders = Seq.fill(PredictWidth)(Module(new RVCExpander))
55492c61038SXuan Hu
55509c6f1ddSLingrui98  val f3_valid   = RegInit(false.B)
556005e809bSJiuyang Liu  val f3_ftq_req = RegEnable(f2_ftq_req, f2_fire)
557005e809bSJiuyang Liu  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
558005e809bSJiuyang Liu  val f3_doubleLine = RegEnable(f2_doubleLine, f2_fire)
559935edac4STang Haojin  val f3_fire       = io.toIbuffer.fire
5601d8f4dcbSJay
561a61a35e0Sssszwic  val f3_cut_data = RegEnable(f2_cut_data, f2_fire)
5621d8f4dcbSJay
56388895b11Sxu_zh  val f3_exception        = RegEnable(f2_exception, f2_fire)
564211986abSxu_zh  val f3_pmp_mmio         = RegEnable(f2_pmp_mmio, f2_fire)
565211986abSxu_zh  val f3_itlb_pbmt        = RegEnable(f2_itlb_pbmt, f2_fire)
566fbdb359dSMuzi  val f3_backendException = RegEnable(f2_backendException, f2_fire)
56709c6f1ddSLingrui98
568935edac4STang Haojin  val f3_instr = RegEnable(f2_instr, f2_fire)
569aeedc8eeSGuokai Chen
57092c61038SXuan Hu  expanders.zipWithIndex.foreach { case (expander, i) =>
57192c61038SXuan Hu    expander.io.in      := f3_instr(i)
57271b6c42eSxu_zh    expander.io.fsIsOff := io.csr_fsIsOff
57392c61038SXuan Hu  }
57492c61038SXuan Hu  // Use expanded instruction only when input is legal.
57592c61038SXuan Hu  // Otherwise use origin illegal RVC instruction.
57692c61038SXuan Hu  val f3_expd_instr = VecInit(expanders.map { expander: RVCExpander =>
57792c61038SXuan Hu    Mux(expander.io.ill, expander.io.in, expander.io.out.bits)
57892c61038SXuan Hu  })
57992c61038SXuan Hu  val f3_ill = VecInit(expanders.map(_.io.ill))
58048a62719SJenius
581935edac4STang Haojin  val f3_pd_wire                 = RegEnable(f2_pd, f2_fire)
582330aad7fSGuokai Chen  val f3_pd                      = WireInit(f3_pd_wire)
583935edac4STang Haojin  val f3_jump_offset             = RegEnable(f2_jump_offset, f2_fire)
58488895b11Sxu_zh  val f3_exception_vec           = RegEnable(f2_exception_vec, f2_fire)
585a2568a60Sxu_zh  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
586e4d2f6a9Smy-mayfly
587e4d2f6a9Smy-mayfly  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
588e4d2f6a9Smy-mayfly  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
589e4d2f6a9Smy-mayfly  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
590e4d2f6a9Smy-mayfly  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
591e4d2f6a9Smy-mayfly
592e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
593e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
594e4d2f6a9Smy-mayfly  // val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
595e4d2f6a9Smy-mayfly
596e4d2f6a9Smy-mayfly  /**
597e4d2f6a9Smy-mayfly    ***********************************************************************
598e4d2f6a9Smy-mayfly    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
599e4d2f6a9Smy-mayfly    ***********************************************************************
600e4d2f6a9Smy-mayfly    */
601e4d2f6a9Smy-mayfly  val f3_half_snpc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
602e4d2f6a9Smy-mayfly  for (i <- 0 until PredictWidth) {
603e4d2f6a9Smy-mayfly    if (i == (PredictWidth - 2)) {
604e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
605e4d2f6a9Smy-mayfly    } else if (i == (PredictWidth - 1)) {
606e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
607e4d2f6a9Smy-mayfly    } else {
608e4d2f6a9Smy-mayfly      f3_half_snpc(i) := f3_pc(i + 2)
609e4d2f6a9Smy-mayfly    }
610e4d2f6a9Smy-mayfly  }
611e4d2f6a9Smy-mayfly
612935edac4STang Haojin  val f3_instr_range       = RegEnable(f2_instr_range, f2_fire)
613935edac4STang Haojin  val f3_foldpc            = RegEnable(f2_foldpc, f2_fire)
614935edac4STang Haojin  val f3_hasHalfValid      = RegEnable(f2_hasHalfValid, f2_fire)
615d7ac23a3SEaston Man  val f3_paddrs            = RegEnable(f2_paddrs, f2_fire)
61691946104Sxu_zh  val f3_gpaddr            = RegEnable(f2_gpaddr, f2_fire)
617ad415ae0SXiaokun-Pei  val f3_isForVSnonLeafPTE = RegEnable(f2_isForVSnonLeafPTE, f2_fire)
618005e809bSJiuyang Liu  val f3_resend_vaddr      = RegEnable(f2_resend_vaddr, f2_fire)
619ee175d78SJay
620cb6e5d3cSssszwic  // Expand 1 bit to prevent overflow when assert
621cb6e5d3cSssszwic  val f3_ftq_req_startAddr     = Cat(0.U(1.W), f3_ftq_req.startAddr)
622cb6e5d3cSssszwic  val f3_ftq_req_nextStartAddr = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
623330aad7fSGuokai Chen  // brType, isCall and isRet generation is delayed to f3 stage
624330aad7fSGuokai Chen  val f3Predecoder = Module(new F3Predecoder)
625330aad7fSGuokai Chen
626330aad7fSGuokai Chen  f3Predecoder.io.in.instr := f3_instr
627330aad7fSGuokai Chen
628330aad7fSGuokai Chen  f3_pd.zipWithIndex.map { case (pd, i) =>
629330aad7fSGuokai Chen    pd.brType := f3Predecoder.io.out.pd(i).brType
630330aad7fSGuokai Chen    pd.isCall := f3Predecoder.io.out.pd(i).isCall
631330aad7fSGuokai Chen    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
632330aad7fSGuokai Chen  }
633330aad7fSGuokai Chen
634330aad7fSGuokai Chen  val f3PdDiff = f3_pd_wire.zip(f3_pd).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _)
635330aad7fSGuokai Chen  XSError(f3_valid && f3PdDiff, "f3 pd diff")
636330aad7fSGuokai Chen
6371d011975SJinYue  when(f3_valid && !f3_ftq_req.ftqOffset.valid) {
638cf7d6b7aSMuzi    assert(
639cf7d6b7aSMuzi      f3_ftq_req_startAddr + (2 * PredictWidth).U >= f3_ftq_req_nextStartAddr,
640cf7d6b7aSMuzi      s"More tha ${2 * PredictWidth} Bytes fetch is not allowed!"
641cf7d6b7aSMuzi    )
6421d011975SJinYue  }
643a1351e5dSJay
6442a3050c2SJay  /*** MMIO State Machine***/
645ee175d78SJay  val f3_mmio_data     = Reg(Vec(2, UInt(16.W)))
646dfb03ba2Sxu_zh  val mmio_exception   = RegInit(0.U(ExceptionType.width.W))
647ee175d78SJay  val mmio_is_RVC      = RegInit(false.B)
648dfb03ba2Sxu_zh  val mmio_has_resend  = RegInit(false.B)
649ee175d78SJay  val mmio_resend_addr = RegInit(0.U(PAddrBits.W))
650dd980d61SXu, Zefan  // NOTE: we dont use GPAddrBits here, refer to ICacheMainPipe.scala L43-48 and PR#3795
651dd980d61SXu, Zefan  val mmio_resend_gpaddr            = RegInit(0.U(PAddrBitsMax.W))
652ad415ae0SXiaokun-Pei  val mmio_resend_isForVSnonLeafPTE = RegInit(false.B)
653c3b2d83aSJay
6541d1e6d4dSJenius  // last instuction finish
6551d1e6d4dSJenius  val is_first_instr = RegInit(true.B)
656cf7d6b7aSMuzi
657ba5ba1dcSmy-mayfly  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
658ba5ba1dcSmy-mayfly  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
659a37fbf10SJay
660cf7d6b7aSMuzi  val m_idle :: m_waitLastCmt :: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil =
661cf7d6b7aSMuzi    Enum(11)
662ee175d78SJay  val mmio_state = RegInit(m_idle)
663a37fbf10SJay
664211986abSxu_zh  // do mmio fetch only when pmp/pbmt shows it is a uncacheable address and no exception occurs
665211986abSxu_zh  /* FIXME: we do not distinguish pbmt is NC or IO now
666211986abSxu_zh   *        but we actually can do speculative execution if pbmt is NC, maybe fix this later for performance
667211986abSxu_zh   */
668211986abSxu_zh  val f3_req_is_mmio =
669211986abSxu_zh    f3_valid && (f3_pmp_mmio || Pbmt.isUncache(f3_itlb_pbmt)) && !ExceptionType.hasException(f3_exception)
670cf7d6b7aSMuzi  val mmio_commit = VecInit(io.rob_commits.map { commit =>
671cf7d6b7aSMuzi    commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx && commit.bits.ftqOffset === 0.U
672cf7d6b7aSMuzi  }).asUInt.orR
673ee175d78SJay  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
674a37fbf10SJay
675ee175d78SJay  val f3_mmio_to_commit      = f3_req_is_mmio && mmio_state === m_waitCommit
676a37fbf10SJay  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
677a37fbf10SJay  val f3_mmio_can_go         = f3_mmio_to_commit && !f3_mmio_to_commit_next
678a37fbf10SJay
6790c70648eSEaston Man  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
680cf7d6b7aSMuzi  fromFtqRedirectReg.bits := RegEnable(
681cf7d6b7aSMuzi    fromFtq.redirect.bits,
682cf7d6b7aSMuzi    0.U.asTypeOf(fromFtq.redirect.bits),
683cf7d6b7aSMuzi    fromFtq.redirect.valid
684cf7d6b7aSMuzi  )
6850c70648eSEaston Man  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
6864a74a727SJenius  val mmioF3Flush           = RegNext(f3_flush, init = false.B)
68756788a33SJinYue  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
68856788a33SJinYue  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
6899bae7d6eSJay
69056788a33SJinYue  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
6919bae7d6eSJay
692ba5ba1dcSmy-mayfly  /**
693ba5ba1dcSmy-mayfly    **********************************************************************************
694ba5ba1dcSmy-mayfly    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
695ba5ba1dcSmy-mayfly    * This is the exception when the first instruction is an MMIO instruction.
696ba5ba1dcSmy-mayfly    **********************************************************************************
697ba5ba1dcSmy-mayfly    */
698ba5ba1dcSmy-mayfly  when(is_first_instr && f3_fire) {
6991d1e6d4dSJenius    is_first_instr := false.B
7001d1e6d4dSJenius  }
7011d1e6d4dSJenius
702cf7d6b7aSMuzi  when(f3_flush && !f3_req_is_mmio)(f3_valid := false.B)
703cf7d6b7aSMuzi    .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)(f3_valid := false.B)
704cf7d6b7aSMuzi    .elsewhen(f2_fire && !f2_flush)(f3_valid := true.B)
705cf7d6b7aSMuzi    .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)(f3_valid := false.B)
706cf7d6b7aSMuzi    .elsewhen(f3_req_is_mmio && f3_mmio_req_commit)(f3_valid := false.B)
707a37fbf10SJay
708a37fbf10SJay  val f3_mmio_use_seq_pc = RegInit(false.B)
709a37fbf10SJay
71056788a33SJinYue  val (redirect_ftqIdx, redirect_ftqOffset) = (fromFtqRedirectReg.bits.ftqIdx, fromFtqRedirectReg.bits.ftqOffset)
711cf7d6b7aSMuzi  val redirect_mmio_req =
712cf7d6b7aSMuzi    fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
713a37fbf10SJay
714cf7d6b7aSMuzi  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)(f3_mmio_use_seq_pc := true.B)
715cf7d6b7aSMuzi    .elsewhen(redirect_mmio_req)(f3_mmio_use_seq_pc := false.B)
716a37fbf10SJay
7178c192ff7Sxu_zh  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
718a37fbf10SJay
7191d1e6d4dSJenius  // mmio state machine
720a37fbf10SJay  switch(mmio_state) {
721ee175d78SJay    is(m_idle) {
7229bae7d6eSJay      when(f3_req_is_mmio) {
7237d889d88Sxu_zh        // in idempotent spaces, we can send request directly (i.e. can do speculative fetch)
7247d889d88Sxu_zh        mmio_state := Mux(f3_itlb_pbmt === Pbmt.nc, m_sendReq, m_waitLastCmt)
7251d1e6d4dSJenius      }
7261d1e6d4dSJenius    }
7271d1e6d4dSJenius
7281d1e6d4dSJenius    is(m_waitLastCmt) {
7291d1e6d4dSJenius      when(is_first_instr) {
730ee175d78SJay        mmio_state := m_sendReq
7311d1e6d4dSJenius      }.otherwise {
7321d1e6d4dSJenius        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
733a37fbf10SJay      }
734a37fbf10SJay    }
735a37fbf10SJay
736ee175d78SJay    is(m_sendReq) {
737935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
738a37fbf10SJay    }
739a37fbf10SJay
740ee175d78SJay    is(m_waitResp) {
741935edac4STang Haojin      when(fromUncache.fire) {
742a37fbf10SJay        val isRVC      = fromUncache.bits.data(1, 0) =/= 3.U
743dfb03ba2Sxu_zh        val exception  = ExceptionType.fromTilelink(fromUncache.bits.corrupt)
744dfb03ba2Sxu_zh        val needResend = !isRVC && f3_paddrs(0)(2, 1) === 3.U && !ExceptionType.hasException(exception)
745ee175d78SJay        mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
746dfb03ba2Sxu_zh        mmio_exception  := exception
747ee175d78SJay        mmio_is_RVC     := isRVC
748dfb03ba2Sxu_zh        mmio_has_resend := needResend
749ee175d78SJay        f3_mmio_data(0) := fromUncache.bits.data(15, 0)
750ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(31, 16)
751a37fbf10SJay      }
752a37fbf10SJay    }
753a37fbf10SJay
754ee175d78SJay    is(m_sendTLB) {
7557b7232f9Sxu_zh      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
756c3b2d83aSJay    }
757a37fbf10SJay
758ee175d78SJay    is(m_tlbResp) {
7597b7232f9Sxu_zh      when(io.iTLBInter.resp.fire) {
7607b7232f9Sxu_zh        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
7617b7232f9Sxu_zh        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
76288895b11Sxu_zh        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
763211986abSxu_zh        // if itlb re-check respond pbmt mismatch with previous check, must be access fault
764211986abSxu_zh        val pbmt_mismatch_exception = Mux(
765211986abSxu_zh          io.iTLBInter.resp.bits.pbmt(0) =/= f3_itlb_pbmt,
766211986abSxu_zh          ExceptionType.af,
767211986abSxu_zh          ExceptionType.none
768211986abSxu_zh        )
769211986abSxu_zh        val exception = ExceptionType.merge(tlb_exception, pbmt_mismatch_exception)
7707b7232f9Sxu_zh        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
771211986abSxu_zh        mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_sendPMP)
7727b7232f9Sxu_zh        // also save itlb response
773dfb03ba2Sxu_zh        mmio_exception                := exception
77403efd994Shappy-lx        mmio_resend_addr              := io.iTLBInter.resp.bits.paddr(0)
775b5a614b9Sxu_zh        mmio_resend_gpaddr            := io.iTLBInter.resp.bits.gpaddr(0)
776ad415ae0SXiaokun-Pei        mmio_resend_isForVSnonLeafPTE := io.iTLBInter.resp.bits.isForVSnonLeafPTE(0)
777ee175d78SJay      }
7787b7232f9Sxu_zh    }
779ee175d78SJay
780ee175d78SJay    is(m_sendPMP) {
781211986abSxu_zh      val pmp_exception = ExceptionType.fromPMPResp(io.pmp.resp)
782211986abSxu_zh      // if pmp re-check respond mismatch with previous check, must be access fault
783211986abSxu_zh      val mmio_mismatch_exception = Mux(
784211986abSxu_zh        io.pmp.resp.mmio =/= f3_pmp_mmio,
785211986abSxu_zh        ExceptionType.af,
786211986abSxu_zh        ExceptionType.none
787211986abSxu_zh      )
788211986abSxu_zh      val exception = ExceptionType.merge(pmp_exception, mmio_mismatch_exception)
78988895b11Sxu_zh      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
790211986abSxu_zh      mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_resendReq)
79188895b11Sxu_zh      // also save pmp response
792dfb03ba2Sxu_zh      mmio_exception := exception
793ee175d78SJay    }
794ee175d78SJay
795ee175d78SJay    is(m_resendReq) {
796935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
797ee175d78SJay    }
798ee175d78SJay
799ee175d78SJay    is(m_waitResendResp) {
800935edac4STang Haojin      when(fromUncache.fire) {
801ee175d78SJay        mmio_state      := m_waitCommit
802dfb03ba2Sxu_zh        mmio_exception  := ExceptionType.fromTilelink(fromUncache.bits.corrupt)
803ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(15, 0)
804a37fbf10SJay      }
805a37fbf10SJay    }
806a37fbf10SJay
807ee175d78SJay    is(m_waitCommit) {
8087d889d88Sxu_zh      // in idempotent spaces, we can skip waiting for commit (i.e. can do speculative fetch)
8097d889d88Sxu_zh      // but we do not skip m_waitCommit state, as other signals (e.g. f3_mmio_can_go relies on this)
8107d889d88Sxu_zh      mmio_state := Mux(mmio_commit || f3_itlb_pbmt === Pbmt.nc, m_commited, m_waitCommit)
811a37fbf10SJay    }
8122a3050c2SJay
813ee175d78SJay    // normal mmio instruction
814ee175d78SJay    is(m_commited) {
815ee175d78SJay      mmio_state                    := m_idle
816dfb03ba2Sxu_zh      mmio_exception                := ExceptionType.none
817ee175d78SJay      mmio_is_RVC                   := false.B
818dfb03ba2Sxu_zh      mmio_has_resend               := false.B
819ee175d78SJay      mmio_resend_addr              := 0.U
820b5a614b9Sxu_zh      mmio_resend_gpaddr            := 0.U
821ad415ae0SXiaokun-Pei      mmio_resend_isForVSnonLeafPTE := false.B
8222a3050c2SJay    }
823a37fbf10SJay  }
824a37fbf10SJay
8258abe1810SEaston Man  // Exception or flush by older branch prediction
8268abe1810SEaston Man  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
827167bcd01SJay  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
828ee175d78SJay    mmio_state                    := m_idle
829dfb03ba2Sxu_zh    mmio_exception                := ExceptionType.none
830ee175d78SJay    mmio_is_RVC                   := false.B
831dfb03ba2Sxu_zh    mmio_has_resend               := false.B
832ee175d78SJay    mmio_resend_addr              := 0.U
833b5a614b9Sxu_zh    mmio_resend_gpaddr            := 0.U
834ad415ae0SXiaokun-Pei    mmio_resend_isForVSnonLeafPTE := false.B
835ee175d78SJay    f3_mmio_data.map(_ := 0.U)
8369bae7d6eSJay  }
8379bae7d6eSJay
838ee175d78SJay  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
839cf7d6b7aSMuzi  toUncache.bits.addr := Mux(mmio_state === m_resendReq, mmio_resend_addr, f3_paddrs(0))
840a37fbf10SJay  fromUncache.ready   := true.B
841a37fbf10SJay
8427b7232f9Sxu_zh  // send itlb request in m_sendTLB state
843ee175d78SJay  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
844ee175d78SJay  io.iTLBInter.req.bits.size               := 3.U
845ee175d78SJay  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
846ee175d78SJay  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
8477b7232f9Sxu_zh  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
8488a4dab4dSHaoyuan Feng  io.iTLBInter.req.bits.isPrefetch         := false.B
8497b7232f9Sxu_zh  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
8507b7232f9Sxu_zh  io.iTLBInter.req.bits.no_translate       := false.B
851db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.fullva             := 0.U
852db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.checkfullva        := false.B
853d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hyperinst          := DontCare
854d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hlvx               := DontCare
8558744445eSMaxpicca-Li  io.iTLBInter.req.bits.memidx             := DontCare
856f1fe8698SLemover  io.iTLBInter.req.bits.debug.robIdx       := DontCare
857ee175d78SJay  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
858149a2326Sweiding liu  io.iTLBInter.req.bits.pmp_addr           := DontCare
8597b7232f9Sxu_zh  // whats the difference between req_kill and req.bits.kill?
8607b7232f9Sxu_zh  io.iTLBInter.req_kill := false.B
8617b7232f9Sxu_zh  // wait for itlb response in m_tlbResp state
8627b7232f9Sxu_zh  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
863ee175d78SJay
864ee175d78SJay  io.pmp.req.valid     := (mmio_state === m_sendPMP) && f3_req_is_mmio
865ee175d78SJay  io.pmp.req.bits.addr := mmio_resend_addr
866ee175d78SJay  io.pmp.req.bits.size := 3.U
867ee175d78SJay  io.pmp.req.bits.cmd  := TlbCmd.exec
868f7c29b0aSJinYue
8692a3050c2SJay  val f3_lastHalf = RegInit(0.U.asTypeOf(new LastHalfInfo))
87009c6f1ddSLingrui98
87109c6f1ddSLingrui98  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
8720be662e4SJay  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if (i == 0) true.B else false.B))
8732a3050c2SJay  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
87409c6f1ddSLingrui98
8752a3050c2SJay  /*** prediction result check   ***/
8762a3050c2SJay  checkerIn.ftqOffset  := f3_ftq_req.ftqOffset
8772a3050c2SJay  checkerIn.jumpOffset := f3_jump_offset
8786ce52296SJinYue  checkerIn.target     := f3_ftq_req.nextStartAddr
8792a3050c2SJay  checkerIn.instrRange := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
8802a3050c2SJay  checkerIn.instrValid := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
8812a3050c2SJay  checkerIn.pds        := f3_pd
8822a3050c2SJay  checkerIn.pc         := f3_pc
8830c70648eSEaston Man  checkerIn.fire_in    := RegNext(f2_fire, init = false.B)
8842a3050c2SJay
88558dbdfc2SJay  /*** handle half RVI in the last 2 Bytes  ***/
8862a3050c2SJay
887cf7d6b7aSMuzi  def hasLastHalf(idx: UInt) =
8885995c9e7SJenius    // !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
889cf7d6b7aSMuzi    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(
890cf7d6b7aSMuzi      idx
891cf7d6b7aSMuzi    ) && !f3_req_is_mmio
8922a3050c2SJay
893b665b650STang Haojin  val f3_last_validIdx = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
8942a3050c2SJay
8952a3050c2SJay  val f3_hasLastHalf    = hasLastHalf((PredictWidth - 1).U)
8962a3050c2SJay  val f3_false_lastHalf = hasLastHalf(f3_last_validIdx)
8972a3050c2SJay  val f3_false_snpc     = f3_half_snpc(f3_last_validIdx)
8982a3050c2SJay
899935edac4STang Haojin  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map(i => if (i == 0) false.B else true.B)).asUInt
9003f785aa3SJenius  val f3_lastHalf_disable = RegInit(false.B)
9012a3050c2SJay
902804985a5SJenius  when(f3_flush || (f3_fire && f3_lastHalf_disable)) {
903804985a5SJenius    f3_lastHalf_disable := false.B
904804985a5SJenius  }
905804985a5SJenius
9062a3050c2SJay  when(f3_flush) {
9072a3050c2SJay    f3_lastHalf.valid := false.B
9082a3050c2SJay  }.elsewhen(f3_fire) {
9093f785aa3SJenius    f3_lastHalf.valid    := f3_hasLastHalf && !f3_lastHalf_disable
9106ce52296SJinYue    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
9112a3050c2SJay  }
9122a3050c2SJay
9132a3050c2SJay  f3_instr_valid := Mux(f3_lastHalf.valid, f3_hasHalfValid, VecInit(f3_pd.map(inst => inst.valid)))
9142a3050c2SJay
9152a3050c2SJay  /*** frontend Trigger  ***/
9162a3050c2SJay  frontendTrigger.io.pds  := f3_pd
9172a3050c2SJay  frontendTrigger.io.pc   := f3_pc
9182a3050c2SJay  frontendTrigger.io.data := f3_cut_data
9192a3050c2SJay
9202a3050c2SJay  frontendTrigger.io.frontendTrigger := io.frontendTrigger
9212a3050c2SJay
9222a3050c2SJay  val f3_triggered       = frontendTrigger.io.triggered
92391946104Sxu_zh  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
9242a3050c2SJay
9252a3050c2SJay  /*** send to Ibuffer  ***/
92691946104Sxu_zh  io.toIbuffer.valid          := f3_toIbuffer_valid
9272a3050c2SJay  io.toIbuffer.bits.instrs    := f3_expd_instr
9282a3050c2SJay  io.toIbuffer.bits.valid     := f3_instr_valid.asUInt
9295995c9e7SJenius  io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
9302a3050c2SJay  io.toIbuffer.bits.pd        := f3_pd
93109c6f1ddSLingrui98  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
9322a3050c2SJay  io.toIbuffer.bits.pc        := f3_pc
933c72c955dSEaston Man  // Find last using PriorityMux
934948e8159SEaston Man  io.toIbuffer.bits.isLastInFtqEntry := Reverse(PriorityEncoderOH(Reverse(io.toIbuffer.bits.enqEnable))).asBools
935cf7d6b7aSMuzi  io.toIbuffer.bits.ftqOffset.zipWithIndex.map { case (a, i) =>
936cf7d6b7aSMuzi    a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio
937cf7d6b7aSMuzi  }
9382a3050c2SJay  io.toIbuffer.bits.foldpc        := f3_foldpc
939a2568a60Sxu_zh  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
940fbdb359dSMuzi  // backendException only needs to be set for the first instruction.
941c1b28b66STang Haojin  // Other instructions in the same block may have pf or af set,
942c1b28b66STang Haojin  // which is a side effect of the first instruction and actually not necessary.
943fbdb359dSMuzi  io.toIbuffer.bits.backendException := (0 until PredictWidth).map {
944fbdb359dSMuzi    case 0 => f3_backendException
945c1b28b66STang Haojin    case _ => false.B
946c1b28b66STang Haojin  }
947dd02bc3fSxu_zh  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(ExceptionType.hasException)
94892c61038SXuan Hu  io.toIbuffer.bits.illegalInstr    := f3_ill
9492a3050c2SJay  io.toIbuffer.bits.triggered       := f3_triggered
9502a3050c2SJay
9512a3050c2SJay  when(f3_lastHalf.valid) {
9525995c9e7SJenius    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
9532a3050c2SJay    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
9542a3050c2SJay  }
9552a3050c2SJay
956*1592abd1SYan Xu  when(io.toIbuffer.valid && io.toIbuffer.ready) {
957*1592abd1SYan Xu    val enqVec = io.toIbuffer.bits.enqEnable
958*1592abd1SYan Xu    val allocateSeqNum = VecInit((0 until PredictWidth).map { i =>
959*1592abd1SYan Xu      val idx  = PopCount(enqVec.take(i + 1))
960*1592abd1SYan Xu      val pc   = f3_pc(i)
961*1592abd1SYan Xu      val code = io.toIbuffer.bits.instrs(i)
962*1592abd1SYan Xu      PerfCCT.createInstMetaAtFetch(idx, pc, code, enqVec(i), clock, reset)
963*1592abd1SYan Xu    })
964*1592abd1SYan Xu    io.toIbuffer.bits.debug_seqNum.zipWithIndex.foreach { case (a, i) =>
965*1592abd1SYan Xu      a := allocateSeqNum(i)
966*1592abd1SYan Xu    }
967*1592abd1SYan Xu  }.otherwise {
968*1592abd1SYan Xu    io.toIbuffer.bits.debug_seqNum.zipWithIndex.foreach { case (a, i) =>
969*1592abd1SYan Xu      a := 0.U
970*1592abd1SYan Xu    }
971*1592abd1SYan Xu  }
972*1592abd1SYan Xu
973d7ac23a3SEaston Man  /** to backend */
97491946104Sxu_zh  // f3_gpaddr is valid iff gpf is detected
975b5a614b9Sxu_zh  io.toBackend.gpaddrMem_wen := f3_toIbuffer_valid && Mux(
976b5a614b9Sxu_zh    f3_req_is_mmio,
977dfb03ba2Sxu_zh    mmio_exception === ExceptionType.gpf,
97888895b11Sxu_zh    f3_exception.map(_ === ExceptionType.gpf).reduce(_ || _)
979b5a614b9Sxu_zh  )
980d7ac23a3SEaston Man  io.toBackend.gpaddrMem_waddr        := f3_ftq_req.ftqIdx.value
981ad415ae0SXiaokun-Pei  io.toBackend.gpaddrMem_wdata.gpaddr := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
982cf7d6b7aSMuzi  io.toBackend.gpaddrMem_wdata.isForVSnonLeafPTE := Mux(
983cf7d6b7aSMuzi    f3_req_is_mmio,
984cf7d6b7aSMuzi    mmio_resend_isForVSnonLeafPTE,
985cf7d6b7aSMuzi    f3_isForVSnonLeafPTE
986cf7d6b7aSMuzi  )
98709c6f1ddSLingrui98
98809c6f1ddSLingrui98  // Write back to Ftq
989a37fbf10SJay  val f3_cache_fetch     = f3_valid && !(f2_fire && !f2_flush)
990a37fbf10SJay  val finishFetchMaskReg = RegNext(f3_cache_fetch)
991a37fbf10SJay
9922a3050c2SJay  val mmioFlushWb        = Wire(Valid(new PredecodeWritebackBundle))
9930be662e4SJay  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
994a37fbf10SJay  f3_mmio_missOffset.valid := f3_req_is_mmio
9950be662e4SJay  f3_mmio_missOffset.bits  := 0.U
9960be662e4SJay
9978abe1810SEaston Man  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
9988abe1810SEaston Man  // When backend redirect, mmio_state reset after 1 cycle.
9998abe1810SEaston Man  // In this case, mask .valid to avoid overriding backend redirect
10008abe1810SEaston Man  mmioFlushWb.valid := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
10018abe1810SEaston Man    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
10022a3050c2SJay  mmioFlushWb.bits.pc := f3_pc
10032a3050c2SJay  mmioFlushWb.bits.pd := f3_pd
10042a3050c2SJay  mmioFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := f3_mmio_range(i) }
10052a3050c2SJay  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
10062a3050c2SJay  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
10072a3050c2SJay  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
10082a3050c2SJay  mmioFlushWb.bits.cfiOffset  := DontCare
1009ee175d78SJay  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U, f3_ftq_req.startAddr + 4.U)
10102a3050c2SJay  mmioFlushWb.bits.jalTarget  := DontCare
10112a3050c2SJay  mmioFlushWb.bits.instrRange := f3_mmio_range
101209c6f1ddSLingrui98
101373e96011SXuan Hu  val mmioRVCExpander = Module(new RVCExpander)
101473e96011SXuan Hu  mmioRVCExpander.io.in      := Mux(f3_req_is_mmio, Cat(f3_mmio_data(1), f3_mmio_data(0)), 0.U)
101571b6c42eSxu_zh  mmioRVCExpander.io.fsIsOff := io.csr_fsIsOff
101673e96011SXuan Hu
10172dfa9e76SJenius  /** external predecode for MMIO instruction */
10182dfa9e76SJenius  when(f3_req_is_mmio) {
10192dfa9e76SJenius    val inst = Cat(f3_mmio_data(1), f3_mmio_data(0))
10202dfa9e76SJenius
10212dfa9e76SJenius    val brType :: isCall :: isRet :: Nil = brInfo(inst)
1022dfb03ba2Sxu_zh    val jalOffset                        = jal_offset(inst, mmio_is_RVC)
1023dfb03ba2Sxu_zh    val brOffset                         = br_offset(inst, mmio_is_RVC)
10242dfa9e76SJenius
102573e96011SXuan Hu    io.toIbuffer.bits.instrs(0) := Mux(mmioRVCExpander.io.ill, mmioRVCExpander.io.in, mmioRVCExpander.io.out.bits)
10262dfa9e76SJenius
10272dfa9e76SJenius    io.toIbuffer.bits.pd(0).valid  := true.B
1028dfb03ba2Sxu_zh    io.toIbuffer.bits.pd(0).isRVC  := mmio_is_RVC
10292dfa9e76SJenius    io.toIbuffer.bits.pd(0).brType := brType
10302dfa9e76SJenius    io.toIbuffer.bits.pd(0).isCall := isCall
10312dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRet  := isRet
10322dfa9e76SJenius
1033dfb03ba2Sxu_zh    io.toIbuffer.bits.exceptionType(0) := mmio_exception
1034dfb03ba2Sxu_zh    // exception can happens in next page only when resend
1035dfb03ba2Sxu_zh    io.toIbuffer.bits.crossPageIPFFix(0) := mmio_has_resend && ExceptionType.hasException(mmio_exception)
103673e96011SXuan Hu    io.toIbuffer.bits.illegalInstr(0)    := mmioRVCExpander.io.ill
10372dfa9e76SJenius
10382dfa9e76SJenius    io.toIbuffer.bits.enqEnable := f3_mmio_range.asUInt
10392dfa9e76SJenius
10402dfa9e76SJenius    mmioFlushWb.bits.pd(0).valid  := true.B
1041dfb03ba2Sxu_zh    mmioFlushWb.bits.pd(0).isRVC  := mmio_is_RVC
10422dfa9e76SJenius    mmioFlushWb.bits.pd(0).brType := brType
10432dfa9e76SJenius    mmioFlushWb.bits.pd(0).isCall := isCall
10442dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRet  := isRet
10452dfa9e76SJenius  }
10462dfa9e76SJenius
1047935edac4STang Haojin  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) && f3_mmio_use_seq_pc)
104809c6f1ddSLingrui98
104900240ba6SJay  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready", io.toIbuffer.valid && !io.toIbuffer.ready)
105000240ba6SJay
105158dbdfc2SJay  /**
105258dbdfc2SJay    ******************************************************************************
105358dbdfc2SJay    * IFU Write Back Stage
105458dbdfc2SJay    * - write back predecode information to Ftq to update
105558dbdfc2SJay    * - redirect if found fault prediction
105658dbdfc2SJay    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
105758dbdfc2SJay    ******************************************************************************
10582a3050c2SJay    */
10590c70648eSEaston Man  val wb_enable  = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
10600c70648eSEaston Man  val wb_valid   = RegNext(wb_enable, init = false.B)
10610c70648eSEaston Man  val wb_ftq_req = RegEnable(f3_ftq_req, wb_enable)
106258dbdfc2SJay
10630c70648eSEaston Man  val wb_check_result_stage1 = RegEnable(checkerOutStage1, wb_enable)
10645995c9e7SJenius  val wb_check_result_stage2 = checkerOutStage2
10650c70648eSEaston Man  val wb_instr_range         = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
1066e4d2f6a9Smy-mayfly
1067e4d2f6a9Smy-mayfly  val wb_pc_lower_result = RegEnable(f3_pc_lower_result, wb_enable)
1068e4d2f6a9Smy-mayfly  val wb_pc_high         = RegEnable(f3_pc_high, wb_enable)
1069e4d2f6a9Smy-mayfly  val wb_pc_high_plus1   = RegEnable(f3_pc_high_plus1, wb_enable)
1070e4d2f6a9Smy-mayfly  val wb_pc              = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
1071e4d2f6a9Smy-mayfly
1072e4d2f6a9Smy-mayfly  // val wb_pc             = RegEnable(f3_pc, wb_enable)
10730c70648eSEaston Man  val wb_pd          = RegEnable(f3_pd, wb_enable)
10740c70648eSEaston Man  val wb_instr_valid = RegEnable(f3_instr_valid, wb_enable)
10752a3050c2SJay
10762a3050c2SJay  /* false hit lastHalf */
10770c70648eSEaston Man  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
10780c70648eSEaston Man  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
10790c70648eSEaston Man  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
10802a3050c2SJay
10812a3050c2SJay  val wb_half_flush  = wb_false_lastHalf
10822a3050c2SJay  val wb_half_target = wb_false_target
10832a3050c2SJay
1084a1351e5dSJay  /* false oversize */
1085a1351e5dSJay  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool())).last && wb_pd.last.isRVC
1086a1351e5dSJay  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
10875995c9e7SJenius  val lastTaken = wb_check_result_stage1.fixedTaken.last
1088a1351e5dSJay
10892a3050c2SJay  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
10902a3050c2SJay
10913f785aa3SJenius  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
10923f785aa3SJenius    * we set a flag to notify f3 that the last half flag need not to be set.
10933f785aa3SJenius    */
1094804985a5SJenius  // f3_fire is after wb_valid
1095076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1096cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire && !RegNext(
1097cf7d6b7aSMuzi      f3_fire,
1098cf7d6b7aSMuzi      init = false.B
1099cf7d6b7aSMuzi    ) && !f3_flush) {
11003f785aa3SJenius    f3_lastHalf_disable := true.B
1101ab6202e2SJenius  }
1102ab6202e2SJenius
1103804985a5SJenius  // wb_valid and f3_fire are in same cycle
1104076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1105cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire) {
1106804985a5SJenius    f3_lastHalf.valid := false.B
1107804985a5SJenius  }
1108804985a5SJenius
11092a3050c2SJay  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
1110cf7d6b7aSMuzi  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map { case (pd, v) =>
1111cf7d6b7aSMuzi    v && pd.isJal
1112cf7d6b7aSMuzi  }))
1113b665b650STang Haojin  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
11142a3050c2SJay  checkFlushWb.valid   := wb_valid
11152a3050c2SJay  checkFlushWb.bits.pc := wb_pc
11162a3050c2SJay  checkFlushWb.bits.pd := wb_pd
11172a3050c2SJay  checkFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := wb_instr_valid(i) }
11182a3050c2SJay  checkFlushWb.bits.ftqIdx          := wb_ftq_req.ftqIdx
11192a3050c2SJay  checkFlushWb.bits.ftqOffset       := wb_ftq_req.ftqOffset.bits
11205995c9e7SJenius  checkFlushWb.bits.misOffset.valid := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
1121cf7d6b7aSMuzi  checkFlushWb.bits.misOffset.bits := Mux(
1122cf7d6b7aSMuzi    wb_half_flush,
1123cf7d6b7aSMuzi    wb_lastIdx,
1124cf7d6b7aSMuzi    ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1125cf7d6b7aSMuzi  )
11265995c9e7SJenius  checkFlushWb.bits.cfiOffset.valid := ParallelOR(wb_check_result_stage1.fixedTaken)
11275995c9e7SJenius  checkFlushWb.bits.cfiOffset.bits  := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
1128cf7d6b7aSMuzi  checkFlushWb.bits.target := Mux(
1129cf7d6b7aSMuzi    wb_half_flush,
1130cf7d6b7aSMuzi    wb_half_target,
1131cf7d6b7aSMuzi    wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx)
1132cf7d6b7aSMuzi  )
1133d10ddd67SGuokai Chen  checkFlushWb.bits.jalTarget  := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
11342a3050c2SJay  checkFlushWb.bits.instrRange := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
11352a3050c2SJay
1136bccc5520SJenius  toFtq.pdWb := Mux(wb_valid, checkFlushWb, mmioFlushWb)
11372a3050c2SJay
11382a3050c2SJay  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
113909c6f1ddSLingrui98
11405b3c20f7SJinYue  /*write back flush type*/
11415995c9e7SJenius  val checkFaultType    = wb_check_result_stage2.faultType
11425b3c20f7SJinYue  val checkJalFault     = wb_valid && checkFaultType.map(_.isjalFault).reduce(_ || _)
1143c670557fSHuSipeng  val checkJalrFault    = wb_valid && checkFaultType.map(_.isjalrFault).reduce(_ || _)
11445b3c20f7SJinYue  val checkRetFault     = wb_valid && checkFaultType.map(_.isRetFault).reduce(_ || _)
11455b3c20f7SJinYue  val checkTargetFault  = wb_valid && checkFaultType.map(_.istargetFault).reduce(_ || _)
11465b3c20f7SJinYue  val checkNotCFIFault  = wb_valid && checkFaultType.map(_.notCFIFault).reduce(_ || _)
11475b3c20f7SJinYue  val checkInvalidTaken = wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_ || _)
11485b3c20f7SJinYue
11495b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_jalFault", checkJalFault)
1150c670557fSHuSipeng  XSPerfAccumulate("predecode_flush_jalrFault", checkJalrFault)
11515b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_retFault", checkRetFault)
11525b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_targetFault", checkTargetFault)
11535b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_notCFIFault", checkNotCFIFault)
11545b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_incalidTakenFault", checkInvalidTaken)
11555b3c20f7SJinYue
1156cf7d6b7aSMuzi  XSDebug(
11578b33cd30Sklin02    checkRetFault,
1158cf7d6b7aSMuzi    "startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1159cf7d6b7aSMuzi    wb_ftq_req.startAddr,
1160cf7d6b7aSMuzi    wb_ftq_req.nextStartAddr,
1161cf7d6b7aSMuzi    wb_ftq_req.ftqOffset.valid,
1162cf7d6b7aSMuzi    wb_ftq_req.ftqOffset.bits
1163cf7d6b7aSMuzi  )
11645b3c20f7SJinYue
11651d8f4dcbSJay  /** performance counter */
1166005e809bSJiuyang Liu  val f3_perf_info = RegEnable(f2_perf_info, f2_fire)
1167935edac4STang Haojin  val f3_req_0     = io.toIbuffer.fire
1168935edac4STang Haojin  val f3_req_1     = io.toIbuffer.fire && f3_doubleLine
1169935edac4STang Haojin  val f3_hit_0     = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1170935edac4STang Haojin  val f3_hit_1     = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
11711d8f4dcbSJay  val f3_hit       = f3_perf_info.hit
1172cd365d4cSrvcoresjw  val perfEvents = Seq(
11732a3050c2SJay    ("frontendFlush                ", wb_redirect),
1174935edac4STang Haojin    ("ifu_req                      ", io.toIbuffer.fire),
1175935edac4STang Haojin    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit),
1176cd365d4cSrvcoresjw    ("ifu_req_cacheline_0          ", f3_req_0),
1177cd365d4cSrvcoresjw    ("ifu_req_cacheline_1          ", f3_req_1),
1178cd365d4cSrvcoresjw    ("ifu_req_cacheline_0_hit      ", f3_hit_1),
1179cd365d4cSrvcoresjw    ("ifu_req_cacheline_1_hit      ", f3_hit_1),
1180935edac4STang Haojin    ("only_0_hit                   ", f3_perf_info.only_0_hit && io.toIbuffer.fire),
1181935edac4STang Haojin    ("only_0_miss                  ", f3_perf_info.only_0_miss && io.toIbuffer.fire),
1182935edac4STang Haojin    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire),
1183935edac4STang Haojin    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire),
1184935edac4STang Haojin    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire),
1185cf7d6b7aSMuzi    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1186cd365d4cSrvcoresjw  )
11871ca0e4f3SYinan Xu  generatePerfEvent()
118809c6f1ddSLingrui98
1189935edac4STang Haojin  XSPerfAccumulate("ifu_req", io.toIbuffer.fire)
1190935edac4STang Haojin  XSPerfAccumulate("ifu_miss", io.toIbuffer.fire && !f3_hit)
1191f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0)
1192f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1)
1193f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0_hit", f3_hit_0)
1194f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1_hit", f3_hit_1)
11952a3050c2SJay  XSPerfAccumulate("frontendFlush", wb_redirect)
1196935edac4STang Haojin  XSPerfAccumulate("only_0_hit", f3_perf_info.only_0_hit && io.toIbuffer.fire)
1197935edac4STang Haojin  XSPerfAccumulate("only_0_miss", f3_perf_info.only_0_miss && io.toIbuffer.fire)
1198935edac4STang Haojin  XSPerfAccumulate("hit_0_hit_1", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire)
1199935edac4STang Haojin  XSPerfAccumulate("hit_0_miss_1", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire)
1200935edac4STang Haojin  XSPerfAccumulate("miss_0_hit_1", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire)
1201935edac4STang Haojin  XSPerfAccumulate("miss_0_miss_1", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1202935edac4STang Haojin  XSPerfAccumulate("hit_0_except_1", f3_perf_info.hit_0_except_1 && io.toIbuffer.fire)
1203935edac4STang Haojin  XSPerfAccumulate("miss_0_except_1", f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1204935edac4STang Haojin  XSPerfAccumulate("except_0", f3_perf_info.except_0 && io.toIbuffer.fire)
1205cf7d6b7aSMuzi  XSPerfHistogram(
1206cf7d6b7aSMuzi    "ifu2ibuffer_validCnt",
1207cf7d6b7aSMuzi    PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable),
1208cf7d6b7aSMuzi    io.toIbuffer.fire,
1209cf7d6b7aSMuzi    0,
1210cf7d6b7aSMuzi    PredictWidth + 1,
1211cf7d6b7aSMuzi    1
1212cf7d6b7aSMuzi  )
121351532d8bSGuokai Chen
1214c686adcdSYinan Xu  val hartId                     = p(XSCoreParamsKey).HartId
1215c686adcdSYinan Xu  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1216c686adcdSYinan Xu  val isWriteIfuWbToFtqTable     = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1217c686adcdSYinan Xu  val fetchToIBufferTable        = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1218c686adcdSYinan Xu  val ifuWbToFtqTable            = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
121951532d8bSGuokai Chen
122051532d8bSGuokai Chen  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
122151532d8bSGuokai Chen  fetchIBufferDumpData.start_addr  := f3_ftq_req.startAddr
122251532d8bSGuokai Chen  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1223935edac4STang 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)
122451532d8bSGuokai Chen  fetchIBufferDumpData.is_cache_hit := f3_hit
122551532d8bSGuokai Chen
122651532d8bSGuokai Chen  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
122751532d8bSGuokai Chen  ifuWbToFtqDumpData.start_addr        := wb_ftq_req.startAddr
122851532d8bSGuokai Chen  ifuWbToFtqDumpData.is_miss_pred      := checkFlushWb.bits.misOffset.valid
122951532d8bSGuokai Chen  ifuWbToFtqDumpData.miss_pred_offset  := checkFlushWb.bits.misOffset.bits
123051532d8bSGuokai Chen  ifuWbToFtqDumpData.checkJalFault     := checkJalFault
1231c670557fSHuSipeng  ifuWbToFtqDumpData.checkJalrFault    := checkJalrFault
123251532d8bSGuokai Chen  ifuWbToFtqDumpData.checkRetFault     := checkRetFault
123351532d8bSGuokai Chen  ifuWbToFtqDumpData.checkTargetFault  := checkTargetFault
123451532d8bSGuokai Chen  ifuWbToFtqDumpData.checkNotCFIFault  := checkNotCFIFault
123551532d8bSGuokai Chen  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
123651532d8bSGuokai Chen
123751532d8bSGuokai Chen  fetchToIBufferTable.log(
123851532d8bSGuokai Chen    data = fetchIBufferDumpData,
1239da3bf434SMaxpicca-Li    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
124051532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
124151532d8bSGuokai Chen    clock = clock,
124251532d8bSGuokai Chen    reset = reset
124351532d8bSGuokai Chen  )
124451532d8bSGuokai Chen  ifuWbToFtqTable.log(
124551532d8bSGuokai Chen    data = ifuWbToFtqDumpData,
1246da3bf434SMaxpicca-Li    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
124751532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
124851532d8bSGuokai Chen    clock = clock,
124951532d8bSGuokai Chen    reset = reset
125051532d8bSGuokai Chen  )
125151532d8bSGuokai Chen
125209c6f1ddSLingrui98}
1253