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, CompiledCodeStencil, 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(
234         &self,
235         func: &Function,
236         want_disasm: bool,
237     ) -> CodegenResult<CompiledCodeStencil>;
238 
239     #[cfg(feature = "unwind")]
240     /// Map a regalloc::Reg to its corresponding DWARF register.
241     fn map_regalloc_reg_to_dwarf(
242         &self,
243         _: crate::machinst::Reg,
244     ) -> Result<u16, RegisterMappingError> {
245         Err(RegisterMappingError::UnsupportedArchitecture)
246     }
247 
248     /// IntCC condition for Unsigned Addition Overflow (Carry).
249     fn unsigned_add_overflow_condition(&self) -> ir::condcodes::IntCC;
250 
251     /// Creates unwind information for the function.
252     ///
253     /// Returns `None` if there is no unwind information for the function.
254     #[cfg(feature = "unwind")]
255     fn emit_unwind_info(
256         &self,
257         result: &CompiledCode,
258         kind: UnwindInfoKind,
259     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>>;
260 
261     /// Creates a new System V Common Information Entry for the ISA.
262     ///
263     /// Returns `None` if the ISA does not support System V unwind information.
264     #[cfg(feature = "unwind")]
265     fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
266         // By default, an ISA cannot create a System V CIE
267         None
268     }
269 
270     /// Returns an object that can be used to build the text section of an
271     /// executable.
272     ///
273     /// This object will internally attempt to handle as many relocations as
274     /// possible using relative calls/jumps/etc between functions.
275     ///
276     /// The `num_labeled_funcs` argument here is the number of functions which
277     /// will be "labeled" or might have calls between them, typically the number
278     /// of defined functions in the object file.
279     fn text_section_builder(&self, num_labeled_funcs: u32) -> Box<dyn TextSectionBuilder>;
280 }
281 
282 /// Methods implemented for free for target ISA!
283 impl<'a> dyn TargetIsa + 'a {
284     /// Get the default calling convention of this target.
285     pub fn default_call_conv(&self) -> CallConv {
286         CallConv::triple_default(self.triple())
287     }
288 
289     /// Get the endianness of this ISA.
290     pub fn endianness(&self) -> ir::Endianness {
291         match self.triple().endianness().unwrap() {
292             target_lexicon::Endianness::Little => ir::Endianness::Little,
293             target_lexicon::Endianness::Big => ir::Endianness::Big,
294         }
295     }
296 
297     /// Returns the code (text) section alignment for this ISA.
298     pub fn code_section_alignment(&self) -> u64 {
299         use target_lexicon::*;
300         match (self.triple().operating_system, self.triple().architecture) {
301             (
302                 OperatingSystem::MacOSX { .. }
303                 | OperatingSystem::Darwin
304                 | OperatingSystem::Ios
305                 | OperatingSystem::Tvos,
306                 Architecture::Aarch64(..),
307             ) => 0x4000,
308             // 64 KB is the maximal page size (i.e. memory translation granule size)
309             // supported by the architecture and is used on some platforms.
310             (_, Architecture::Aarch64(..)) => 0x10000,
311             _ => 0x1000,
312         }
313     }
314 
315     /// Returns the minimum symbol alignment for this ISA.
316     pub fn symbol_alignment(&self) -> u64 {
317         match self.triple().architecture {
318             // All symbols need to be aligned to at least 2 on s390x.
319             Architecture::S390x => 2,
320             _ => 1,
321         }
322     }
323 
324     /// Get the pointer type of this ISA.
325     pub fn pointer_type(&self) -> ir::Type {
326         ir::Type::int(self.pointer_bits() as u16).unwrap()
327     }
328 
329     /// Get the width of pointers on this ISA.
330     pub(crate) fn pointer_width(&self) -> PointerWidth {
331         self.triple().pointer_width().unwrap()
332     }
333 
334     /// Get the width of pointers on this ISA, in units of bits.
335     pub fn pointer_bits(&self) -> u8 {
336         self.pointer_width().bits()
337     }
338 
339     /// Get the width of pointers on this ISA, in units of bytes.
340     pub fn pointer_bytes(&self) -> u8 {
341         self.pointer_width().bytes()
342     }
343 
344     /// Get the information needed by frontends producing Cranelift IR.
345     pub fn frontend_config(&self) -> TargetFrontendConfig {
346         TargetFrontendConfig {
347             default_call_conv: self.default_call_conv(),
348             pointer_width: self.pointer_width(),
349         }
350     }
351 
352     /// Returns the flavor of unwind information emitted for this target.
353     pub(crate) fn unwind_info_kind(&self) -> UnwindInfoKind {
354         match self.triple().operating_system {
355             #[cfg(feature = "unwind")]
356             OperatingSystem::Windows => UnwindInfoKind::Windows,
357             #[cfg(feature = "unwind")]
358             _ => UnwindInfoKind::SystemV,
359             #[cfg(not(feature = "unwind"))]
360             _ => UnwindInfoKind::None,
361         }
362     }
363 }
364 
365 impl Debug for &dyn TargetIsa {
366     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
367         write!(
368             f,
369             "TargetIsa {{ triple: {:?}, pointer_width: {:?}}}",
370             self.triple(),
371             self.pointer_width()
372         )
373     }
374 }
375