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