use core::sync::atomic::{AtomicU8, Ordering};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Features {
pub bmi2: bool,
pub huf_asm: bool,
}
impl Features {
#[inline]
pub(crate) fn detect() -> Self {
let bmi2 = bmi2();
let huf_asm = bmi2
&& match ASM.load(Ordering::Relaxed) {
ASM_ON => true,
ASM_OFF => false,
_ => !amd(),
};
Features { bmi2, huf_asm }
}
}
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
#[inline]
fn bmi2() -> bool {
#[cfg(feature = "std")]
{
std::is_x86_feature_detected!("bmi2")
&& std::is_x86_feature_detected!("bmi1")
&& std::is_x86_feature_detected!("lzcnt")
&& std::is_x86_feature_detected!("ssse3")
}
#[cfg(not(feature = "std"))]
{
cfg!(all(
target_feature = "bmi2",
target_feature = "bmi1",
target_feature = "lzcnt",
target_feature = "ssse3"
))
}
}
#[cfg(not(all(target_arch = "x86_64", not(feature = "portable"))))]
#[inline]
fn bmi2() -> bool {
false
}
#[doc(hidden)]
pub fn selected_paths() -> &'static [&'static str] {
let f = Features::detect();
match (f.bmi2, f.huf_asm) {
(true, true) => &["bmi2", "asm"],
(true, false) => &["bmi2"],
_ => &[],
}
}
const ASM_AUTO: u8 = 0;
const ASM_ON: u8 = 1;
const ASM_OFF: u8 = 2;
static ASM: AtomicU8 = AtomicU8::new(ASM_AUTO);
#[doc(hidden)]
pub fn set_asm(mode: Option<bool>) {
let v = match mode {
None => ASM_AUTO,
Some(true) => ASM_ON,
Some(false) => ASM_OFF,
};
ASM.store(v, Ordering::Relaxed);
}
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
static VENDOR: AtomicU8 = AtomicU8::new(0);
#[cfg(all(target_arch = "x86_64", not(feature = "portable")))]
fn amd() -> bool {
match VENDOR.load(Ordering::Relaxed) {
1 => return true,
2 => return false,
_ => {}
}
#[allow(unsafe_code, unused_unsafe)]
let r = unsafe { core::arch::x86_64::__cpuid(0) };
let vendor = (
r.ebx.to_le_bytes(),
r.edx.to_le_bytes(),
r.ecx.to_le_bytes(),
);
let amd = vendor == (*b"Auth", *b"enti", *b"cAMD") || vendor == (*b"Hygo", *b"nGen", *b"uine");
VENDOR.store(if amd { 1 } else { 2 }, Ordering::Relaxed);
amd
}
#[cfg(not(all(target_arch = "x86_64", not(feature = "portable"))))]
fn amd() -> bool {
false
}
#[inline(always)]
pub(crate) fn prefetch_l1(p: *const u8) {
#[cfg(all(target_arch = "x86_64", not(miri)))]
#[allow(unsafe_code, unused_unsafe)]
unsafe {
use core::arch::x86_64::{_MM_HINT_T0, _mm_prefetch};
_mm_prefetch::<_MM_HINT_T0>(p.cast());
}
#[cfg(not(all(target_arch = "x86_64", not(miri))))]
let _ = p;
}