std_detect/detect/os/linux/
loongarch.rs

1//! Run-time feature detection for LoongArch on Linux.
2
3use core::arch::asm;
4
5use super::auxvec;
6use crate::detect::{Feature, bit, cache};
7
8/// Try to read the features from the auxiliary vector.
9pub(crate) fn detect_features() -> cache::Initializer {
10    let mut value = cache::Initializer::default();
11    let enable_feature = |value: &mut cache::Initializer, feature, enable| {
12        if enable {
13            value.set(feature as u32);
14        }
15    };
16
17    // The values are part of the platform-specific [cpucfg]
18    //
19    // [cpucfg]: LoongArch Reference Manual Volume 1: Basic Architecture v1.1
20    let cpucfg2: usize;
21    unsafe {
22        asm!(
23            "cpucfg {}, {}",
24            out(reg) cpucfg2, in(reg) 2,
25            options(pure, nomem, preserves_flags, nostack)
26        );
27    }
28    let cpucfg3: usize;
29    unsafe {
30        asm!(
31            "cpucfg {}, {}",
32            out(reg) cpucfg3, in(reg) 3,
33            options(pure, nomem, preserves_flags, nostack)
34        );
35    }
36    enable_feature(&mut value, Feature::frecipe, bit::test(cpucfg2, 25));
37
38    // The values are part of the platform-specific [asm/hwcap.h][hwcap]
39    //
40    // [hwcap]: https://github.com/torvalds/linux/blob/master/arch/loongarch/include/uapi/asm/hwcap.h
41    if let Ok(auxv) = auxvec::auxv() {
42        enable_feature(&mut value, Feature::f, bit::test(cpucfg2, 1) && bit::test(auxv.hwcap, 3));
43        enable_feature(&mut value, Feature::d, bit::test(cpucfg2, 2) && bit::test(auxv.hwcap, 3));
44        enable_feature(&mut value, Feature::lsx, bit::test(auxv.hwcap, 4));
45        enable_feature(&mut value, Feature::lasx, bit::test(auxv.hwcap, 5));
46        enable_feature(
47            &mut value,
48            Feature::lbt,
49            bit::test(auxv.hwcap, 10) && bit::test(auxv.hwcap, 11) && bit::test(auxv.hwcap, 12),
50        );
51        enable_feature(&mut value, Feature::lvz, bit::test(auxv.hwcap, 9));
52        enable_feature(&mut value, Feature::ual, bit::test(auxv.hwcap, 2));
53        return value;
54    }
55    value
56}