Path: blob/main/cranelift/codegen/src/isa/riscv64/mod.rs
3081 views
//! risc-v 64-bit Instruction Set Architecture.12use crate::dominator_tree::DominatorTree;3use crate::ir::{Function, Type};4use crate::isa::riscv64::settings as riscv_settings;5use crate::isa::{6Builder as IsaBuilder, FunctionAlignment, IsaFlagsHashKey, OwnedTargetIsa, TargetIsa,7};8use crate::machinst::{9CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet,10TextSectionBuilder, VCode, compile,11};12use crate::result::CodegenResult;13use crate::settings::{self as shared_settings, Flags};14use crate::{CodegenError, ir};15use alloc::string::String;16use alloc::{boxed::Box, vec::Vec};17use core::fmt;18use cranelift_control::ControlPlane;19use target_lexicon::{Architecture, Triple};20mod abi;21pub(crate) mod inst;22mod lower;23mod settings;24#[cfg(feature = "unwind")]25use crate::isa::unwind::systemv;2627use self::inst::EmitInfo;2829/// An riscv64 backend.30pub struct Riscv64Backend {31triple: Triple,32flags: shared_settings::Flags,33isa_flags: riscv_settings::Flags,34}3536impl Riscv64Backend {37/// Create a new riscv64 backend with the given (shared) flags.38pub fn new_with_flags(39triple: Triple,40flags: shared_settings::Flags,41isa_flags: riscv_settings::Flags,42) -> Riscv64Backend {43Riscv64Backend {44triple,45flags,46isa_flags,47}48}4950/// This performs lowering to VCode, register-allocates the code, computes block layout and51/// finalizes branches. The result is ready for binary emission.52fn compile_vcode(53&self,54func: &Function,55domtree: &DominatorTree,56ctrl_plane: &mut ControlPlane,57) -> CodegenResult<(VCode<inst::Inst>, regalloc2::Output)> {58let emit_info = EmitInfo::new(self.flags.clone(), self.isa_flags.clone());59let sigs = SigSet::new::<abi::Riscv64MachineDeps>(func, &self.flags)?;60let abi = abi::Riscv64Callee::new(func, self, &self.isa_flags, &sigs)?;61compile::compile::<Riscv64Backend>(func, domtree, self, abi, emit_info, sigs, ctrl_plane)62}63}6465impl TargetIsa for Riscv64Backend {66fn compile_function(67&self,68func: &Function,69domtree: &DominatorTree,70want_disasm: bool,71ctrl_plane: &mut ControlPlane,72) -> CodegenResult<CompiledCodeStencil> {73let (vcode, regalloc_result) = self.compile_vcode(func, domtree, ctrl_plane)?;7475let want_disasm = want_disasm || log::log_enabled!(log::Level::Debug);76let emit_result = vcode.emit(®alloc_result, want_disasm, &self.flags, ctrl_plane);77let value_labels_ranges = emit_result.value_labels_ranges;78let buffer = emit_result.buffer;7980if let Some(disasm) = emit_result.disasm.as_ref() {81log::debug!("disassembly:\n{disasm}");82}8384Ok(CompiledCodeStencil {85buffer,86vcode: emit_result.disasm,87value_labels_ranges,88bb_starts: emit_result.bb_offsets,89bb_edges: emit_result.bb_edges,90})91}9293fn name(&self) -> &'static str {94"riscv64"95}96fn dynamic_vector_bytes(&self, _dynamic_ty: ir::Type) -> u32 {971698}99100fn triple(&self) -> &Triple {101&self.triple102}103104fn flags(&self) -> &shared_settings::Flags {105&self.flags106}107108fn isa_flags(&self) -> Vec<shared_settings::Value> {109self.isa_flags.iter().collect()110}111112fn isa_flags_hash_key(&self) -> IsaFlagsHashKey<'_> {113IsaFlagsHashKey(self.isa_flags.hash_key())114}115116#[cfg(feature = "unwind")]117fn emit_unwind_info(118&self,119result: &CompiledCode,120kind: crate::isa::unwind::UnwindInfoKind,121) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {122use crate::isa::unwind::UnwindInfo;123use crate::isa::unwind::UnwindInfoKind;124Ok(match kind {125UnwindInfoKind::SystemV => {126let mapper = self::inst::unwind::systemv::RegisterMapper;127Some(UnwindInfo::SystemV(128crate::isa::unwind::systemv::create_unwind_info_from_insts(129&result.buffer.unwind_info[..],130result.buffer.data().len(),131&mapper,132)?,133))134}135UnwindInfoKind::Windows => None,136_ => None,137})138}139140#[cfg(feature = "unwind")]141fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {142Some(inst::unwind::systemv::create_cie())143}144145fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {146Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))147}148149#[cfg(feature = "unwind")]150fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, systemv::RegisterMappingError> {151inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)152}153154fn function_alignment(&self) -> FunctionAlignment {155inst::Inst::function_alignment()156}157158fn page_size_align_log2(&self) -> u8 {159debug_assert_eq!(1 << 12, 0x1000);16012161}162163#[cfg(feature = "disas")]164fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {165use capstone::prelude::*;166let mut cs_builder = Capstone::new().riscv().mode(arch::riscv::ArchMode::RiscV64);167168// Enable C instruction decoding if we have compressed instructions enabled.169//170// We can't enable this unconditionally because it will cause Capstone to171// emit weird instructions and generally mess up when it encounters unknown172// instructions, such as any Zba,Zbb,Zbc or Vector instructions.173//174// This causes the default disassembly to be quite unreadable, so enable175// it only when we are actually going to be using them.176let uses_compressed = self177.isa_flags()178.iter()179.filter(|f| ["has_zca", "has_zcb", "has_zcd"].contains(&f.name))180.any(|f| f.as_bool().unwrap_or(false));181if uses_compressed {182cs_builder = cs_builder.extra_mode([arch::riscv::ArchExtraMode::RiscVC].into_iter());183}184185let mut cs = cs_builder.build()?;186187// Similar to AArch64, RISC-V uses inline constants rather than a separate188// constant pool. We want to skip disassembly over inline constants instead189// of stopping on invalid bytes.190cs.set_skipdata(true)?;191Ok(cs)192}193194fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {195// TODO-RISC-V: implement proper register pretty-printing.196format!("{reg:?}")197}198199fn has_native_fma(&self) -> bool {200true201}202203fn has_round(&self) -> bool {204true205}206207fn has_blendv_lowering(&self, _: Type) -> bool {208false209}210211fn has_x86_pshufb_lowering(&self) -> bool {212false213}214215fn has_x86_pmulhrsw_lowering(&self) -> bool {216false217}218219fn has_x86_pmaddubsw_lowering(&self) -> bool {220false221}222223fn default_argument_extension(&self) -> ir::ArgumentExtension {224// According to https://riscv.org/wp-content/uploads/2024/12/riscv-calling.pdf225// it says:226//227// > In RV64, 32-bit types, such as int, are stored in integer228// > registers as proper sign extensions of their 32-bit values; that229// > is, bits 63..31 are all equal. This restriction holds even for230// > unsigned 32-bit types.231//232// leading to `sext` here.233ir::ArgumentExtension::Sext234}235}236237impl fmt::Display for Riscv64Backend {238fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {239f.debug_struct("MachBackend")240.field("name", &self.name())241.field("triple", &self.triple())242.field("flags", &format!("{}", self.flags()))243.finish()244}245}246247/// Create a new `isa::Builder`.248pub fn isa_builder(triple: Triple) -> IsaBuilder {249match triple.architecture {250Architecture::Riscv64(..) => {}251_ => unreachable!(),252}253IsaBuilder {254triple,255setup: riscv_settings::builder(),256constructor: isa_constructor,257}258}259260fn isa_constructor(261triple: Triple,262shared_flags: Flags,263builder: &shared_settings::Builder,264) -> CodegenResult<OwnedTargetIsa> {265let isa_flags = riscv_settings::Flags::new(&shared_flags, builder);266267// The RISC-V backend does not work without at least the G extension enabled.268// The G extension is simply a combination of the following extensions:269// - I: Base Integer Instruction Set270// - M: Integer Multiplication and Division271// - A: Atomic Instructions272// - F: Single-Precision Floating-Point273// - D: Double-Precision Floating-Point274// - Zicsr: Control and Status Register Instructions275// - Zifencei: Instruction-Fetch Fence276//277// Ensure that those combination of features is enabled.278if !(isa_flags.has_m()279&& isa_flags.has_a()280&& isa_flags.has_f()281&& isa_flags.has_d()282&& isa_flags.has_zicsr()283&& isa_flags.has_zifencei())284{285return Err(CodegenError::Unsupported(286"The RISC-V Backend currently requires all the features in the G Extension enabled"287.into(),288));289}290291let backend = Riscv64Backend::new_with_flags(triple, shared_flags, isa_flags);292Ok(backend.wrapped())293}294295296