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