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