use std::sync::OnceLock;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Prefetch {
near: usize,
lines: usize,
}
const LINE: usize = 64;
impl Prefetch {
pub(crate) fn detect() -> Self {
static POLICY: OnceLock<Prefetch> = OnceLock::new();
*POLICY.get_or_init(Self::for_this_cpu)
}
#[cfg(target_arch = "x86_64")]
fn for_this_cpu() -> Self {
Self::for_x86(amd())
}
#[cfg(any(target_arch = "x86_64", test))]
fn for_x86(amd: Option<(u32, u32)>) -> Self {
match amd {
Some((ZEN_5.., _)) => Self { near: 8, lines: 8 },
Some((ZEN_3_AND_4, model)) if is_zen_4(model) => Self { near: 0, lines: 32 },
_ => Self { near: 0, lines: 8 },
}
}
#[cfg(all(target_arch = "aarch64", target_vendor = "apple"))]
fn for_this_cpu() -> Self {
Self { near: 0, lines: 256 }
}
#[cfg(all(target_arch = "aarch64", not(target_vendor = "apple")))]
fn for_this_cpu() -> Self {
Self { near: 0, lines: 16 }
}
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn for_this_cpu() -> Self {
Self { near: 0, lines: 0 }
}
pub(crate) fn for_dims<E>(self, dims: usize) -> Self {
let lines = self.lines.min((dims * size_of::<E>()).div_ceil(LINE));
Self { near: self.near.min(lines), lines }
}
#[inline(always)]
pub(crate) fn vector<E>(self, vector: &[E]) {
let start = vector.as_ptr().cast::<u8>();
for line in 0..self.near {
hint(start.wrapping_add(line * LINE), true);
}
for line in self.near..self.lines {
hint(start.wrapping_add(line * LINE), false);
}
}
}
pub(crate) fn group_width(bytes: usize) -> usize {
static ZEN_5_OR_LATER: OnceLock<bool> = OnceLock::new();
if bytes < 1024 {
return 1;
}
#[cfg(target_arch = "x86_64")]
let wide = *ZEN_5_OR_LATER.get_or_init(|| matches!(amd(), Some((ZEN_5.., _))));
#[cfg(not(target_arch = "x86_64"))]
let wide = *ZEN_5_OR_LATER.get_or_init(|| false);
if wide { 8 } else { 4 }
}
#[inline(always)]
pub(crate) fn list(start: *const u8, bytes: usize) {
for offset in (0..bytes).step_by(LINE) {
hint(start.wrapping_add(offset), true);
}
}
#[inline(always)]
fn hint(line: *const u8, near: bool) {
#[cfg(target_arch = "x86_64")]
unsafe {
use std::arch::x86_64::{_MM_HINT_T0, _MM_HINT_T1, _mm_prefetch};
if near {
_mm_prefetch::<_MM_HINT_T0>(line.cast());
} else {
_mm_prefetch::<_MM_HINT_T1>(line.cast());
}
}
#[cfg(target_arch = "aarch64")]
unsafe {
use std::arch::asm;
if near {
asm!("prfm pldl1keep, [{0}]", in(reg) line, options(nostack, preserves_flags, readonly));
} else {
asm!("prfm pldl2keep, [{0}]", in(reg) line, options(nostack, preserves_flags, readonly));
}
}
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
let _ = (line, near);
}
#[cfg(any(target_arch = "x86_64", test))]
const ZEN_5: u32 = 0x1a;
#[cfg(any(target_arch = "x86_64", test))]
const ZEN_3_AND_4: u32 = 0x19;
#[cfg(any(target_arch = "x86_64", test))]
fn is_zen_4(model: u32) -> bool {
matches!(model, 0x10..=0x1f | 0x60..=0xaf)
}
#[cfg(target_arch = "x86_64")]
#[allow(unused_unsafe)] fn amd() -> Option<(u32, u32)> {
use std::arch::x86_64::__cpuid;
let (vendor, version) = unsafe { (__cpuid(0), __cpuid(1).eax) };
let amd = (vendor.ebx, vendor.edx, vendor.ecx) == (0x6874_7541, 0x6974_6e65, 0x444d_4163);
let family = ((version >> 8) & 0xf) + ((version >> 20) & 0xff);
let model = ((version >> 4) & 0xf) | ((version >> 12) & 0xf0);
amd.then_some((family, model))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_prefetching_past_the_end_of_the_data_is_harmless() {
let policy = Prefetch::detect();
for dims in [0, 1, 3, 16, 17, 128, 1536] {
let vector = vec![1.0f32; dims];
policy.vector(&vector);
policy.for_dims::<f32>(dims).vector(&vector);
list(vector.as_ptr().cast(), dims * 4);
}
}
#[test]
fn test_a_short_vector_gets_no_more_lines_than_it_has() {
let into_l1 = Prefetch { near: 8, lines: 8 };
assert_eq!(into_l1.for_dims::<f32>(0), Prefetch { near: 0, lines: 0 });
assert_eq!(into_l1.for_dims::<f32>(17), Prefetch { near: 2, lines: 2 });
assert_eq!(into_l1.for_dims::<f32>(1536), into_l1);
let into_l2 = Prefetch { near: 0, lines: 8 };
assert_eq!(into_l2.for_dims::<f32>(16), Prefetch { near: 0, lines: 1 });
assert_eq!(into_l2.for_dims::<u16>(128), Prefetch { near: 0, lines: 4 });
assert_eq!(
Prefetch { near: 0, lines: 256 }.for_dims::<u16>(1536),
Prefetch { near: 0, lines: 48 }
);
}
#[test]
fn test_each_measured_x86_processor_gets_its_policy() {
let (into_l1, into_l2) = (Prefetch { near: 8, lines: 8 }, Prefetch { near: 0, lines: 8 });
let deeper = Prefetch { near: 0, lines: 32 };
assert_eq!(Prefetch::for_x86(Some((0x19, 0x01))), into_l2);
assert_eq!(Prefetch::for_x86(Some((0x19, 0x11))), deeper);
assert_eq!(Prefetch::for_x86(Some((0x1a, 0x02))), into_l1);
assert_eq!(Prefetch::for_x86(None), into_l2);
assert_eq!(Prefetch::for_x86(Some((0x19, 0x21))), into_l2);
assert_eq!(Prefetch::for_x86(Some((0x19, 0x61))), deeper);
assert_eq!(Prefetch::for_x86(Some((0x17, 0x31))), into_l2);
assert_eq!(Prefetch::for_x86(Some((0x1b, 0x00))), into_l1);
assert_eq!(deeper.for_dims::<f32>(128), into_l2);
}
#[test]
fn test_short_vectors_are_not_grouped() {
assert_eq!(group_width(512), 1);
assert_eq!(group_width(1023), 1);
#[cfg(target_arch = "x86_64")]
let zen_5 = matches!(amd(), Some((ZEN_5.., _)));
#[cfg(not(target_arch = "x86_64"))]
let zen_5 = false;
assert_eq!(group_width(1024), if zen_5 { 8 } else { 4 });
assert_eq!(group_width(1024), group_width(6144));
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_amd_family_and_model_are_real() {
let real = |(family, model)| (0xf..0x100).contains(&family) && model < 0x100;
assert!(amd().is_none_or(real));
}
}