compiler_builtins/math/libm_math/arch/x86/detect.rs
1// Using runtime feature detection requires atomics. Currently there are no x86 targets
2// that support sse but not `AtomicPtr`.
3
4#[cfg(target_arch = "x86")]
5use core::arch::x86::{__cpuid, __cpuid_count, _xgetbv, CpuidResult};
6#[cfg(target_arch = "x86_64")]
7use core::arch::x86_64::{__cpuid, __cpuid_count, _xgetbv, CpuidResult};
8
9use crate::support::feature_detect::{Flags, get_or_init_flags_cache, unique_masks};
10
11/// CPU features that get cached (doesn't correlate to anything on the CPU).
12pub mod cpu_flags {
13 use super::unique_masks;
14
15 unique_masks! {
16 u32,
17 SSE3,
18 F16C,
19 SSE,
20 SSE2,
21 ERMSB,
22 MOVRS,
23 FMA,
24 FMA4,
25 AVX512FP16,
26 AVX512BF16,
27 }
28}
29
30/// Get CPU features, loading from a cache if available.
31pub fn get_cpu_features() -> Flags {
32 use core::sync::atomic::AtomicU32;
33 static CACHE: AtomicU32 = AtomicU32::new(0);
34 get_or_init_flags_cache(&CACHE, load_x86_features)
35}
36
37/// Read from cpuid and translate to a `Flags` instance, using `cpu_flags`.
38///
39/// Implementation is taken from [std-detect][std-detect].
40///
41/// [std-detect]: https://github.com/rust-lang/stdarch/blob/690b3a6334d482874163bd6fcef408e0518febe9/crates/std_detect/src/detect/os/x86.rs#L142
42fn load_x86_features() -> Flags {
43 let mut value = Flags::empty();
44
45 if cfg!(target_env = "sgx") {
46 // doesn't support this because it is untrusted data
47 return Flags::empty();
48 }
49
50 // Calling `__cpuid`/`__cpuid_count` from here on is safe because the CPU
51 // has `cpuid` support.
52
53 // 0. EAX = 0: Basic Information:
54 // - EAX returns the "Highest Function Parameter", that is, the maximum leaf
55 // value for subsequent calls of `cpuinfo` in range [0, 0x8000_0000].
56 // - The vendor ID is stored in 12 u8 ascii chars, returned in EBX, EDX, and ECX
57 // (in that order)
58 let mut vendor_id = [0u8; 12];
59 let max_basic_leaf;
60 unsafe {
61 let CpuidResult { eax, ebx, ecx, edx } = __cpuid(0);
62 max_basic_leaf = eax;
63 vendor_id[0..4].copy_from_slice(&ebx.to_ne_bytes());
64 vendor_id[4..8].copy_from_slice(&edx.to_ne_bytes());
65 vendor_id[8..12].copy_from_slice(&ecx.to_ne_bytes());
66 }
67
68 if max_basic_leaf < 1 {
69 // Earlier Intel 486, CPUID not implemented
70 return value;
71 }
72
73 // EAX = 1, ECX = 0: Queries "Processor Info and Feature Bits";
74 // Contains information about most x86 features.
75 let CpuidResult { ecx, edx, .. } = unsafe { __cpuid(0x0000_0001_u32) };
76 let proc_info_ecx = Flags::from_bits(ecx);
77 let proc_info_edx = Flags::from_bits(edx);
78
79 // EAX = 7: Queries "Extended Features";
80 // Contains information about bmi,bmi2, and avx2 support.
81 let mut extended_features_ebx = Flags::empty();
82 let mut extended_features_edx = Flags::empty();
83 let mut extended_features_eax_leaf_1 = Flags::empty();
84 if max_basic_leaf >= 7 {
85 let CpuidResult { ebx, edx, .. } = unsafe { __cpuid(0x0000_0007_u32) };
86 extended_features_ebx = Flags::from_bits(ebx);
87 extended_features_edx = Flags::from_bits(edx);
88
89 let CpuidResult { eax, .. } = unsafe { __cpuid_count(0x0000_0007_u32, 0x0000_0001_u32) };
90 extended_features_eax_leaf_1 = Flags::from_bits(eax)
91 }
92
93 // EAX = 0x8000_0000, ECX = 0: Get Highest Extended Function Supported
94 // - EAX returns the max leaf value for extended information, that is,
95 // `cpuid` calls in range [0x8000_0000; u32::MAX]:
96 let extended_max_basic_leaf = unsafe { __cpuid(0x8000_0000_u32) }.eax;
97
98 // EAX = 0x8000_0001, ECX=0: Queries "Extended Processor Info and Feature Bits"
99 let mut extended_proc_info_ecx = Flags::empty();
100 if extended_max_basic_leaf >= 1 {
101 let CpuidResult { ecx, .. } = unsafe { __cpuid(0x8000_0001_u32) };
102 extended_proc_info_ecx = Flags::from_bits(ecx);
103 }
104
105 let mut enable = |regflags: Flags, regbit, flag| {
106 if regflags.test_nth(regbit) {
107 value.insert(flag);
108 }
109 };
110
111 enable(proc_info_ecx, 0, cpu_flags::SSE3);
112 enable(proc_info_ecx, 29, cpu_flags::F16C);
113 enable(proc_info_edx, 25, cpu_flags::SSE);
114 enable(proc_info_edx, 26, cpu_flags::SSE2);
115 enable(extended_features_ebx, 9, cpu_flags::ERMSB);
116 enable(extended_features_eax_leaf_1, 31, cpu_flags::MOVRS);
117
118 // `XSAVE` and `AVX` support:
119 let cpu_xsave = proc_info_ecx.test_nth(26);
120 if cpu_xsave {
121 // 0. Here the CPU supports `XSAVE`.
122
123 // 1. Detect `OSXSAVE`, that is, whether the OS is AVX enabled and
124 // supports saving the state of the AVX/AVX2 vector registers on
125 // context-switches, see:
126 //
127 // - [intel: is avx enabled?][is_avx_enabled],
128 // - [mozilla: sse.cpp][mozilla_sse_cpp].
129 //
130 // [is_avx_enabled]: https://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
131 // [mozilla_sse_cpp]: https://hg.mozilla.org/mozilla-central/file/64bab5cbb9b6/mozglue/build/SSE.cpp#l190
132 let cpu_osxsave = proc_info_ecx.test_nth(27);
133
134 if cpu_osxsave {
135 // 2. The OS must have signaled the CPU that it supports saving and
136 // restoring the:
137 //
138 // * SSE -> `XCR0.SSE[1]`
139 // * AVX -> `XCR0.AVX[2]`
140 // * AVX-512 -> `XCR0.AVX-512[7:5]`.
141 // * AMX -> `XCR0.AMX[18:17]`
142 //
143 // by setting the corresponding bits of `XCR0` to `1`.
144 //
145 // This is safe because the CPU supports `xsave` and the OS has set `osxsave`.
146 let xcr0 = unsafe { _xgetbv(0) };
147 // Test `XCR0.SSE[1]` and `XCR0.AVX[2]` with the mask `0b110 == 6`:
148 let os_avx_support = xcr0 & 6 == 6;
149 // Test `XCR0.AVX-512[7:5]` with the mask `0b1110_0000 == 0xe0`:
150 let os_avx512_support = xcr0 & 0xe0 == 0xe0;
151
152 // Only if the OS and the CPU support saving/restoring the AVX
153 // registers we enable `xsave` support:
154 if os_avx_support {
155 // See "13.3 ENABLING THE XSAVE FEATURE SET AND XSAVE-ENABLED
156 // FEATURES" in the "Intel® 64 and IA-32 Architectures Software
157 // Developer’s Manual, Volume 1: Basic Architecture":
158 //
159 // "Software enables the XSAVE feature set by setting
160 // CR4.OSXSAVE[bit 18] to 1 (e.g., with the MOV to CR4
161 // instruction). If this bit is 0, execution of any of XGETBV,
162 // XRSTOR, XRSTORS, XSAVE, XSAVEC, XSAVEOPT, XSAVES, and XSETBV
163 // causes an invalid-opcode exception (#UD)"
164
165 // FMA (uses 256-bit wide registers):
166 enable(proc_info_ecx, 12, cpu_flags::FMA);
167
168 // For AVX-512 the OS also needs to support saving/restoring
169 // the extended state, only then we enable AVX-512 support:
170 if os_avx512_support {
171 enable(extended_features_edx, 23, cpu_flags::AVX512FP16);
172 enable(extended_features_eax_leaf_1, 5, cpu_flags::AVX512BF16);
173 }
174 }
175 }
176 }
177
178 // As Hygon Dhyana originates from AMD technology and shares most of the architecture with
179 // AMD's family 17h, but with different CPU Vendor ID("HygonGenuine")/Family series number
180 // (Family 18h).
181 //
182 // For CPUID feature bits, Hygon Dhyana(family 18h) share the same definition with AMD
183 // family 17h.
184 //
185 // Related AMD CPUID specification is https://www.amd.com/system/files/TechDocs/25481.pdf
186 // (AMD64 Architecture Programmer's Manual, Appendix E).
187 // Related Hygon kernel patch can be found on
188 // http://lkml.kernel.org/r/5ce86123a7b9dad925ac583d88d2f921040e859b.1538583282.git.puwen@hygon.cn
189 if vendor_id == *b"AuthenticAMD" || vendor_id == *b"HygonGenuine" {
190 // These features are available on AMD arch CPUs:
191 enable(extended_proc_info_ecx, 16, cpu_flags::FMA4);
192 }
193
194 value
195}
196
197#[cfg(test)]
198mod tests {
199 extern crate std;
200 use std::is_x86_feature_detected;
201
202 use super::*;
203
204 #[test]
205 fn check_matches_std() {
206 let features = get_cpu_features();
207 for i in 0..cpu_flags::ALL.len() {
208 let flag = cpu_flags::ALL[i];
209 let name = cpu_flags::NAMES[i];
210
211 let std_detected = match flag {
212 cpu_flags::SSE3 => is_x86_feature_detected!("sse3"),
213 cpu_flags::F16C => is_x86_feature_detected!("f16c"),
214 cpu_flags::SSE => is_x86_feature_detected!("sse"),
215 cpu_flags::SSE2 => is_x86_feature_detected!("sse2"),
216 cpu_flags::ERMSB => is_x86_feature_detected!("ermsb"),
217 cpu_flags::MOVRS => continue, // only very recent support in std
218 cpu_flags::FMA => is_x86_feature_detected!("fma"),
219 cpu_flags::FMA4 => continue, // not yet supported in std
220 cpu_flags::AVX512FP16 => is_x86_feature_detected!("avx512fp16"),
221 cpu_flags::AVX512BF16 => is_x86_feature_detected!("avx512bf16"),
222 _ => panic!("untested CPU flag {name}"),
223 };
224
225 assert_eq!(
226 std_detected,
227 features.contains(flag),
228 "different flag {name}. flags: {features:?}"
229 );
230 }
231 }
232}