Skip to main content

cranelift_codegen/isa/riscv64/
mod.rs

1//! risc-v 64-bit Instruction Set Architecture.
2
3use crate::dominator_tree::DominatorTree;
4use crate::ir::{Function, Type};
5use crate::isa::riscv64::settings as riscv_settings;
6use crate::isa::{
7    Builder as IsaBuilder, FunctionAlignment, IsaFlagsHashKey, OwnedTargetIsa, TargetIsa,
8};
9use crate::loop_analysis::LoopAnalysis;
10use crate::machinst::CompiledCode;
11use crate::machinst::{
12    CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet, TextSectionBuilder, VCode,
13    compile,
14};
15use crate::result::CodegenResult;
16use crate::settings::{self as shared_settings, Flags};
17use crate::{CodegenError, ir};
18use alloc::string::String;
19use alloc::{boxed::Box, vec::Vec};
20use core::fmt;
21use cranelift_control::ControlPlane;
22use target_lexicon::{Architecture, Triple};
23mod abi;
24pub(crate) mod inst;
25mod lower;
26mod settings;
27#[cfg(feature = "unwind")]
28use crate::isa::unwind::systemv;
29
30use self::inst::EmitInfo;
31
32/// An riscv64 backend.
33pub struct Riscv64Backend {
34    triple: Triple,
35    flags: shared_settings::Flags,
36    isa_flags: riscv_settings::Flags,
37}
38
39impl Riscv64Backend {
40    fn supports_vector_element_type(&self, ty: Type) -> bool {
41        use ir::types::*;
42
43        match ty {
44            I8 | I16 | I32 | I64 => true,
45            // FP16 vector operations require Zvfh.
46            F16 => self.isa_flags.has_f() && self.isa_flags.has_zvfh(),
47            F32 => self.isa_flags.has_f(),
48            F64 => self.isa_flags.has_d(),
49            _ => false,
50        }
51    }
52
53    /// Create a new riscv64 backend with the given (shared) flags.
54    pub fn new_with_flags(
55        triple: Triple,
56        flags: shared_settings::Flags,
57        isa_flags: riscv_settings::Flags,
58    ) -> Riscv64Backend {
59        Riscv64Backend {
60            triple,
61            flags,
62            isa_flags,
63        }
64    }
65
66    /// This performs lowering to VCode, register-allocates the code, computes block layout and
67    /// finalizes branches. The result is ready for binary emission.
68    fn compile_vcode(
69        &self,
70        func: &Function,
71        domtree: &DominatorTree,
72        loop_analysis: &LoopAnalysis,
73        regalloc_ctx: &mut regalloc2::Ctx,
74        ctrl_plane: &mut ControlPlane,
75    ) -> CodegenResult<VCode<inst::Inst>> {
76        let emit_info = EmitInfo::new(self.flags.clone(), self.isa_flags.clone());
77        let sigs = SigSet::new::<abi::Riscv64MachineDeps>(func, &self.flags)?;
78        let abi = abi::Riscv64Callee::new(func, self, &self.isa_flags, &sigs)?;
79        compile::compile::<Riscv64Backend>(
80            func,
81            domtree,
82            loop_analysis,
83            regalloc_ctx,
84            self,
85            abi,
86            emit_info,
87            sigs,
88            ctrl_plane,
89        )
90    }
91}
92
93impl TargetIsa for Riscv64Backend {
94    fn compile_function(
95        &self,
96        func: &Function,
97        domtree: &DominatorTree,
98        loop_analysis: &LoopAnalysis,
99        regalloc_ctx: &mut regalloc2::Ctx,
100        want_disasm: bool,
101        ctrl_plane: &mut ControlPlane,
102    ) -> CodegenResult<CompiledCodeStencil> {
103        let vcode = self.compile_vcode(func, domtree, loop_analysis, regalloc_ctx, ctrl_plane)?;
104
105        let want_disasm = want_disasm || log::log_enabled!(log::Level::Debug);
106        let emit_result = vcode.emit(&regalloc_ctx.output, want_disasm, &self.flags, ctrl_plane)?;
107        let value_labels_ranges = emit_result.value_labels_ranges;
108        let buffer = emit_result.buffer;
109
110        if let Some(disasm) = emit_result.disasm.as_ref() {
111            log::debug!("disassembly:\n{disasm}");
112        }
113
114        Ok(CompiledCodeStencil(CompiledCode {
115            buffer,
116            vcode: emit_result.disasm,
117            value_labels_ranges,
118            bb_starts: emit_result.bb_offsets,
119            bb_edges: emit_result.bb_edges,
120        }))
121    }
122
123    fn name(&self) -> &'static str {
124        "riscv64"
125    }
126    fn dynamic_vector_bytes(&self, _dynamic_ty: ir::Type) -> u32 {
127        16
128    }
129
130    fn triple(&self) -> &Triple {
131        &self.triple
132    }
133
134    fn flags(&self) -> &shared_settings::Flags {
135        &self.flags
136    }
137
138    fn isa_flags(&self) -> Vec<shared_settings::Value> {
139        self.isa_flags.iter().collect()
140    }
141
142    fn isa_flags_hash_key(&self) -> IsaFlagsHashKey<'_> {
143        IsaFlagsHashKey(self.isa_flags.hash_key())
144    }
145
146    #[cfg(feature = "unwind")]
147    fn emit_unwind_info(
148        &self,
149        result: &CompiledCode,
150        kind: crate::isa::unwind::UnwindInfoKind,
151    ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
152        use crate::isa::unwind::UnwindInfo;
153        use crate::isa::unwind::UnwindInfoKind;
154        Ok(match kind {
155            UnwindInfoKind::SystemV => {
156                let mapper = self::inst::unwind::systemv::RegisterMapper;
157                Some(UnwindInfo::SystemV(
158                    crate::isa::unwind::systemv::create_unwind_info_from_insts(
159                        &result.buffer.unwind_info[..],
160                        result.buffer.data().len(),
161                        &mapper,
162                    )?,
163                ))
164            }
165            UnwindInfoKind::Windows => None,
166            _ => None,
167        })
168    }
169
170    #[cfg(feature = "unwind")]
171    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
172        Some(inst::unwind::systemv::create_cie())
173    }
174
175    fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {
176        Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))
177    }
178
179    #[cfg(feature = "unwind")]
180    fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, systemv::RegisterMappingError> {
181        inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)
182    }
183
184    fn function_alignment(&self) -> FunctionAlignment {
185        inst::Inst::function_alignment()
186    }
187
188    fn page_size_align_log2(&self) -> u8 {
189        debug_assert_eq!(1 << 12, 0x1000);
190        12
191    }
192
193    #[cfg(feature = "disas")]
194    fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
195        use capstone::prelude::*;
196        let mut cs_builder = Capstone::new().riscv().mode(arch::riscv::ArchMode::RiscV64);
197
198        // Enable C instruction decoding if we have compressed instructions enabled.
199        //
200        // We can't enable this unconditionally because it will cause Capstone to
201        // emit weird instructions and generally mess up when it encounters unknown
202        // instructions, such as any Zba,Zbb,Zbc or Vector instructions.
203        //
204        // This causes the default disassembly to be quite unreadable, so enable
205        // it only when we are actually going to be using them.
206        let uses_compressed = self
207            .isa_flags()
208            .iter()
209            .filter(|f| ["has_zca", "has_zcb", "has_zcd"].contains(&f.name))
210            .any(|f| f.as_bool().unwrap_or(false));
211        if uses_compressed {
212            cs_builder = cs_builder.extra_mode([arch::riscv::ArchExtraMode::RiscVC].into_iter());
213        }
214
215        let mut cs = cs_builder.build()?;
216
217        // Similar to AArch64, RISC-V uses inline constants rather than a separate
218        // constant pool. We want to skip disassembly over inline constants instead
219        // of stopping on invalid bytes.
220        cs.set_skipdata(true)?;
221        Ok(cs)
222    }
223
224    fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {
225        // TODO-RISC-V: implement proper register pretty-printing.
226        format!("{reg:?}")
227    }
228
229    fn has_native_fma(&self) -> bool {
230        true
231    }
232
233    fn supports_vector_load_store(&self, ty: Type) -> bool {
234        ty.is_vector()
235            && u64::from(ty.bits()) <= self.isa_flags.min_vec_reg_size()
236            && self.supports_vector_element_type(ty.lane_type())
237    }
238
239    fn has_round(&self) -> bool {
240        true
241    }
242
243    fn has_blendv_lowering(&self, _: Type) -> bool {
244        false
245    }
246
247    fn has_x86_pshufb_lowering(&self) -> bool {
248        false
249    }
250
251    fn has_x86_pmulhrsw_lowering(&self) -> bool {
252        false
253    }
254
255    fn has_x86_pmaddubsw_lowering(&self) -> bool {
256        false
257    }
258
259    fn default_argument_extension(&self) -> ir::ArgumentExtension {
260        // According to https://riscv.org/wp-content/uploads/2024/12/riscv-calling.pdf
261        // it says:
262        //
263        // > In RV64, 32-bit types, such as int, are stored in integer
264        // > registers as proper sign extensions of their 32-bit values; that
265        // > is, bits 63..31 are all equal. This restriction holds even for
266        // > unsigned 32-bit types.
267        //
268        // leading to `sext` here.
269        ir::ArgumentExtension::Sext
270    }
271}
272
273impl fmt::Display for Riscv64Backend {
274    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
275        f.debug_struct("MachBackend")
276            .field("name", &self.name())
277            .field("triple", &self.triple())
278            .field("flags", &format!("{}", self.flags()))
279            .finish()
280    }
281}
282
283/// Create a new `isa::Builder`.
284pub fn isa_builder(triple: Triple) -> IsaBuilder {
285    match triple.architecture {
286        Architecture::Riscv64(..) => {}
287        _ => unreachable!(),
288    }
289    IsaBuilder {
290        triple,
291        setup: riscv_settings::builder(),
292        constructor: isa_constructor,
293    }
294}
295
296fn isa_constructor(
297    triple: Triple,
298    shared_flags: Flags,
299    builder: &shared_settings::Builder,
300) -> CodegenResult<OwnedTargetIsa> {
301    let isa_flags = riscv_settings::Flags::new(&shared_flags, builder);
302
303    // The RISC-V backend does not work without at least the G extension enabled.
304    // The G extension is simply a combination of the following extensions:
305    // - I: Base Integer Instruction Set
306    // - M: Integer Multiplication and Division
307    // - A: Atomic Instructions
308    // - F: Single-Precision Floating-Point
309    // - D: Double-Precision Floating-Point
310    // - Zicsr: Control and Status Register Instructions
311    // - Zifencei: Instruction-Fetch Fence
312    //
313    // Ensure that those combination of features is enabled.
314    if !(isa_flags.has_m()
315        && isa_flags.has_a()
316        && isa_flags.has_f()
317        && isa_flags.has_d()
318        && isa_flags.has_zicsr()
319        && isa_flags.has_zifencei())
320    {
321        return Err(CodegenError::Unsupported(
322            "The RISC-V Backend currently requires all the features in the G Extension enabled"
323                .into(),
324        ));
325    }
326
327    let backend = Riscv64Backend::new_with_flags(triple, shared_flags, isa_flags);
328    Ok(backend.wrapped())
329}