cranelift_native/
lib.rs

1//! Performs autodetection of the host for the purposes of running
2//! Cranelift to generate code to run on the same machine.
3
4#![deny(
5    missing_docs,
6    trivial_numeric_casts,
7    unused_extern_crates,
8    unstable_features
9)]
10#![warn(unused_import_braces)]
11#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
12#![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))]
13#![cfg_attr(
14    feature = "cargo-clippy",
15    warn(
16        clippy::float_arithmetic,
17        clippy::mut_mut,
18        clippy::nonminimal_bool,
19        clippy::map_unwrap_or,
20        clippy::clippy::print_stdout,
21        clippy::unicode_not_nfc,
22        clippy::use_self
23    )
24)]
25
26use cranelift_codegen::isa;
27use cranelift_codegen::settings::Configurable;
28use target_lexicon::Triple;
29
30/// Return an `isa` builder configured for the current host
31/// machine, or `Err(())` if the host machine is not supported
32/// in the current configuration.
33pub fn builder() -> Result<isa::Builder, &'static str> {
34    builder_with_options(true)
35}
36
37/// Return an `isa` builder configured for the current host
38/// machine, or `Err(())` if the host machine is not supported
39/// in the current configuration.
40///
41/// Selects the given backend variant specifically; this is
42/// useful when more than oen backend exists for a given target
43/// (e.g., on x86-64).
44pub fn builder_with_options(infer_native_flags: bool) -> Result<isa::Builder, &'static str> {
45    let mut isa_builder = isa::lookup(Triple::host()).map_err(|err| match err {
46        isa::LookupError::SupportDisabled => "support for architecture disabled at compile time",
47        isa::LookupError::Unsupported => "unsupported architecture",
48    })?;
49    if infer_native_flags {
50        self::infer_native_flags(&mut isa_builder)?;
51    }
52    Ok(isa_builder)
53}
54
55/// Return an `isa` builder configured for the current host
56/// machine, or `Err(())` if the host machine is not supported
57/// in the current configuration.
58///
59/// Selects the given backend variant specifically; this is
60/// useful when more than oen backend exists for a given target
61/// (e.g., on x86-64).
62pub fn infer_native_flags(isa_builder: &mut dyn Configurable) -> Result<(), &'static str> {
63    #[cfg(target_arch = "x86_64")]
64    {
65        if !std::is_x86_feature_detected!("sse2") {
66            return Err("x86 support requires SSE2");
67        }
68
69        // These are temporarily enabled by default (see #3810 for
70        // more) so that a default-constructed `Flags` can work with
71        // default Wasmtime features. Otherwise, the user must
72        // explicitly use native flags or turn these on when on x86-64
73        // platforms to avoid a configuration panic. In order for the
74        // "enable if detected" logic below to work, we must turn them
75        // *off* (differing from the default) and then re-enable below
76        // if present.
77        isa_builder.set("has_sse3", "false").unwrap();
78        isa_builder.set("has_ssse3", "false").unwrap();
79        isa_builder.set("has_sse41", "false").unwrap();
80        isa_builder.set("has_sse42", "false").unwrap();
81
82        if std::is_x86_feature_detected!("sse3") {
83            isa_builder.enable("has_sse3").unwrap();
84        }
85        if std::is_x86_feature_detected!("ssse3") {
86            isa_builder.enable("has_ssse3").unwrap();
87        }
88        if std::is_x86_feature_detected!("sse4.1") {
89            isa_builder.enable("has_sse41").unwrap();
90        }
91        if std::is_x86_feature_detected!("sse4.2") {
92            isa_builder.enable("has_sse42").unwrap();
93        }
94        if std::is_x86_feature_detected!("popcnt") {
95            isa_builder.enable("has_popcnt").unwrap();
96        }
97        if std::is_x86_feature_detected!("avx") {
98            isa_builder.enable("has_avx").unwrap();
99        }
100        if std::is_x86_feature_detected!("avx2") {
101            isa_builder.enable("has_avx2").unwrap();
102        }
103        if std::is_x86_feature_detected!("fma") {
104            isa_builder.enable("has_fma").unwrap();
105        }
106        if std::is_x86_feature_detected!("bmi1") {
107            isa_builder.enable("has_bmi1").unwrap();
108        }
109        if std::is_x86_feature_detected!("bmi2") {
110            isa_builder.enable("has_bmi2").unwrap();
111        }
112        if std::is_x86_feature_detected!("avx512bitalg") {
113            isa_builder.enable("has_avx512bitalg").unwrap();
114        }
115        if std::is_x86_feature_detected!("avx512dq") {
116            isa_builder.enable("has_avx512dq").unwrap();
117        }
118        if std::is_x86_feature_detected!("avx512f") {
119            isa_builder.enable("has_avx512f").unwrap();
120        }
121        if std::is_x86_feature_detected!("avx512vl") {
122            isa_builder.enable("has_avx512vl").unwrap();
123        }
124        if std::is_x86_feature_detected!("avx512vbmi") {
125            isa_builder.enable("has_avx512vbmi").unwrap();
126        }
127        if std::is_x86_feature_detected!("lzcnt") {
128            isa_builder.enable("has_lzcnt").unwrap();
129        }
130    }
131
132    #[cfg(target_arch = "aarch64")]
133    {
134        if std::arch::is_aarch64_feature_detected!("lse") {
135            isa_builder.enable("has_lse").unwrap();
136        }
137
138        if std::arch::is_aarch64_feature_detected!("paca") {
139            isa_builder.enable("has_pauth").unwrap();
140        }
141
142        if cfg!(target_os = "macos") {
143            // Pointer authentication is always available on Apple Silicon.
144            isa_builder.enable("sign_return_address").unwrap();
145            // macOS enforces the use of the B key for return addresses.
146            isa_builder.enable("sign_return_address_with_bkey").unwrap();
147        }
148    }
149
150    // There is no is_s390x_feature_detected macro yet, so for now
151    // we use getauxval from the libc crate directly.
152    #[cfg(all(target_arch = "s390x", target_os = "linux"))]
153    {
154        let v = unsafe { libc::getauxval(libc::AT_HWCAP) };
155        const HWCAP_S390X_VXRS_EXT2: libc::c_ulong = 32768;
156        if (v & HWCAP_S390X_VXRS_EXT2) != 0 {
157            isa_builder.enable("has_vxrs_ext2").unwrap();
158            // There is no separate HWCAP bit for mie2, so assume
159            // that any machine with vxrs_ext2 also has mie2.
160            isa_builder.enable("has_mie2").unwrap();
161        }
162    }
163
164    // `is_riscv_feature_detected` is nightly only for now, use
165    // getauxval from the libc crate directly as a temporary measure.
166    #[cfg(all(target_arch = "riscv64", target_os = "linux"))]
167    {
168        let v = unsafe { libc::getauxval(libc::AT_HWCAP) };
169
170        const HWCAP_RISCV_EXT_A: libc::c_ulong = 1 << (b'a' - b'a');
171        const HWCAP_RISCV_EXT_C: libc::c_ulong = 1 << (b'c' - b'a');
172        const HWCAP_RISCV_EXT_D: libc::c_ulong = 1 << (b'd' - b'a');
173        const HWCAP_RISCV_EXT_F: libc::c_ulong = 1 << (b'f' - b'a');
174        const HWCAP_RISCV_EXT_M: libc::c_ulong = 1 << (b'm' - b'a');
175        const HWCAP_RISCV_EXT_V: libc::c_ulong = 1 << (b'v' - b'a');
176
177        if (v & HWCAP_RISCV_EXT_A) != 0 {
178            isa_builder.enable("has_a").unwrap();
179        }
180
181        if (v & HWCAP_RISCV_EXT_C) != 0 {
182            isa_builder.enable("has_c").unwrap();
183        }
184
185        if (v & HWCAP_RISCV_EXT_D) != 0 {
186            isa_builder.enable("has_d").unwrap();
187        }
188
189        if (v & HWCAP_RISCV_EXT_F) != 0 {
190            isa_builder.enable("has_f").unwrap();
191
192            // TODO: There doesn't seem to be a bit associated with this extension
193            // rust enables it with the `f` extension:
194            // https://github.com/rust-lang/stdarch/blob/790411f93c4b5eada3c23abb4c9a063fb0b24d99/crates/std_detect/src/detect/os/linux/riscv.rs#L43
195            isa_builder.enable("has_zicsr").unwrap();
196        }
197
198        if (v & HWCAP_RISCV_EXT_M) != 0 {
199            isa_builder.enable("has_m").unwrap();
200        }
201
202        if (v & HWCAP_RISCV_EXT_V) != 0 {
203            isa_builder.enable("has_v").unwrap();
204        }
205
206        // In general extensions that are longer than one letter
207        // won't have a bit associated with them. The Linux kernel
208        // is currently working on a new way to query the extensions.
209    }
210    Ok(())
211}
212
213#[cfg(test)]
214mod tests {
215    use super::builder;
216    use cranelift_codegen::isa::CallConv;
217    use cranelift_codegen::settings;
218
219    #[test]
220    fn test() {
221        if let Ok(isa_builder) = builder() {
222            let flag_builder = settings::builder();
223            let isa = isa_builder
224                .finish(settings::Flags::new(flag_builder))
225                .unwrap();
226
227            if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
228                assert_eq!(isa.default_call_conv(), CallConv::AppleAarch64);
229            } else if cfg!(any(unix, target_os = "nebulet")) {
230                assert_eq!(isa.default_call_conv(), CallConv::SystemV);
231            } else if cfg!(windows) {
232                assert_eq!(isa.default_call_conv(), CallConv::WindowsFastcall);
233            }
234
235            if cfg!(target_pointer_width = "64") {
236                assert_eq!(isa.pointer_bits(), 64);
237            } else if cfg!(target_pointer_width = "32") {
238                assert_eq!(isa.pointer_bits(), 32);
239            } else if cfg!(target_pointer_width = "16") {
240                assert_eq!(isa.pointer_bits(), 16);
241            }
242        }
243    }
244}
245
246/// Version number of this crate.
247pub const VERSION: &str = env!("CARGO_PKG_VERSION");