1 //! Instruction Set Architectures.
2 //!
3 //! The `isa` module provides a `TargetIsa` trait which provides the behavior specialization needed
4 //! by the ISA-independent code generator. The sub-modules of this module provide definitions for
5 //! the instruction sets that Cranelift can target. Each sub-module has it's own implementation of
6 //! `TargetIsa`.
7 //!
8 //! # Constructing a `TargetIsa` instance
9 //!
10 //! The target ISA is built from the following information:
11 //!
12 //! - The name of the target ISA as a string. Cranelift is a cross-compiler, so the ISA to target
13 //!   can be selected dynamically. Individual ISAs can be left out when Cranelift is compiled, so a
14 //!   string is used to identify the proper sub-module.
15 //! - Values for settings that apply to all ISAs. This is represented by a `settings::Flags`
16 //!   instance.
17 //! - Values for ISA-specific settings.
18 //!
19 //! The `isa::lookup()` function is the main entry point which returns an `isa::Builder`
20 //! appropriate for the requested ISA:
21 //!
22 //! ```
23 //! # #[macro_use] extern crate target_lexicon;
24 //! use cranelift_codegen::isa;
25 //! use cranelift_codegen::settings::{self, Configurable};
26 //! use std::str::FromStr;
27 //! use target_lexicon::Triple;
28 //!
29 //! let shared_builder = settings::builder();
30 //! let shared_flags = settings::Flags::new(shared_builder);
31 //!
32 //! match isa::lookup(triple!("x86_64")) {
33 //!     Err(_) => {
34 //!         // The x86_64 target ISA is not available.
35 //!     }
36 //!     Ok(mut isa_builder) => {
37 //!         isa_builder.set("use_popcnt", "on");
38 //!         let isa = isa_builder.finish(shared_flags);
39 //!     }
40 //! }
41 //! ```
42 //!
43 //! The configured target ISA trait object is a `Box<TargetIsa>` which can be used for multiple
44 //! concurrent function compilations.
45 
46 pub use crate::isa::call_conv::CallConv;
47 
48 use crate::flowgraph;
49 use crate::ir::{self, Function};
50 #[cfg(feature = "unwind")]
51 use crate::isa::unwind::systemv::RegisterMappingError;
52 use crate::machinst::{CompiledCode, TextSectionBuilder, UnwindInfoKind};
53 use crate::settings;
54 use crate::settings::SetResult;
55 use crate::CodegenResult;
56 use alloc::{boxed::Box, vec::Vec};
57 use core::fmt;
58 use core::fmt::{Debug, Formatter};
59 use target_lexicon::{triple, Architecture, OperatingSystem, PointerWidth, Triple};
60 
61 // This module is made public here for benchmarking purposes. No guarantees are
62 // made regarding API stability.
63 #[cfg(feature = "x86")]
64 pub mod x64;
65 
66 #[cfg(feature = "arm64")]
67 pub(crate) mod aarch64;
68 
69 #[cfg(feature = "s390x")]
70 mod s390x;
71 
72 pub mod unwind;
73 
74 mod call_conv;
75 
76 /// Returns a builder that can create a corresponding `TargetIsa`
77 /// or `Err(LookupError::SupportDisabled)` if not enabled.
78 macro_rules! isa_builder {
79     ($name: ident, $cfg_terms: tt, $triple: ident) => {{
80         #[cfg $cfg_terms]
81         {
82             Ok($name::isa_builder($triple))
83         }
84         #[cfg(not $cfg_terms)]
85         {
86             Err(LookupError::SupportDisabled)
87         }
88     }};
89 }
90 
91 /// Look for an ISA for the given `triple`.
92 /// Return a builder that can create a corresponding `TargetIsa`.
93 pub fn lookup(triple: Triple) -> Result<Builder, LookupError> {
94     match triple.architecture {
95         Architecture::X86_64 => {
96             isa_builder!(x64, (feature = "x86"), triple)
97         }
98         Architecture::Aarch64 { .. } => isa_builder!(aarch64, (feature = "arm64"), triple),
99         Architecture::S390x { .. } => isa_builder!(s390x, (feature = "s390x"), triple),
100         _ => Err(LookupError::Unsupported),
101     }
102 }
103 
104 /// Look for a supported ISA with the given `name`.
105 /// Return a builder that can create a corresponding `TargetIsa`.
106 pub fn lookup_by_name(name: &str) -> Result<Builder, LookupError> {
107     use alloc::str::FromStr;
108     lookup(triple!(name))
109 }
110 
111 /// Describes reason for target lookup failure
112 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
113 pub enum LookupError {
114     /// Support for this target was disabled in the current build.
115     SupportDisabled,
116 
117     /// Support for this target has not yet been implemented.
118     Unsupported,
119 }
120 
121 // This is manually implementing Error and Display instead of using thiserror to reduce the amount
122 // of dependencies used by Cranelift.
123 impl std::error::Error for LookupError {}
124 
125 impl fmt::Display for LookupError {
126     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
127         match self {
128             LookupError::SupportDisabled => write!(f, "Support for this target is disabled"),
129             LookupError::Unsupported => {
130                 write!(f, "Support for this target has not been implemented yet")
131             }
132         }
133     }
134 }
135 
136 /// Builder for a `TargetIsa`.
137 /// Modify the ISA-specific settings before creating the `TargetIsa` trait object with `finish`.
138 #[derive(Clone)]
139 pub struct Builder {
140     triple: Triple,
141     setup: settings::Builder,
142     constructor:
143         fn(Triple, settings::Flags, settings::Builder) -> CodegenResult<Box<dyn TargetIsa>>,
144 }
145 
146 impl Builder {
147     /// Gets the triple for the builder.
148     pub fn triple(&self) -> &Triple {
149         &self.triple
150     }
151 
152     /// Iterates the available settings in the builder.
153     pub fn iter(&self) -> impl Iterator<Item = settings::Setting> {
154         self.setup.iter()
155     }
156 
157     /// Combine the ISA-specific settings with the provided
158     /// ISA-independent settings and allocate a fully configured
159     /// `TargetIsa` trait object. May return an error if some of the
160     /// flags are inconsistent or incompatible: for example, some
161     /// platform-independent features, like general SIMD support, may
162     /// need certain ISA extensions to be enabled.
163     pub fn finish(self, shared_flags: settings::Flags) -> CodegenResult<Box<dyn TargetIsa>> {
164         (self.constructor)(self.triple, shared_flags, self.setup)
165     }
166 }
167 
168 impl settings::Configurable for Builder {
169     fn set(&mut self, name: &str, value: &str) -> SetResult<()> {
170         self.setup.set(name, value)
171     }
172 
173     fn enable(&mut self, name: &str) -> SetResult<()> {
174         self.setup.enable(name)
175     }
176 }
177 
178 /// After determining that an instruction doesn't have an encoding, how should we proceed to
179 /// legalize it?
180 ///
181 /// The `Encodings` iterator returns a legalization function to call.
182 pub type Legalize =
183     fn(ir::Inst, &mut ir::Function, &mut flowgraph::ControlFlowGraph, &dyn TargetIsa) -> bool;
184 
185 /// This struct provides information that a frontend may need to know about a target to
186 /// produce Cranelift IR for the target.
187 #[derive(Clone, Copy, Hash)]
188 pub struct TargetFrontendConfig {
189     /// The default calling convention of the target.
190     pub default_call_conv: CallConv,
191 
192     /// The pointer width of the target.
193     pub pointer_width: PointerWidth,
194 }
195 
196 impl TargetFrontendConfig {
197     /// Get the pointer type of this target.
198     pub fn pointer_type(self) -> ir::Type {
199         ir::Type::int(self.pointer_bits() as u16).unwrap()
200     }
201 
202     /// Get the width of pointers on this target, in units of bits.
203     pub fn pointer_bits(self) -> u8 {
204         self.pointer_width.bits()
205     }
206 
207     /// Get the width of pointers on this target, in units of bytes.
208     pub fn pointer_bytes(self) -> u8 {
209         self.pointer_width.bytes()
210     }
211 }
212 
213 /// Methods that are specialized to a target ISA.
214 ///
215 /// Implies a Display trait that shows the shared flags, as well as any ISA-specific flags.
216 pub trait TargetIsa: fmt::Display + Send + Sync {
217     /// Get the name of this ISA.
218     fn name(&self) -> &'static str;
219 
220     /// Get the target triple that was used to make this trait object.
221     fn triple(&self) -> &Triple;
222 
223     /// Get the ISA-independent flags that were used to make this trait object.
224     fn flags(&self) -> &settings::Flags;
225 
226     /// Get the ISA-dependent flag values that were used to make this trait object.
227     fn isa_flags(&self) -> Vec<settings::Value>;
228 
229     /// Get the ISA-dependent maximum vector register size, in bytes.
230     fn dynamic_vector_bytes(&self, dynamic_ty: ir::Type) -> u32;
231 
232     /// Compile the given function.
233     fn compile_function(&self, func: &Function, want_disasm: bool) -> CodegenResult<CompiledCode>;
234 
235     #[cfg(feature = "unwind")]
236     /// Map a regalloc::Reg to its corresponding DWARF register.
237     fn map_regalloc_reg_to_dwarf(
238         &self,
239         _: crate::machinst::Reg,
240     ) -> Result<u16, RegisterMappingError> {
241         Err(RegisterMappingError::UnsupportedArchitecture)
242     }
243 
244     /// IntCC condition for Unsigned Addition Overflow (Carry).
245     fn unsigned_add_overflow_condition(&self) -> ir::condcodes::IntCC;
246 
247     /// Creates unwind information for the function.
248     ///
249     /// Returns `None` if there is no unwind information for the function.
250     #[cfg(feature = "unwind")]
251     fn emit_unwind_info(
252         &self,
253         result: &CompiledCode,
254         kind: UnwindInfoKind,
255     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>>;
256 
257     /// Creates a new System V Common Information Entry for the ISA.
258     ///
259     /// Returns `None` if the ISA does not support System V unwind information.
260     #[cfg(feature = "unwind")]
261     fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
262         // By default, an ISA cannot create a System V CIE
263         None
264     }
265 
266     /// Returns an object that can be used to build the text section of an
267     /// executable.
268     ///
269     /// This object will internally attempt to handle as many relocations as
270     /// possible using relative calls/jumps/etc between functions.
271     ///
272     /// The `num_labeled_funcs` argument here is the number of functions which
273     /// will be "labeled" or might have calls between them, typically the number
274     /// of defined functions in the object file.
275     fn text_section_builder(&self, num_labeled_funcs: u32) -> Box<dyn TextSectionBuilder>;
276 }
277 
278 /// Methods implemented for free for target ISA!
279 impl<'a> dyn TargetIsa + 'a {
280     /// Get the default calling convention of this target.
281     pub fn default_call_conv(&self) -> CallConv {
282         CallConv::triple_default(self.triple())
283     }
284 
285     /// Get the endianness of this ISA.
286     pub fn endianness(&self) -> ir::Endianness {
287         match self.triple().endianness().unwrap() {
288             target_lexicon::Endianness::Little => ir::Endianness::Little,
289             target_lexicon::Endianness::Big => ir::Endianness::Big,
290         }
291     }
292 
293     /// Returns the code (text) section alignment for this ISA.
294     pub fn code_section_alignment(&self) -> u64 {
295         use target_lexicon::*;
296         match (self.triple().operating_system, self.triple().architecture) {
297             (
298                 OperatingSystem::MacOSX { .. }
299                 | OperatingSystem::Darwin
300                 | OperatingSystem::Ios
301                 | OperatingSystem::Tvos,
302                 Architecture::Aarch64(..),
303             ) => 0x4000,
304             // 64 KB is the maximal page size (i.e. memory translation granule size)
305             // supported by the architecture and is used on some platforms.
306             (_, Architecture::Aarch64(..)) => 0x10000,
307             _ => 0x1000,
308         }
309     }
310 
311     /// Get the pointer type of this ISA.
312     pub fn pointer_type(&self) -> ir::Type {
313         ir::Type::int(self.pointer_bits() as u16).unwrap()
314     }
315 
316     /// Get the width of pointers on this ISA.
317     pub(crate) fn pointer_width(&self) -> PointerWidth {
318         self.triple().pointer_width().unwrap()
319     }
320 
321     /// Get the width of pointers on this ISA, in units of bits.
322     pub fn pointer_bits(&self) -> u8 {
323         self.pointer_width().bits()
324     }
325 
326     /// Get the width of pointers on this ISA, in units of bytes.
327     pub fn pointer_bytes(&self) -> u8 {
328         self.pointer_width().bytes()
329     }
330 
331     /// Get the information needed by frontends producing Cranelift IR.
332     pub fn frontend_config(&self) -> TargetFrontendConfig {
333         TargetFrontendConfig {
334             default_call_conv: self.default_call_conv(),
335             pointer_width: self.pointer_width(),
336         }
337     }
338 
339     /// Returns the flavor of unwind information emitted for this target.
340     pub(crate) fn unwind_info_kind(&self) -> UnwindInfoKind {
341         match self.triple().operating_system {
342             #[cfg(feature = "unwind")]
343             OperatingSystem::Windows => UnwindInfoKind::Windows,
344             #[cfg(feature = "unwind")]
345             _ => UnwindInfoKind::SystemV,
346             #[cfg(not(feature = "unwind"))]
347             _ => UnwindInfoKind::None,
348         }
349     }
350 }
351 
352 impl Debug for &dyn TargetIsa {
353     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
354         write!(
355             f,
356             "TargetIsa {{ triple: {:?}, pointer_width: {:?}}}",
357             self.triple(),
358             self.pointer_width()
359         )
360     }
361 }
362