xref: /XiangShan/src/main/scala/xiangshan/frontend/PreDecode.scala (revision 57bb43b5f11c3f1e89ac52f232fe73056b35d9bd)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.frontend
18
19import chipsalliance.rocketchip.config.Parameters
20import freechips.rocketchip.rocket.{RVCDecoder, ExpandedInstruction}
21import chisel3.{util, _}
22import chisel3.util._
23import utils._
24import xiangshan._
25import xiangshan.frontend.icache._
26import xiangshan.backend.decode.isa.predecode.PreDecodeInst
27
28trait HasPdConst extends HasXSParameter with HasICacheParameters with HasIFUConst{
29  def isRVC(inst: UInt) = (inst(1,0) =/= 3.U)
30  def isLink(reg:UInt) = reg === 1.U || reg === 5.U
31  def brInfo(instr: UInt) = {
32    val brType::Nil = ListLookup(instr, List(BrType.notCFI), PreDecodeInst.brTable)
33    val rd = Mux(isRVC(instr), instr(12), instr(11,7))
34    val rs = Mux(isRVC(instr), Mux(brType === BrType.jal, 0.U, instr(11, 7)), instr(19, 15))
35    val isCall = (brType === BrType.jal && !isRVC(instr) || brType === BrType.jalr) && isLink(rd) // Only for RV64
36    val isRet = brType === BrType.jalr && isLink(rs) && !isCall
37    List(brType, isCall, isRet)
38  }
39  def jal_offset(inst: UInt, rvc: Bool): UInt = {
40    val rvc_offset = Cat(inst(12), inst(8), inst(10, 9), inst(6), inst(7), inst(2), inst(11), inst(5, 3), 0.U(1.W))
41    val rvi_offset = Cat(inst(31), inst(19, 12), inst(20), inst(30, 21), 0.U(1.W))
42    val max_width = rvi_offset.getWidth
43    SignExt(Mux(rvc, SignExt(rvc_offset, max_width), SignExt(rvi_offset, max_width)), XLEN)
44  }
45  def br_offset(inst: UInt, rvc: Bool): UInt = {
46    val rvc_offset = Cat(inst(12), inst(6, 5), inst(2), inst(11, 10), inst(4, 3), 0.U(1.W))
47    val rvi_offset = Cat(inst(31), inst(7), inst(30, 25), inst(11, 8), 0.U(1.W))
48    val max_width = rvi_offset.getWidth
49    SignExt(Mux(rvc, SignExt(rvc_offset, max_width), SignExt(rvi_offset, max_width)), XLEN)
50  }
51
52  def NOP = "h4501".U(16.W)
53}
54
55object BrType {
56  def notCFI   = "b00".U
57  def branch  = "b01".U
58  def jal     = "b10".U
59  def jalr    = "b11".U
60  def apply() = UInt(2.W)
61}
62
63object ExcType {  //TODO:add exctype
64  def notExc = "b000".U
65  def apply() = UInt(3.W)
66}
67
68class PreDecodeInfo extends Bundle {  // 8 bit
69  val valid   = Bool()
70  val isRVC   = Bool()
71  val brType  = UInt(2.W)
72  val isCall  = Bool()
73  val isRet   = Bool()
74  //val excType = UInt(3.W)
75  def isBr    = brType === BrType.branch
76  def isJal   = brType === BrType.jal
77  def isJalr  = brType === BrType.jalr
78  def notCFI  = brType === BrType.notCFI
79}
80
81class PreDecodeResp(implicit p: Parameters) extends XSBundle with HasPdConst {
82  val pd = Vec(PredictWidth, new PreDecodeInfo)
83  val hasHalfValid = Vec(PredictWidth, Bool())
84  val expInstr = Vec(PredictWidth, UInt(32.W))
85  val jumpOffset = Vec(PredictWidth, UInt(XLEN.W))
86//  val hasLastHalf = Bool()
87  val triggered    = Vec(PredictWidth, new TriggerCf)
88}
89
90class PreDecode(implicit p: Parameters) extends XSModule with HasPdConst{
91  val io = IO(new Bundle() {
92    val in = Input(new IfuToPreDecode)
93    val out = Output(new PreDecodeResp)
94  })
95
96  val data          = io.in.data
97//  val lastHalfMatch = io.in.lastHalfMatch
98  val validStart, validEnd = Wire(Vec(PredictWidth, Bool()))
99  val h_validStart, h_validEnd = Wire(Vec(PredictWidth, Bool()))
100
101  val rawInsts = if (HasCExtension) VecInit((0 until PredictWidth).map(i => Cat(data(i+1), data(i))))
102  else         VecInit((0 until PredictWidth).map(i => data(i)))
103
104  for (i <- 0 until PredictWidth) {
105    val inst           =WireInit(rawInsts(i))
106    val expander       = Module(new RVCExpander)
107    val currentIsRVC   = isRVC(inst)
108    val currentPC      = io.in.pc(i)
109    expander.io.in             := inst
110
111    val brType::isCall::isRet::Nil = brInfo(inst)
112    val jalOffset = jal_offset(inst, currentIsRVC)
113    val brOffset  = br_offset(inst, currentIsRVC)
114
115    //val lastIsValidEnd =  if (i == 0) { !lastHalfMatch } else { validEnd(i-1) || !HasCExtension.B }
116    val lastIsValidEnd =   if (i == 0) { true.B } else { validEnd(i-1) || !HasCExtension.B }
117    validStart(i)   := (lastIsValidEnd || !HasCExtension.B)
118    validEnd(i)     := validStart(i) && currentIsRVC || !validStart(i) || !HasCExtension.B
119
120    //prepared for last half match
121    //TODO if HasCExtension
122    val h_lastIsValidEnd = if (i == 0) { false.B } else { h_validEnd(i-1) || !HasCExtension.B }
123    h_validStart(i)   := (h_lastIsValidEnd || !HasCExtension.B)
124    h_validEnd(i)     := h_validStart(i) && currentIsRVC || !h_validStart(i) || !HasCExtension.B
125
126    io.out.hasHalfValid(i)        := h_validStart(i)
127
128    io.out.triggered(i)   := DontCare//VecInit(Seq.fill(10)(false.B))
129
130
131    io.out.pd(i).valid         := validStart(i)
132    io.out.pd(i).isRVC         := currentIsRVC
133    io.out.pd(i).brType        := brType
134    io.out.pd(i).isCall        := isCall
135    io.out.pd(i).isRet         := isRet
136
137    io.out.expInstr(i)         := expander.io.out.bits
138    io.out.jumpOffset(i)       := Mux(io.out.pd(i).isBr, brOffset, jalOffset)
139  }
140
141//  io.out.hasLastHalf := !io.out.pd(PredictWidth - 1).isRVC && io.out.pd(PredictWidth - 1).valid
142
143  for (i <- 0 until PredictWidth) {
144    XSDebug(true.B,
145      p"instr ${Hexadecimal(io.out.expInstr(i))}, " +
146        p"validStart ${Binary(validStart(i))}, " +
147        p"validEnd ${Binary(validEnd(i))}, " +
148        p"isRVC ${Binary(io.out.pd(i).isRVC)}, " +
149        p"brType ${Binary(io.out.pd(i).brType)}, " +
150        p"isRet ${Binary(io.out.pd(i).isRet)}, " +
151        p"isCall ${Binary(io.out.pd(i).isCall)}\n"
152    )
153  }
154}
155
156class RVCExpander(implicit p: Parameters) extends XSModule {
157  val io = IO(new Bundle {
158    val in = Input(UInt(32.W))
159    val out = Output(new ExpandedInstruction)
160  })
161
162  if (HasCExtension) {
163    io.out := new RVCDecoder(io.in, XLEN).decode
164  } else {
165    io.out := new RVCDecoder(io.in, XLEN).passthrough
166  }
167}
168
169/* ---------------------------------------------------------------------
170 * Predict result check
171 *
172 * ---------------------------------------------------------------------
173 */
174
175object FaultType {
176  def noFault         = "b000".U
177  def jalFault        = "b001".U    //not CFI taken or invalid instruction taken
178  def retFault        = "b010".U    //not CFI taken or invalid instruction taken
179  def targetFault     = "b011".U
180  def notCFIFault    = "b100".U    //not CFI taken or invalid instruction taken
181  def invalidTaken    = "b101".U
182  def apply() = UInt(3.W)
183}
184
185class CheckInfo extends Bundle {  // 8 bit
186  val value  = UInt(3.W)
187  def isjalFault      = value === FaultType.jalFault
188  def isRetFault      = value === FaultType.retFault
189  def istargetFault   = value === FaultType.targetFault
190  def invalidTakenFault    = value === FaultType.invalidTaken
191  def notCFIFault          = value === FaultType.notCFIFault
192}
193
194class PredCheckerResp(implicit p: Parameters) extends XSBundle with HasPdConst {
195  //to Ibuffer write port (timing critical)
196  val fixedRange  = Vec(PredictWidth, Bool())
197  val fixedTaken  = Vec(PredictWidth, Bool())
198  //to Ftq write back port (not timing critical)
199  val fixedTarget = Vec(PredictWidth, UInt(VAddrBits.W))
200  val fixedMissPred = Vec(PredictWidth,  Bool())
201  val faultType   = Vec(PredictWidth, new CheckInfo)
202}
203
204
205class PredChecker(implicit p: Parameters) extends XSModule with HasPdConst {
206  val io = IO( new Bundle{
207    val in = Input(new IfuToPredChecker)
208    val out = Output(new PredCheckerResp)
209  })
210
211  val (takenIdx, predTaken)     = (io.in.ftqOffset.bits, io.in.ftqOffset.valid)
212  val predTarget                = (io.in.target)
213  val (instrRange, instrValid)  = (io.in.instrRange, io.in.instrValid)
214  val (pds, pc, jumpOffset)     = (io.in.pds, io.in.pc, io.in.jumpOffset)
215
216  val jalFaultVec, retFaultVec, targetFault, notCFITaken, invalidTaken = Wire(Vec(PredictWidth, Bool()))
217
218  /** remask fault may appear together with other faults, but other faults are exclusive
219    * so other f ault mast use fixed mask to keep only one fault would be found and redirect to Ftq
220    * we first detecct remask fault and then use fixedRange to do second check
221    **/
222
223  /** first check: remask Fault */
224  jalFaultVec         := VecInit(pds.zipWithIndex.map{case(pd, i) => pd.isJal && instrRange(i) && instrValid(i) && (takenIdx > i.U && predTaken || !predTaken) })
225  retFaultVec         := VecInit(pds.zipWithIndex.map{case(pd, i) => pd.isRet && instrRange(i) && instrValid(i) && (takenIdx > i.U && predTaken || !predTaken) })
226  val remaskFault      = VecInit((0 until PredictWidth).map(i => jalFaultVec(i) || retFaultVec(i)))
227  val remaskIdx        = ParallelPriorityEncoder(remaskFault.asUInt)
228  val needRemask       = ParallelOR(remaskFault)
229  val fixedRange       = instrRange.asUInt & (Fill(PredictWidth, !needRemask) | Fill(PredictWidth, 1.U(1.W)) >> ~remaskIdx)
230
231  io.out.fixedRange := fixedRange.asTypeOf((Vec(PredictWidth, Bool())))
232
233  io.out.fixedTaken := VecInit(pds.zipWithIndex.map{case(pd, i) => instrValid (i) && fixedRange(i) && (pd.isRet || pd.isJal || takenIdx === i.U && predTaken && !pd.notCFI)  })
234
235  /** second check: faulse prediction fault and target fault */
236  notCFITaken  := VecInit(pds.zipWithIndex.map{case(pd, i) => fixedRange(i) && instrValid(i) && i.U === takenIdx && pd.notCFI && predTaken })
237  invalidTaken := VecInit(pds.zipWithIndex.map{case(pd, i) => fixedRange(i) && !instrValid(i)  && i.U === takenIdx  && predTaken })
238
239  /** target calculation  */
240  val jumpTargets          = VecInit(pds.zipWithIndex.map{case(pd,i) => pc(i) + jumpOffset(i)})
241  targetFault      := VecInit(pds.zipWithIndex.map{case(pd,i) => fixedRange(i) && instrValid(i) && (pd.isJal || pd.isBr) && takenIdx === i.U && predTaken  && (predTarget =/= jumpTargets(i))})
242
243  val seqTargets = VecInit((0 until PredictWidth).map(i => pc(i) + Mux(pds(i).isRVC || !instrValid(i), 2.U, 4.U ) ))
244
245  io.out.faultType.zipWithIndex.map{case(faultType, i) => faultType.value := Mux(jalFaultVec(i) , FaultType.jalFault ,
246                                                                             Mux(retFaultVec(i), FaultType.retFault ,
247                                                                             Mux(targetFault(i), FaultType.targetFault ,
248                                                                             Mux(notCFITaken(i) , FaultType.notCFIFault,
249                                                                             Mux(invalidTaken(i), FaultType.invalidTaken,  FaultType.noFault)))))}
250
251  io.out.fixedMissPred.zipWithIndex.map{case(missPred, i ) => missPred := jalFaultVec(i) || retFaultVec(i) || notCFITaken(i) || invalidTaken(i) || targetFault(i)}
252  io.out.fixedTarget.zipWithIndex.map{case(target, i) => target := Mux(jalFaultVec(i) || targetFault(i), jumpTargets(i),  seqTargets(i) )}
253
254}
255
256class FrontendTrigger(implicit p: Parameters) extends XSModule {
257  val io = IO(new Bundle(){
258    val frontendTrigger = Input(new FrontendTdataDistributeIO)
259    val csrTriggerEnable = Input(Vec(4, Bool()))
260    val triggered    = Output(Vec(PredictWidth, new TriggerCf))
261
262    val pds           = Input(Vec(PredictWidth, new PreDecodeInfo))
263    val pc            = Input(Vec(PredictWidth, UInt(VAddrBits.W)))
264    val data          = if(HasCExtension) Input(Vec(PredictWidth + 1, UInt(16.W)))
265                        else Input(Vec(PredictWidth, UInt(32.W)))
266  })
267
268  val data          = io.data
269
270  val rawInsts = if (HasCExtension) VecInit((0 until PredictWidth).map(i => Cat(data(i+1), data(i))))
271                        else         VecInit((0 until PredictWidth).map(i => data(i)))
272
273  val tdata = RegInit(VecInit(Seq.fill(4)(0.U.asTypeOf(new MatchTriggerIO))))
274  when(io.frontendTrigger.t.valid) {
275    tdata(io.frontendTrigger.t.bits.addr) := io.frontendTrigger.t.bits.tdata
276  }
277  io.triggered.map{i => i := 0.U.asTypeOf(new TriggerCf)}
278  val triggerEnable = RegInit(VecInit(Seq.fill(4)(false.B))) // From CSR, controlled by priv mode, etc.
279  triggerEnable := io.csrTriggerEnable
280  XSDebug(triggerEnable.asUInt.orR, "Debug Mode: At least one frontend trigger is enabled\n")
281
282  for (i <- 0 until 4) {PrintTriggerInfo(triggerEnable(i), tdata(i))}
283
284  for (i <- 0 until PredictWidth) {
285    val currentPC = io.pc(i)
286    val currentIsRVC = io.pds(i).isRVC
287    val inst = WireInit(rawInsts(i))
288    val triggerHitVec = Wire(Vec(4, Bool()))
289
290    for (j <- 0 until 4) {
291      triggerHitVec(j) := Mux(tdata(j).select, TriggerCmp(Mux(currentIsRVC, inst(15, 0), inst), tdata(j).tdata2, tdata(j).matchType, triggerEnable(j)),
292        TriggerCmp(currentPC, tdata(j).tdata2, tdata(j).matchType, triggerEnable(j)))
293    }
294
295    // fix chains this could be moved further into the pipeline
296    io.triggered(i).frontendHit := triggerHitVec
297    val enableChain = tdata(0).chain
298    when(enableChain){
299      io.triggered(i).frontendHit(0) := triggerHitVec(0) && triggerHitVec(1) && (tdata(0).timing === tdata(1).timing)
300      io.triggered(i).frontendHit(1) := triggerHitVec(0) && triggerHitVec(1) && (tdata(0).timing === tdata(1).timing)
301    }
302    for(j <- 0 until 2) {
303      io.triggered(i).backendEn(j) := Mux(tdata(j+2).chain, triggerHitVec(j+2), true.B)
304      io.triggered(i).frontendHit(j+2) := !tdata(j+2).chain && triggerHitVec(j+2) // temporary workaround
305    }
306    XSDebug(io.triggered(i).getHitFrontend, p"Debug Mode: Predecode Inst No. ${i} has trigger hit vec ${io.triggered(i).frontendHit}" +
307      p"and backend en ${io.triggered(i).backendEn}\n")
308  }
309}
310