Skip to main content

fearless_simd/
lib.rs

1// Copyright 2024 the Fearless_SIMD Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4// After you edit the crate's doc comment, run this command, then check README.md for any missing links
5// cargo rdme --workspace-project=fearless_simd
6
7//! `fearless_simd` takes `unsafe` out of SIMD.
8//!
9//! No matter what level of abstraction you're after, be it autovectorization and multiversioning, or portable SIMD, or safe access to raw
10//! intrinsics and nothing more, `fearless_simd` has you covered!
11//!
12//! The core crate has zero dependencies, safe public APIs, and
13//! [very little](https://shnatsel.github.io/safe-simd-in-rust-even-on-the-inside/)
14//! `unsafe` under the hood.
15//!
16//! # Usage
17//!
18//! Add the core library and optional `#[simd]` macro to your `Cargo.toml`:
19//!
20//! ```toml
21//! [dependencies]
22//! fearless_simd = "1.0"
23//! fearless_simd_macros = "0.1"
24//! ```
25//!
26//! # Automatic vectorization
27//!
28//! The easiest way to define a SIMD-generic function is the
29//! [`#[simd]`](https://docs.rs/fearless_simd_macros/latest/fearless_simd_macros/attr.simd.html)
30//! attribute from the separately versioned `fearless_simd_macros` crate. The companion macro
31//! crate is optional: `fearless_simd` does not depend on it, so users of only the core API do not
32//! pay for its procedural-macro dependencies.
33//!
34//! [`dispatch!`] generates implementations for the available SIMD levels and selects the best one
35//! at runtime:
36//!
37//! ```ignore
38//! use fearless_simd::{dispatch, Level, Simd};
39//! use fearless_simd_macros::simd;
40//!
41//! #[simd]
42//! fn double_u32s<S: Simd>(_: S, values: &mut [u32]) {
43//!     for value in values {
44//!         *value = *value * 2;
45//!     }
46//! }
47//!
48//! let mut values = [1, 2, 3, 4, 5];
49//! let level = Level::new();
50//! dispatch!(level, simd => double_u32s(simd, &mut values));
51//! assert_eq!(values, [2, 4, 6, 8, 10]);
52//! ```
53//!
54//! # Portable SIMD
55//!
56//! Use the vector types for explicit lane-wise operations while staying generic over the SIMD level:
57//!
58//! ```ignore
59//! use fearless_simd::{dispatch, prelude::*, Level};
60//! use fearless_simd_macros::simd;
61//!
62//! #[simd]
63//! fn double_u32s<S: Simd>(simd: S, values: &mut [u32]) {
64//!     let mut chunks = values.chunks_exact_mut(S::u32s::LEN); // the CPU's native SIMD width
65//!     for chunk in &mut chunks {
66//!         let v = S::u32s::from_slice(simd, chunk);
67//!         (v * 2).store_slice(chunk);
68//!     }
69//!     for value in chunks.into_remainder() {
70//!         *value = *value * 2;
71//!     }
72//! }
73//!
74//! let mut values = [1, 2, 3, 4, 5];
75//! let level = Level::new();
76//! dispatch!(level, simd => double_u32s(simd, &mut values));
77//! assert_eq!(values, [2, 4, 6, 8, 10]);
78//! ```
79//!
80//! You can also use fixed-size types such as [u32x8] instead of using the hardware's native SIMD width.
81//!
82//! # Explicit intrinsics
83//!
84//! If you need access to raw intrinsics, [`kernel!`][kernel] creates a function where they can be called safely:
85//!
86//! ```rust
87//! use fearless_simd::{prelude::*, Level, u32x4};
88//!
89//! fearless_simd::kernel!(
90//!     fn double_u32s_neon(neon: Neon, values: &mut [u32]) {
91//!         use core::arch::aarch64::*;
92//!
93//!         let mut chunks = values.chunks_exact_mut(4);
94//!         for chunk in &mut chunks {
95//!             let v: uint32x4_t = u32x4::from_slice(neon, chunk).into(); // safe load
96//!             let doubled = vmulq_u32(v, vdupq_n_u32(2)); // safe access to a NEON intrinsic
97//!             let doubled: u32x4<_> = doubled.simd_into(neon);
98//!             doubled.store_slice(chunk);
99//!         }
100//!         for value in chunks.into_remainder() {
101//!             *value = *value * 2;
102//!         }
103//!     }
104//! );
105//!
106//! #[cfg(target_arch = "aarch64")]
107//! {
108//!     let level = Level::new();
109//!     if let Some(neon) = level.as_neon() {
110//!         let mut values = [1, 2, 3, 4, 5];
111//!         double_u32s_neon(neon, &mut values);
112//!         assert_eq!(values, [2, 4, 6, 8, 10]);
113//!     }
114//! }
115//! ```
116//!
117//! You can also [mix and match](https://github.com/linebender/fearless_simd/blob/main/fearless_simd/examples/srgb.rs)
118//! intrinsics with the other approaches, using high-level code most of the time and dropping down to
119//! hardware-specific intrinsics only when necessary.
120//!
121//! ## The `#[simd]` annotation
122//!
123//! It is recommended to annotate functions that use SIMD with the `#[simd]` attribute from the `fearless_simd_macros` crate. Without it the code will still compile, but requires special care to achieve full performance.
124//!
125//! If you cannot use proc macros, [you can achieve the same effect manually](https://github.com/linebender/fearless_simd/blob/main/fearless_simd/MANUAL_INLINING.md), but it requires some care. The use of `#[simd]` is recommended as the more robust and ergonomic option.
126//!
127//! # Instruction set support
128//!
129//! - x86/x86-64: SSE2 baseline, [v2](https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels) (SSE4.2), [v3](https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels) (AVX2), [Ice Lake](https://en.wikipedia.org/wiki/AVX-512#CPUs_with_AVX-512) (AVX-512, avoiding early slow implementations)
130//! - Aarch64: Baseline [NEON](https://en.wikipedia.org/wiki/Arm_architecture_family#Advanced_SIMD_(Neon))
131//! - WebAssembly: [128-bit packed SIMD](https://github.com/WebAssembly/spec/blob/main/proposals/simd/SIMD.md), [relaxed SIMD](https://github.com/WebAssembly/relaxed-simd/blob/main/proposals/relaxed-simd/Overview.md)
132//!
133//! A scalar fallback is also provided for platforms, so your code still works even if SIMD is not available.
134//!
135//! # WebAssembly
136//!
137//! WASM SIMD doesn't have feature detection, and so you need to compile two versions of your bundle for WASM, one with SIMD and one without,
138//! then select the appropriate one for your user's browser. This can be done via [the `wasm-feature-detect`
139//! library](https://github.com/GoogleChromeLabs/wasm-feature-detect).
140//!
141//! You can compile WebAssembly with the SIMD128 feature enabled via the `RUSTFLAGS` environment variable
142//! (`RUSTFLAGS="-Ctarget-feature=+simd128"`), or by adding the compiler flags in your [Cargo
143//! config.toml](https://doc.rust-lang.org/cargo/reference/config.html):
144//!
145//! ```toml
146//! [target.'cfg(target_arch = "wasm32")']
147//! rustflags = ["-Ctarget-feature=+simd128"]
148//! rustdocflags = ["-Ctarget-feature=+simd128"]
149//! ```
150//!
151//! If you want to compile both SIMD and non-SIMD versions of your WebAssembly library, your best option right now is to create a shell script
152//! that builds it once with the `RUSTFLAGS` specified, and once without. [Cargo currently does not allow specifying compiler flags
153//! per-profile.](https://github.com/rust-lang/cargo/issues/10271)
154//!
155//! ## Relaxed SIMD
156//!
157//! Fearless SIMD can make use of the [relaxed SIMD](https://github.com/WebAssembly/relaxed-simd/blob/main/proposals/relaxed-simd/Overview.md)
158//! WebAssembly instructions, if the requisite target feature is enabled. These instructions can return implementation-dependent results
159//! depending on what is fastest on the underlying hardware. They are only used for operations where we already give hardware-dependent results.
160//!
161//! At the time of writing, relaxed SIMD is only supported in Chrome. To make use of it, you'll need to build two versions of your library, one
162//! with relaxed SIMD enabled (`RUSTFLAGS="-Ctarget-feature=+simd128,+relaxed-simd"`) and one with it disabled, and then feature-detect at
163//! runtime.
164//!
165//! # Multiversioning on x86
166//!
167//! x86 CPUs are not guaranteed to have any SIMD particular instruction set, so `fearless_simd` compiles a version
168//! of each function generic over [`Simd`] for each instruction set, and [`dispatch`] selects the best one at runtime.
169//!
170//! This is necessary to take advantage of SIMD, but results in an increased binary size on x86.
171//! If binary size is a concern, the increase can be partially mitigated by setting
172//! [`codegen-units=1`](https://nnethercote.github.io/perf-book/build-configuration.html#codegen-units)
173//! or [`lto=true`](https://nnethercote.github.io/perf-book/build-configuration.html#link-time-optimization) in your Cargo.toml,
174//! at the cost of longer build times.
175//!
176//! As a last resort, you can turn off multiversioning for specific SIMD instruction sets by passing
177//! `--cfg disable_dispatch_sse2`, `--cfg disable_dispatch_sse4_2`, `--cfg disable_dispatch_avx2`, or `--cfg disable_dispatch_avx512` in `RUSTFLAGS`.
178//! These configuration flags only control automatic multiversioning. Disabling one does not remove its token type, its
179//! [`Simd`] implementation, or explicit [`kernel`] support; for example, an `Avx2` token can still be used to call an
180//! AVX2 kernel when the CPU supports it.
181//! `disable_dispatch_sse2` has no effect when SSE2 is part of the ambient target baseline, because
182//! that baseline remains the terminal dispatch backend.
183//!
184//! Note that later extensions can be beneficial even if you are only using 128-bit vectors:
185//! AVX2 and AVX-512 provide more efficient instructions for some operations,
186//! and AVX-512 also more than doubles the number of vector registers of all sizes.
187//!
188//! You can also [disable certain instruction sets for select functions](https://github.com/linebender/fearless_simd/blob/main/fearless_simd/examples/disable_avx2_for_one_function.rs)
189//! without disabling them globally.
190//!
191//! # Feature Flags
192//!
193//! The following crate [feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) are available:
194//!
195//! - `std` (enabled by default): Get floating point functions from the standard library (likely using your target's libc).
196//!   Also allows using [`Level::new`] on all platforms, to detect which target features are enabled.
197//! - `libm`: Use floating point implementations from [libm]. Useful for `#[no_std]`.
198//! - `force_support_fallback`: Force scalar fallback, to be supported, even if your compilation target has a better baseline.
199//!
200//! At least one of `std` and `libm` is required; `std` overrides `libm`.
201//!
202//! # Credits
203//!
204//! This crate was inspired by [`pulp`], [`std::simd`], among others in the Rust ecosystem, though makes many decisions differently.
205//! It benefited from conversations with Luca Versari, though he is not responsible for any of the mistakes or bad decisions.
206//!
207//! [`pulp`]: https://crates.io/crates/pulp
208#![cfg_attr(feature = "libm", doc = "[libm]: libm")]
209#![cfg_attr(not(feature = "libm"), doc = "[libm]: https://crates.io/crates/libm")]
210// LINEBENDER LINT SET - lib.rs - v3
211// See https://linebender.org/wiki/canonical-lints/
212// These lints shouldn't apply to examples or tests.
213#![cfg_attr(not(test), warn(unused_crate_dependencies))]
214// These lints shouldn't apply to examples.
215#![warn(clippy::print_stdout, clippy::print_stderr)]
216// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit.
217#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))]
218// END LINEBENDER LINT SET
219#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
220#![cfg_attr(docsrs, feature(doc_cfg))]
221#![allow(non_camel_case_types, reason = "TODO")]
222#![expect(clippy::unused_unit, reason = "easier for code generation")]
223#![no_std]
224
225#[cfg(feature = "std")]
226extern crate std;
227
228#[cfg(all(not(feature = "libm"), not(feature = "std")))]
229compile_error!("fearless_simd requires either the `std` or `libm` feature");
230
231// Some native SIMD backends do not need libm unless fallback support is also enabled.
232// Keep the optional dependency marked as used for every supported target configuration.
233#[cfg(feature = "libm")]
234use libm as _;
235
236mod generated;
237mod kernel_macros;
238mod macros;
239mod support;
240mod traits;
241mod transmute;
242
243pub use generated::*;
244pub use traits::*;
245
246/// This prelude module re-exports every SIMD trait defined in this library. It's useful for accessing trait methods.
247///
248/// Only traits are exported through the prelude; types must be exported separately.
249pub mod prelude {
250    pub use crate::generated::simd_trait::*;
251    pub use crate::traits::*;
252}
253
254/// Implementations of [`Simd`] for 64 bit ARM.
255#[cfg(target_arch = "aarch64")]
256pub mod aarch64 {
257    pub use crate::generated::Neon;
258}
259
260/// Implementations of [`Simd`] for webassembly.
261#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
262pub mod wasm32 {
263    pub use crate::generated::WasmSimd128;
264}
265
266/// Implementations of [`Simd`] on x86 architectures (both 32 and 64 bit).
267#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
268pub mod x86 {
269    pub use crate::generated::Avx2;
270    pub use crate::generated::Avx512;
271    pub use crate::generated::Sse2;
272    pub use crate::generated::Sse4_2;
273}
274
275#[cfg(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))]
276use std::sync::LazyLock;
277
278#[cfg(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))]
279/// Caches the CPU level detection on x86.
280// Aligned128 is used to avoid the data crossing cache line boundary,
281// which would incur two cache misses instead of one.
282static X86_LEVEL: support::Aligned128<LazyLock<Level>> =
283    support::Aligned128(LazyLock::new(detect_x86_level));
284
285// Sourced from `rustc --print=cfg --target x86_64-unknown-linux-gnu -C target-cpu=icelake-server`
286// and pruned against the features implied by `avx512f` which can be viewed via
287// `rustc --print=cfg --target x86_64-unknown-linux-gnu -C target-feature='+avx2'`
288#[cfg(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))]
289#[inline]
290fn x86_detects_icelake_avx512() -> bool {
291    std::arch::is_x86_feature_detected!("adx")
292        && std::arch::is_x86_feature_detected!("aes")
293        && std::arch::is_x86_feature_detected!("avx512bitalg")
294        && std::arch::is_x86_feature_detected!("avx512bw")
295        && std::arch::is_x86_feature_detected!("avx512cd")
296        && std::arch::is_x86_feature_detected!("avx512dq")
297        && std::arch::is_x86_feature_detected!("avx512f")
298        && std::arch::is_x86_feature_detected!("avx512ifma")
299        && std::arch::is_x86_feature_detected!("avx512vbmi")
300        && std::arch::is_x86_feature_detected!("avx512vbmi2")
301        && std::arch::is_x86_feature_detected!("avx512vl")
302        && std::arch::is_x86_feature_detected!("avx512vnni")
303        && std::arch::is_x86_feature_detected!("avx512vpopcntdq")
304        && std::arch::is_x86_feature_detected!("bmi1")
305        && std::arch::is_x86_feature_detected!("bmi2")
306        && std::arch::is_x86_feature_detected!("cmpxchg16b")
307        && std::arch::is_x86_feature_detected!("fma")
308        && std::arch::is_x86_feature_detected!("fxsr")
309        && std::arch::is_x86_feature_detected!("gfni")
310        && std::arch::is_x86_feature_detected!("lzcnt")
311        && std::arch::is_x86_feature_detected!("movbe")
312        && std::arch::is_x86_feature_detected!("pclmulqdq")
313        && std::arch::is_x86_feature_detected!("popcnt")
314        && std::arch::is_x86_feature_detected!("rdrand")
315        && std::arch::is_x86_feature_detected!("rdseed")
316        && std::arch::is_x86_feature_detected!("sha")
317        && std::arch::is_x86_feature_detected!("vaes")
318        && std::arch::is_x86_feature_detected!("vpclmulqdq")
319        && std::arch::is_x86_feature_detected!("xsave")
320        && std::arch::is_x86_feature_detected!("xsavec")
321        && std::arch::is_x86_feature_detected!("xsaveopt")
322        && std::arch::is_x86_feature_detected!("xsaves")
323}
324
325#[cfg(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))]
326#[cold]
327fn detect_x86_level() -> Level {
328    if x86_detects_icelake_avx512() {
329        // Safety: All features required by Avx512 were detected above.
330        unsafe { Level::Avx512(Avx512::assume_supported()) }
331    // Feature list sourced from `rustc --print=cfg --target x86_64-unknown-linux-gnu -C target-cpu=x86-64-v3`
332    // However, the following features are implied by avx2 and do not need to be spelled out:
333    // avx,sse,sse2,sse3,sse4.1,sse4.2,ssse3
334    // This can be verified by running:
335    // rustc --print=cfg --target=i586-unknown-linux-gnu -C target-feature=+avx2
336    } else if std::arch::is_x86_feature_detected!("avx2")
337        && std::arch::is_x86_feature_detected!("bmi1")
338        && std::arch::is_x86_feature_detected!("bmi2")
339        && std::arch::is_x86_feature_detected!("cmpxchg16b")
340        && std::arch::is_x86_feature_detected!("f16c")
341        && std::arch::is_x86_feature_detected!("fma")
342        && std::arch::is_x86_feature_detected!("fxsr")
343        && std::arch::is_x86_feature_detected!("lzcnt")
344        && std::arch::is_x86_feature_detected!("movbe")
345        && std::arch::is_x86_feature_detected!("popcnt")
346        && std::arch::is_x86_feature_detected!("xsave")
347    {
348        // Safety: All features required by Avx2 were detected above.
349        unsafe { Level::Avx2(Avx2::assume_supported()) }
350    // All x86 CPUs that ever shipped with sse4.2 also have cmpxchg16b and popcnt:
351    // Intel Nehalem, AMD Bulldozer and VIA Isaiah II were the first with SSE4.2
352    // and have these extensions already.
353    //
354    // This set of instructions maps to the x86-64-v2 level:
355    // rustc --print=cfg --target=x86_64-unknown-linux-gnu -C target-cpu=x86-64-v2
356    //
357    // All SSE levels are implied by SSE4.2, which can be verified by running:
358    // rustc --print=cfg --target=i586-unknown-linux-gnu -C target-feature=+sse4.2
359    } else if std::arch::is_x86_feature_detected!("fxsr")
360        && std::arch::is_x86_feature_detected!("sse4.2")
361        && std::arch::is_x86_feature_detected!("cmpxchg16b")
362        && std::arch::is_x86_feature_detected!("popcnt")
363    {
364        // Safety: All features required by Sse4_2 were detected above.
365        unsafe { Level::Sse4_2(Sse4_2::assume_supported()) }
366    } else if std::arch::is_x86_feature_detected!("sse2")
367        && std::arch::is_x86_feature_detected!("fxsr")
368    {
369        // Safety: All features required by Sse2 were detected above.
370        unsafe { Level::Sse2(Sse2::assume_supported()) }
371    } else {
372        Level::baseline()
373    }
374}
375
376/// The level enum with the specific SIMD capabilities available.
377///
378/// The contained values serve as a proof that the associated target
379/// feature is available.
380#[derive(Clone, Copy, Debug)]
381#[non_exhaustive]
382pub enum Level {
383    /// Scalar fallback level, i.e. no supported SIMD features are to be used.
384    ///
385    /// This variant is **absent** on targets that supports a higher baseline
386    /// (`aarch64-*`, `i686-*`, `x86_64-*`, WASM with SIMD) unless the `force_support_fallback`
387    /// Cargo feature is enabled. Instead of matching on this variant,
388    /// call [`is_fallback`](Level::is_fallback) which is always available.
389    ///
390    /// This can be created with [`Level::fallback`].
391    // Keep this predicate in sync with the fallback module and `dispatch!`.
392    #[cfg(any(
393        feature = "force_support_fallback",
394        not(any(
395            all(target_arch = "aarch64", target_feature = "neon"),
396            all(
397                any(target_arch = "x86", target_arch = "x86_64"),
398                target_feature = "sse2",
399                target_feature = "fxsr"
400            ),
401            all(target_arch = "wasm32", target_feature = "simd128")
402        ))
403    ))]
404    Fallback(Fallback),
405    /// The Neon instruction set on 64 bit ARM.
406    #[cfg(target_arch = "aarch64")]
407    Neon(Neon),
408    /// The SIMD 128 instructions on 32-bit WebAssembly.
409    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
410    WasmSimd128(WasmSimd128),
411    /// The SSE2 instruction set on (32 and 64 bit) x86.
412    ///
413    /// This is the baseline for i686 and x86-64 targets.
414    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
415    Sse2(Sse2),
416    /// The SSE4.2 instruction set on (32 and 64 bit) x86, plus `popcnt` and `cmpxchg16b`.
417    /// Also known as x86-64-v2.
418    ///
419    /// All production CPUs with SSE4.2 also support the other two extensions, so it is safe to require them.
420    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
421    Sse4_2(Sse4_2),
422    /// Ice Lake-class AVX-512 on (32 and 64 bit) x86.
423    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
424    Avx512(Avx512),
425    /// The x86-64-v3 instruction set on (32 and 64 bit) x86, including AVX2 and FMA.
426    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
427    Avx2(Avx2),
428    // If new variants are added, make sure to handle them in `Level::dispatch`
429    // and `dispatch!()`
430}
431
432impl Level {
433    /// Return the best SIMD level available on the CPU. This value should be passed to [`dispatch`].
434    ///
435    /// On x86 and x86-64 targets, this detects the available CPU features on the first call and
436    /// caches the result. Other targets return their strongest statically supported level.
437    /// This may change in the future if runtime-detected levels for other platforms are added.
438    ///
439    /// This function requires the standard library on targets other than wasm32. On wasm32, the
440    /// available level is known statically, so the standard library isn't required.
441    ///
442    /// On x86-64, it is sometimes possible to detect the available features on `#[no_std]`
443    /// by parsing the output of `cpuid` instruction, but this function
444    /// [does not do that](https://github.com/linebender/fearless_simd/issues/157).
445    /// If you do this, you can create the SIMD token via [`assume_supported`](Avx2::assume_supported)
446    /// and then get the [level](Simd::level) from it.
447    ///
448    /// Libraries that use SIMD on `#[no_std]` should let the user pass the appropriate SIMD level
449    /// the user detected through other means (e.g. `cpuid`), to avoid using the fallback level
450    /// when a better SIMD level is available in hardware.
451    #[cfg(any(feature = "std", target_arch = "wasm32"))]
452    #[must_use]
453    #[expect(
454        clippy::new_without_default,
455        reason = "The `Level::new()` function is not always available, and we also want to be explicit about when runtime feature detection happens"
456    )]
457    #[inline]
458    pub fn new() -> Self {
459        #[cfg(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))]
460        {
461            *X86_LEVEL.0
462        }
463
464        // targets other than x86 do not perform any runtime detection
465        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
466        {
467            Self::baseline()
468        }
469    }
470
471    /// Get the target feature level suitable for this run.
472    ///
473    /// Should be used in libraries if they wish to handle the case where
474    /// target features cannot be detected at runtime.
475    /// Most users should prefer [`new`](Self::new).
476    /// This is discussed in more detail in `new`'s documentation.
477    #[allow(clippy::allow_attributes, reason = "Only needed in some cfgs.")]
478    #[allow(unreachable_code, reason = "Fallback unreachable in some cfgs.")]
479    pub fn try_detect() -> Option<Self> {
480        #[cfg(any(feature = "std", target_arch = "wasm32"))]
481        return Some(Self::new());
482        None
483    }
484
485    /// Check whether this is the `Fallback` level; that is, whether no better feature level could
486    /// be statically or dynamically detected. This is useful if there's a scalarized version of
487    /// your algorithm that runs faster if SIMD isn't supported.
488    ///
489    /// This method is always available, even when the fallback backend is not compiled. In that
490    /// case, it always returns `false`.
491    #[inline]
492    pub fn is_fallback(self) -> bool {
493        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
494        return self.as_sse2().is_none();
495
496        #[cfg(target_arch = "aarch64")]
497        return self.as_neon().is_none();
498
499        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
500        return self.as_wasm_simd128().is_none();
501
502        #[cfg(any(
503            all(target_arch = "wasm32", not(target_feature = "simd128")),
504            not(any(
505                target_arch = "x86",
506                target_arch = "x86_64",
507                target_arch = "aarch64",
508                target_arch = "wasm32"
509            ))
510        ))]
511        return true;
512    }
513
514    /// If this is a proof that Neon (or better) is available, access that instruction set.
515    ///
516    /// This method should be preferred over matching against the `Neon` variant of self,
517    /// because if Fearless SIMD gets support for an instruction set which is a superset of Neon,
518    /// this method will return the Neon token even if that "better" instruction set is available.
519    ///
520    /// This can be used in combination with the [kernel] macro to safely access level-specific
521    /// SIMD intrinsics.
522    #[cfg(target_arch = "aarch64")]
523    #[inline]
524    pub fn as_neon(self) -> Option<Neon> {
525        #[allow(
526            unreachable_patterns,
527            reason = "On machines which statically support `neon`, there is only one variant."
528        )]
529        match self {
530            Self::Neon(neon) => Some(neon),
531            _ => None,
532        }
533    }
534
535    /// If this is a proof that SIMD 128 (or better) is available, access that instruction set.
536    ///
537    /// This method should be preferred over matching against the `WasmSimd128` variant of self,
538    /// because if Fearless SIMD gets support for an instruction set which is a superset of SIMD 128,
539    /// this method will return the SIMD 128 token even if that "better" instruction set is available.
540    ///
541    /// This can be used in combination with the [kernel] macro to safely access level-specific
542    /// SIMD intrinsics.
543    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
544    #[inline]
545    pub fn as_wasm_simd128(self) -> Option<WasmSimd128> {
546        #[allow(
547            unreachable_patterns,
548            reason = "On machines which statically support `simd128`, there is only one variant."
549        )]
550        match self {
551            Self::WasmSimd128(simd128) => Some(simd128),
552            _ => None,
553        }
554    }
555
556    /// If this is a proof that SSE2 (or better) is available, access that instruction set.
557    ///
558    /// See [`Sse2::assume_supported`] for the exact list of CPU features this token enables.
559    ///
560    /// This method should be preferred over matching against the `Sse2` variant of self,
561    /// because if the CPU supports a superset of SSE2 (e.g. SSE4.2, AVX2, or AVX-512),
562    /// this method will return the SSE2 token even if that "better" instruction set is available.
563    ///
564    /// This can be used in combination with the [kernel] macro to safely access level-specific
565    /// SIMD intrinsics.
566    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
567    #[inline]
568    pub fn as_sse2(self) -> Option<Sse2> {
569        match self {
570            // Safety: Every stronger x86 SIMD level in this crate includes the `fxsr`,
571            // `sse`, and `sse2` features required by Sse2.
572            Self::Avx512(_avx512) => unsafe { Some(Sse2::assume_supported()) },
573            Self::Avx2(_avx2) => unsafe { Some(Sse2::assume_supported()) },
574            Self::Sse4_2(_sse4_2) => unsafe { Some(Sse2::assume_supported()) },
575            Self::Sse2(sse2) => Some(sse2),
576            #[allow(
577                unreachable_patterns,
578                reason = "This arm is reachable on x86 targets without SSE2."
579            )]
580            _ => None,
581        }
582    }
583
584    /// If this is a proof that x86-64-v2 feature set (or better) is available, access that
585    /// instruction set.
586    ///
587    /// See [`Sse4_2::assume_supported`] for the exact list of CPU features this token enables.
588    ///
589    /// This method should be preferred over matching against the `Sse4_2` variant of self,
590    /// because if the CPU supports a superset of SSE4.2 (e.g. AVX2 or AVX-512),
591    /// this method will return the SSE4.2 token even if that "better" instruction set is available.
592    ///
593    /// This can be used in combination with the [kernel] macro to safely access level-specific
594    /// SIMD intrinsics.
595    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
596    #[inline]
597    pub fn as_sse4_2(self) -> Option<Sse4_2> {
598        match self {
599            // Safety: The Avx512 struct represents an Ice Lake feature set, which includes the
600            // `sse4.2`, `cmpxchg16b`, and `popcnt` features required by Sse4_2.
601            Self::Avx512(_avx512) => unsafe { Some(Sse4_2::assume_supported()) },
602            // Safety: The Avx2 struct represents the x86-64-v3 feature set being enabled, which
603            // includes the `sse4.2`, `cmpxchg16b`, and `popcnt` features required by Sse4_2.
604            Self::Avx2(_avx) => unsafe { Some(Sse4_2::assume_supported()) },
605            Self::Sse4_2(sse42) => Some(sse42),
606            _ => None,
607        }
608    }
609
610    /// If this is a proof that the x86-64-v3 feature set (or better) is available, access that
611    /// instruction set.
612    ///
613    /// See [`Avx2::assume_supported`] for the exact list of CPU features this token enables.
614    ///
615    /// This method should be preferred over matching against the `Avx2` variant of self,
616    /// because if the CPU supports a superset of AVX2 (e.g. AVX-512),
617    /// this method will return the AVX2 token even if that "better" instruction set is available.
618    ///
619    /// This can be used in combination with the [kernel] macro to safely access level-specific
620    /// SIMD intrinsics.
621    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
622    #[inline]
623    pub fn as_avx2(self) -> Option<Avx2> {
624        #[allow(
625            unreachable_patterns,
626            reason = "On machines which statically support `avx2`, there is only one variant."
627        )]
628        match self {
629            // Safety: The Ice Lake AVX-512 feature set includes the x86-64-v3 features required by Avx2.
630            Self::Avx512(_avx512) => unsafe { Some(Avx2::assume_supported()) },
631            Self::Avx2(avx2) => Some(avx2),
632            _ => None,
633        }
634    }
635
636    /// If this is a proof that the Ice Lake AVX-512 feature set is available, access that
637    /// instruction set.
638    ///
639    /// See [`Avx512::assume_supported`] for the exact list of CPU features this token enables.
640    ///
641    /// This can be used in combination with the [kernel] macro to safely access level-specific
642    /// SIMD intrinsics.
643    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
644    #[inline]
645    pub fn as_avx512(self) -> Option<Avx512> {
646        match self {
647            Self::Avx512(avx512) => Some(avx512),
648            _ => None,
649        }
650    }
651
652    /// Get the strongest statically supported SIMD level.
653    ///
654    /// That is, if your compilation run ambiently declares that a target feature is enabled,
655    /// this method will take that into account.
656    /// In most cases, you should use [`Level::new`] or [`Level::try_detect`].
657    /// This method is mainly useful for libraries, where:
658    ///
659    /// 1) Your crate features request that you not use the standard library, i.e. doesn't enable
660    ///    your `"std"` crate feature reason (so you can't use [`Level::new`] and
661    ///    [`Level::try_detect`] returns `None`); AND
662    /// 2) Your caller does not provide a [`Level`]; AND
663    /// 3) The library doesn't want to panic when it can't find a SIMD level.
664    ///
665    /// Note that in these cases, the library should clearly inform the integrator
666    /// that it is using a fallback and so not getting optimal performance (e.g. by panicking if
667    /// `debug_assertions` are enabled, and emitting a log with the "error" level otherwise).
668    /// The messages given should also provide actionable fixes, such as pointing to the
669    /// entry-point which provides a `Level`, or your `"std"` feature.
670    ///
671    /// Note that this is unaffected by the `force-support-fallback` feature.
672    /// Instead, you should use [`Level::fallback`] if you require the fallback level.
673    #[inline]
674    pub const fn baseline() -> Self {
675        // TODO: How do we possibly test that this method works in all cases?
676        // Note that you can use the `check_targets.sh` script to at least ensure that it compiles in all reasonable cases.
677        #[cfg(not(any(
678            target_arch = "x86",
679            target_arch = "x86_64",
680            target_arch = "aarch64",
681            target_arch = "wasm32"
682        )))]
683        {
684            return Self::Fallback(Fallback::new());
685        }
686        #[cfg(target_arch = "aarch64")]
687        {
688            #[cfg(target_feature = "neon")]
689            return unsafe { Self::Neon(Neon::assume_supported()) };
690            #[cfg(not(target_feature = "neon"))]
691            return Self::Fallback(Fallback::new());
692        }
693        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
694        {
695            #[cfg(all(
696                target_feature = "adx",
697                target_feature = "aes",
698                target_feature = "avx512bitalg",
699                target_feature = "avx512bw",
700                target_feature = "avx512cd",
701                target_feature = "avx512dq",
702                target_feature = "avx512f",
703                target_feature = "avx512ifma",
704                target_feature = "avx512vbmi",
705                target_feature = "avx512vbmi2",
706                target_feature = "avx512vl",
707                target_feature = "avx512vnni",
708                target_feature = "avx512vpopcntdq",
709                target_feature = "bmi1",
710                target_feature = "bmi2",
711                target_feature = "cmpxchg16b",
712                target_feature = "fma",
713                target_feature = "fxsr",
714                target_feature = "gfni",
715                target_feature = "lzcnt",
716                target_feature = "movbe",
717                target_feature = "pclmulqdq",
718                target_feature = "popcnt",
719                target_feature = "rdrand",
720                target_feature = "rdseed",
721                target_feature = "sha",
722                target_feature = "vaes",
723                target_feature = "vpclmulqdq",
724                target_feature = "xsave",
725                target_feature = "xsavec",
726                target_feature = "xsaveopt",
727                target_feature = "xsaves"
728            ))]
729            return unsafe { Self::Avx512(Avx512::assume_supported()) };
730            #[cfg(all(
731                target_feature = "avx2",
732                target_feature = "bmi1",
733                target_feature = "bmi2",
734                target_feature = "cmpxchg16b",
735                target_feature = "f16c",
736                target_feature = "fma",
737                target_feature = "fxsr",
738                target_feature = "lzcnt",
739                target_feature = "movbe",
740                target_feature = "popcnt",
741                target_feature = "xsave",
742                not(all(
743                    target_feature = "adx",
744                    target_feature = "aes",
745                    target_feature = "avx512bitalg",
746                    target_feature = "avx512bw",
747                    target_feature = "avx512cd",
748                    target_feature = "avx512dq",
749                    target_feature = "avx512f",
750                    target_feature = "avx512ifma",
751                    target_feature = "avx512vbmi",
752                    target_feature = "avx512vbmi2",
753                    target_feature = "avx512vl",
754                    target_feature = "avx512vnni",
755                    target_feature = "avx512vpopcntdq",
756                    target_feature = "bmi1",
757                    target_feature = "bmi2",
758                    target_feature = "cmpxchg16b",
759                    target_feature = "fma",
760                    target_feature = "fxsr",
761                    target_feature = "gfni",
762                    target_feature = "lzcnt",
763                    target_feature = "movbe",
764                    target_feature = "pclmulqdq",
765                    target_feature = "popcnt",
766                    target_feature = "rdrand",
767                    target_feature = "rdseed",
768                    target_feature = "sha",
769                    target_feature = "vaes",
770                    target_feature = "vpclmulqdq",
771                    target_feature = "xsave",
772                    target_feature = "xsavec",
773                    target_feature = "xsaveopt",
774                    target_feature = "xsaves"
775                ))
776            ))]
777            return unsafe { Self::Avx2(Avx2::assume_supported()) };
778            #[cfg(all(
779                all(
780                    target_feature = "fxsr",
781                    target_feature = "sse4.2",
782                    target_feature = "cmpxchg16b",
783                    target_feature = "popcnt"
784                ),
785                not(all(
786                    target_feature = "avx2",
787                    target_feature = "bmi1",
788                    target_feature = "bmi2",
789                    target_feature = "cmpxchg16b",
790                    target_feature = "f16c",
791                    target_feature = "fma",
792                    target_feature = "fxsr",
793                    target_feature = "lzcnt",
794                    target_feature = "movbe",
795                    target_feature = "popcnt",
796                    target_feature = "xsave"
797                ))
798            ))]
799            return unsafe { Self::Sse4_2(Sse4_2::assume_supported()) };
800            #[cfg(all(
801                target_feature = "sse2",
802                target_feature = "fxsr",
803                not(all(
804                    target_feature = "fxsr",
805                    target_feature = "sse4.2",
806                    target_feature = "cmpxchg16b",
807                    target_feature = "popcnt"
808                ))
809            ))]
810            return unsafe { Self::Sse2(Sse2::assume_supported()) };
811            #[cfg(not(all(target_feature = "sse2", target_feature = "fxsr")))]
812            return Self::Fallback(Fallback::new());
813        }
814        #[cfg(target_arch = "wasm32")]
815        {
816            #[cfg(target_feature = "simd128")]
817            return Self::WasmSimd128(WasmSimd128::assume_supported());
818            #[cfg(not(target_feature = "simd128"))]
819            return Self::Fallback(Fallback::new());
820        }
821    }
822
823    #[doc(hidden)]
824    #[inline]
825    pub fn __dispatch_target(self) -> Self {
826        // Dispatch compiles only the selected multiversioned backends, but public tokens can
827        // still name lower levels even when the ambient target baseline makes those backends
828        // redundant. Normalize the proof to the best dispatchable level, while leaving exact
829        // token identity available for `kernel!` and explicit token use.
830        #[cfg(feature = "force_support_fallback")]
831        #[allow(
832            irrefutable_let_patterns,
833            reason = "On targets without supported SIMD, Fallback is the only Level variant."
834        )]
835        if let Self::Fallback(fallback) = self {
836            return Self::Fallback(fallback);
837        }
838
839        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
840        {
841            #[allow(unused_variables, reason = "Unused with all cfgs active")]
842            let baseline = Self::baseline();
843
844            #[cfg(not(disable_dispatch_avx512))]
845            if let Some(avx512) = self.as_avx512().or_else(|| baseline.as_avx512()) {
846                return Self::Avx512(avx512);
847            }
848
849            #[cfg(not(disable_dispatch_avx2))]
850            if let Some(avx2) = self.as_avx2().or_else(|| baseline.as_avx2()) {
851                return Self::Avx2(avx2);
852            }
853
854            #[cfg(not(disable_dispatch_sse4_2))]
855            if let Some(sse4_2) = self.as_sse4_2().or_else(|| baseline.as_sse4_2()) {
856                return Self::Sse4_2(sse4_2);
857            }
858
859            // The ambient SSE2 baseline is the terminal backend and cannot be disabled. Falling
860            // below it would require compiling the otherwise-unneeded fallback implementation.
861            #[cfg(any(
862                not(disable_dispatch_sse2),
863                all(target_feature = "sse2", target_feature = "fxsr")
864            ))]
865            if let Some(sse2) = self.as_sse2().or_else(|| baseline.as_sse2()) {
866                return Self::Sse2(sse2);
867            }
868        }
869
870        #[cfg(target_arch = "aarch64")]
871        {
872            let baseline = Self::baseline();
873            if let Some(neon) = self.as_neon().or_else(|| baseline.as_neon()) {
874                return Self::Neon(neon);
875            }
876        }
877
878        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
879        {
880            let baseline = Self::baseline();
881            if let Some(wasm) = self
882                .as_wasm_simd128()
883                .or_else(|| baseline.as_wasm_simd128())
884            {
885                return Self::WasmSimd128(wasm);
886            }
887        }
888
889        Self::baseline()
890    }
891
892    /// Create a scalar fallback level, which uses no SIMD instructions.
893    ///
894    /// This is primarily intended for tests; most users should prefer [`Level::new`] or [`Level::baseline`].
895    ///
896    /// Note that enabling the scalar fallback does *not* mean that the fallback branch will not
897    /// contain SIMD instructions. This is because the "ambient" compilation environment has SIMD
898    /// instructions available, which may be utilised by LLVM to auto-vectorise that path.
899    #[inline]
900    #[cfg(feature = "force_support_fallback")]
901    pub const fn fallback() -> Self {
902        Self::Fallback(Fallback::new())
903    }
904}
905
906#[cfg(test)]
907mod tests {
908    use crate::Level;
909
910    const fn assert_is_send_sync<T: Send + Sync>() {}
911    /// If this test compiles, we know that [`Level`] is properly `Send` and `Sync`.
912    #[test]
913    fn level_is_send_sync() {
914        assert_is_send_sync::<Level>();
915    }
916
917    #[test]
918    fn baseline_reports_whether_fallback_is_required() {
919        let has_simd_baseline = cfg!(any(
920            all(target_arch = "aarch64", target_feature = "neon"),
921            all(
922                any(target_arch = "x86", target_arch = "x86_64"),
923                target_feature = "sse2",
924                target_feature = "fxsr"
925            ),
926            all(target_arch = "wasm32", target_feature = "simd128")
927        ));
928
929        assert_eq!(Level::baseline().is_fallback(), !has_simd_baseline);
930    }
931
932    #[cfg(all(
933        any(feature = "std", target_arch = "wasm32"),
934        not(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))
935    ))]
936    #[test]
937    fn level_new_uses_baseline_outside_x86() {
938        assert_eq!(
939            core::mem::discriminant(&Level::new()),
940            core::mem::discriminant(&Level::baseline())
941        );
942    }
943}