Skip to main content

cranelift_codegen/isa/aarch64/
mod.rs

1//! ARM 64-bit Instruction Set Architecture.
2
3use crate::dominator_tree::DominatorTree;
4use crate::ir::{self, Function, Type};
5use crate::isa::aarch64::settings as aarch64_settings;
6#[cfg(feature = "unwind")]
7use crate::isa::unwind::systemv;
8use crate::isa::{Builder as IsaBuilder, FunctionAlignment, IsaFlagsHashKey, TargetIsa};
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 as shared_settings;
17use alloc::string::String;
18use alloc::{boxed::Box, vec::Vec};
19use core::fmt;
20use cranelift_control::ControlPlane;
21use target_lexicon::{Aarch64Architecture, Architecture, Triple};
22
23// New backend:
24mod abi;
25pub mod inst;
26mod lower;
27pub mod settings;
28
29use self::inst::EmitInfo;
30
31/// An AArch64 backend.
32pub struct AArch64Backend {
33    triple: Triple,
34    flags: shared_settings::Flags,
35    isa_flags: aarch64_settings::Flags,
36}
37
38impl AArch64Backend {
39    /// Create a new AArch64 backend with the given (shared) flags.
40    pub fn new_with_flags(
41        triple: Triple,
42        flags: shared_settings::Flags,
43        isa_flags: aarch64_settings::Flags,
44    ) -> AArch64Backend {
45        AArch64Backend {
46            triple,
47            flags,
48            isa_flags,
49        }
50    }
51
52    /// This performs lowering to VCode, register-allocates the code, computes block layout and
53    /// finalizes branches. The result is ready for binary emission.
54    fn compile_vcode(
55        &self,
56        func: &Function,
57        domtree: &DominatorTree,
58        ctrl_plane: &mut ControlPlane,
59    ) -> CodegenResult<(VCode<inst::Inst>, regalloc2::Output)> {
60        let emit_info = EmitInfo::new(self.flags.clone(), self.isa_flags.clone());
61        let sigs = SigSet::new::<abi::AArch64MachineDeps>(func, &self.flags)?;
62        let abi = abi::AArch64Callee::new(func, self, &self.isa_flags, &sigs)?;
63        compile::compile::<AArch64Backend>(func, domtree, self, abi, emit_info, sigs, ctrl_plane)
64    }
65}
66
67impl TargetIsa for AArch64Backend {
68    fn compile_function(
69        &self,
70        func: &Function,
71        domtree: &DominatorTree,
72        want_disasm: bool,
73        ctrl_plane: &mut ControlPlane,
74    ) -> CodegenResult<CompiledCodeStencil> {
75        let (vcode, regalloc_result) = self.compile_vcode(func, domtree, ctrl_plane)?;
76
77        let emit_result = vcode.emit(&regalloc_result, want_disasm, &self.flags, ctrl_plane);
78        let value_labels_ranges = emit_result.value_labels_ranges;
79        let buffer = emit_result.buffer;
80
81        if let Some(disasm) = emit_result.disasm.as_ref() {
82            log::debug!("disassembly:\n{disasm}");
83        }
84
85        Ok(CompiledCodeStencil {
86            buffer,
87            vcode: emit_result.disasm,
88            value_labels_ranges,
89            bb_starts: emit_result.bb_offsets,
90            bb_edges: emit_result.bb_edges,
91        })
92    }
93
94    fn name(&self) -> &'static str {
95        "aarch64"
96    }
97
98    fn triple(&self) -> &Triple {
99        &self.triple
100    }
101
102    fn flags(&self) -> &shared_settings::Flags {
103        &self.flags
104    }
105
106    fn isa_flags(&self) -> Vec<shared_settings::Value> {
107        self.isa_flags.iter().collect()
108    }
109
110    fn isa_flags_hash_key(&self) -> IsaFlagsHashKey<'_> {
111        IsaFlagsHashKey(self.isa_flags.hash_key())
112    }
113
114    fn is_branch_protection_enabled(&self) -> bool {
115        self.isa_flags.use_bti()
116    }
117
118    fn dynamic_vector_bytes(&self, _dyn_ty: Type) -> u32 {
119        16
120    }
121
122    #[cfg(feature = "unwind")]
123    fn emit_unwind_info(
124        &self,
125        result: &CompiledCode,
126        kind: crate::isa::unwind::UnwindInfoKind,
127    ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
128        use crate::isa::unwind::UnwindInfo;
129        use crate::isa::unwind::UnwindInfoKind;
130        Ok(match kind {
131            UnwindInfoKind::SystemV => {
132                let mapper = self::inst::unwind::systemv::RegisterMapper;
133                Some(UnwindInfo::SystemV(
134                    crate::isa::unwind::systemv::create_unwind_info_from_insts(
135                        &result.buffer.unwind_info[..],
136                        result.buffer.data().len(),
137                        &mapper,
138                    )?,
139                ))
140            }
141            UnwindInfoKind::Windows => Some(UnwindInfo::WindowsArm64(
142                crate::isa::unwind::winarm64::create_unwind_info_from_insts(
143                    &result.buffer.unwind_info[..],
144                )?,
145            )),
146            _ => None,
147        })
148    }
149
150    #[cfg(feature = "unwind")]
151    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
152        if self.isa_flags.sign_return_address()
153            && self.isa_flags.sign_return_address_with_bkey()
154            && !self.triple.operating_system.is_like_darwin()
155        {
156            unimplemented!(
157                "Specifying that the B key is used with pointer authentication instructions in the CIE is not implemented."
158            );
159        }
160
161        Some(inst::unwind::systemv::create_cie())
162    }
163
164    fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {
165        Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))
166    }
167
168    #[cfg(feature = "unwind")]
169    fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, systemv::RegisterMappingError> {
170        inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)
171    }
172
173    fn function_alignment(&self) -> FunctionAlignment {
174        inst::Inst::function_alignment()
175    }
176
177    fn page_size_align_log2(&self) -> u8 {
178        if self.triple().operating_system.is_like_darwin() {
179            debug_assert_eq!(1 << 14, 0x4000);
180            14
181        } else {
182            debug_assert_eq!(1 << 16, 0x10000);
183            16
184        }
185    }
186
187    #[cfg(feature = "disas")]
188    fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
189        use capstone::prelude::*;
190        let mut cs = Capstone::new()
191            .arm64()
192            .mode(arch::arm64::ArchMode::Arm)
193            .detail(true)
194            .build()?;
195        // AArch64 uses inline constants rather than a separate constant pool right now.
196        // Without this option, Capstone will stop disassembling as soon as it sees
197        // an inline constant that is not also a valid instruction. With this option,
198        // Capstone will print a `.byte` directive with the bytes of the inline constant
199        // and continue to the next instruction.
200        cs.set_skipdata(true)?;
201        Ok(cs)
202    }
203
204    fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {
205        inst::regs::pretty_print_reg(reg)
206    }
207
208    fn has_native_fma(&self) -> bool {
209        true
210    }
211
212    fn has_round(&self) -> bool {
213        true
214    }
215
216    fn has_blendv_lowering(&self, _: Type) -> bool {
217        false
218    }
219
220    fn has_x86_pshufb_lowering(&self) -> bool {
221        false
222    }
223
224    fn has_x86_pmulhrsw_lowering(&self) -> bool {
225        false
226    }
227
228    fn has_x86_pmaddubsw_lowering(&self) -> bool {
229        false
230    }
231
232    fn default_argument_extension(&self) -> ir::ArgumentExtension {
233        // This is copied/carried over from a historical piece of code in
234        // Wasmtime:
235        //
236        // https://github.com/bytecodealliance/wasmtime/blob/a018a5a9addb77d5998021a0150192aa955c71bf/crates/cranelift/src/lib.rs#L366-L374
237        //
238        // Whether or not it is still applicable here is unsure, but it's left
239        // the same as-is for now to reduce the likelihood of problems arising.
240        ir::ArgumentExtension::Uext
241    }
242}
243
244impl fmt::Display for AArch64Backend {
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    assert!(triple.architecture == Architecture::Aarch64(Aarch64Architecture::Aarch64));
257    IsaBuilder {
258        triple,
259        setup: aarch64_settings::builder(),
260        constructor: |triple, shared_flags, builder| {
261            let isa_flags = aarch64_settings::Flags::new(&shared_flags, builder);
262            let backend = AArch64Backend::new_with_flags(triple, shared_flags, isa_flags);
263            Ok(backend.wrapped())
264        },
265    }
266}