1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//! Which instruction sets the CPU has, and which code path a scan uses.
use std::fmt;
use crate::error::{Error, Result};
use crate::value::Value;
/// A code path for the distance kernels, named after the instructions it needs.
///
/// Every path returns exactly what [`Isa::Scalar`] returns; the test suite checks each path the CPU
/// running it has against the plain reference. [`Isa::best_for`] picks one for a width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Isa {
/// Portable Rust with no instruction set assumed beyond the build target's. Always available.
Scalar,
/// The x86-64 `popcnt` instruction, one 64-bit word at a time.
Popcnt,
/// x86-64 AVX2: four 64-bit words a step, counting bits with a nibble lookup table.
Avx2,
/// x86-64 AVX-512 F and BW without `VPOPCNTDQ`, as on Skylake-X and Cascade Lake servers: the
/// AVX2 nibble lookup on 512-bit vectors, eight 64-bit words a step.
Avx512Bw,
/// x86-64 AVX-512 with `VPOPCNTDQ`: eight 64-bit words a step, counted by one instruction.
Avx512,
/// Arm NEON: two 64-bit words a vector, each counted on its own.
Neon,
/// Arm NEON, eight 64-bit values a step in four vectors, their counts narrowed into one vector
/// and compared with the radius there, so only a step with a survivor leaves the vector unit.
/// At 256 bits it runs the [`Isa::Neon`] kernel.
NeonWide,
}
impl Isa {
/// Every path, in order from the plainest to the widest, x86-64 first.
pub const ALL: [Self; 7] = [
Self::Scalar,
Self::Popcnt,
Self::Avx2,
Self::Avx512Bw,
Self::Avx512,
Self::Neon,
Self::NeonWide,
];
/// The path's name, such as `avx512`.
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Scalar => "scalar",
Self::Popcnt => "popcnt",
Self::Avx2 => "avx2",
Self::Avx512Bw => "avx512bw",
Self::Avx512 => "avx512",
Self::Neon => "neon",
Self::NeonWide => "neon-wide",
}
}
/// The path named `name`, as [`name`](Self::name) gives it, whether or not this CPU has it.
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|isa| isa.name() == name)
}
/// How the path counts bits, so a benchmark result can be traced to the code behind it.
#[must_use]
pub const fn technique(self) -> &'static str {
match self {
Self::Scalar => "count_ones per word as the build target compiles it, four records unrolled",
Self::Popcnt => "hardware popcnt per word, four records unrolled",
Self::Avx2 => {
"nibble lookup with vpshufb and vpsadbw per 64-bit lane (Mula, Kurz and Lemire 2018), \
four records a vector"
}
Self::Avx512Bw => {
"nibble lookup with 512-bit vpshufb and vpsadbw per 64-bit lane, a compare to a mask, \
eight records a vector"
}
Self::Avx512 => "vpopcntq per 64-bit lane and a compare to a mask, eight records a vector",
Self::Neon => "vcntq_u8 and pairwise widening adds per 64-bit lane, two records a vector",
Self::NeonWide => {
"vcntq_u8 on four vectors, pairwise adds narrowing eight records' counts into one \
vector, compared with the radius there; the neon kernel at 256 bits"
}
}
}
/// Whether this CPU, and this build, can run the path. Checked at run time.
#[must_use]
pub fn is_available(self) -> bool {
match self {
Self::Scalar => true,
#[cfg(target_arch = "x86_64")]
Self::Popcnt => std::arch::is_x86_feature_detected!("popcnt"),
#[cfg(target_arch = "x86_64")]
Self::Avx2 => std::arch::is_x86_feature_detected!("avx2") && std::arch::is_x86_feature_detected!("popcnt"),
#[cfg(target_arch = "x86_64")]
Self::Avx512Bw => {
std::arch::is_x86_feature_detected!("avx512f")
&& std::arch::is_x86_feature_detected!("avx512bw")
&& std::arch::is_x86_feature_detected!("popcnt")
}
#[cfg(target_arch = "x86_64")]
Self::Avx512 => {
std::arch::is_x86_feature_detected!("avx512f")
&& std::arch::is_x86_feature_detected!("avx512vpopcntdq")
&& std::arch::is_x86_feature_detected!("popcnt")
}
#[cfg(target_arch = "aarch64")]
Self::Neon | Self::NeonWide => std::arch::is_aarch64_feature_detected!("neon"),
#[allow(unreachable_patterns, reason = "which arms remain depends on the target")]
_ => false,
}
}
/// The paths this CPU can run, plainest first.
#[must_use]
pub fn available() -> Vec<Self> {
Self::ALL.into_iter().filter(|isa| isa.is_available()).collect()
}
/// The fastest path this CPU can run for values of type `V`, by what was measured on each kind
/// of CPU (the crate's README has the numbers).
///
/// On x86-64, at either width: AVX-512 with `VPOPCNTDQ`, then AVX-512 BW, then AVX2, then
/// `popcnt`, then [`Isa::Scalar`]. On `aarch64`, where NEON is detected, the answer depends on
/// the width: at 256 bits [`Isa::Neon`], which ran 1.6 times the scalar code on an Apple M2 Pro;
/// at 64 bits [`Isa::NeonWide`], which ran 1.4 to 1.6 times the scalar code on the same CPU on
/// every workload measured. The [`Isa::Neon`] kernel at 64 bits ran 0.68 times the scalar
/// code there, and stays selectable by name for comparison.
#[must_use]
pub fn best_for<V: Value>() -> Self {
let order: &[Self] = if cfg!(target_arch = "aarch64") {
if V::BITS == 64 {
&[Self::NeonWide]
} else {
&[Self::Neon]
}
} else {
&[Self::Avx512, Self::Avx512Bw, Self::Avx2, Self::Popcnt]
};
order
.iter()
.copied()
.find(|isa| isa.is_available())
.unwrap_or(Self::Scalar)
}
/// Return the path if this CPU can run it.
///
/// # Errors
///
/// [`Error::IsaUnavailable`] if it can't.
pub fn require(self) -> Result<Self> {
if self.is_available() {
Ok(self)
} else {
Err(Error::IsaUnavailable(self.name()))
}
}
}
impl fmt::Display for Isa {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// What the running machine offers, for a report or a benchmark record.
///
/// ```
/// let cpu = legit_hamming::Cpu::detect();
/// assert!(cpu.paths.contains(&cpu.best64) && cpu.paths.contains(&cpu.best256));
/// println!("{} with {:?}: {} at 64 bits, {} at 256", cpu.arch, cpu.features, cpu.best64, cpu.best256);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cpu {
/// The architecture the crate was built for, such as `x86_64`.
pub arch: &'static str,
/// The instruction-set extensions that matter to this crate and that the CPU reports, by
/// their `is_x86_feature_detected!` or `is_aarch64_feature_detected!` names, such as
/// `avx512vpopcntdq`.
pub features: Vec<&'static str>,
/// The paths this CPU can run.
pub paths: Vec<Isa>,
/// The path [`Isa::best_for`] chooses for 64-bit values.
pub best64: Isa,
/// The path [`Isa::best_for`] chooses for 256-bit values.
pub best256: Isa,
/// The threads the operating system lets this process run at once, or 1 if it won't say.
pub threads: usize,
}
impl Cpu {
/// Detect the running CPU.
#[must_use]
pub fn detect() -> Self {
Self {
arch: std::env::consts::ARCH,
features: features(),
paths: Isa::available(),
best64: Isa::best_for::<u64>(),
best256: Isa::best_for::<[u64; 4]>(),
threads: std::thread::available_parallelism().map_or(1, usize::from),
}
}
}
#[cfg(target_arch = "x86_64")]
fn features() -> Vec<&'static str> {
use std::arch::is_x86_feature_detected as has;
let mut found = Vec::new();
for (name, present) in [
("popcnt", has!("popcnt")),
("bmi2", has!("bmi2")),
("avx2", has!("avx2")),
("avx512f", has!("avx512f")),
("avx512bw", has!("avx512bw")),
("avx512vl", has!("avx512vl")),
("avx512vpopcntdq", has!("avx512vpopcntdq")),
("avx512bitalg", has!("avx512bitalg")),
] {
if present {
found.push(name);
}
}
found
}
#[cfg(target_arch = "aarch64")]
fn features() -> Vec<&'static str> {
use std::arch::is_aarch64_feature_detected as has;
let mut found = Vec::new();
for (name, present) in [("neon", has!("neon")), ("sve", has!("sve")), ("sve2", has!("sve2"))] {
if present {
found.push(name);
}
}
found
}
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn features() -> Vec<&'static str> {
Vec::new()
}