cranelift_codegen/isa/mod.rs
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
46use crate::dominator_tree::DominatorTree;
47pub use crate::isa::call_conv::CallConv;
48
49use crate::flowgraph;
50use crate::ir::{self, Function, Type};
51#[cfg(feature = "unwind")]
52use crate::isa::unwind::{systemv::RegisterMappingError, UnwindInfoKind};
53use crate::machinst::{CompiledCode, CompiledCodeStencil, TextSectionBuilder};
54use crate::settings;
55use crate::settings::Configurable;
56use crate::settings::SetResult;
57use crate::CodegenResult;
58use alloc::{boxed::Box, sync::Arc, vec::Vec};
59use core::fmt;
60use core::fmt::{Debug, Formatter};
61use cranelift_control::ControlPlane;
62use target_lexicon::{triple, Architecture, PointerWidth, Triple};
63
64// This module is made public here for benchmarking purposes. No guarantees are
65// made regarding API stability.
66#[cfg(feature = "x86")]
67pub mod x64;
68
69#[cfg(feature = "arm64")]
70pub mod aarch64;
71
72#[cfg(feature = "riscv64")]
73pub mod riscv64;
74
75#[cfg(feature = "s390x")]
76mod s390x;
77
78#[cfg(feature = "pulley")]
79mod pulley32;
80#[cfg(feature = "pulley")]
81mod pulley64;
82#[cfg(feature = "pulley")]
83mod pulley_shared;
84
85pub mod unwind;
86
87mod call_conv;
88
89/// Returns a builder that can create a corresponding `TargetIsa`
90/// or `Err(LookupError::SupportDisabled)` if not enabled.
91macro_rules! isa_builder {
92 ($name: ident, $cfg_terms: tt, $triple: ident) => {{
93 #[cfg $cfg_terms]
94 {
95 Ok($name::isa_builder($triple))
96 }
97 #[cfg(not $cfg_terms)]
98 {
99 Err(LookupError::SupportDisabled)
100 }
101 }};
102}
103
104/// Look for an ISA for the given `triple`.
105/// Return a builder that can create a corresponding `TargetIsa`.
106pub fn lookup(triple: Triple) -> Result<Builder, LookupError> {
107 match triple.architecture {
108 Architecture::X86_64 => {
109 isa_builder!(x64, (feature = "x86"), triple)
110 }
111 Architecture::Aarch64 { .. } => isa_builder!(aarch64, (feature = "arm64"), triple),
112 Architecture::S390x { .. } => isa_builder!(s390x, (feature = "s390x"), triple),
113 Architecture::Riscv64 { .. } => isa_builder!(riscv64, (feature = "riscv64"), triple),
114 Architecture::Pulley32 => isa_builder!(pulley32, (feature = "pulley"), triple),
115 Architecture::Pulley64 => isa_builder!(pulley64, (feature = "pulley"), triple),
116 _ => Err(LookupError::Unsupported),
117 }
118}
119
120/// The string names of all the supported, but possibly not enabled, architectures. The elements of
121/// this slice are suitable to be passed to the [lookup_by_name] function to obtain the default
122/// configuration for that architecture.
123pub const ALL_ARCHITECTURES: &[&str] = &["x86_64", "aarch64", "s390x", "riscv64"];
124
125/// Look for a supported ISA with the given `name`.
126/// Return a builder that can create a corresponding `TargetIsa`.
127pub fn lookup_by_name(name: &str) -> Result<Builder, LookupError> {
128 lookup(triple!(name))
129}
130
131/// Describes reason for target lookup failure
132#[derive(PartialEq, Eq, Copy, Clone, Debug)]
133pub enum LookupError {
134 /// Support for this target was disabled in the current build.
135 SupportDisabled,
136
137 /// Support for this target has not yet been implemented.
138 Unsupported,
139}
140
141// This is manually implementing Error and Display instead of using thiserror to reduce the amount
142// of dependencies used by Cranelift.
143impl std::error::Error for LookupError {}
144
145impl fmt::Display for LookupError {
146 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
147 match self {
148 LookupError::SupportDisabled => write!(f, "Support for this target is disabled"),
149 LookupError::Unsupported => {
150 write!(f, "Support for this target has not been implemented yet")
151 }
152 }
153 }
154}
155
156/// The type of a polymorphic TargetISA object which is 'static.
157pub type OwnedTargetIsa = Arc<dyn TargetIsa>;
158
159/// Type alias of `IsaBuilder` used for building Cranelift's ISAs.
160pub type Builder = IsaBuilder<CodegenResult<OwnedTargetIsa>>;
161
162/// Builder for a `TargetIsa`.
163/// Modify the ISA-specific settings before creating the `TargetIsa` trait object with `finish`.
164#[derive(Clone)]
165pub struct IsaBuilder<T> {
166 triple: Triple,
167 setup: settings::Builder,
168 constructor: fn(Triple, settings::Flags, &settings::Builder) -> T,
169}
170
171impl<T> IsaBuilder<T> {
172 /// Creates a new ISA-builder from its components, namely the `triple` for
173 /// the ISA, the ISA-specific settings builder, and a final constructor
174 /// function to generate the ISA from its components.
175 pub fn new(
176 triple: Triple,
177 setup: settings::Builder,
178 constructor: fn(Triple, settings::Flags, &settings::Builder) -> T,
179 ) -> Self {
180 IsaBuilder {
181 triple,
182 setup,
183 constructor,
184 }
185 }
186
187 /// Creates a new [Builder] from a [TargetIsa], copying all flags in the
188 /// process.
189 pub fn from_target_isa(target_isa: &dyn TargetIsa) -> Builder {
190 // We should always be able to find the builder for the TargetISA, since presumably we
191 // also generated the previous TargetISA at some point
192 let triple = target_isa.triple().clone();
193 let mut builder = self::lookup(triple).expect("Could not find triple for target ISA");
194
195 // Copy ISA Flags
196 for flag in target_isa.isa_flags() {
197 builder.set(&flag.name, &flag.value_string()).unwrap();
198 }
199
200 builder
201 }
202
203 /// Gets the triple for the builder.
204 pub fn triple(&self) -> &Triple {
205 &self.triple
206 }
207
208 /// Iterates the available settings in the builder.
209 pub fn iter(&self) -> impl Iterator<Item = settings::Setting> {
210 self.setup.iter()
211 }
212
213 /// Combine the ISA-specific settings with the provided
214 /// ISA-independent settings and allocate a fully configured
215 /// `TargetIsa` trait object. May return an error if some of the
216 /// flags are inconsistent or incompatible: for example, some
217 /// platform-independent features, like general SIMD support, may
218 /// need certain ISA extensions to be enabled.
219 pub fn finish(&self, shared_flags: settings::Flags) -> T {
220 (self.constructor)(self.triple.clone(), shared_flags, &self.setup)
221 }
222}
223
224impl<T> settings::Configurable for IsaBuilder<T> {
225 fn set(&mut self, name: &str, value: &str) -> SetResult<()> {
226 self.setup.set(name, value)
227 }
228
229 fn enable(&mut self, name: &str) -> SetResult<()> {
230 self.setup.enable(name)
231 }
232}
233
234/// After determining that an instruction doesn't have an encoding, how should we proceed to
235/// legalize it?
236///
237/// The `Encodings` iterator returns a legalization function to call.
238pub type Legalize =
239 fn(ir::Inst, &mut ir::Function, &mut flowgraph::ControlFlowGraph, &dyn TargetIsa) -> bool;
240
241/// This struct provides information that a frontend may need to know about a target to
242/// produce Cranelift IR for the target.
243#[derive(Clone, Copy, Hash)]
244pub struct TargetFrontendConfig {
245 /// The default calling convention of the target.
246 pub default_call_conv: CallConv,
247
248 /// The pointer width of the target.
249 pub pointer_width: PointerWidth,
250
251 /// The log2 of the target's page size and alignment.
252 ///
253 /// Note that this may be an upper-bound that is larger than necessary for
254 /// some platforms since it may depend on runtime configuration.
255 pub page_size_align_log2: u8,
256}
257
258impl TargetFrontendConfig {
259 /// Get the pointer type of this target.
260 pub fn pointer_type(self) -> ir::Type {
261 ir::Type::int(self.pointer_bits() as u16).unwrap()
262 }
263
264 /// Get the width of pointers on this target, in units of bits.
265 pub fn pointer_bits(self) -> u8 {
266 self.pointer_width.bits()
267 }
268
269 /// Get the width of pointers on this target, in units of bytes.
270 pub fn pointer_bytes(self) -> u8 {
271 self.pointer_width.bytes()
272 }
273}
274
275/// Methods that are specialized to a target ISA.
276///
277/// Implies a Display trait that shows the shared flags, as well as any ISA-specific flags.
278pub trait TargetIsa: fmt::Display + Send + Sync {
279 /// Get the name of this ISA.
280 fn name(&self) -> &'static str;
281
282 /// Get the target triple that was used to make this trait object.
283 fn triple(&self) -> &Triple;
284
285 /// Get the ISA-independent flags that were used to make this trait object.
286 fn flags(&self) -> &settings::Flags;
287
288 /// Get the ISA-dependent flag values that were used to make this trait object.
289 fn isa_flags(&self) -> Vec<settings::Value>;
290
291 /// Get a flag indicating whether branch protection is enabled.
292 fn is_branch_protection_enabled(&self) -> bool {
293 false
294 }
295
296 /// Get the ISA-dependent maximum vector register size, in bytes.
297 fn dynamic_vector_bytes(&self, dynamic_ty: ir::Type) -> u32;
298
299 /// Compile the given function.
300 fn compile_function(
301 &self,
302 func: &Function,
303 domtree: &DominatorTree,
304 want_disasm: bool,
305 ctrl_plane: &mut ControlPlane,
306 ) -> CodegenResult<CompiledCodeStencil>;
307
308 #[cfg(feature = "unwind")]
309 /// Map a regalloc::Reg to its corresponding DWARF register.
310 fn map_regalloc_reg_to_dwarf(
311 &self,
312 _: crate::machinst::Reg,
313 ) -> Result<u16, RegisterMappingError> {
314 Err(RegisterMappingError::UnsupportedArchitecture)
315 }
316
317 /// Creates unwind information for the function.
318 ///
319 /// Returns `None` if there is no unwind information for the function.
320 #[cfg(feature = "unwind")]
321 fn emit_unwind_info(
322 &self,
323 result: &CompiledCode,
324 kind: UnwindInfoKind,
325 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>>;
326
327 /// Creates a new System V Common Information Entry for the ISA.
328 ///
329 /// Returns `None` if the ISA does not support System V unwind information.
330 #[cfg(feature = "unwind")]
331 fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
332 // By default, an ISA cannot create a System V CIE
333 None
334 }
335
336 /// Returns an object that can be used to build the text section of an
337 /// executable.
338 ///
339 /// This object will internally attempt to handle as many relocations as
340 /// possible using relative calls/jumps/etc between functions.
341 ///
342 /// The `num_labeled_funcs` argument here is the number of functions which
343 /// will be "labeled" or might have calls between them, typically the number
344 /// of defined functions in the object file.
345 fn text_section_builder(&self, num_labeled_funcs: usize) -> Box<dyn TextSectionBuilder>;
346
347 /// Returns the minimum function alignment and the preferred function
348 /// alignment, for performance, required by this ISA.
349 fn function_alignment(&self) -> FunctionAlignment;
350
351 /// The log2 of the target's page size and alignment.
352 ///
353 /// Note that this may be an upper-bound that is larger than necessary for
354 /// some platforms since it may depend on runtime configuration.
355 fn page_size_align_log2(&self) -> u8;
356
357 /// Create a polymorphic TargetIsa from this specific implementation.
358 fn wrapped(self) -> OwnedTargetIsa
359 where
360 Self: Sized + 'static,
361 {
362 Arc::new(self)
363 }
364
365 /// Generate a `Capstone` context for disassembling bytecode for this architecture.
366 #[cfg(feature = "disas")]
367 fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
368 Err(capstone::Error::UnsupportedArch)
369 }
370
371 /// Returns whether this ISA has a native fused-multiply-and-add instruction
372 /// for floats.
373 ///
374 /// Currently this only returns false on x86 when some native features are
375 /// not detected.
376 fn has_native_fma(&self) -> bool;
377
378 /// Returns whether the CLIF `x86_blendv` instruction is implemented for
379 /// this ISA for the specified type.
380 fn has_x86_blendv_lowering(&self, ty: Type) -> bool;
381
382 /// Returns whether the CLIF `x86_pshufb` instruction is implemented for
383 /// this ISA.
384 fn has_x86_pshufb_lowering(&self) -> bool;
385
386 /// Returns whether the CLIF `x86_pmulhrsw` instruction is implemented for
387 /// this ISA.
388 fn has_x86_pmulhrsw_lowering(&self) -> bool;
389
390 /// Returns whether the CLIF `x86_pmaddubsw` instruction is implemented for
391 /// this ISA.
392 fn has_x86_pmaddubsw_lowering(&self) -> bool;
393}
394
395/// Function alignment specifications as required by an ISA, returned by
396/// [`TargetIsa::function_alignment`].
397#[derive(Copy, Clone)]
398pub struct FunctionAlignment {
399 /// The minimum alignment required by an ISA, where all functions must be
400 /// aligned to at least this amount.
401 pub minimum: u32,
402 /// A "preferred" alignment which should be used for more
403 /// performance-sensitive situations. This can involve cache-line-aligning
404 /// for example to get more of a small function into fewer cache lines.
405 pub preferred: u32,
406}
407
408/// Methods implemented for free for target ISA!
409impl<'a> dyn TargetIsa + 'a {
410 /// Get the default calling convention of this target.
411 pub fn default_call_conv(&self) -> CallConv {
412 CallConv::triple_default(self.triple())
413 }
414
415 /// Get the endianness of this ISA.
416 pub fn endianness(&self) -> ir::Endianness {
417 match self.triple().endianness().unwrap() {
418 target_lexicon::Endianness::Little => ir::Endianness::Little,
419 target_lexicon::Endianness::Big => ir::Endianness::Big,
420 }
421 }
422
423 /// Returns the minimum symbol alignment for this ISA.
424 pub fn symbol_alignment(&self) -> u64 {
425 match self.triple().architecture {
426 // All symbols need to be aligned to at least 2 on s390x.
427 Architecture::S390x => 2,
428 _ => 1,
429 }
430 }
431
432 /// Get the pointer type of this ISA.
433 pub fn pointer_type(&self) -> ir::Type {
434 ir::Type::int(self.pointer_bits() as u16).unwrap()
435 }
436
437 /// Get the width of pointers on this ISA.
438 pub(crate) fn pointer_width(&self) -> PointerWidth {
439 self.triple().pointer_width().unwrap()
440 }
441
442 /// Get the width of pointers on this ISA, in units of bits.
443 pub fn pointer_bits(&self) -> u8 {
444 self.pointer_width().bits()
445 }
446
447 /// Get the width of pointers on this ISA, in units of bytes.
448 pub fn pointer_bytes(&self) -> u8 {
449 self.pointer_width().bytes()
450 }
451
452 /// Get the information needed by frontends producing Cranelift IR.
453 pub fn frontend_config(&self) -> TargetFrontendConfig {
454 TargetFrontendConfig {
455 default_call_conv: self.default_call_conv(),
456 pointer_width: self.pointer_width(),
457 page_size_align_log2: self.page_size_align_log2(),
458 }
459 }
460}
461
462impl Debug for &dyn TargetIsa {
463 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
464 write!(
465 f,
466 "TargetIsa {{ triple: {:?}, pointer_width: {:?}}}",
467 self.triple(),
468 self.pointer_width()
469 )
470 }
471}